-
Notifications
You must be signed in to change notification settings - Fork 7
/
elf2json.py
executable file
·72 lines (56 loc) · 2.03 KB
/
elf2json.py
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
#!/usr/bin/python3 -tt
import os
import sys
import json
import re
from collections import OrderedDict # beacuse normal dictionary looses their
def elf2json(elf_binary,output_file="temp/output.json"):
#check if sys.argv[1] file exists or not, if exists, is it ELF or similar
if not os.path.isfile(elf_binary):
raise FileNotFoundError('ELF binary not found')
return None
os.system("objdump -M intel -d "+elf_binary+" > temp/objdump_op")
wf=open(output_file,"w")
opened_section=False #for checking json curly brace is opened for section or not
opended_func=False
opened_instruction=False
printed_instruction=False #varialbe will tell last iteration of loop wf.writeed instruction or not #for deciding to put comma at end or not
fl=open("temp/objdump_op","rU")
wf.write("{\n")
for line in fl:
#for sections
if line.find("Disassembly of section") != -1:
section_name=re.search(r'Disassembly of section (.+?)\:',line).groups()[0]
if opened_section:
wf.write("\t}\n},\n\n")
opened_section=False
opended_func=False
wf.write("\""+section_name+"\": { \n\n")
printed_instruction=False
opened_section=True
# for functions
mat_obj=re.search(r'.+?\<(.+?)\>\:',line)
if mat_obj:
if opended_func:
wf.write("\t},\n\n")
opended_func=False
wf.write("\t\""+mat_obj.groups()[0]+"\": { \n\n")
printed_instruction=False
opended_func=True
mat_obj=None
#for instructions
mat_obj=re.search(r'\s(\w+?):.+?\t(.+?)\n',line)
if mat_obj:
tup=mat_obj.groups()
if printed_instruction: #varialbe will tell last iteration of loop wf.writeed instruction or not
wf.write(",\n")
wf.write("\t\t\""+tup[0]+"\":\""+tup[1]+"\"")
printed_instruction=True
mat_obj=None
#adding starting address in json
wf.write("}},\n\"start_addr\":\"")
wf.close()
os.system("objdump -f "+elf_binary+" | grep 'start address' | cut -d ' ' -f 3 | tr -d '\n' >> "+output_file+" && echo '\"}' >> "+output_file)
#wf.write("")
elf_obj=json.loads(open(output_file).read(),object_pairs_hook=OrderedDict)
return elf_obj