在 GCC 中禁用 GOT

Disable GOT in GCC

Global Offset Table (GOT):用于 ELF 符号的重定位(已实现的 GCC),它有助于共享相同的二进制文件而无需任何特定链接每个过程。从而减少内存中相同二进制图像的副本。

我的问题是,有什么方法可以禁用可重定位 ELF 映像中的 R_386_GOT32R_386_GOTOFF 类型重定位条目吗?我的意思是,我可以强制 GCC 使用 R_386_PC32R_386_32 类型重定位而不是 GOT 类型重定位吗?

如果没有,能否请您解释一下GOT的实现方式?我正在为 ELF 编写一个动态链接和加载库。

编辑:
参考链接
https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-74186.html
http://man7.org/linux/man-pages/man8/ld.so.8.html
http://wiki.osdev.org/ELF

终于破解了!
不,不可能限制 GCC 输出非 GOT 类型重定位。
现在如何解决GOT类型重定位?
GOT 是由动态 linker 分配的固定 128KB 内存块(它的工作原理是写时复制),其中包含用于重定位的条目。
仅当 ELF 二进制文件中存在任何类型的(下面列出的)GOT 重定位时,动态链接器才分配 GOT。

R_386_GOTOFF (== 0x9)
此重定位类型计算符号值与全局偏移地址 table 之间的差异。它还指示 link-editor 创建全局偏移量 table.

R_386_GOTPC (== 0xA)
此重定位类型类似于 R_386_PC32,只是它在计算中使用全局偏移地址 table。

如何实现?
注意:以下代码片段属于 Atom OS 源代码,受封闭源代码许可保护。但是我(Atom 开发人员)特此声明此代码片段可以免费使用:)

    uint GOT = Heap.kmalloc(1024 * 128); // 128 KB
    ...
    private static void Relocate(Elf_Header* aHeader, Elf_Shdr* aShdr, uint GOT)
    {
        uint BaseAddress = (uint)aHeader;
        Elf32_Rel* Reloc = (Elf32_Rel*)aShdr->sh_addr;
        Elf_Shdr* TargetSection = (Elf_Shdr*)(BaseAddress + aHeader->e_shoff) + aShdr->sh_info;

        uint RelocCount = aShdr->sh_size / aShdr->sh_entsize;

        uint SymIdx, SymVal, RelocType;
        for (int i = 0; i < RelocCount; i++, Reloc++)
        {
            SymVal = 0;
            SymIdx = (Reloc->r_info >> 8);
            RelocType = Reloc->r_info & 0xFF;

            if (SymIdx != SHN_UNDEF)
            {
                if (RelocType == R_386_GOTPC)
                    SymVal = GOT;
                else
                    SymVal = GetSymValue(aHeader, TargetSection->sh_link, SymIdx);
            }

            uint* add_ref = (uint*)(TargetSection->sh_addr + Reloc->r_offset);
            switch(RelocType)
            {
                case R_386_32:
                    *add_ref = SymVal + *add_ref; // S + A
                    break;
                case R_386_GOTOFF:
                    *add_ref = SymVal + *add_ref - GOT; // S + A - GOT
                    break;
                case R_386_PLT32:   // L + A - P
                case R_386_PC32:    // S + A - P
                case R_386_GOTPC:   // GOT + A - P
                    *add_ref = SymVal + *add_ref - (uint)add_ref;
                    break;
                default:
                    throw new Exception("[ELF]: Unsupported Relocation type");
            }
        }
    }

您可以尝试使用 gcc 选项:-fPIC 和 -fpie,这将禁用 GOT。

gcc -fno-plt -fno-pic 会将重定位类型限制为 R_386_PC32 和 R_386_32(或者至少在我的情况下有效)。接受的答案在声称这是不可能的方面具有误导性。