Mr.Mips
Mr.Mips

Reputation: 389

Example of "copy_from_user" in Linux Kernel (just copying a pointer to an int)

I know there are a lot of posts on this, but most are very complex and I'm hoping someone can help me with my simple example.

I'm writing a system call and the function I'm writing has the form:

SYS_CALLDEFINE4(calc, int, param1, int, param2, char, operation, int*, result) 
{
//Do system call stuff here
} 

I know that the pointer to the int will be a problem, because the userspace application could have passed a pointer to vital system space (and we don't want to mess with that). So I need to use the copy_from_user function.

Can someone possibly give an example of how to correctly use those two functions in the context of making sure you can access that pointer correctly?

Upvotes: 0

Views: 2524

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65870

Replacement for

*result = <value>;

would be

int local_value = <value>;
if (copy_to_user(&local_value, result, sizeof(*result)))
{
    // 'result' points to inaccessible memory.
}
// assigning 'result' has been successful.

Alternatively, because the size of the result is small (int in your case), you may use put_user, which is simpler and more effective:

if (put_user(<value>, result) < 0)
{
    // 'result' points to inaccessible memory.
}
// assigning 'result' has been successful.

Upvotes: 1

Related Questions