动态链接器:在 x86_64 上为 ELF 实现运行时链接

来源:OSDev Wiki· 阅读原文 ↗

迟早你会达到需要共享库的阶段。这里我们不讨论静态链接和动态链接的区别,你应该已经熟悉这些了。

本文介绍的是 ELF 在 x86_64 架构上的情况,但可以轻松移植到其他系统,因为概念是相似的。

家庭作业

内存布局

我假设你已经创建了一个新的、空的地址空间,并且已经在其中加载了可执行文件。我还假设你已经在可执行文件的段之后加载了 libc 共享库。现在你卡住了,因为你不知道如何从可执行文件中调用 printf。

由于可执行文件是由你加载的,你应该知道内存中 ELF 魔数字节的虚拟地址。以此作为起点。

Elf64_Ehdr *ehdr = (Elf64_Ehdr *)(ptr);

if(!kmemcmp(ehdr->e_ident, ELFMAG,SELFMAG) &&
   ehdr->e_ident[EI_CLASS] == ELFCLASS64 &&
   ehdr->e_ident[EI_DATA] == ELFDATA2LSB &&
   ehdr->e_type == ET_EXEC && ehdr->e_shnum > 0)
{
   // We have a valid image with sections
}

首先我们检查魔数字节和 ELF64 的格式。作为额外检查,我们还验证它是否是可执行文件并且具有非空的节表(我们将需要用到它)。

现在让我们看看 GNU 工具链为我们做了什么来找到 printf。

段内调用

为了弄清楚这一点,首先我们应该了解段内调用是如何工作的。为此我们将使用一个非常简单的源代码。

void localfunction()
{
}

int main(int,char**)
{
    localfunction();
}

它编译为:

$ objdump -d test
000000000020016f <localfunction>:
  20016f:	55                   	push   %rbp
  200170:	48 89 e5             	mov    %rsp,%rbp
  200173:	90                   	nop
  200174:	5d                   	pop    %rbp
  200175:	c3                   	retq   

0000000000200176 <main>:
  200176:	55                   	push   %rbp
  200177:	48 89 e5             	mov    %rsp,%rbp
  20017a:	b8 00 00 00 00       	mov    $0x0,%eax
  20017f:	e8 eb ff ff ff       	callq  20016f <localfunction>
  200184:	90                   	nop
  200185:	5d                   	pop    %rbp
  200186:	c3                   	retq

这很简单,在 20017f 处使用了 rip 相对寻址。

跨段调用

现在让我们稍微修改源代码以使用 libc 调用:

int main(int,char**)
{
    printf("Hello World");
}

编译并查看生成了什么。

000000000020016f <main>:
  20016f:	55                   	push   %rbp
  200170:	48 89 e5             	mov    %rsp,%rbp
  200173:	48 8d 3d b6 01 00 00 	lea    0x1b6(%rip),%rdi        # 200330 <_DYNAMIC+0x110>
  20017a:	b8 00 00 00 00       	mov    $0x0,%eax
  20017f:	e8 8c 00 00 00       	callq  200210 <printf@plt>
  200184:	90                   	nop
  200185:	5d                   	pop    %rbp
  200186:	c3                   	retq   

0000000000200200 <printf@plt-0x10>:
  200200:	ff 35 4a 0e 00 00    	pushq  0xe4a(%rip)        # 201050 <_GLOBAL_OFFSET_TABLE_+0x8>
  200206:	ff 25 4c 0e 00 00    	jmpq   *0xe4c(%rip)        # 201058 <_GLOBAL_OFFSET_TABLE_+0x10>
  20020c:	0f 1f 40 00          	nopl   0x0(%rax)

0000000000200210 <printf@plt>:
  200210:	ff 25 4a 0e 00 00    	jmpq   *0xe4a(%rip)        # 201060 <_GLOBAL_OFFSET_TABLE_+0x18>
  200216:	68 00 00 00 00       	pushq  $0x0
  20021b:	e9 e0 ff ff ff       	jmpq   200200 <main+0x91>

什么?多了两个局部函数?这里发生了什么?GNU 工具链有一个延迟运行时链接的概念。这意味着地址在被引用之前不会被解析。为了实现这一点,它需要辅助函数(生成到文本段的 .plt 节中)。

