1

I am trying to understand assembly code. I am stuck in the portion where the pointer is assigned and the code after leaq command

This is my C code:

#include <stdio.h>
#include<stdlib.h>

int main(){
    int x=50;
    int *y=&x;
    return 0;
}

This is my corresponding ASSEMBLY code:

.file   "AssemlyCode.c"
    .def    __main; .scl    2;  .type   32; .endef
    .text
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    pushq   %rbp
    .seh_pushreg    %rbp
    movq    %rsp, %rbp
    .seh_setframe   %rbp, 0
    subq    $48, %rsp
    .seh_stackalloc 48
    .seh_endprologue
    call    __main
    movl    $50, -12(%rbp)
    leaq    -12(%rbp), %rax
    movq    %rax, -8(%rbp)
    movl    $0, %eax
    addq    $48, %rsp
    popq    %rbp
    ret
    .seh_endproc
    .ident  "GCC: (GNU) 5.4.0"
zx485
  • 28,498
  • 28
  • 50
  • 59
BrainsOfSteel
  • 107
  • 10
  • `int y=&x;` is invalid. `y` is not a pointer – phuclv Nov 30 '16 at 06:21
  • Sorry i made a rookie mistake while writing the code..... I have corrected it now – BrainsOfSteel Nov 30 '16 at 06:29
  • Easier to read example: pass a pointer to a local to an external function. Then you can enable optimization without everything optimizing away. [See source + asm on the Godbolt compiler explorer](https://godbolt.org/g/N6ESby), which strips out all the `.seh_` and other directives that set metadata for the object file. – Peter Cordes Nov 30 '16 at 07:39

1 Answers1

6
    leaq    -8(%rbp), %rax
    movl    %eax, -4(%rbp)
    movl    $0, %eax
    addq    $48, %rsp
    popq    %rbp
    ret
  1. leaq saves address of variable x on the stack to register rax. Variable x is automatic variable on the stack, hence it address is calculated as offset from register that holds stack frame pointer(rbp).

  2. movl eax to stack saves argc argument to the stack.

  3. next step is to put return value in eax register from main function(return 0)

  4. two next opcodes are function epilogue - you are cleaning up used stack and restore previous frame pointer register.

  5. and the last one instruction is simple return.

  • Would probably be good to point out why rbp-8 is `&x`: because it's on the stack. I'm not sure which part the OP doesn't understand, whether it's what [LEA does](http://stackoverflow.com/questions/1658294/whats-the-purpose-of-the-lea-instruction), or why it's used *that way*. – Peter Cordes Nov 30 '16 at 07:42