Why does this function prologue use several instructions to calculate the esp reduction?

前端 未结 1 822
南笙
南笙 2021-01-22 16:56

I have looked at a few dumps of assembler code and there is this section (found here and here) in the main function:

:    push   %ebp


        
相关标签:
1条回答
  • 2021-01-22 17:15

    So you want a full walk-through without doing any research yourself? Sounds legit.

    main+9: mov $0x0, %eax

    Loads the register eax with hex 0 (=dec 0).

    main+14: add $0xf, %eax

    Adds hex F (= dec 15) to the zero in eax.

    main+17: add $0xf, %eax

    Adds hex F (= dec 15) to eax again. These three instructions could have also been done by

    movl $0x1e, %eax
    

    but who's counting instructions... Anyway, at this point eax contains hex 1E which is dec 30.

    main+20: shr $0x4, %eax

    Shifts the contents of eax to the right by four bits.

    main+23: shl $0x4, %eax

    Shifts eax right back. Why? Because this clears the lowest four bits. Now eax contains hex 10 (= dec 16)

    main+26: sub %eax, %esp

    Substracts eax from esp (the stack pointer). Since

    main+6: and $0xfffffff0, %esp

    cleared the lower four bits in esp previously, the new esp will be sixteen byte aligned, as per ABI. Why not simply use esp after main+6? Because on x86, the stack grows downwards from the top of memory. Simply masking off the lower bits of esp risks clobbering local variables. Hence the subtraction to grow the stack down to the sixteen byte boundary.

    0 讨论(0)
提交回复
热议问题