3 ms·
The thing is that (as I mentioned upthread) "growing the stack" isn't a well-defined operation. What actually happens is that you overflow the stack by a very l
by geofft 9y ago
The thing is that (as I mentioned upthread) "growing the stack" isn't a well-defined operation. What actually happens is that you overflow the stack by a very little bit, and the kernel says "Oh, I bet you want more stack pages" and maps some virtual memory for you. But the kernel is guessing; it has no way of knowing that you meant to grow the stack. Maybe you dereferenced a wild pointer that, by chance, happened to point right below the current stack.
Conversely, if you grow your stack by some value on the order of gigabytes, you're basically coming up with a pointer that appears to have no relation to the stack, and dereferencing it. So the platform is going to do exactly what it does if you were to dereference the same pointer value with no stack involved: read/write memory if it's mapped and segfault if not.
You could totally imagine a platform where growing the stack were a more well-defined operation. You want to avoid each function call and local allocation having the overhead of a system call, though: the nice thing about the current scheme is that it's zero-overhead if there's a mapped stack page. So the scheme was designed (or probably emerged more than was intentionally designed) for the case where syscalls are very slow, MMUs work fine, and perfect memory safety isn't the goal, i.e., the original UNIX target audience. :-)
You could keep a thread-local variable somewhere indicating the current stack limit, and make a system call when you need to increment it. That doesn't require an MMU at all: the userspace API is that you call some system routine when you need to expand the stack, and it says yes or no (or it either says yes or kills you with a segfault, or whatever). In an MMU-less system, you can just keep track of the amount of heap allocation, and have the system routine fail when you're too close to your heap.
Or you could do stack probing, which works but requires an MMU.