Machine-Level Programming III:Procedure
Today
- Procedures
- Mechanisms(机制)
- Stack Structure
- Calling Conventions(调用规则)
- Passing control(传递控制)
- Passing data(传递数据)
- Managing local data
- Illustration of Recursion(递归说明)
补充术语:
Program 程序员写的一个完整程序代码
Procedure 就是程序中一段完成一定功能的代码
Process 就是一个完整的程序加载到内存中运行的形式,是正在运行的处于动态的program
Mechanisms in Procedures(总体机制学习)
- passing control
- To beignning of procedure code
- Back to return point
- passing data
- Procedure arguments
- Return value
- Memory management
- Allocate during procedure excution
- Deallocate upon return
- Mechanisms all implemented with machine instructions
- x86-64 implementation of a procedure uses only those mechanisms required
解读:
程序机制包括:传递控制、传递数据和内存分配三个部分。
这些机制都是由机器指令实现的,x86-64在程序中使用的机制只有以上这些。
调用控制: 开始时跳转到代码段开头+结束后跳转回调用位置
调用数据: 代码段使用到的参数+返回值、
内存安排: 代码段执行过程中分配内存+返回时解除分配
三个机制分别各由一半在调用开始时,一半在调用结束返回时。
Machine instructions implement the mechanisms, but the choices are determined by designers. These choices make up the Application Binary Interface(ABI)
Stack Structure(调用中要使用的存储方式)
Region of memory managed with stack discipline(规则)
There are two points. Firstly, Memory viewed as array of bytes. Secondly, Different regions have different purpose.(Like ABI, a policy decision)
栈向小地址生长。
相关指令
pushq Src
//从Src获取操作数,栈顶(%rsp)自减,操作数写入栈顶
popq Dest
//从栈顶读数据,存到Dest,栈顶自增
作为存储
Calling Coventrol
Passing control
Ues stack to support procesure call and return
Procedure call: call lable
//返回地址(调用位置的下一条指令)压栈,跳转到标签处
Procedure return: ret
//弹出返回地址,跳转到返回地址
//过程中通过修改%rip的值实现跳转!!!
Procedure Data Flow(Passing data)
寄存器的使用:
前六个参数:%rdi %rsi %rdx %rcx %r8 %r9
返回值:%rax
Stack: 向小地址生长。参数7到参数n存入栈中,7最靠近栈底。(Only allocate stack space when needed)
Managing local data
Languages that support recursion(递归) must be “Reentrant”(可重入):multiple simultaneous instantiations of single procedure(单个过程的多个实例化)
Need some place to store state of each instantiation from when called to when return
- Arguments
- Local variables
- Return pointer
stack allcoated in Frames(按帧分配的堆栈)state for single procedure instantiation
Stack Frames
Contents:
- Return information
- Local storage (if needed)
- Temporary space (if needed)
Management is done by “call” and “ret”
Frame Pointer: %rbp (Optional)
Stack Pointer: %rsp
栈帧解读:(有很多理解关键点)
Whenever we enter a new procedure, we have to deal with two Frames: Current Stack Frame and Caller Stack Frame.
notes1:此次call的参数的构建是在调用者帧里完成的。
notes2:被调用者的参数是可选项,当它是叶函数(不调用其它函数的函数)时,不需要存储参数构建和当前栈帧指针(%rbp),当
解读:对于过程(procedure)的使用,需要进行实例化(instantiations)。
为每个实例分配的内存包含三个部分(参数、本地变量、返回指针,前两者需要时才会分配),此时堆栈是按照帧分配的。