简体   繁体   English

汇编代码:计算偏移量到堆栈中的逻辑

[英]Assembly code: logic behind calculating offset into stack

I am a newbie to assembly programming and i am trying to decode the assembly emitted by 64 but GNC Compiler (GCC). 我是汇编编程的新手,我正在尝试对64位但GNC编译器(GCC)发出的汇编进行解码。

void fun(int a, int b)
    {
    int h=0;
    }

    int main()
    {
    int d = 0;
    fun(d,10);
    }

The assembly for this is 的组装是

.globl fun
    .def    fun;    .scl    2;  .type   32; .endef
fun:
    pushq   %rbp     #
    movq    %rsp, %rbp   #,
    subq    $16, %rsp    #,
    movl    %ecx, 16(%rbp)   # a, a
    movl    %edx, 24(%rbp)   # b, b
    movl    $0, -4(%rbp)     #, h
    leave
    ret
    .def    __main; .scl    2;  .type   32; .endef
.globl main
    .def    main;   .scl    2;  .type   32; .endef
main:
    pushq   %rbp     #
    movq    %rsp, %rbp   #,
    subq    $48, %rsp    #,
    call    __main   #
    movl    $0, -4(%rbp)     #, d
    movl    -4(%rbp), %eax   # d, tmp59
    movl    $10, %edx    #,
    movl    %eax, %ecx   # tmp59,
    call    fun  #
    leave
    ret

I have some doubts on this assembly. 我对这次大会有些怀疑。

[1] what is the exact arithmetic for subtracting 48 from stack pointer in main. [1]从main中的堆栈指针减去48的确切算法是什么。 [2] In fun, I believe the offset from base pointer to access the function argument starts from 16 (return address and base pointer that is two memory location into stack (stack frame being 8 bytes) , but why the next offset is 24 instead of 16. [2]有趣的是,我相信从基址指针访问函数参数的偏移量从16开始(返回地址和基址指针是堆栈中两个存储位置(堆栈帧为8字节),但是为什么下一个偏移量为24共16。

    movl    %ecx, 16(%rbp)   # a, a
    movl    %edx, 24(%rbp)   # b, b

Why it is not: movl %ecx, 16(%rbp) # a, a movl %edx, 20(%rbp) # b, b 为什么不是:movl%ecx,16(%rbp)#a,movl%edx,20(%rbp)#b,b

[3] What is the logic behind subtracting 16 from stack pointer in fun, when only one local variable is involved. [3]当只涉及一个局部变量时,从堆栈指针中减去16的逻辑是什么? Shouldnt be it 8? 不应该是8吗?

Thanks. 谢谢。

  1. In general you can only guess why the compiler does what it does. 通常,您只能猜测编译器为什么会执行它的操作。 In this case, optimizations are clearly not enabled, so the compiler presumably just allocates a worst-case stack frame that just doesn't get optimized down. 在这种情况下,显然不会启用优化,因此编译器可能只是分配了一个最坏情况的堆栈帧,而该堆栈帧并未得到优化。 You might want to try with optimizations enabled. 您可能要尝试启用优化。
  2. rbp points to the pushed rbp on the stack, rbp+8 is the return address, rbp+16 is first argument, rbp+24 is second argument. rbp指向堆栈中压入的rbprbp+8是返回地址, rbp+16是第一个参数, rbp+24是第二个参数。 Note that in 64 bit mode stack is used in 8 byte chunks. 请注意,在64位模式下,堆栈使用8个字节块。
  3. Presumably calling convention mandates 16 byte alignment. 大概调用约定要求16字节对齐。

For points [2] and [3] see the appropriate abi documentation. 对于点[2][3]请参见相应的abi文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM