1. The content of "hello.S":
section .text
global _start ;must be declared for linker (ld)
_start: ;tell linker entry point
mov edx,len ;message length
mov ecx,msg ;message to write
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write); be defined in "/usr/include/asm/unistd_32.h"
int 0x80 ;call kernel
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db 'Hello, world!',0xa ;our dear string
len equ $ - msg ;length of our dear string
2. Generate the executable file:
nasm -f elf hello.S # this will produce hello.o ELF object file
ld -s -o hello hello.o # this will produce hello executable
3. Execute "hello":
./hello
Reference: http://asm.sourceforge.net/intro/Assembly-Intro.html
P.S.
A program can be divided into sections: .text for your code (read-only), .data for your data (read-write), .bss for uninitialized data (read-write); there can actually be a few other standard sections, as well as some user-defined sections, but there's rare need to use them and they are out of our interest here. A program must have at least .text section.
In the Linux, the system function number is passed in eax, and arguments are passed through registers, not the stack. There can be up to six arguments in ebx, ecx, edx, esi, edi, ebp consequently. If there are more arguments, they are simply passed though the structure as first argument. The result is returned in eax, and the stack is not touched at all.
沒有留言:
張貼留言