函数前言和结语在C [英] Function Prologue and Epilogue in C

查看:164
本文介绍了函数前言和结语在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道嵌套函数调用中的数据转到堆栈。堆栈本身实现一个逐步的方法,用于在函数被调用或返回时从堆栈中存储和检索数据。这些方法的名称是最知名的作为序言和结语。

I know data in nested function calls go to the Stack.The stack itself implements a step-by-step method for storing and retrieving data from the stack as the functions get called or returns.The name of these methods is most known as Prologue and Epilogue.

我没有成功地搜索关于此主题的资料。你们知道关于功能序言和结语在C中一般工作的任何资源(网站,视频,文章)吗?或者如果你能解释会更好。

I tried with no success to search material on this topic. Do you guys know any resource ( site,video, article ) about how function prologue and epilogue works generally in C ? Or if you can explain would be even better.

PS:我只想要一些一般的视图,不要太详细。

P.S : I just want some general view, not too detailed.

推荐答案

有很多资源可以解释这一点:

There are lots of resources out there that explain this:

  • Function prologue (Wikipedia)
  • x86 Disassembly/Calling Conventions (WikiBooks)
  • Considerations for Writing Prolog/Epilog Code (MSDN)

基本上,你有点描述,堆栈在程序执行的几个目的:

Basically, as you somewhat described, "the stack" serves several purposes in the execution of a program:


  1. 跟踪返回的位置, a

  2. 在函数调用的上下文中存储局部变量

  3. 将调用函数的参数传递给callee。

代码是在函数开始时发生的。它的职责是设置被调用函数的堆栈帧。完全相反:它是函数中最后发生的事情,其目的是恢复调用(父)函数的堆栈框架。

The prolouge is what happens at the beginning of a function. Its responsibility is to set up the stack frame of the called function. The epilog is the exact opposite: it is what happens last in a function, and its purpose is to restore the stack frame of the calling (parent) function.

在IA -32(x86)cdecl, ebp 寄存器由语言使用以跟踪函数的堆栈帧。处理器使用 esp 寄存器指向堆栈中最近的添加(顶值)。

In IA-32 (x86) cdecl, the ebp register is used by the language to keep track of the function's stack frame. The esp register is used by the processor to point to the most recent addition (the top value) on the stack.

call 指令做两件事:首先将返回地址压入堆栈,然后跳转到被调用的函数。紧跟调用后, esp 指向堆栈上的返回地址。

The call instruction does two things: First it pushes the return address onto the stack, then it jumps to the function being called. Immediately after the call, esp points to the return address on the stack.

然后执行序言:

push  ebp         ; Save the stack-frame base pointer (of the calling function).
mov   ebp, esp    ; Set the stack-frame base pointer to be the current
                  ; location on the stack.
sub   esp, N      ; Grow the stack by N bytes to reserve space for local variables

此时, p>

At this point, we have:

...
ebp + 4:    Return address
ebp + 0:    Calling function's old ebp value
ebp - 4:    (local variables)
...

epilog:

mov   esp, ebp    ; Put the stack pointer back where it was when this function
                  ; was called.
pop   ebp         ; Restore the calling function's stack frame.
ret               ; Return to the calling function.

这篇关于函数前言和结语在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