組合語言程式可以分為三個部分:
-
數據段
-
bss段部分
-
文字部分
數據段
用於聲明初始化數據或常量的數據段。在運行時,此數據不改變。在本節中可以聲明不同的常量值,檔案名或緩衝區大小等。
聲明數據段的語法是:
section .data
bss段
BSS部分是用於聲明變數。聲明bss段段的語法是:
section .bss
文本段
文字部分用於保存實際的代碼。本節開頭必須的的聲明global_start,告訴內核程式開始執行。
聲明文本部分的語法是:
section .text global _start _start:
注釋
組合語言注釋以分號(;)。它可能包含任何可列印的字元,包括空白。它可以出現一行本身,如:
; This program displays a message on screen
或者,在同一行上的指令,如:
add eax ,ebx ; adds ebx to eax
Assembly組合語言語句
組合語言程式包括三個類型的語句:
-
可執行指令或指令
-
彙編指令或偽操作
-
宏
可執行指令或簡單指示告訴的處理器該怎麼做。每個指令由操作碼(操作碼)可執行指令生成的機器語言指令。
彙編指令或偽操作告訴彙編有關彙編過程的各個方面。這些都是非可執行檔,並不會產生機器語言指令。
宏基本上是一個文本替換機制。
組合語言語句的語法
組合語言語句輸入每行一個語句。每個語句如下的格式如下:
[label] mnemonic [operands] [;comment]
方括號中的字段是可選的。基本指令有兩部分組成,第一個是要執行的指令(助記符)的名稱和所述第二命令的運算元或參數的。
以下是一些典型的組合語言語句的例子:
INC COUNT ; Increment the memory variable COUNT MOV TOTAL, 48 ; Transfer the value 48 in the ; memory variable TOTAL ADD AH, BH ; Add the content of the ; BH register into the AH register AND MASK1, 128 ; Perform AND operation on the ; variable MASK1 and 128 ADD MARKS, 10 ; Add 10 to the variable MARKS MOV AL, 10 ; Transfer the value 10 to the AL register
Assembly Hello World程式
下麵的組合語言代碼顯示字串 'Hello World'在螢幕上:
section .text global _start ;must be declared for linker (ld) _start: ;tells linker entry zaixian 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) 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
上面的代碼編譯和執行時,它會產生以下結果:
Hello, world!
一個組合語言程式的編譯和鏈接在NASM
請確保已設置NASM和LD的二進位檔的路徑在PATH環境變數中。現在上述程式的編譯和鏈接採取以下步驟:
-
使用文本編輯器,輸入上面的代碼保存為hello.asm。
-
請確保hello.asm檔保存在同一目錄
-
要組合語言程式,請鍵入 nasm -f elf hello.asm
-
如果有錯誤將提示。否則hello.o程式將創建一個對象檔。
-
要鏈接目標檔,並創建一個可執行檔案名hello,請鍵入 ld -m elf_i386 -s -o hello hello.o
-
通過輸入執行程式 ./hello
如果所做的一切都是正確的,它會顯示 Hello, world!在螢幕上。