Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make syscalls from my C program

How do I make system calls from my C program. For example, how do I call the following function? What headers would I have to include?

asmlinkage long sys_exit(int error_code);
like image 736
SivaDotRender Avatar asked May 17 '15 18:05

SivaDotRender


2 Answers

You would normally call C library wrappers for the system calls (for example open() and read() are just wrappers). Wrappers are more friendly.

As an alternative to do the work yourself in assembly, you can try the syscall(2) function from glibc. This function makes a system call without a wrapper, and is specially useful when invoking a system call that has no wrapper function. In this manner you just need to provide symbolic constants for system call numbers, and also i think is more portable than coding the system call in assembler instructions.

Example from the doc:

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
int
main(int argc, char *argv[])
{
    pid_t tid;
    tid = syscall(SYS_gettid);
    tid = syscall(SYS_tgkill, getpid(), tid);
}
like image 177
JosEduSol Avatar answered Nov 07 '22 15:11

JosEduSol


asm volatile(
              "xorq %%rdi, %%rdi;"  /* return value */
              "movq $60, %%rax;"    /* syscall id (/asm/unistd_64.h   */
              "syscall;" 
              ::: "rdi", "rax"
            );

You can't call it from pure C but you need to invoke it from assembly as would any wrapper like glibc. Another way is using int 80h, but that's rather outdated.

In rdi you put error_code (0 in this case) while in rax the number which identifies the system call, available in /usr/include/asm/unistd.h that will in turn point you to the 32 or 64 bit version.

#define __NR_exit 60
like image 37
edmz Avatar answered Nov 07 '22 17:11

edmz