Graphics Programs Reference
In-Depth Information
The following stack_example.c code has two functions: main() and
test_function() .
stack_example.c
void test_function(int a, int b, int c, int d) {
int flag;
char buffer[10];
flag = 31337;
buffer[0] = 'A';
}
int main() {
test_function(1, 2, 3, 4);
}
This program first declares a test function that has four arguments, which
are all declared as integers: a , b , c , and d . The local variables for the function
include a single character called flag and a 10-character buffer called buffer .
The memory for these variables is in the stack segment, while the machine
instructions for the function's code is stored in the text segment. After
compiling the program, its inner workings can be examined with GDB. The
following output shows the disassembled machine instructions for main() and
test_function() . The main() function starts at 0x08048357 and test_function()
starts at 0x08048344 . The first few instructions of each function (shown in
bold below) set up the stack frame. These instructions are collectively called
the procedure prologue or function prologue . They save the frame pointer on the
stack, and they save stack memory for the local function variables. Sometimes
the function prologue will handle some stack alignment as well. The exact
prologue instructions will vary greatly depending on the compiler and
compiler options, but in general these instructions build the stack frame.
reader@hacking:~/booksrc $ gcc -g stack_example.c
reader@hacking:~/booksrc $ gdb -q ./a.out
Using host libthread_db library "/lib/tls/i686/cmov/libthread_db.so.1".
(gdb) disass main
Dump of assembler code for function main():
0x08048357 <main+0>: push ebp
0x08048358 <main+1>: mov ebp,esp
0x0804835a <main+3>: sub esp,0x18
0x0804835d <main+6>: and esp,0xfffffff0
0x08048360 <main+9>: mov eax,0x0
0x08048365 <main+14>: sub esp,eax
0x08048367 <main+16>: mov DWORD PTR [esp+12],0x4
0x0804836f <main+24>: mov DWORD PTR [esp+8],0x3
0x08048377 <main+32>: mov DWORD PTR [esp+4],0x2
0x0804837f <main+40>: mov DWORD PTR [esp],0x1
0x08048386 <main+47>: call 0x8048344 <test_function>
0x0804838b <main+52>: leave
0x0804838c <main+53>: ret
Search WWH ::




Custom Search