Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c code to paint an embedded stack with a pattern say (0xABABABAB) just after main begins?

I am working on dynamic memory analysis using stack painting/foot print analysis method.

dynamic-stack-depth-determination-using-footprint-analysis

basically the idea is to fill the entire amount of memory allocated to the stack area with a dedicated fill value, for example 0xABABABAB, before the application starts executing. Whenever the execution stops, the stack memory can be searched upwards from the end of the stack until a value that is not 0xABABABABis found, which is assumed to be how far the stack has been used. If the dedicated value cannot be found, the stack has consumed all stack space and most likely has overflowed.

I want a c code to fill the stack from top to bottom with a pattern.

void FillSystemStack()
{
    extern char __stack_start,_Stack_bottom;


}

NOTE

  • I am using STM32F407VG board emulated with QEMU on eclipse.
  • stack is growing from higher address to lower address
  • start of the stack is 0x20020000
  • bottom of the stack is Ox2001fc00
like image 289
K. Sai Bharadwaj Avatar asked Sep 01 '25 20:09

K. Sai Bharadwaj


1 Answers

You shouldn't completely fill the stack after main() begins, because the stack is in use once main() begins. Completely filling the stack would overwrite the bit of stack that has already been used and could lead to undefined behavior. I suppose you could fill a portion of the stack soon after main() begins as long as you're careful not to overwrite the portion that has been used already.

But a better plan is to fill the stack with a pattern before main() is called. Review the startup code for your tool chain. The startup code initializes variable values and sets the stack pointer before calling main(). The startup code may be in assembly depending on your tool chain. The code that initializes variables is probably a simple loop that copies bytes or words from the appropriate ROM to RAM sections. You can probably use this code as an example to write a new loop that will fill the stack memory range with a pattern.

like image 163
kkrambo Avatar answered Sep 05 '25 06:09

kkrambo