Created
April 25, 2022 15:07
-
-
Save jay-tux/89e9c6806d82ed439d2c257f86979090 to your computer and use it in GitHub Desktop.
Stack information using %esp and %ebp in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
unsigned int stack_zero; | |
unsigned int stack_last; | |
#define GETREG(reg, out) \ | |
asm("movl %%" #reg ", %0"\ | |
: "=r" (out)\ | |
: \ | |
) | |
#define LOGESP() \ | |
unsigned int __esp__; \ | |
unsigned int __ebp__; \ | |
GETREG(esp, __esp__); \ | |
GETREG(ebp, __ebp__); \ | |
std::cout << "%esp = " << __esp__ << "; %ebp = " << __ebp__ << std::endl; | |
void subfun(int amrec) { | |
LOGESP(); | |
unsigned int stack_old = stack_last; | |
std::cout << "Stack size: " << ((long)stack_zero - (long)__esp__) << "B " << "(frame size: " << ((long)stack_last - (long)__ebp__) << "B " | |
<< "[from " << stack_last << " to " << __esp__ << "])" << std::endl << std::endl; | |
stack_last = __ebp__; | |
if(amrec <= 0) return; | |
subfun(amrec - 1); | |
stack_last = stack_old; | |
} | |
template <int M> inline size_t factorial() { | |
std::cout << "[factorial<" << M << ">]: "; | |
LOGESP(); | |
if constexpr(M == 0) return 0; | |
else if constexpr(M == 1) return 1; | |
else return M * factorial<M - 1>(); | |
} | |
int main() { | |
LOGESP(); | |
stack_zero = __ebp__; | |
stack_last = __ebp__; | |
std::cout << "+---" << std::endl | |
<< "| Calling subfun(3)" << std::endl | |
<< "+---" << std::endl; | |
subfun(3); | |
stack_last = __ebp__; | |
std::cout << "+---" << std::endl | |
<< "| Calling subfun(7)" << std::endl | |
<< "+---" << std::endl; | |
subfun(7); | |
std::cout << "+---" << std::endl | |
<< "| Calling factorial<6>()" << std::endl | |
<< "+---" << std::endl; | |
std::cout << factorial<6>() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output with
-O3
(g++)