如何调用的函数返回到调用者,被调用后? [英] How do called functions return to their caller, after being called?

查看:259
本文介绍了如何调用的函数返回到调用者,被调用后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到,当一个函数调用是由程序进行,被调用函数必须知道如何返回到它的调用者。

I read that when a function call is made by a program, the called function must know how to return to its caller.

我的问题是:如何被调用的函数知道如何返回到它的调用者?有没有通过编译器的幕后工作机制?

My question is: How does the called function know how to return to its caller? Is there a mechanism working behind the scenes through the compiler?

推荐答案

编译器遵循特定的调用约定,定义为您的目标ABI的一部分。该调用约定将包括系统知道返回到什么地址的方法。调用约定通常需要硬件对过程调用的支持优势。英特尔,例如,返回地址被压入堆栈:

The compiler obeys a particular "calling convention", defined as part of the ABI you're targeting. That calling convention will include a way for the system to know what address to return to. The calling convention usually takes advantage of the hardware's support for procedure calls. On Intel, for example, the return address is pushed to the stack:

...处理器将跟随在 EIP 寄存器的值(其中包含的指令的偏移量在 呼叫 在栈上的指令)(稍后用作返回指令指针)。

...the processor pushes the value of the EIP register (which contains the offset of the instruction following the CALL instruction) on the stack (for use later as a return-instruction pointer).

从函数返回通过 RET 指令完成的:

Returning from a function is done via the ret instruction:

...处理器从堆栈中弹出的顶部进入返回指令指针(偏移量)在 EIP 注册并开始执行程序在新的指令指针。

... the processor pops the return instruction pointer (offset) from the top of the stack into the EIP register and begins program execution at the new instruction pointer.

要相比之下,ARM,返回地址被放入链接寄存器:

To contrast, on ARM, the return address is put in the link register:

BL BLX 指令复制下一条指令的地址到 LR R14 链接寄存器)。

The BL and BLX instructions copy the address of the next instruction into lr (r14, the link register).

返回通过执行 MOVS PC,LR 将地址从复制链接回注册到程序计数器寄存器常见的做。

Returns are commonly done by executing movs pc, lr to copy the address from the link register back into the program counter register.

参考文献:


  1. 英特尔软件开发者手册

  2. ARM信息中心

  1. Intel Software Developers Manual
  2. ARM Information Center

这篇关于如何调用的函数返回到调用者,被调用后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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