3 ms·
That is basically how it works, with the caveat that if you want the kernel to arbitrate your stack expansion you must only expand by a page at a time (and that
by caf 9y ago
That is basically how it works, with the caveat that if you want the kernel to arbitrate your stack expansion you must only expand by a page at a time (and that's what gcc's -fstack-check does).
If you decrement your stack pointer by a large value and then offset it - which is essentially what's happening in these cases - the kernel can't arbitrate that because if the access lands in otherwise allocated memory it doesn't fault and so the kernel never sees the access at all.
- e12e 9y agoI meant that the equivalent for mallloc would be that if you allocate 1mb buffer and a 2mb buffer, the kernel might return a 2mb buffer overlapping your earlier 1mb buffer - and be all like: "you asked for 1, you asked for 2 - and you've got 2 - if you wanted 3, you should've asked for 3". Afaik mallloc doesn't work like that - it assumes that you want more memory (and can fail or succeed etc). I can see how the current stack/heap thing evolved - but I still think it's crazy :-)
- caf 9y agoThe stack doesn't work like that either. All that's happening here is that userspace is moving its stack pointer into the heap it had previously allocated. Note that "moving the stack pointer" is not a kernel-mediated operation.
- e12e 9y agoNo of course, but the fact that you can "ask for more memory" by growing the stack onto your heap (rather than say, having the two start somewhere together and grow apart) - means that there's an asymmetry: mallloc will give you more ram or fail; growing the stack - can make your allocated memory overlap.
- caf 9y agoYour stack has to grow towards something. Sure, you can have it grow towards the bottom of the address space (which, due to wraparound, is also the top - where it will safely collide with the kernel addresses) but that only works for one stack - as soon as you create another thread, its thread has to grow towards something else.