The Stack
The stack is a very important structure to understand when developing a debugger. The stack stores information about how a function is called, the parameters it takes, and how it should return after it is finished executing. The stack is a First In, Last Out (FILO) structure, where arguments are pushed onto the stack for a function call and popped off the stack when the function is finished. The ESP register is used to track the very top of the stack frame, and the EBP register is used to track the bottom of the stack frame. The stack grows from high memory addresses to low memory addresses. Let's use our previously covered function my_socks() as a simplified example of how the stack works.
Function Call in C
int my_socks(color_one, color_two, color_three);
Function Call in x86 Assembly
push color_three
push color_two
push color_one
call my_socks
To see what the stack frame would look like, refer to Figure 2-1.
Image from book
Figure 2-1: Stack frame for the my_socks() function call
As you can see, this is a straightforward data structure and is the basis for all function calls inside a binary. When the my_socks() function returns, it pops off all the values on the stack and jumps to the return address to continue executing in the parent function that called it. The other consideration is the notion of local variables. Local variables are slices of memory that are valid only for the function that is executing. To expand our my_socks() function a bit, let's assume that the first thing it does is set up a character array into which to copy the parameter color_one. The code would look like this:
int my_socks(color_one, color_two, color_three)
{
char stinky_sock_color_one[10];
...
}
The variable stinky_sock_color_one would be allocated on the stack so that it can be used within the current stack frame. Once this allocation has occurred, the stack frame will look like the image in Figure 2-2.
Image from book
Figure 2-2: The stack frame after the local variable stinky_sock_color_one has been allocated
Now you can see how local variables are allocated on the stack and how the stack pointer gets incremented to continue to point to the top of the stack. The ability to capture the stack frame inside a debugger is very useful for tracing functions, capturing the stack state on a crash, and tracking down stack-based overflows.
I stumbled on an open source project that looks very interesting. I am posting this to remind me to come back to it later when I have some more time to check out the code, and what it's all about. The source code is hosted on google here: http://code.google.com/p/opendpi/ This the project's website: http://opendpi.org/ I might write more about it later.
Comments
Post a Comment