Reputation: 641
I've just added a system call to the linux kernel. It simply takes a char*
argument name and prints Hello name.
This is system call code:
asmlinkage long sys_hello(char* name) { printk("Hello %s \n", name); return 0; }
and this is the code which should run the system call for testing:
int main()
{
long int amma = syscall(318,"Winston");
printf("Returned %lu \n" ,amma);
return 0;
}
but when I run this, I get a killed output. Any ideas about fixing this? Thanks in advance.
Upvotes: 1
Views: 1680
Reputation:
Your code is executed in kernel context whilst the buffer with data comes from the userspace. If you need to process some string from the userspace, copy it to the kernel memory using strncpy_from_user() function. If you don't follow the scheme and simply try to access the data directly, this will lead to a memory access violation.
A better solution (based on your code) would look somewhat like this:
asmlinkage long sys_hello(char* name) {
long nb_symbols;
char *name_internal;
long i;
/*
* Estimate the buffer length sufficient
* to accommodate the string
*/
for (i = 1; ; ++i) {
nb_symbols = strnlen_user(name, i);
if (nb_symbols <= 0)
return -EFAULT;
if (nb_symbols < i)
break;
}
/* Allocate the storage */
name_internal = kmalloc(nb_symbols + 1, GFP_KERNEL);
if (name_internal == NULL)
return -ENOMEM;
if (strncpy_from_user(name_internal, name, nb_symbols + 1) !=
nb_symbols) {
kfree(name_internal);
return -EFAULT;
}
printk("The 'name' is '%s'\n", name_internal);
kfree(name_internal);
return 0;
}
However, please note that such a loop (as one in my example) might not be an acceptable solution for buffer length estimation. Ideally, you could drop it and use a static char
array of fixed length to use strncpy_from_user()
with.
Upvotes: 5
Reputation:
This is one of the classic examples how to NOT write kernel code - it tries to directly access the userspace buffer which is an extreme no-no.
If you got a crash, that's probably SMAP in action. Hard to say for sure since you did not provide the log.
So the real question is: where did you take the above from? are you doing a university course which has the above in its material?
Upvotes: 0