C到汇编调用约定32位和64位 [英] C to assembly call convention 32bit vs 64bit

查看:291
本文介绍了C到汇编调用约定32位和64位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注优秀的《 Programming Ground Up》一书,想学习汇编.尽管这时不在本书中,但我还是想在32位计算机上从C.调用我的汇编函数,这在从本书中进行操作时是一样的.

I have been following the excellent book Programming Ground Up, wanting to learn assembly. Although not in the book at this point, I wanted to call my assembly function from C. on a 32 bit machine, this works as is when working from the book.

我在这里要做的是将第一个参数存储在%ebx中,第二个参数存储在%ecx中.

What I do here is storing the first argument in %ebx and the second in %ecx.

.type power, @function
.globl power
power:
    pushq   %ebp
    movl    %esp, %ebp
    subl    $4, %esp

    movl    8(%ebp), %ebx
    movl    12(%ebp), %ecx

我将此(以及函数的其余部分)编译成一个目标文件,创建一个main.c,在其中对函数进行原型设计并调用它,如下所示:

I compile this (and the rest of the function) into an object file, create a main.c, where I prototype the function and call it, something like this:

int power(int b, int x);
int a = power(2, 1);

但是,当我在64位计算机上进行编译时,会得到一些非常意外的结果.我修改了显而易见的内容,例如需要用%rsp%rpb替换%esp%epb的事实,但是对GDB的挖掘表明,在堆栈上找不到任何参数!

However, when I compile this on a 64 bit machine, I get some very unexpected results. I modified the obvious, like the fact that %esp and %epb needs to be replaced with %rsp and %rpb, but digging with GDB reveals that the arguments are nowhere to be found on the stack!

通过在GCC中使用-S选项来检查会发生什么,我可以看到,GCC没有将变量压入堆栈,而是将参数存储在寄存器中.

Checking out what happens by using the -S option to GCC I can see that instead of pushing the variables on the stack, GCC stores the arguments in registers.

 movl $1, %esi
 movl $2, %edi
 call power

在32位计算机上,它执行了我期望的操作并将参数压入堆栈:

On the 32 bit machine, it does what I expect and push the arguments on the stack:

 movl $1, 4(%esp)
 movl $2, (%esp)
 call power

现在这是怎么回事?为什么GCC在64位和32位堆栈上传递参数在寄存器中?这非常令人困惑!我在任何地方都找不到任何提及.有任何人可以启发我这种情况吗?

Now what is going on here? Why does GCC pass the arguments in registers on 64 bit and on the stack on 32 bit? This is very confusing! And I can't find any mention on this anywhere. Is there anyone who can enlighten me on this situation?

推荐答案

64位C调用约定为:%rdi,%rsi,%rdx,%rcx,%r8和%r9

64-bit C calling convention is: %rdi, %rsi, %rdx, %rcx, %r8 and %r9

在此处查看完整说明: 系统V应用程序二进制接口:AMD64体系结构处理器增补程序" http://www.x86-64.org/documentation/abi.pdf

See full description here: "System V Application Binary Interface: AMD64 Architecture Processor Supplement" http://www.x86-64.org/documentation/abi.pdf

3.2函数调用顺序

当我学习相同的主题时,我制作了具有所需功能的小型C程序,并在64位编译器中对其进行了编译,并阅读了由C编译器生成的汇编代码. C/C ++编译器可以像汇编参考一样使用.

When I learned the same topic, I made small C programs with required functions, compiled them in 64 bit compiler and read the Assembly code produced by C compiler. C/C++ compiler can be used like kind of Assembly reference.

这篇关于C到汇编调用约定32位和64位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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