pmor
pmor

Reputation: 6296

GCC: how -pie affects address of file scope variable?

Consider this code:

#include <stdio.h>
int gprs[32];
int main(void)
{
   printf("%p\n", (void*)&gprs);
}

being compiled with -pie (seems to be the default) produces:

0x55c183951040

while being compiled with -no-pie produces:

0x404060

Can someone explain how -pie affects address of file scope variable?

Note: Clang seems to have -no-pie by default.

Upvotes: 0

Views: 155

Answers (1)

Martin Rosenau
Martin Rosenau

Reputation: 18523

Can someone explain how -pie affects address of file scope variable?

Using -pie, the operating system can load the executable file to any address in memory. Under Windows, this is done using a "base relocation table"; under Linux this is done using "position-independent code".

In this case, many modern OSs load an executable file to any (random) address in memory for security reasons (because it is harder to write a virus accessing the variable gprs if its address is not known).

This means that the difference between the addresses of the (static or global) variables a and b in the following example:

printf("%p, %p\n", &a, &b);

... should be constant but the address of a (and b) may be different every time you run the program.

Using -no-pie, "position-dependent code" is generated under both OSs and no "base relocation table" is generated under Windows.

This means that the executable file can only be loaded into a fixed memory address. And for this reason, the address of a static or global variable (but not necessarily of a non-static local variable) should not change when you run the program multiple times.

Upvotes: 1

Related Questions