当 CPU 执行这段代码时,它首先会调用 20017f 处的一个普通局部函数。该函数是辅助函数之一,其目的是从 GOT+0x18 加载一个地址并跳转到它。默认情况下,该值指向下一条指令,该指令将 0 保存到栈上并调用 200200 处的另一个辅助函数。那个是引用解析器,其工作是将 GOT 中的地址替换为重定位后的地址。

由于解析器函数在链接时未知,它的地址也在 GOT 的 0x10 处。此外,它可以接收一个参数,存储在 GOT+0x8。我们还可以注意到,在 200206 处的指令是跳转而不是调用,因此解析器永远不会返回到这个辅助函数,相反它应该跳转到重定位后的地址。

实现动态链接器

所有这些反汇编教会了我们关于动态链接器的两件事:

1. it has to locate and write the GOT
2. it has two parts: load time linker and a run time resolver.

第一部分在线程启动之前运行,并将第二部分的地址和参数保存到 GOT 中。另一方面,第二部分在线程已经运行时运行,并将重定位后的地址保存到 GOT 中。如你所见,两部分都需要 GOT 的地址。为了节省资源,不应该两次定位 GOT:这就是解析器参数的用处。虽然你技术上可以在这个 GOT 槽位中插入任何内容,但最好的选择是存储一些能够轻松标识请求程序的东西——例如,GOT 起始位置的地址。

要继续,我们必须在内存中定位 GOT 并弄清楚它有哪些条目。

定位 GOT

是时候看看目标文件里有什么了。

$ readelf -a test
Section Headers:
  [Nr] Name              Type             Address           Offset
       Size              EntSize          Flags  Link  Info  Align
  [10] '.got.plt'        PROGBITS         0000000000201048  00001048
       0000000000000020  0000000000000008  WA       0     0     8

Symbol table .symtab contains 23 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
    15: 0000000000201048     0 OBJECT  LOCAL  DEFAULT   10 _GLOBAL_OFFSET_TABLE_

符号表显示 GOT 位于 201048。我们也可以在 '.got.plt' 的节头中看到相同的值。这意味着我们不必解析符号就能获得 GOT 的地址,这简化了第一部分。我们还可以了解到,在我们的示例中 GOT 的长度是 32(0x20)字节。

注意:对于大多数可执行文件,GOT 的地址也可以在动态节中找到,位于标记为 'DT_PLTGOT.' 的条目下。

GOT 里有什么?

我们已经知道

1. GOT+0x0 entry is unused
2. GOT+0x8 is an argument to second part
3. GOT+0x10 is function reference to second part

但其余部分呢,从我们示例中的 201060 开始?这里我们只有一个引用,所以很明显,但如果我们有更多引用呢?我们如何知道哪个符号对应哪个条目?

$ readelf -a test
Section Headers:
  [Nr] Name              Type             Address           Offset
       Size              EntSize          Flags  Link  Info  Align
  [ 4] '.rela.plt'       RELA             00000000002001e8  000001e8
       0000000000000018  0000000000000018  AI       2    10     8

Relocation section .rela.plt at offset 0x1e8 contains 1 entries:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
000000201060  000100000007 R_X86_64_JUMP_SLO 0000000000000000 printf + 0

多么方便,另一个表也记录在节头中。它叫做 '.rela.plt',恰好描述了这一点。当解析器获得控制权时,栈上的第二个参数将是该节中的一个索引,即指向所请求符号的这样一个条目的偏移量(在 x86-64 上是 16 字节的条目,在 32 位 x86 上是 8 字节的条目)。

我的库在哪里?

到目前为止,我们假设共享库已经加载。libc 的情况确实如此,但我们如何知道可执行文件还需要哪些其他共享库?

$ readelf -a test
Section Headers:
  [Nr] Name              Type             Address           Offset
       Size              EntSize          Flags  Link  Info  Align
  [ 6] '.dynamic'        DYNAMIC          0000000000200220  00000220
       0000000000000110  0000000000000010  WA       3     0     8

Dynamic section at offset 0x220 contains 12 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libc.so]

毫不意外,答案再次在节头中。有一个名为 '.dynamic' 的表指针。该表有若干记录,但我们真正感兴趣的是标记为 "NEEDED" 的那些。

符号查找

要找到 printf 的地址,我们应该首先在共享库中定位它的符号。

