I'm reading a GNU as introductory book for programs running on top of an OS. I'm at the stack memory part and I was curious how the stack looks like in a freestanding environment.
I'm guessing that within an OS, the program only sees virtual memory and the stack is set up by the OS.
However in a freestanding environment, where does SP/ESP/RSP points to at the beginning? Does the CPU reserves the stack at initialization?
There is no specific location for an initial stack pointer in freestanding, if you go back to the very beginning of program execution. CPU does not do that.
Usually there would be a bootloader/pre-execution environment which executes before any user program could be run, and it could set up some initial stack. However usually it is up to the user program to reserve some amount of space somewhere and to set stack pointer register. E.g. if you look at any example of a MCU firmware you'd find there's a stack area reserved (usually in the in linker script), and SP is set to point to that very early in the firmware execution. Take a look at any MBR bootloader and you're likely to see it resets SP to some hardcoded location in the very first instructions, etc (even though BIOS has set up some stack, it is safer to reset it to some place under user control).
UEFI can be thought to be an exception to this as it does set up a stack, but then one can argue UEFI applications/bootloaders are not really executing in freestanding environment. UEFI is a sort of OS for those applications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With