Question

Have a look at this main:

int 
main() 
{
  int asd = 10;
  printf("%p\n", &asd);
  return 0;
}

Address of asd at at a given moment:

0x7ffff5f7c16c

Address of main (always the same):

(gdb) disass main
Dump of assembler code for function main:
    0x00000000004005b4 <+0>:    push   %rbp

Why the addresses of the variables, of a regular c program, change at every execution, whereas the starting address of the program itself it is always the same (assuming that it is not position independent)? I see that the address variability is due to the ASLR mode, but why it does affect only the program variables, and does not affect where the code is allocated? Is this related to the fact that as being the code section ro it doesn't make sense randomizing it when not strictly necessary?

Furthermore, why is there an enormous gap between the tarting address of the main and the address of the variable asd?

Was it helpful?

Solution

ASLR happens mostly at mmap(2) time. The stack segment of the main thread is allocated at execve(2) time (of your program) -but may be "randomly" located. The initial stack pointer of your main also depends on various factors (notably your environment - see environ(7)).

The stack pointer is set at execve time. It is passed to the crt0.o startup object file (which calls your main) by conventions defined in e.g. the x86-64 ABI specifications.

The address of main is fixed inside the ELF executable file. Unless your code is position independent code (i.e. compiled with -fPIE or -fPIC etc...), it cannot be moved (because that would require specific relocation). Use objdump -f badnack on your badnack executable to find out. Also pmap on your process. And PIC has a small cost (It uses more registers).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top