extract.py
1.57 KB
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
#!/usr/bin/python
import sys, os, string, struct
prefix = ""
def compute_sig(obj, symbol):
num_bytes = symbol["len"]
offset = symbol["offset"]
f = open("routines/%s" % symbol["name"], "w+")
f.write(obj[offset:offset+num_bytes])
f.close()
def extract_doto(archive, doto):
#sys.stderr.write("Extracting '%s'\n" % doto)
res = os.system("ar x %s %s" % (archive, doto))
#sys.stderr.write(" res = %d\n" % res)
os.chmod(doto, 0400)
def extract_symbols(doto):
symbol_table = os.popen("readelf -s %s" % doto).readlines()
symbols = []
for sym in symbol_table:
l = string.split(sym)
if len(l) == 8 and l[3] == 'FUNC' and l[6] != 'UND' and l[2] != '0':
d = {}
d["name"] = l[7]
d["offset"] = string.atoi(l[1], 16)
d["len"] = string.atoi(l[2])
d["file"] = doto
symbols.append(d)
return symbols
def get_text_offset(doto):
sections = os.popen("readelf -S %s | cut -c 8-" % doto).readlines()
offset = 0
for s in sections:
l = string.split(s)
if len(l) > 0 and l[0] == ".text":
offset = string.atoi(l[3], 16)
break
return offset
def main(argv):
archive = argv[1]
global prefix
prefix = string.split(string.split(archive, '.')[0], '/')[-1]
ofiles = string.split(os.popen("ar t %s" % archive).read())
for doto in ofiles:
extract_doto(archive, doto)
symbols = extract_symbols(doto)
offset = get_text_offset(doto)
if offset != 0:
obj = open(doto).read()[offset:]
for sym in symbols:
compute_sig(obj, sym)
os.unlink(doto)
if __name__ == '__main__':
main(sys.argv)