Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

address randomization: print address of a static var in c

I am reading an OS textbook, there is an example the verify whether the system is supporting virtual addresses and says the following program should print the same result every time. I see some difference on my macbook pro.

#include <stdio.h>

int var = 0;
int main(void)
{
  var += 1;
  printf("Address: %x, value: %d\n", &var, var);
  return 0;
}

when run it I see the address changes in some bytes(not all of them however):

./main
Address: e8c6018, value: 1
./main
Address: 9032018, value: 1
./main
Address: 1bc7018, value: 1

When I run in GDB, I always see 1018:

(gdb) r
Starting program: /Users/xilan/temp/main
Address: 1018, value: 1
[Inferior 1 (process 19631) exited normally]
(gdb) r
Starting program: /Users/xilan/temp/main
Address: 1018, value: 1
[Inferior 1 (process 19636) exited normally]
(gdb) r
Starting program: /Users/xilan/temp/main
Address: 1018, value: 1
[Inferior 1 (process 19654) exited normally]

So what the different in running it directly and in GDB ? Why I see the address varies when run it directly ?

like image 528
user2018791 Avatar asked Dec 08 '16 10:12

user2018791


2 Answers

Your book is old. Many operating systems today are randomising where programs and libraries are loaded to make things just a bit more secure against certain attacks.

MacOS randomises where programs are loaded in memory. It does disable that randomisation for gdb though, this is why the address looks the same in gdb all the time.

like image 162
Art Avatar answered Oct 27 '22 05:10

Art


In GDB, we always get the same address, even run with different processes, but The normal behavior should be like below, if run directly in Linux

./main
Address: e8c6018, value: 1
./main
Address: 9032018, value: 1
./main
Address: 1bc7018, value: 1

Because This is due to the fact that in GDB, the disable-randomization is turned on by default. It should be turned off if we expect regular output:

set disable-randomization off

Reference link : http://visualgdb.com/gdbreference/commands/set_disable-randomization

like image 43
msc Avatar answered Oct 27 '22 05:10

msc