As far as i have understood x86 has dedicated registers for pointers to code-, data- and stack segment, but not bss- and heap segment. How does the computer remember where these segments are? Especially heap, since bss is directly after data, but heap often is placed a different place in memory.
The heap is usually created by the C runtine which is linked with your code (statically or dynamically). It decides an address in the virtual address, calls the operating system provided system calls to map pages and stores the address in some data structure which is used by malloc (and family of functions) as heap. All this code is either executed before calling main or is statically initialized in the binary.
As for the bss section, As you know it is filled with all zeroes. The binary has information on the size of the .bss section and the base address. The loader maps pages to this virtual address and clears them with zeroes (in an efficient way).
You can see the address of the bss segment and its size by running dumpbin /HEADERS binary.exe if on windows. On Linux you can use objdump. I believe the required flag is -x.
About your question that how can they be moved around if the offsets are hard coded in the instructions -
The binary also has a table called the relocation table which has addresses of all instructions that access these values on a particular section. The loader may decide to place the segment somewhere else (usually happens when you load multiple dlls or shared libraries in Linux).
In that case it patches all the instructions looking at the relocation table. It actually changes the offsets in the instruction. This is done by the loader before executing the main.
Ofcourse this has an overhead and can be done only if the relocation information is available. Some binaries may choose to omit the relocation table and in that case the binary fails loading if the section cannot be placed at the specified location.
Hope that clears some of the confusion.
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