Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 匯編語言開發指南:語法格式、工具鏈、系統調用、內聯匯編與優化實戰

編輯:Linux 教學

為何仍需匯編

  • 內核啟動、硬件初始化、中斷向量表:C 語言無法直接操作
  • 極致性能熱點:手工指令調度、SIMD 內聯
  • 嵌入式體積壓縮:無 libc 依賴,二進制極小
  • 安全/逆向分析:理解編譯器輸出、殼代碼構造

AT&T vs Intel 語法核心差異

項目AT&T (GAS 默認)Intel (NASM)
寄存器前綴%eaxeax
立即數前綴$11
操作數順序src, dstdst, src
操作數長度後綴movl/movw/movbdword ptr / word ptr / byte ptr
間接跳轉jmp *%eaxjmp eax
內存寻址section:disp(base,index,scale)section:[base+index*scale+disp]

Hello World 兩種寫法

AT&T (hello.s)

.data
msg: .string "Hello, world!\n"
len = . - msg
.text
.global _start
_start:
    movl $len, %edx
    movl $msg, %ecx
    movl $1, %ebx
    movl $4, %eax
    int $0x80
    movl $0, %ebx
    movl $1, %eax
    int $0x80

Intel (hello.asm)

section .data
msg db "Hello, world!", 0xA
len equ $ - msg
section .text
global _start
_start:
    mov edx, len
    mov ecx, msg
    mov ebx, 1
    mov eax, 4
    int 0x80
    mov ebx, 0
    mov eax, 1
    int 0x80

工具鏈

  • GAS:as --gstabs -o hello.o hello.s (含符號表)
  • NASM:nasm -f elf hello.asm
  • LD:ld -o hello hello.o (勿加 -s 保留符號)
  • 調試:GDB/DDD (源碼級) / ALD (專用匯編調試器)

系統調用協議 (int 0x80 / syscall)

  • 調用號 → EAX/RAX
  • 參數 1-6 → EBX/RDI, ECX/RSI, EDX/RDX, ESI/R10, EDI/R8, EBP/R9
  • 返回值 → EAX/RAX
  • 參數 >5 時:內存連續區地址 → EBX/RDI
  • 常用號:/usr/include/asm/unistd.h 定義 SYS_write 等

命令行參數獲取

棧頂依次為 argc、argv[]、envp[],popl %ecx 取 argc,循環 popl %ecx 遍歷 argv。

GCC 內聯匯編完整模板

__asm__ __volatile__(
    "movl %1, %%eax\n\t"
    "movl %%eax, %0"
    : "=r" (output)   // 輸出約束
    : "r" (input)     // 輸入約束
    : "%eax"          // 破壞寄存器列表
);

約束修飾符:= 輸出、+ 輸入輸出、& 早期剪切。常用約束字母:r 任意寄存器、q abcd、a/b/c/d 指定 eax/ebx/ecx/edx、m 內存、I 常數。

優化建議

  • 優先用 C + -O2 -march=native,僅對熱點內聯匯編
  • 內聯匯編標註 __volatile__ 防編譯器重排/刪除
  • 大塊匯編獨立 .s 文件,.cfi_* 指令保證異常展棧正確
  • 使用 perf record -g 定位熱點再決定是否手寫
Copyright © Windows教程網 All Rights Reserved