Brain Dump

Process Stack

Tags
comp-arch

Is part of a processes memory layout where automatically allocated variables and function call returns addresses are stored. Every time a new variable is declared the program moves the stack pointer down to reserve space for it.

This segment of the stack is writable but not executable (controlled by the NX/XOR bit) which prevents malicious code such as shellcode from being run on the stack. If the stack grows too much (exceeding a predefined limit or intersecting the heap) then program will Stack Overflow most likely resulting in a SEGFAULT.

The size of the stack is monitored using a simple pointer: The Stack Pointer. Every time a thread calls another function we move the stack-pointer down such that there's more space for parameters and automatic variables. Once it returns the stack pointer is moved back up (using a pointer to the previous position that's always kept in the current stack frame). This structure is why makes freeing memory used by automatic variables easier because the program just needs to quickly change the stack-pointer.

The value at the beginning of each stack-frame is a pointer to the Return Address in the text-segment, essentially the instruction which called the function leading to the creation of the current stack frame. The value returned from a function is copied into some value in the previous stack frame.

void foo() {
    double value = getValue(1, 2.5);
}

double getValue(int a, double b) {
    double res = a + b;
    return res;
}
Code Snippet 1: Example of stack allocations. The call to foo creates a new stack frame with size for a double value. The call to getValue creates a new stack frame copying the values of into the new stack-frame a, b and allocating memory for res. On return the value of res in getValue is copied into the memory of value in the previous stack-frame.