0. 說明
本學習系列代碼幾乎完全摘自:asmtutor.com,如果英文可以的(也可以用谷歌瀏覽器翻譯看),可以直接看asmtutor.com上的教程
系統環境搭建:(我用的是ubuntu18.04.4 server,安裝gcc、g++)
sudo apt install nasm
sudo apt install gcc-multilib
1. 完整示例
; Hello World Program - asmtutor.com
; Compile with: nasm -f elf helloworld.asm
; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld.o -o helloworld
; Run with: ./helloworld
SECTION .data
msg db 'Hello World!', 0Ah ; assign msg variable with your message string
SECTION .text
global _start
_start:
mov edx, 13 ; number of bytes to write - one for each letter plus 0Ah (line feed character)
mov ecx, msg ; move the memory address of our message string into ecx
mov ebx, 1 ; write to the STDOUT file
mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4)
int 80h
mov ebx, 0 ; return 0 status on exit - 'No Errors'
mov eax, 1 ; invoke SYS_EXIT (kernel opcode 1)
int 80h
編譯、鏈接和運行方法:(其實代碼中已經寫了)
nasm -f elf helloworld.asm -o helloworld # 可以用nasm -h看幫助信息,-f elf是輸出32位elf,-f elf64是64
ld -m elf_i386 helloworld.o -o helloworld # ld是鏈接器,可以用ld -h看幫助信息,-m elf_i386是格式為i386,也有其他的可選
# Run with:
./helloworld
2. 系統函數調用
Linux的系統調用通過int 80h實現,在此之前需要先要給eax寄存器賦值(opcode,operation code,操作碼),例如調用sys_write函數的opcode是4,那么就給eax賦值4:mov eax, 4,類似的sys_exit的opcode為1。
3. 參數傳遞
參數分別按照依次傳遞給ebx, ecx, edx,例如sys_write的系統調用:
#include
ssize_t write(int fd, const void *buf, size_t count);
ebx:第一個參數,文件描述符,1是標準輸出(0是標準輸入,2是錯誤),這個就是寫入到標準輸出,即打印到屏幕
ecx:第二個參數,內存地址,傳遞的是msg,數據段中的地址(SECTION .data)
edx:把待打印的字符數傳遞給edx
windows c編程中好像有stdcall等函數調用約定,約定參數傳遞的順序,是從右至左還是反之
windows 32位下參數通過壓棧的方式傳遞的
當執行到int 80后,因為opcode是4,所以調用sys_write,然后取ebx、ecx、edx作為參數執行,相當于write(1, msg, 13)。
類似的,sys_exit函數為:
#include
void _exit(int status);
把0傳遞給ebx,然后執行exit,相當于exit(0)。
系統調用的參數列表:可以在linux shell命令行中輸入man 2 write man 2 exit查看,man手冊第2部分就是關于系統調用的。