Make checksum of the current stack

I would like to do a checksum of the current stack basically to check if it has been changed between two points.

For example:

int main(void) { ... stack_checksum(); ... process ... if(stack_checksum() != ...) altered. } 

How can I grab the base stack address and current top stack address?

EDIT: With help @Miroslav BajtoΕ‘ help, step by step approach:

  • Put a local variable in the structure
  • Check backtrace array returned
+7
source share
2 answers

It depends on which compiler / implementation of the standard library you are using.

For gcc (or any other compiler that uses glibc), you can use the backtrace() functions in execinfo.h - see these answers for more details: How to create stacktrace when my gcc C ++ application works and How to get more detailed backtrace

You can use the StackWalk64() function for the Microsoft compiler; for more information, see this article: Walking-the-callstack . There was also a similar question asked here in StackOverflow: StackWalk64 on Windows - get character name

The computational checksum should be simple as soon as you can walk on the stack.

+6
source

I think you will have to use the built-in assembly for this. The following code stores the current values ​​of the base pointer and current pointer in base and current . It is 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 should use ebp and esp instead of rbp and rsp and movl instead of movq .
I recommend that you check out this built-in compilation for gcc if you have any questions with syntax.

+3
source

All Articles