IA32 Assembly Programming in Linux 작성자: 박창범
Sample Code (AT&T syntax) /* ssize_t write(int fd, const void *buf, size_t count); */ /* write(fileno(stdout), "hello", 6); */ .include "defines.h" .data hello: .string "hello world\n" .text .globl _start _start: movl $SYS_write,%eax // SYS_write = 4 movl $STDOUT,%ebx // fd = fileno(stdio) movl $hello,%ecx // buf = str movl $12,%edx // count = 0x6 int $0x80 movl $SYS_exit,%eax xorl %ebx,%ebx ret Section Declaration .data section var_name: .var_type [value] .text section .globl function_name function_name: [codes]
System Call System call number goes into %eax The args go in %ebx,%ecx,%edx,%esi,%edi in order The return value of the syscall is stored in %eax Calling: int $0x80 The syscall number can be found in /usr/include/sys/syscall.h The macros are defined as SYS_<syscall name> i.e. SYS_exit, SYS_close, in provided sample code and “defines.h”
Syscalls with > 5 args Same as Syscalls with < 6 args but except argument passing the args are arranged in memory and the pointer to the first arg is stored in %ebx /* mappedptr=mmap(NULL,filelen,PROT_READ,MAP_SHARED,fd,0); */ movl %edx,(%esp) movl %eax,4(%esp) movl $PROT_READ,8(%esp) movl $MAP_SHARED,12(%esp) movl $fd,%ebx movl (%ebx),%eax movl %eax,16(%esp) movl %edx,20(%esp) movl $SYS_mmap,%eax movl %esp,%ebx int $0x80
Mixing C-Assembly Make object file Use Makefile %> gcc –c xxx.S Use Makefile We can use another assembler GAS(AT&T syntax), NASM(Intel syntax)
Tips Use gcc –S xxx.c We can get xxx.S Referring assembly code generated by compiler could be helpful (don’t just copy generated code)
References http://www.linuxassembly.org/ http://www.linuxassembly.org/howto/Assembly-HOWTO.html http://linuxassembly.org/articles/linasm.html