如何调用的函数返回到调用者,被调用后?

编程入门 行业动态 更新时间:2024-10-24 04:44:38
本文介绍了如何调用的函数返回到调用者,被调用后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

参考文献:

  • 英特尔软件开发者手册
  • ARM信息中心
  • Intel Software Developers Manual
  • ARM Information Center
  • 更多推荐

    如何调用的函数返回到调用者,被调用后?

    本文发布于:2023-10-31 07:25:31,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1545424.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数   调用者

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!