Procedures are a key abstraction in software. They provide a way to package code that implements some functionality with 一组指定的参数以及一个可选的返回值. This function can then be invoked from different points in a program. Well-designed software uses procedures as an abstraction mechanism, hiding the detailed implementation of some action while providing a clear and concise interface definition of what values will be computed and what effects the procedure will have on the program state. Procedures 在不同的编程语言中有多种表现形式—functions, methods, subroutines, handlers, and so on—but they all share a general set of features.
There are many different attributes that must be handled when providing machine-level support for procedures. 以如下为例,假设procedure P 调用了 procedure Q, and Q then executes and returns back to P. These actions involve one or more of the following mechanisms:
- Passing control:The program counter must be set to the starting address of the code for Q upon entry and then set to the instruction in P following the call to Q upon return.
- Passing data:P must be able to provide one or more parameters to Q, and Q must be able to return a value back to P.
- Allocating and deallocating memory:Q may need to allocate space for local variables when it begins and then free that storage before it returns.
The x86-64 implementation of procedures involves a combination of special instructions and a set of conventions on how to use the machine resources, such as the registers and the program memory. Great effort has been made to minimize the overhead involved in invoking a procedure. As a consequence, it follows what can be seen as a minimalist strategy, implementing only as much of the above set
of mechanisms as is required for each particular procedure. In our presentation, we build up the different mechanisms step by step, first describing control, then data passing, and, finally, memory management.
1 Run-Time Stack
C以及其他大多数语言中procedure调用机制的一个核心特征是利用栈作为内存管理discipline。仍以上面P调用Q为例,当Q正在执行时,P以及调用链条中其他的procedures被暂时挂起。此时只有Q需要为局部变量分配新的内存空间或者调用其他procedure。另一方面,当Q返回时,它所分配的任何局部存储空间都可以被释放。Therefore, a program can manage the storage required by its procedures using a stack, where the stack and the program registers store the information required for passing control and data, and for allocating memory. 当P调用Q时,control and data information被添加到栈中。这些信息当P返回时会被释放。
x86-64栈向低地址进行扩张并且栈指针%rsp指向栈顶元素。数据可以通过pushq以及popq指令来压入或弹出栈。Space for data with no specified initial value can be allocated on the stack by simply decrementing the stack pointer by an appropriate amount. 相似地,空间可以通过增加栈指针得到释放。
当x86-64 procedure所需的存储空间超出寄存器的极限时,它会在栈上分配空间。这个区域被称为procedure’s stack frame。图3.25展示了run-time stack的整体结构,包括its partitioning into stack frames, in its most general form.

当前执行的procedure的frame总是位于栈的顶部。当procedure P调用procedure Q时,它会将返回

本文围绕程序过程调用机制展开,以x86-64为例,介绍了运行时栈、控制转移、数据传递等内容。运行时栈用于管理过程所需存储,控制转移通过call和ret指令实现,数据传递可经寄存器和栈完成,还提及栈上局部存储和寄存器局部存储的相关规则。
最低0.47元/天 解锁文章
12

被折叠的 条评论
为什么被折叠?



