I was curious about how to catch stack overflows in C and stumble across the GNU libsigseg library.
This library can catch stack overflows on a lot of platforms and provides an implementation example.
In order to install a stack overflow listener with this library, one must first reserve some space for an alternate stack.
From what I understood, this alternate stack is used to run the listener because the real stack is unusable.
The alternate stack is reserved in altstack.h (line 40), and looks like this:
[][ ][ ][ ]
| | | |
| | | crumple_zone (8 KiB)
| | usable_space (16 KiB)
| crumple_zone (8 KiB)
offset (31 B)
The usable space is what is actually used and the crumple zones are here to prevent an overflow on the alternate stack: If it overflows, it does it into allocated space, preventing a segfault, and one might have time to detect it.
But,
- I don't understand why there is a crumple zone before AND after the stack; The stack grows in only one direction. Is it because some platforms have stack that grows in one direction, and other platforms in the other direction?
- I don't understand why there is an offset.
Here is the explanation given by the author:
glibc says: Users should use SIGSTKSZ as the size of user-supplied buffers. We want to detect stack overflow of the alternate stack in a nicer manner than just crashing, so we overallocate in comparison to what we hand libsigsegv. Also, we intentionally hand an unaligned pointer, to ensure the alternate stack still ends up aligned.
The last statement lost me a bit: "... we intentionally hand an unaligned pointer, to ensure the alternate stack still ends up aligned". How can the stack ends up aligned if we make so it's unaligned?
question from:https://stackoverflow.com/questions/65865908/understanding-stack-overflow-handling-in-c