Compilers: Understanding assembly code generated from small programs

前端 未结 3 1344
礼貌的吻别
礼貌的吻别 2021-02-04 06:46

I\'m self-studying how compilers works. I\'m learning by reading the disassembly of GCC generated code from small 64-bit Linux programs.

I wrote this C

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 07:27

    Anything after the ret cannot be relied on to be code. Decoding as nop means "No OPeration"

    The 2nd point is the compiler detecting you leave the main function without returning a value and it inserts a return 0 (only defined for main).

    The rbp register, with bp meaning "Base Pointer", points to the stack frame of the currect function. A function call often results in the function entry saving rbp and using the current value of rsp for rbp. Fetching/storing function arguments and local variables are done relative to rbp.


    I think your third question needs some more attention, "Why doesn't the compiler allocate space on the stack with sub rsp,0x10? Why doesn't it use the rbp register for referencing local stack data?"

    Actually, the compiler does allocate space on the stack. But it does not change the stackpointer. It can do that because the functon calls no other functions. It just uses space below the curent sp (the stack grows down) and it uses rbp to access i ([rbp-0x8]) and k ([rbp-0x4]).


    I must add the following note: not adjusting sp for the use of local variables seems not interrupt safe and so the compiler relies on the hardware automatically switching to a system stack when interrupts occur. Otherwise, the first interrupt that came along would push the instruction pointer onto the stack and would overwrite the local variable.

    Question of interrupts solved in Compiler using local variables without adjusting RSP

提交回复
热议问题