summaryrefslogtreecommitdiff
path: root/elf-layout.py
blob: ee8530b42eb2b6658ec3e4a93067516f5751fd94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import sys

if len(sys.argv) < 2:
    print("First arg should be name of the binary")
    exit()

with open(sys.argv[1], "rb") as f:
    data = f.read()

def toi(val):
    res = 0
    shift = 0
    for i in val:
        res += i << shift
        shift += 8
    return res


def field(offset, size):
    return data[offset:offset + size]

magic = field(0x00, 4)
plat_bit = field(0x04, 1)
endian = field(0x05, 1)
ver = field(0x06, 1)
abi = field(0x07, 1)
abi_ver = field(0x08, 1)
padding = field(0x09, 7)
obj_t = field(0x10, 2)
isa = field(0x12, 2)
orig_ver = field(0x14, 4)

bit32 = toi(plat_bit) == 1
bit64 = toi(plat_bit) == 2

# expect 64-bit
entry = field(0x18, 8)
phoff = field(0x20, 8)
shoff = field(0x28, 8)
flags = field(0x30, 4)
ehsize = field(0x34, 2)

phentsize = field(0x36, 2)
phnum = field(0x38, 2)

shentsize = field(0x3a, 2)
shnum = field(0x3c, 2)
shstrndx = field(0x3e, 2)

print(data[0x3e])
print(list(shstrndx))
shstrndx = toi(shstrndx)
shnum = toi(shnum)
shoff = toi(shoff)

strshtab_off = 0

for i in range(shnum):
    sh_name      = toi(field(shoff + 0x40 * i + 0x00, 4))
    sh_type      = toi(field(shoff + 0x40 * i + 0x04, 4))
    sh_flags     = toi(field(shoff + 0x40 * i + 0x08, 8))
    sh_addr      = toi(field(shoff + 0x40 * i + 0x10, 8))
    sh_offset    = toi(field(shoff + 0x40 * i + 0x18, 8))
    sh_size      = toi(field(shoff + 0x40 * i + 0x20, 8))
    sh_link      = toi(field(shoff + 0x40 * i + 0x28, 4))
    sh_info      = toi(field(shoff + 0x40 * i + 0x2c, 4))
    sh_addralign = toi(field(shoff + 0x40 * i + 0x30, 8))
    sh_entsize   = toi(field(shoff + 0x40 * i + 0x38, 8))

    if i == shstrndx:
        strshtab_off = sh_offset
        break

for i in range(shnum):
    sh_name      = toi(field(shoff + 0x40 * i + 0x00, 4))
    sh_type      = toi(field(shoff + 0x40 * i + 0x04, 4))
    sh_flags     = toi(field(shoff + 0x40 * i + 0x08, 8))
    sh_addr      = toi(field(shoff + 0x40 * i + 0x10, 8))
    sh_offset    = toi(field(shoff + 0x40 * i + 0x18, 8))
    sh_size      = toi(field(shoff + 0x40 * i + 0x20, 8))
    sh_link      = toi(field(shoff + 0x40 * i + 0x28, 4))
    sh_info      = toi(field(shoff + 0x40 * i + 0x2c, 4))
    sh_addralign = toi(field(shoff + 0x40 * i + 0x30, 8))
    sh_entsize   = toi(field(shoff + 0x40 * i + 0x38, 8))

    if sh_type == 0:
        continue
    #  print(sh_name)
    name = []
    name_idx = strshtab_off + sh_name
    while data[name_idx] != 0:
        name.append(data[name_idx])
        name_idx += 1
    name = bytes(name).decode()
    #  print(name)