index.md (2687B)
1 +++ 2 title = 'System calls' 3 +++ 4 # System calls 5 6 - every process starts with 3 files open: stdin, stdout, stderr 7 - steps: 8 9 ![](3008f702882cb6bfcab5abd16d53719a.png) 10 11 - what has to happen to print hello world to stdout? 12 - build process: 13 14 ![](5b26d2fb6045ae318661888ee0febe89.png) 15 16 - iteration 1 17 18 ```c 19 #include <stdio.h> 20 int main(int argc, char **argv) { 21 printf("Hello World!\n"); 22 return 0; 23 } 24 ``` 25 26 - iteration 2 27 28 ```c 29 #include <unistd.h> 30 #define STDOUT 1 31 int main(int argc, char **argv) { 32 char msg[] = "Hello World!\n"; 33 write(STDOUT, msg, sizeof(msg)); 34 return 0; 35 } 36 ``` 37 38 - iteration 3 39 ```c 40 #define _GNU_SOURCE 41 #include <sys/syscall.h> 42 #define STDOUT 1 43 int main(int argc, char **argv) { 44 char msg[] = "Hello World!\n”; 45 int nr = SYS_write; 46 syscall(nr, STDOUT, msg, sizeof(msg)); 47 return 0; 48 } 49 ``` 50 - syscall diagram 51 52 ![](7398350cc1064e43b0aa996f2fa2b199.png) 53 54 - syscall (x86 Linux) is triggered by instruction (like 0x80): 55 - privilege level changed to kernel mode 56 - program counter set to specific location 57 - arguments passed in registers: 58 - rax <- syscall number 59 - ebx, ecdx, edx, esi, edi, ebp <- arguments 60 - stack <- more arguments 61 - x86-64 supports legacy int 0x80, new instruction syscall 62 - rax <- syscall number (different from 32bit) 63 - rdi, rsi, rdx, r10, r8, r9 <- arguments 64 - hello world without glibc -- manual system calls, in-line assembly: 65 66 ```c 67 ssize_t write(int fd, const void *buf, size_t nbytes) { 68 ssize_t ret; 69 asm volatile 70 ( 71 /* request syscall to OS (can also be ‘int $0x80’) */ 72 “syscall” 73 74 /* return result in %eax */ 75 : "=a" (ret) 76 77 /* __NR_write (1) into same place as operand 0, fd into %rdi, buffer into %rsi, length into %rdx */ 78 79 : "0" (__NR_write), "D"(fd), "S"(buf), "d"(nbytes) 80 81 /* modified cc, registers %rcx and %r11, and memory */ 82 : "cc", "rcx", "r11", "memory" 83 ); 84 return ret; 85 } 86 ``` 87 - actual objdump of this program 88 89 ![](d9c7a810130c9f8fd2152d4c2c1e48b5.png)