Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the address of a function change with every run?

I'm struggling with mapping addresses to their symbols for debugging purposes (getting the callstack). The MS dbghelp.dll can tell the symbol from an address (see SymFromAddr, MSDN). However, it doesn't work and I wonder how this could ever work, because addresses seem to change with every run of the program:

#include <iostream>
void Foo() {}

int _tmain(int argc, _TCHAR* argv[])
{
    const long unsigned int addr = reinterpret_cast<long unsigned int>(&Foo);
    std::cout << "Address: " << std::hex << addr << std::endl;
    return 0;
}

Output:

D:\dev\Sandbox\Debug>Sandbox.exe
Address: 901320
D:\dev\Sandbox\Debug>Sandbox.exe
Address: ce1320
D:\dev\Sandbox\Debug>Sandbox.exe
Address: 3a1320
D:\dev\Sandbox\Debug>Sandbox.exe
Address: 3f1320

How could a different program ever read address like from a stacktrace and map it to functions? This sounds like magic to me. I didn't find anything in the linked documentation which says I would have to subtract something from the address or whatever.

In my understanding since we overcome the real-mode every process has a virtual memory space anyway, so no need to roll the dice for a load address any more. I would understand uncertainties of absolute address in case of DLLs, but not the main executable.

Tried on Win7 with VS2008.

like image 656
Borph Avatar asked Dec 09 '22 15:12

Borph


2 Answers

Address Space Layout Randomization

like image 64
MSalters Avatar answered Dec 26 '22 12:12

MSalters


Because your code is compiled to use Address Space Layout Randomization, which makes code less vulnerable to attacks from "StackOverflows".

If you really want to change that, there is a linker option for that.

like image 25
Mats Petersson Avatar answered Dec 26 '22 11:12

Mats Petersson