Search code examples
c++memoryprocessportable-executable

Why does the PE sections change between runs?


I have stumbled on a problem that I hope you could help me understand.

In my application i have a snapshot function that copies(ReadProcessMemory or memcpy, same result) all of its code + read only data sections and writes them to a file. I then have a verification function that reads the file and does a memcmp on what's in the file and what's on memory.

If I run the snapshot function and then run the verification function in the same session, it will keep saying that they are identical no matter how many times I run the verification.

When I take the snapshot in one session and then restart the app and run verification it seems completely random if the memory is identical or not, sometimes it works for 3-4 restarts of the application but sooner or later it doesn't think that the data in the file is identical to the pe section code.

Here's a link of the comparison of the pe code section between runs:

http://i45.tinypic.com/4kad7b.jpg

it's always the same thing, it's changing one character to another(in this case ? to an elevated 1) but from and to what character is always different.

Can anyone explain why this is happening? Should it be like this, if so why? or am I doing something wrong?

Note: I've tested this in both debug and release with and without a debugger attached.


Solution

  • For security reasons modern operating systems randomize in-memory layout of processes. The mechanism is called Address Space Layout Randomization (ALSR).

    In case of a vulnerability in an executable this makes it much more complicated to inject foreign code into the application by an attack.