The manpage for _syscall(2)
states:
Starting around kernel 2.6.18, the _syscall macros were removed from header files supplied to user space. Use syscall(2) instead. (Some architectures, notably ia64, never provided the _syscall macros; on those architectures, syscall(2) was always required.)
Thus, your desired approach can't work on more modern kernels. (You can clearly see that if you run the preprocessor on your code. It won't resolve the _syscall0
macro) Try to use the syscall
function instead:
Here is an example for the usage, cited from syscall(2)
:
#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);
}
As you asked for a direct way to call the Linux kernel without any userspace wrappers, I'll show you examples for the 80386 and the amd64 architecture.
First, you have to get the system call number from a table, such as this one. In case of getpid
, the system call number is 39 for amd64 and 20 for 80386. Next, we create a function that calls the system for us. On the 80386 processor you use the interrupt 128 to call the system, on amd64 we use the special syscall
instruction. The system call number goes into register eax, the output is also written to this register. In order to make the program easier, we write it in assembly. You can later use strace to verify it works correctly.
This is the code for 80386. It should return the lowest byte of its pid as exit status.
.global _start
_start: mov $20,%eax #system call number 20:
int $128 #call the system
mov %eax,%ebx #move pid into register ebx
mov $1,%eax #system call number 1: exit, argument in ebx
int $128 #exit
Assemble with:
as -m32 -o 80386.o 80386.s
ld -m elf_i386 -o 80386 80386.o
This is the same code for amd64:
.global _start
_start: mov $39,%eax #system call 39: getpid
syscall #call the system
mov %eax,%edi #move pid into register edi
mov $60,%eax #system call 60: exit
syscall #call the system
Assemble with:
as -o amd64.o amd64.s
ld -o amd64 amd64.o