Peeter Joot's (OLD) Blog.

• Archives

 Adam C Scott on avoiding gdb signal noise… Ken on Scotiabank iTrade RESP …… Alan Ball on Oops. Fixing a drill hole in P… Peeter Joot's B… on Stokes theorem in Geometric… Exploring Stokes The… on Stokes theorem in Geometric…

• 317,257

Poking around to see how much stack to corrupt to alter a local variable.

Posted by peeterjoot on September 10, 2012

I’ve got a scenerio where it appears that the last stack variable declared appears to be have been corrupted (the highest order 32-bits of this 64-bit integer look like they’ve been zeroed). That got me wondering how far a calling function would have to corrupt to muck up this variable. Here’s what I wrote to test this:

```#include <stdio.h>

int foo( int r )
{
Uint64         x ;
Uint64         y ;
Uint64         z ;
Uint64         w = 0 ;

w = 1 ;

printf( "&x: 0x%0lx\n", (long)&x ) ;
printf( "&w: 0x%0lx\n", (long)&w ) ;

if ( r )
{
foo( r - 1 ) ;
}

return w ;
}

int main()
{
foo( 2 ) ;

return 0 ;
}
```

and the results on this (linuxamd64) system:

```&x: 0x7fffffffd490
&w: 0x7fffffffd488
&x: 0x7fffffffd450
&w: 0x7fffffffd448
&x: 0x7fffffffd410
&w: 0x7fffffffd408
```

So, it looks like I need about at least a (0x88-0x50 =) 56 byte corruption to do the job.

A quirk: Also see how the variables in my function actually got laid out in reverse address order on the stack. I’d not have expected that. However, since I don’t really have any reason to expect any specific stack layout so perhaps I shouldn’t be surprised.