Re: Why system call need to copy the date from the userspace before using it

Vadim Lobanov
2005-04-13T05:30:41Z

On Wed, 13 Apr 2005, Tomko wrote:

> Hi all,
>
> I am new to linux , hope someone can help me.
> While i am reading the source code of the linux system call , i find
> that the system call need to call copy_from_user() to copy the data from
> user space to kernel space before using it . Why not use it directly as
> the system call has got the address ? Furthermore , how to distinguish
> between user space and kernel space ?
>
> Thx a lot,
>
> TOM
> -

The quick and simple answer to this question is: data integrity.

The main thing to understand is that, from the perspective of the
kernel, any user input provided in the form of system calls must have
immutable data. Only if the data is immutable can the kernel code parse
it and decide what to do, without getting into really hairy race
conditions. And, for that matter, it's much simpler and less error-prone
to program code where you don't have to worry about the inputs changing
around you all the time.

So, you might say, what's wrong with the user code giving the kernel a
pointer to a userland buffer? After all, the calling task will be
blocked while the system call is being executed on its behalf. The
biggest problem is that the buffer can still be modified, while the
system call is executing, by another userland thread running in the same
virtual memory context. Or, for that matter, by another process that has
this chunk of memory shared with the original task. There are
innumerable ways for the data to potentially change in the middle of the
system call, and the simplest solution ends up being to copy the data to
kernelspace before working with it. That way, no userland tasks can
change it on you.

I'm sure there are other reasons for doing the copy, that someone will
be able to chime in with. Other input is always welcome. :-)

-Vadim Lobanov