Reverse Engineering for Beginners

(avery) #1
CHAPTER 5. STACK CHAPTER 5. STACK
If you declaremain()asmain()without arguments, they are, nevertheless, still present in the stack, but are not used. If
you declaremain()asmain(int argc, char *argv[]), you will be able to use first two arguments, and the third
will remain “invisible” for your function. Even more, it is possible to declaremain(int argc), and it will work.

5.2.3 Local variable storage.


A function could allocate space in the stack for its local variables just by decreasing thestack pointertowards the stack
bottom.Hence, it’s very fast, no matter how many local variables are defined.

It is also not a requirement to store local variables in the stack. You could store local variables wherever you like, but
traditionally this is how it’s done.

5.2.4 x86: alloca() function.


It is worth noting thealloca()function^12. This function works likemalloc(), but allocates memory directly on the
stack.

The allocated memory chunk does not need to be freed via afree()function call, since the function epilogue (4 on page 22)
returnsESPback to its initial state and the allocated memory is justdropped.

It is worth noting howalloca()is implemented. In simple terms, this function just shiftsESPdownwards toward the
stack bottom by the number of bytes you need and setsESPas a pointer to theallocatedblock.

Let’s try:

#ifdef __GNUC__
#include <alloca.h> // GCC
#else
#include <malloc.h> // MSVC
#endif
#include <stdio.h>

void f()
{
char *buf=(char*)alloca (600);
#ifdef __GNUC__
snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // GCC
#else
_snprintf (buf, 600, "hi! %d, %d, %d\n", 1, 2, 3); // MSVC
#endif

puts (buf);
};

_snprintf()function works just likeprintf(), but instead of dumping the result intostdout(e.g., to terminal or console),
it writes it to thebufbuffer. Functionputs()copies the contents ofbuftostdout. Of course, these two function calls
might be replaced by oneprintf()call, but we have to illustrate small buffer usage.


MSVC

Let’s compile (MSVC 2010):

Listing 5.1: MSVC 2010
...

mov eax, 600 ; 00000258H
call __alloca_probe_16
mov esi, esp

push 3
push 2
push 1
push OFFSET $SG2672
push 600 ; 00000258H

(^12) In MSVC, the function implementation can be found inalloca16.asmandchkstk.asminC:\Program Files (x86)\Microsoft Visual
Studio 10.0\VC\crt\src\intel

Free download pdf