核心除錯、效能最佳化、開機程式,都離不開組合語言與 C 的混用。要混得順,關鍵是遵守同一套呼叫慣例(calling convention)。
call 呼叫 C 函式,它做兩件事:把下一條指令的位址壓到堆疊頂端,並把 eip 指向被呼叫程式的起點。ret 返回,它把返回位址從堆疊彈出並跳去執行。功能設計:定義全域變數 i,在 main 中呼叫 assembly.s 的 a_add() 並傳入 i 的位址;a_add() 把 i 加 1 後再呼叫 gnuc.c 的 c_add(),一樣傳位址;c_add() 把指標所指的值再加 1;最後 main 印出 i。
#include <stdio.h>
static int i = 0;
void c_add(int *k)
{
(*k)++;
}
int main(void)
{
a_add(&i);
printf("%d\n", i);
return 0;
}
.section .text
.type a_add,@function
.globl a_add
a_add:
pushl %ebp # 現場保護
movl %esp,%ebp
movl 8(%ebp),%eax # 取得 C 函式傳過來的參數
pushl %ecx # 保護 ecx,用作臨時變量
movl (%eax),%ecx # 取得指標所指的內容
addl $1,%ecx # 內容 +1
movl %ecx,(%eax) # 把結果寫回指標所指處
popl %ecx # 恢復 ecx
pushl %eax # 壓棧,準備傳參給 C 函式
call c_add # 呼叫 C 函式
addl $4,%esp # 清理參數佔用的堆疊
popl %ebp # 恢復現場
ret # 返回
幾處關鍵:8(%ebp) 之所以是第一個參數,是因為 ebp 之上依序是返回位址(4(%ebp))與第一個參數(8(%ebp));addl $4,%esp 對應「呼叫者負責清堆疊」的規則,少這一句,堆疊會慢慢失衡;而 pushl %ebp / movl %esp,%ebp 與收尾的 popl %ebp 則是標準的棧框建立與拆除。
gcc -m32 gnuc.c assembly.s -o demo ./demo
輸出為 2,符合預期:C 端加了一次,組合語言端加了一次。只要守住這幾條約定,C 與組合語言就能自由互推,不必擔心參數錯位或堆疊被踩壞。