Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the initial value of the stack pointer determined?

The program loader initializes/loads the text, data+bss areas. These are allocated in the process' virtual address space near the beginning. The heap would then grow (after data+bss) towards larger addresses. The stack grows from something large towards lower addresses.

I wonder how the initial value of the stack pointer is determined.

If I ask for the virtual address limit per process (ulimit -v) I get

virtual memory          (kbytes, -v) unlimited

Now, this unlimited certainly refers to the technical limits put by a finite number of bits available for addressing (on 64 bit Linux I recall 48 bits?!)

So, is it that simple that unless a different ulimit applies the stack pointer is roughly initialized to (start of vmem + 2^48 bits)?

like image 835
ritter Avatar asked Jul 23 '12 12:07

ritter


1 Answers

This is a highly platform dependent question, and depends on the bit-ness of the program you are running, the operating system version in use, system configuration options, whether or not the program is single or multi-threaded, and other factors:

  • For modern Linux systems the initial stack base for single threaded programs is controlled by the kernel Address Space Layout Randomization (ASLR) feature.
  • In the ancient days before ASLR I think the main thread's stack used to be at a high fixed address for 32-bit Linux. For 64-bit before ASLR (or if you disable it), it was probably at a fixed address somewhere well away from everything else, but I wouldn't be surprised if that address was kernel version dependent.
  • For multi-threaded Linux programs the stack is allocated using mmap by glibc before the clone() call that starts the thread (see: nptl/allocatestack.c)
  • On 32-bit single threaded AIX the stack and heap (sbrk controlled) used to co-exist in one of the 16 256 mb segments (I forget which one.) I recall there was lots of fun to be had for all if you compiled with options that allowed the stack to grow into heap.
  • ...
like image 97
Peeter Joot Avatar answered Nov 24 '22 04:11

Peeter Joot