$ readelf -a libc.so 
Section Headers:
  [Nr] Name              Type             Address           Offset
       Size              EntSize          Flags  Link  Info  Align
  [ 2] '.dynsym'         DYNSYM           0000000100000218  00000218
       00000000000003c0  0000000000000018   A       3     1     8
  [ 3] '.dynstr'         STRTAB           00000001000005d8  000005d8
       0000000000000124  0000000000000000   A       0     0     1

Symbol table .dynsym contains 40 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     8: 0000000100000175    93 FUNC    GLOBAL DEFAULT    1 printf

找到了!在我们的示例中它是 100000175。

给我代码!

我已经把以上所有内容整合到一个非常简单的示例中,见 elftool.c 在 gitlab 上。

当我在可执行文件上运行它时,输出是:

$ gcc elftool.c -o elftool
$ ./elftool -d mytestelf.o
Stringtable 000003f0 (118 bytes), symbols 000002b8 (312 bytes, one entry 24)

--- IMPORT ---
Dynamic 00001e20 (464 bytes, one entry 16):
  0. /lib/libc.so.6

GOT 00002000 (104 bytes), Rela 000004d0 (240 bytes, one entry 24):
  0. 00602018 +0 puts
  1. 00602020 +0 fread
  2. 00602028 +0 fclose
  3. 00602030 +0 printf
  4. 00602038 +0 strcmp
  5. 00602040 +0 ftell
  6. 00602048 +0 malloc
  7. 00602050 +0 fseek
  8. 00602058 +0 fopen
  9. 00602060 +0 exit

--- EXPORT ---

如你所见,这里我们有一个导入节,但没有要导出的内容。现在让我们看看一个共享库!

$ ./elftool -d /lib/libc.so.6
Stringtable 00011038 (23041 bytes), symbols 00003d90 (53928 bytes, one entry 24)

--- IMPORT ---
Dynamic 00197b60 (496 bytes, one entry 16):
  0. /lib/ld-linux-x86-64.so.2

GOT 00198000 (88 bytes), Rela 0001f760 (192 bytes, one entry 24):
  0. 00398050 +844d0 
  1. 00398048 +a8560 
  2. 00398040 +7ff80 
  3. 00398038 +867c0 
  4. 00398030 +823f0 
  5. 00398028 +82780 
  6. 00398020 +a8640 
  7. 00398018 +83b50 

--- EXPORT ---
  8. 0008e850 __strspn_c1
  9. 0006aad0 putwchar
 10. 000f8640 __gethostname_chk
 11. 0008e870 __strspn_c2
 12. 0010f210 setrpcent
 13. 0009eda0 __wcstod_l
 14. 0008e8a0 __strspn_c3
 15. 000e8d10 epoll_create
 16. 000d1b50 sched_get_priority_min
 17. 000f8660 __getdomainname_chk
 18. 000e8f20 klogctl
 19. 0002c380 __tolower_l
 20. 0004f440 dprintf
 21. 000b8e00 setuid
 22. 000a3d20 __wcscoll_l
... lot more lines to come ...

这次它有大量的函数要导出,并且它还导入了 Linux 的动态链接器,在 GOT 中带有 addend 偏移量。

总结

总结一下,动态链接器应该看起来像:

1. load-time linker
  1.1. locates GOT by '.got.plt' section, and saves that address in GOT+0x8
  1.2. stores second part's address at GOT+0x10
  1.3. reads '.dynamic' section to load shared libraries
2. run-time reference resolver
  2.1. it's called by a helper
  2.2. that helper places index-0x18 and the address of GOT as arguments on the stack
  2.3. it has to locate '.rela.plt' to get the symbol for the reference
  2.4. the symbol is looked up in the shared library's '.dynsym' section to get relocated address
  2.5. that relocated address has to be saved in the GOT (index and base on the stack)
  2.6. clean up stack, restore registers and jump to the relocated address

就这些,希望对某人有帮助!祝你实现自己的动态链接器顺利!

来源与翻译说明

本文根据原文快照翻译,保留原有代码、数值、技术限定及历史背景。原文中的命令与运行结果不代表本站已实际执行验证。

原文:Dynamic Linker;离线修订号:30293。

原作者:OSDev Wiki 社区贡献者。原文及引用资料的版权与许可声明继续适用:版权声明 许可说明

评论

暂无评论