Reputation: 12781
As far as I understand, the OS is often involved in managing the heap and its bookkeeping. For example, the process of a user program needs to invoke a system call to be able to allocate and de-allocate memory from the heap.
How does that work for the stack? To my knowledge:
Is my understanding above correct?
More broadly speaking, is the OS involved in any way in runtime operations involving the stack? (e.g. popping and pushing new stack frames, their organization, etc.), and if so, how?
Or is the OS only involved in allocating the stack memory of the entire task / thread / process ahead of time?
Upvotes: 1
Views: 130
Reputation: 69276
This gives me the (perhaps wrong) impression that a user program may be compiled directly to assembly code to execute stack push / pop CPU instructions that don't involve the OS in any way
Indeed that's right.
I understand it must know and get involved the moment a user program is trying to work with the stack (e.g. pushing and popping call stack frames, etc).
Not really. The OS does not need to get involved in every single push/pop or any other kind of read/write operation on the stack, and in fact it isn't. If you think about it, requesting OS intervention at every single stack access would be painfully slow and counterproductive.
is the OS involved in any way in runtime operations involving the stack? (e.g. popping and pushing new stack frames, their organization, etc.), and if so, how?
No, it isn't. Managing the stack is a duty of the process that owns it.
if stack operations are done directly at the CPU level from compiled assembly code, the OS is only perhaps involved at the startup of the program in "delineating" the virtual address range for the stack?
Yes, exactly, you are getting there.
When a new process is created, the kernel will reserve space for the stack, and it will also copy some data like command line arguments at the very bottom of the stack. All of this is done before starting the process.
Stack operations (for example push and pop, which are the simplest ones), are done directly by the CPU. In other words, instructions like push and pop are directly executed.
The OS only intervenes in certain situations when necessary. A (non exhaustive) list:
Upvotes: 1