Chapter 7 Linking

#CSAPP
命令行工具 gcc 属于 compiler driver,内部包含了对 C 的预处理(cpp)、编译(cc1)、汇编(as)、链接(ld)步骤。

静态链接是通过一系列对象文件构建可执行程序的过程,源代码的编写、编译的解耦得益于链接。两个主要机制

对象文件(object file, object module)包括三种

object file format

Relocatable object files content in seq

Symbol Resolution

relocatable module m‘s symbols category, in the context of a linker:

每个 symbol 在 .symtab 中都有一个 entry。.symtab 实体由 assembler 构造,由 compiler 指导构建 symtab entry.png symtab real.png

symbol resolution:

解决 duplicated symbol names:

static library

Relocation

relocation

语言层面的 symbol 在汇编层面中的形式

汇编器提供的所有机制中底层实现机制大部分都较为直白,对于 symbol(作为语言层面的一部分 data 和 procedure 底层实现,作为机器码中地址引用的上层抽象)而言,其实现机制为 symbol table + symbol resolution 确定 label reference 和 definition 之间的对应关系,然后在 relocation 中确定 definition 的 run-time 地址后,尝试将一部分可以确定 run-time addr 的 symbol 替换为地址,剩余部分做一些准备工作(relocation entry)交给连接器处理

当汇编器遇到不明确 run-time 地址的 reference 时会在其 section 的 relocation entries 中生成对应 entry,原文件处为留白。 ELF Relocation entry.png

relocation types:

链接器对 relocation entry 的处理机制:
linker resolve relocation entry.png

Executable Object Files ELF executable file.png

Loader

run time memory image.png

Dynamic Linking

static library

dynamic library

PIC

为了让多 processes 共享同一块 shared library 代码,必须实现 shared library 为 position independent code,即"无需 relocate"的 code

pic data reference PIC data reference.png
pic function callls PIC function calls.png