https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124027

--- Comment #3 from Pali Rohár <pali at kernel dot org> ---
> Position Independence is achieved differently in PE-COFF by means of the 
> .reloc section.

Seems that there is a confusion between compile-time position independent code
(pic) and load-time relocable code (reloc). Those are two different (opposite)
things, and position independence cannot be done via relocation.

Position independent code means to be not fixed at specific location and
without need to be patched at load-time via reloc. Basically what I have
described in the issue description and what is gcc already doing for ELF/linux.

Relocable code means that the code is generated for fixed address locations
with additional .reloc section which contains information how to patch the
binary code at runtime to move it to different location than the one used
during compiling. It means that the library/executable cannot be "shared"
between processes.

I found blog posts with very good descriptions how it works for both 32-bit and
64-bit x86 cpu on linux/elf:
https://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries/
https://eli.thegreenplace.net/2011/11/03/position-independent-code-pic-in-shared-libraries
https://eli.thegreenplace.net/2011/11/11/position-independent-code-pic-in-shared-libraries-on-x64

There is also described how to achieve .reloc code for 64-bit linux/elf.

And basically same thing can be achieved also for COFF format. Just the ELF GOT
related stuff needs to be replaced by references to the PE-COFF import table.

Currently for 32-bit coff x86, it seems that gcc's -fpic flag is doing
absolutely nothing, it is generating same code as without the -fpic flag. The
generated asm code uses fixed addressing and generating .reloc section for
runtime relocations.

I consider this as a bug as -fpic should generate position independent code (as
opposite of the default .reloc code, when -fpic is not used).

> /* Don't allow flag_pic to propagate since gas may produce invalid code
>    otherwise.  */

This sounds like that in this flag_pic case gcc generates position independent
code via RIP-relative addressing which is invalid code in 32-bit x86 (it is
only valid in 64-bit x86).

For 32-bit x86 it is needed to use __x86.get_pc_thunk as I have described in
the issue description, similar to what is gcc already doing for 32-bit x86
elf/linux.

I will try to look into the "flag_pic" related code in gcc, if I found
something useful for me. I'm not familiar with the gcc code base.

Reply via email to