汇编语言过程(子程序)
系统剖析 CALL/RET 返回地址压弹栈原理、寄存器与栈两种参数传递方式、标准函数序言/尾声与 EBP 栈帧结构、局部变量分配及 cdecl/stdcall/fastcall 调用约定对比。
学完这一章,你能够
- 系统剖析 CALL/RET 返回地址压弹栈原理、寄存器与栈两种参数传递方式、标准函数序言/尾声与 EBP 栈帧结构、局部变量分配及 cdecl/stdcall/fastcall 调用约定对比。
过程概念、CALL/RET 机制与寄存器保护
过程(Procedure)是汇编语言实现代码模块化与复用的子程序机制,相当于高级语言的函数。调用方执行 `CALL label` 时,CPU 自动把下一条指令地址(返回地址)压入栈再跳转到目标标签;被调过程末尾执行 `RET` 时,CPU 从栈顶弹出返回地址写回 `EIP` 恢复执行(详见下表)。过程内部若修改了非返回值寄存器,须按 `push` 顺序压栈保存并在返回前按相反(LIFO)顺序 `pop` 恢复,避免破坏调用方现场。
参数传递、EBP 标准栈帧、返回值与局部变量
小规模私有子程序可直接通过约定寄存器传参(如 `EAX` 与 `EBX` 传入 `add_two` 求和返回至 `EAX`);通用函数与 C 互操作则采用栈传参(cdecl 从右向左压参,调用返回后由调用方 `add esp, 8` 清理参数)。被调函数入口执行标准序言(Prologue)`push ebp; mov ebp, esp` 建立稳定基准指针,使得 `[ebp+4]` 固定指向返回地址、`[ebp+8]` 与 `[ebp+12]` 依次指向第 1、2 参数、`[ebp]` 存放旧 `EBP`,而 `[ebp-4]` 以下为局部变量区;返回前以尾声(Epilogue)`pop ebp; ret` 或 `leave; ret` 销毁栈帧。
过程返回值惯例以 32 位存 `EAX`、64 位存 `EDX:EAX`。需要在函数内使用临时局部变量时,在序言后执行 `sub esp, N` 向下开辟 N 字节栈空间(如 `multiply_add(x, y)` 分配 8 字节分别在 `[ebp-4]` 存 `x*y`、`[ebp-8]` 存 `x+y`,汇总得 230),返回前 `mov esp, ebp; pop ebp`(等价于单条 `leave` 指令)自动释放局部变量。工程上常见的 `cdecl`、`stdcall` 与 `fastcall` 在参数传递渠道与由谁平衡参数栈上各有明确分工(见下表)。
CALL 与 RET 指令底层栈操作对照
| 指令 | 实际执行的操作 |
|---|---|
| CALL label | 将下一条指令地址(返回地址)压入栈顶(ESP -= 4),随后跳转至 label。 |
| RET | 从栈顶弹出返回地址(ESP += 4)并恢复至 EIP,继续执行调用点之后指令。 |
32 位 x86 三大过程调用约定对比
| 约定 | 参数传递 | 栈清理者 | 寄存器保存 | 返回值 |
|---|---|---|---|---|
| cdecl | 全部经栈(从右向左压入,支持变参) | 调用者(Caller) | EAX/ECX/EDX 调用者保存,其余 callee-saved | EAX |
| stdcall | 全部经栈(从右向左压入,固定参数) | 被调用者(RET imm) | EAX/ECX/EDX 调用者保存,其余 callee-saved | EAX |
| fastcall | 前两参经 ECX、EDX,其余经栈 | 被调用者(RET imm) | EAX/ECX/EDX 调用者保存,其余 callee-saved | EAX |
离线模拟 CALL/RET 现场保存、cdecl EBP 栈帧局部变量计算与调用约定核对
"""Offline x86/NASM semantic verification lab for Chapter 18 (procedure)."""
import json
VERSION = "CPython 3.12.14 offline x86/NASM semantic verifier (nasm/ld/gdb absent)"
def case_call_ret_and_reg_preserve():
stack = {}
esp = 0xFFFF0000
saved_order = []
restored_order = []
def push(val):
nonlocal esp
esp -= 4
stack[esp] = val
def pop():
nonlocal esp
val = stack.pop(esp)
esp += 4
return val
# Simulate CALL print_message -> push ret_addr -> save regs -> restore regs -> RET
ret_addr = 0x08048085
push(ret_addr)
regs_in = {"eax": 11, "ebx": 22, "ecx": 33, "edx": 44}
for r in ("eax", "ebx", "ecx", "edx"):
push(regs_in[r])
saved_order.append(r)
regs_out = {}
for r in ("edx", "ecx", "ebx", "eax"):
regs_out[r] = pop()
restored_order.append(r)
popped_ret = pop()
expected = {
"ret_addr_hex": "0x8048085",
"esp_restored": "0xffff0000",
"regs_preserved": True,
"lifo_order_reversed": True,
"add_two_10_20": 30,
}
actual = {
"ret_addr_hex": hex(popped_ret),
"esp_restored": hex(esp),
"regs_preserved": regs_out == regs_in,
"lifo_order_reversed": saved_order == list(reversed(restored_order)),
"add_two_10_20": 10 + 20,
}
return {
"name": "call_ret_and_reg_preserve",
"summary": "模拟 CALL 压栈返回地址、过程内寄存器 LIFO 保存恢复、RET 弹址及寄存器传参求和",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cdecl_stack_frame_and_locals():
mem = {}
esp = 0xFFFF1000
ebp = 0xFFFF1100
def push(v):
nonlocal esp
esp -= 4
mem[esp] = v
def pop():
nonlocal esp
v = mem.pop(esp)
esp += 4
return v
# Caller pushes args right-to-left: multiply_add(x=20, y=10) -> wait: push 10 (y), push 20 (x)
push(10) # [ebp+12] = y
push(20) # [ebp+8] = x
push(0x08048100) # return address [ebp+4]
# Prologue: push ebp; mov ebp, esp; sub esp, 8
push(ebp)
ebp = esp
esp -= 8
# Offsets check
arg1 = mem[ebp + 8]
arg2 = mem[ebp + 12]
ret_addr = mem[ebp + 4]
# Locals: [ebp-4] = x*y, [ebp-8] = x+y
mem[ebp - 4] = arg1 * arg2
mem[ebp - 8] = arg1 + arg2
eax = mem[ebp - 4] + mem[ebp - 8]
# Epilogue (leave; ret): mov esp, ebp; pop ebp; pop eip
esp = ebp
ebp = pop()
eip = pop()
# Caller cleans 8 bytes of args (cdecl)
esp += 8
expected = {
"arg1_ebp_plus_8": 20,
"arg2_ebp_plus_12": 10,
"local1_prod": 200,
"local2_sum": 30,
"return_eax": 230,
"returned_eip_hex": "0x8048100",
"esp_back_to_start": "0xffff1000",
"ebp_restored": "0xffff1100",
}
actual = {
"arg1_ebp_plus_8": arg1,
"arg2_ebp_plus_12": arg2,
"local1_prod": mem[0xFFFF1000 - 16 - 4],
"local2_sum": mem[0xFFFF1000 - 16 - 8],
"return_eax": eax,
"returned_eip_hex": hex(eip),
"esp_back_to_start": hex(esp),
"ebp_restored": hex(ebp),
}
return {
"name": "cdecl_stack_frame_and_locals",
"summary": "精确模拟 cdecl 栈帧布局([ebp+8]/[ebp+12] 参数、[ebp-4]/[ebp-8] 局部变量)与 leave/ret 清理",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_return_values_and_calling_conventions():
ret32 = 42
ret64_edx, ret64_eax = 0x00000000, 0x00000001
ret64 = (ret64_edx << 32) | ret64_eax
conventions = {
"cdecl": {"stack_cleaner": "caller", "arg_order": "right_to_left", "ret_reg": "EAX"},
"stdcall": {"stack_cleaner": "callee", "arg_order": "right_to_left", "ret_reg": "EAX"},
"fastcall": {"stack_cleaner": "callee", "arg_regs": ["ECX", "EDX"], "ret_reg": "EAX"},
}
expected = {
"ret32": 42,
"ret64": 1,
"cdecl_cleaner": "caller",
"stdcall_cleaner": "callee",
"fastcall_regs": ["ECX", "EDX"],
}
actual = {
"ret32": ret32,
"ret64": ret64,
"cdecl_cleaner": conventions["cdecl"]["stack_cleaner"],
"stdcall_cleaner": conventions["stdcall"]["stack_cleaner"],
"fastcall_regs": conventions["fastcall"]["arg_regs"],
}
return {
"name": "return_values_and_calling_conventions",
"summary": "核对 EAX/EDX:EAX 32/64 位返回值约定与 cdecl/stdcall/fastcall 三种调用约定栈清理责任",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_call_ret_and_reg_preserve(),
case_cdecl_stack_frame_and_locals(),
case_return_values_and_calling_conventions(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证返回地址压弹栈、multiply_add(20,10)=230 时 [ebp+8]/[ebp+12]/[ebp-4]/[ebp-8] 精确布局及 ESP 恢复平衡。
所需环境:Windows x64、CPython 3.12.14 离线 x86/NASM 寄存器、标志位与内存语义验证器(本机未安装 nasm/ld/gdb)。
当前源码 SHA256:2a2ed399d51dd938584fdc48fa663d1f1e82b8cf70da771102291f00d57b1793
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 x86/NASM 寄存器、标志位与内存语义验证器(本机未安装 nasm/ld/gdb)。
ZIP SHA256:e9c81300dcb8b3c170f60cfc293e039216a460d93cd8f5c0cc3c262cf694527d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在标准 32 位 cdecl 栈帧建立(`push ebp; mov ebp, esp`)之后,为什么第 1 个函数参数位于 `[ebp + 8]` 而不是 `[ebp + 4]`?
展开参考解答
因为 `[ebp]` 处存放着刚压入的旧 `EBP`(4 字节),`[ebp + 4]` 处存放着 `CALL` 指令自动压入的返回地址(4 字节),所以紧邻其上方高地址处的第 1 个参数正好位于 `[ebp + 8]`。