編譯
$ cc -arch i386 syscalltest.s
$ ./a.out
hello, world
代碼
.text
.globl _main
.p2align 4, 0x90
_main:
pushl %ebp
movl %esp, %ebp
call L_0
L_0:
popl %eax
leal L_str-L_0(%eax), %eax
pushl $nbyte # nbyte
pushl %eax # buf
pushl $1 # fildes stdout
subl $4, %esp # stack 16-bytes aligned
movl $4, %eax # ssize_t write(int fildes, const void *buf, size_t nbyte);
int $0x80
movl %ebp, %esp
popl %ebp
ret
.cstring
L_str:
.asciz "hello, world\n"
.equ nbyte, . - L_str
說明
arguments passed on the stack, pushed right-to-left
stack 16-bytes aligned
syscall number in the eax register
call by interrupt 0x80
So what we have to do to print a “Hello world” is:push the length of the string (int) to the stack
push a pointer to the string to the stack
push the stdout file descriptor (1) to the stack
align the stack by moving the stack pointer 4 more bytes (16 - 4 * 3)
set the eax register to the write syscall number (4)
interrupt 0x80
系統調用號所在頭文件
/usr/include/sys/syscall.h
可以通過如下命令查找
$ cat /usr/include/sys/syscall.h | grep SYS_write
#define SYS_write 4
#define SYS_writev 121
#define SYS_write_nocancel 397
#define SYS_writev_nocancel 412
文件描述符通過如下命令查看
$ ls -l /dev/std*
lr-xr-xr-x 1 root wheel 0 8 3 23:34 /dev/stderr -> fd/2
lr-xr-xr-x 1 root wheel 0 8 3 23:34 /dev/stdin -> fd/0
lr-xr-xr-x 1 root wheel 0 8 3 23:34 /dev/stdout -> fd/1
標準輸出的文件描述符號爲1