# 《程序员的自我修养》- ELF文件预备知识

### #sections 与 segments

The segments contain information that is necessary for runtime execution of the file, while sections contain important data for linking and relocation. Any byte in the entire file can be owned by at most one section, and there can be orphan bytes which are not owned by any section.

Section Headers是由一种特定的数据结构组成的数组，称为section header table，用于索引文件中所有sections的位置。这个数组的下标被称为section header table index。这个数据的详细信息保存在ELF文件的文件头中，可以使用readelf -h查看：

Value

Name

Explanation

0x0000

SHN_UNDEF

Marks a meaningless section reference

0xfff1

SHN_ABS

Specifies absolute values for the corresponding reference

0xfff2

SHN_COMMON

Symbols defined relative to it are common symbols

sh_type的值有以下几种：

Value

Name

Explanation

0

SHT_NULL

1

SHT_PROGBITS

Information defined completely by the program

2

SHT_SYMTAB

All symbols needed during linking and some unnecessary ones

3

SHT_STRTAB

A string table (can be mutiple)

4

SHT_RELA

Relocation entries with explict addends (can be mutiple)

9

SHT_REL

Relocation entries without explict addends (can be mutiple)

5

SHT_HASH

A symbol hash table used in dynamic linking

6

SHT_DYNAMIC

11

SHT_DYNSYM

Only the symbols needed during linking

7

SHT_NOTE

Information that marks the file in some way

8

SHT_NOBITS

Looks like SHT_PROGBITS but occupies no space

10

SHT_SHLIB

(Reserved but semantics not specified)

0x70000000

SHT_LOPROC

Reserved for processor-specific semantics

0x7fffffff

SHT_HIPROC

Reserved for processor-specific semantics

0x80000000

SHT_LOUSER

The lower bound of the range of index reserved for application programs

0xffffffff

SHT_HIUSER

The upper bound of the range of index reserved for application programs

sh_flag的值如下所示：

Nama

Value

Explanation

SHF_WRITE

0x1

Data in this section should be writable during process execution

SHF_ALLOC

0x2

The section occupies memory during process execution

SHF_EXECINSTR

0x4

This section contains executable machine instructions

0xf0000000

Reserved section

sh_type

sh_info

SHT_DYNAMIC

The section header index of the string table used by entries in the section

0

SHT_HASH

The section header index of the symbol table to which the hash table applies

0

SHT_REL
SHT_RELA

The section header index of the associated symbol table

The section header index of the section to which the relocation applies

SHT_SYMTAB
SHT_DYNSYM

The section header index of the associated string table

One greater than the symbol table index of the last local symbol (binding STB_LOCAL).

other

SHN_UNDEF

0