0

I am trying to understand how the amount of bytes to substract from esp is calculated in a 32 bit machine. I understand that it is done in order to create a stack frame and that the bytes are multiples of 8, but I can't figure out why a specific amount is allocated. I created some mock functions but I still have some questions.

// push   ebp
// mov    ebp,esp
// call   <func>
// pop    ebp
// ret

int main() { 
    func();
}
^ no sub esp command
// push   ebp
// mov    ebp,esp
// sub    esp,0x10 // sub of 16 bytes
// mov    DWORD PTR [ebp-0x4],0x5
// leave
// ret

void func2() {
    int n = 5;
}
^ sub of 16 - why not 8 if int is 4 bytes?
// push   ebp
// mov    ebp,esp
// sub    esp,0x18 // sub of 24 bytes
// mov    DWORD PTR [ebp-0xc],0x5
// call   <func4>
// leave
// ret

void func3() { 
    int m = 5;
    func4();
}
^ sub of 24 - why not 16, if function call in main didn't
have a sub command and func had a sub of 16 ?
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
D.Joe
  • 1
  • 1
  • 2
  • Does this answer your question? [why the compiler reserves just 0x10 bits for a int?](https://stackoverflow.com/questions/19615639/why-the-compiler-reserves-just-0x10-bits-for-a-int) – Nate Eldredge Dec 29 '21 at 16:28
  • Not quite, as it says that the memory keeps 16-byte alignment but in that case, the next memory block should be 32 bytes and not 24. Thank you though! – D.Joe Dec 29 '21 at 16:41
  • Don't forget the size of the return address pushed by the caller, and the `push ebp`. – Peter Cordes Dec 29 '21 at 18:20
  • What system did you compile for? That `main` isn't maintaining 16-byte alignment, so it's not modern 32-bit GNU/Linux where `ESP % 16 == 12` on function entry. It's exactly what you'd expect for x86-64 where 8-byte stack operations *would* be maintaining stack alignment, though. (@NateEldredge: it doesn't look like a duplicate of that Q&A you linked, but [Why does GCC allocate more space than necessary on the stack, beyond what's needed for alignment?](https://stackoverflow.com/q/63009070) is possibly related.) – Peter Cordes Dec 29 '21 at 18:28
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 07 '22 at 13:54

0 Answers0