函数调用过程中堆栈运行情况

本文详细介绍了IA32程序如何利用程序栈支持过程调用,包括栈帧的分配、参数传递、返回地址保存及局部变量存储。解释了为什么在某些情况下需要使用栈存储本地变量,并提供了栈操作指令的使用说明。
《Computer Systems》一书中关于函数调用的描述:

    IA32 programs make use of the program stack to support procedure calls. The stack is used to pass procedure arguments, to store return information, to save registers for later restoration, and for local storage. The portion of the stack allocated for a single procedure call is called a stack frame. Figure 3.16 diagrams the general structure of a stack frame. The topmost stack frame is delimited by two pointers, with register %ebp serving as the frame pointer, and register %esp serving as the stack pointer. The stack pointer can move while the procedure is executing, and hence most information is accessed relative to the frame pointer.

    Suppose procedure P (the caller) calls procedure Q (the callee). The arguments to Q are contained within the stack frame for P. In addition, when P calls Q, the return address within P where the program should resume execution when it returns from Q is pushed on the stack, forming the end of P’s stack frame. The stack frame for Q starts with the saved value of the frame pointer (i.e., %ebp). followed by copies of any other saved register values.
    Procedure Q also uses the stack for any local variables that cannot be stored in registers. This can occur for the following reasons:
    1. There are not enough registers to hold all of the local data.
    2. Some of the local variables are arrays or structures and hence must be accessed by array or structure references.
    3. The address operator ‘&’ is applied to one of the local variables, and hence we must be able to generate an address for it.
    Finally, Q will use the stack frame for storing arguments to any procedures it calls.

    As described earlier, the stack grows toward lower addresses and the stack pointer %esp points to the top element of the stack. Data can be stored on and retrieved from the stack using the pushl and popl instructions. Space for data with no specified initial value can be allocated on the stack by simply decrementing the stack pointer by an appropriate amount. Similarly, space can be deallocated by incrementing the stack pointer.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值