views:

121

answers:

1

For global variables in C like

int aglobal = 5;

When does the 5 get transferred into aglobal by the loader and how does it know to put 5 in aglobal.

Same situation with a static declaration in a function. Like

int afunc() { static int astatic = 8; return astatic; }

+2  A: 

An int-sized space is made in a data section, with the value 5 encoded in it and a global non-function symbol named 'aglobal' is added to the symbol table pointing at it. References to aglobal are turned into relocations that are resolved at link-time to point to that data block, so in a fully-linked image instructions will load directly from that spot in memory that holds the 5 value

For example, the (x86) assembly might look something like:

.data
.globl aglobal
aglobal: .long 5

.text
main:
    mov eax, aglobal

In an object file, the mov instruction will turn into mov eax, 0 with a relocation R_386_32 aglobal+0, because the object file doesn't know for sure where the data section will be in memory.

In a fully-linked image, it might be something like:

mov eax, 0x804a010

Now the actual address of the 4 bytes in the data section is known, so it's specified directly

Michael Mrozek
Thanks this helps. Correct me if I am wrong...So if read or write to aglobal in my code it is accessing the .data section. The .data section is initialized by the loader copying the .data section from the elf file to memory.
newguy
Right, the data section is loaded into memory just like the text section (but generally it's non-executable and text is non-writable, to try and prevent exploits). At link time the location that particular word in the data section will be at is determined and all the instructions that reference it (they'll have a relocation with the name 'aglobal') are fixed up to point to that offset. All the loader needs to do is shift the whole image from its base address to the address it actually gets loaded at in memory (a lot of images have a base address of 0, so it just adds the start memory address)
Michael Mrozek
Thanks. I appreciate the help Mike.
newguy