I would like to make a checksum of the current stack in the main, in order to check if it has been altered between two points.
For example:
int main(void) {
...
stack_checksum();
... process ...
if(stack_checksum() != ...)
altered.
}
How can I grab the base stack address and the current address of the stack's top ?
EDIT: With @Miroslav Bajtoš help, step for approach:
It depends on which compiler/implementation of standard library you are using.
For gcc (or any other compiler that uses glibc), you can use backtrace()
functions in execinfo.h
- see these answers for more details: How to generate a stacktrace when my gcc C++ app crashes and How to get more detailed backtrace
For Microsoft compiler, you can use StackWalk64()
function, see this article for more details: Walking-the-callstack. There was also a similar quesion asked here on StackOverflow: StackWalk64 on Windows - Get symbol name
Computing checksum should be easy once you can walk the stack.
I think you will have to use inline assembly for this. The following code stores the current values of the base pointer and the current pointer in base
and current
. It's for gcc
on a 64-bit machine:
// make these variables global (if not, the stack registers would change)
void *base, *current;
__asm__("movq %%rbp, %0;"
"movq %%rsp, %1;"
: "=r"(base), "=r"(current)
:
:
);
If you are on a 32-bit machine you have to use ebp
and esp
instead of rbp
and rsp
and movl
instead of movq
.
I recommend you to check out this inline assembly tutorial for gcc if you have any questions with the syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With