1
#include <linux/kernel.h>
#include <linux/uaccess.h>    
unsigned long long cnt = 0;
asmlinkage long sys_customcall(unsigned long long __user *output)
{
     unsigned long err;            
     err = copy_to_user(output, &cnt, sizeof(unsigned long long));
     return err;
}  

I'm implementing a simple system call. I would like to copy a value from the kernel (cnt) to user pointer (output). However, when I run the code err = 8 which is sizeof(unsigned long long) - user side values are not changing. What have I done wrong? I'm using linux-kernel version 5.4.59.

The user-level code is as following.

#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
int main()
{
    unsigned long long cnt=0;
    long int err = syscall(436, &cnt);
    printf("System call returned %lu\n", err);
    printf("System call returned %llu\n", cnt);
    return 0;
}
SY LEE
  • 11
  • 2
  • 1
    Need to see implementation of `copy_to_user()` how you called `sys_customcall()`. Even better would be a [mcve] – ryyker Sep 16 '20 at 12:15
  • Return value 8 means that all 8 bytes pointed by `output` are not writable for the user program. In other words, you pass incorrect pointer to your system call. You may print that pointer in the user program (using `prtinf()`) and in your syscall implementation (using `printk`) and check, that the kernel get the intended value. – Tsyvarev Sep 16 '20 at 13:12
  • @Tsyvarev Thank you! That was a valid point. The kernel didn't get the intended value. Still... I'm lost on why it's different. – SY LEE Sep 17 '20 at 10:19
  • Have you tried to google on why the arguments are passed incorrectly? E.g. have you checked [that question](https://stackoverflow.com/questions/59851520/system-call-hooking-example-arguments-are-incorrect) and answers for it? For the future: when ask a question about Linux kernel always point **kernel version** you use. This is noted in the description of [tag:linux-kernel] tag. – Tsyvarev Sep 17 '20 at 10:31
  • Great thanks to @Tsyvarev !! Your link was very helpful. I used SYSCALL_DEFINE instead of asmlinkage and it ran just fine. It's not certain but I believe it had something to do with x86_64 system call wrapper. – SY LEE Sep 17 '20 at 13:13
  • Does this answer your question? [System call hooking example arguments are incorrect](https://stackoverflow.com/questions/59851520/system-call-hooking-example-arguments-are-incorrect). Lets mark your question as a [duplicate](https://stackoverflow.com/help/duplicates), so further readers would easily find all approaches related to the problem. – Tsyvarev Sep 17 '20 at 13:15

1 Answers1

0

Problem got solved when I changed asmlinkage to SYSCALL_DEFINEx macro. It's not certain but I believe it had something to do with x86_64 system call wrapper. This link was helpful. Thank you all.

SY LEE
  • 11
  • 2