了解Assembly中的C程序

Jor*_* Jr 3 c assembly x86-64

我试图理解这个简单的C程序:

int square(int num) {
    return num * num; 
}
Run Code Online (Sandbox Code Playgroud)

当它在汇编代码中时:

square(int): 
  push rbp ;push rbp register onto stack
  mov rbp, rsp ;move contents of rbp register into rsp register 
  mov DWORD PTR [rbp-4], edi ;not sure what happens here 
  mov eax, DWORD PTR [rbp-4] ;not sure what happens here
  imul eax, DWORD PTR [rbp-4] ;multiply eax and DWORD PTR [rbp-4] (?)
  pop rbp ;pop original register out of stack
  ret ;return 
Run Code Online (Sandbox Code Playgroud)
  1. 第3和第4行发生了什么?
  2. 为什么必须使用两个寄存器(edi和eax)而不是rsp?
  3. DWORD PTR [rbp-4]实际发生了什么?

Joh*_*ode 8

mov DWORD PTR [rbp-4], edi ;not sure what happens here
Run Code Online (Sandbox Code Playgroud)

x86_64 System V ABI通过寄存器传递函数参数 - 第一个整数参数在rdi/edi寄存器中传递.因此,该行将参数复制num到本地(从存储在其中的帧指针值偏移-4个字节rbp).

mov eax, DWORD PTR [rbp-4] ;not sure what happens here
Run Code Online (Sandbox Code Playgroud)

这会将本地的值复制到eax寄存器中.

imul eax, DWORD PTR [rbp-4] ;multiply eax and DWORD PTR [rbp-4] (?)
Run Code Online (Sandbox Code Playgroud)

并且它将值乘以eaxlocal,并将结果存储到eax(也恰好是存储函数返回值的寄存器).

正如其他人在评论中指出,与优化的编译可能会消除局部,并直接从编写edieax.