blob: 43afed0c337cd3cb465a24e0e8300703ef9ca974 [file] [log] [blame]
rjw6c1fd8f2022-11-30 14:33:01 +08001import os, subprocess, re, sys, struct
2import binascii
3
4debug_log = True
5tool_chain_prefix = ''
6
7def log(stuff):
8 if not debug_log:
9 return
10 print(stuff)
11
12print(sys.argv)
13
14if len(sys.argv) < 5:
15 print("Usage: %s [Output file] [Toolchain prefix] [C file] [ELF file] (gcc option file ~inc_def.tmp)"%(sys.argv[0]))
16 exit(0)
17
18elf_file = sys.argv[4]
19cmd_list = []
20if len(sys.argv) >= 6:
21 cmd_list = ['@'+sys.argv[5]]
22
23tool_chain_prefix = sys.argv[2]
24step1o_fname = os.path.join(os.path.dirname(sys.argv[1]),'~mdmp_step1.o')
25step2o_fname = os.path.join(os.path.dirname(sys.argv[1]),'~mdmp_step2.o')
26if subprocess.call([tool_chain_prefix + 'gcc', '-G0', '-EL', '-c', '-o' + step1o_fname] + cmd_list + [sys.argv[3]]) != 0:
27 exit(1)
28
29if subprocess.call([tool_chain_prefix + 'ld', '-EL', '--entry=mdmp_profile_list', '--just-symbols=' + elf_file, '-o' + step2o_fname, step1o_fname]) != 0:
30 exit(2)
31
32def readSymbolTableV2(objFile, prefix = False):
33 global tool_chain_prefix
34
35 sec_tbl = []
36 r = re.compile(br'\[\s?(\d+)\](.*)')
37 proc = subprocess.Popen([tool_chain_prefix + 'readelf', '-WS', objFile], stdout=subprocess.PIPE)
38 for line in proc.stdout:
39 m = r.search(line.rstrip())
40 if m is None:
41 continue
42
43 s = m.group(2).split()
44 sec_tbl.append({'addr':int(s[2], 16), 'offset':int(s[3], 16), 'size':int(s[4], 16)})
45
46 symDict = {}
47 r = re.compile(br'\d+: (\w*)\s+(\d+).+ (\w+) ([^\s]+)$')
48
49 proc = subprocess.Popen([tool_chain_prefix + 'readelf', '-Ws', objFile], stdout=subprocess.PIPE)
50 for line in proc.stdout:
51 m = r.search(line)
52 if m is None: continue
53 s = m.group(4)
54 if prefix is not False and not s.startswith(prefix): continue
55
56 v = int(m.group(1), 16)
57 if m.group(3).isdigit():
58 t = sec_tbl[int(m.group(3))]
59 v = (v - t['addr']) + t['offset']
60 symDict.update({s:{'val':v, 'size':int(m.group(2))}})
61
62 return symDict
63
64def readFromFileV2(objFile, offset, size, isNullTerminated = False):
65 fd = open(objFile, 'rb')
66 fd.seek(offset)
67 d = fd.read(size)
68 if (isNullTerminated):
69 b = d.find(b'\x00')
70 if b is not False: d=d[:b]
71 return d
72
73_sec_info = None
74def getDataSectionInfo():
75 global _sec_info
76 if _sec_info == None:
77 proc = subprocess.Popen([tool_chain_prefix + 'readelf', '-S', step2o_fname], stdout=subprocess.PIPE)
78 r = re.compile(br'\[\s?(\d+)\](.*)')
79 for line in proc.stdout:
80 m = r.search(line.rstrip())
81 if m is None:
82 continue
83 s = m.group(2).split()
84 if s[0] != b'.data':
85 continue
86 _sec_info = {'idx':m.group(1), 'addr':int(s[2], 16), 'offset':int(s[3], 16), 'size':int(s[4], 16)}
87 return _sec_info
88
89_sym_table = None
90def getSymbolTable():
91 global _sym_table
92 if _sym_table is None:
93 _sym_table = []
94 proc = subprocess.Popen([tool_chain_prefix + 'readelf', '--syms', '--wide', step2o_fname], stdout=subprocess.PIPE)
95 for line in proc.stdout:
96 s = line.split()
97 if len(s) != 8 or s[3] != b'OBJECT' or not s[6].isdigit():
98 continue
99 _sym_table.append({'symbol': s[7], 'addr':int(s[1], 16), 'size':int(s[2])})
100 log('==== Symbol Table ====')
101 log(_sym_table)
102 log('======================')
103 return _sym_table
104
105def getAddrOffsetSizeByAddr(address):
106 sec_info = getDataSectionInfo()
107 if address < sec_info['addr'] or address >= sec_info['addr'] + sec_info['size']:
108 raise ValueError('Address not in range.')
109 offset = address-sec_info['addr']+sec_info['offset']
110
111 sym_table = getSymbolTable()
112 for e in sym_table:
113 if e['addr'] == address:
114 return {'addr': address, 'offset': offset, 'size':e['size']}
115 raise IndexError('Address not found in symbol list.')
116 return None
117
118def getAddrBySymbol(symbol):
119 sym_table = getSymbolTable()
120 for e in sym_table:
121 if e['symbol'] == symbol:
122 return e['addr']
123 raise IndexError('Symbol not found.')
124 return None
125
126
127def getElementListByAddr(address, fd, fmt):
128 r = []
129 if address != 0:
130 aos = getAddrOffsetSizeByAddr(address)
131 # log(['getElementListByAddr',aos])
132 fd.seek(aos['offset'])
133 bytes_remain = aos['size']
134 size = struct.calcsize(fmt)
135 while bytes_remain > 0:
136 r.append(struct.unpack(fmt, fd.read(size)))
137 bytes_remain -= size
138 return r
139
140
141bin_obj = {}
142
143def genBinObj(addr, build_function, *args):
144 global bin_obj
145 if addr == 0:
146 return
147 if addr in bin_obj:
148 log('Bin addr {:08X} already exists'.format(addr))
149 return
150 bin_obj[addr] = build_function(*args)
151 log('Bin addr {:08X} created'.format(addr))
152
153
154def buildSelectiveTable(selective_tbl):
155 r = struct.pack('<I', len(selective_tbl))
156 for s in selective_tbl:
157 r = r + struct.pack('<IIBBxx', s[0], s[1], s[2], s[3])
158
159 return r
160
161
162def buildRegionTable(num_mem_type, num_option, region_tbl):
163 # Handle region table
164 option_size = (num_option+7)//8
165 mem = [bytearray(option_size) for y in range(num_mem_type)]
166 for r in region_tbl:
167 mem_type = r[0]
168 for x in r[1:]:
169 if x == 0:
170 break
171 x=x-1
172 mem[mem_type][x//8] = mem[mem_type][x//8] ^ (1<<(x%8))
173
174 # log(['Config:', r])
175 # log(['Mem:', mem])
176
177 log(['num_mem_type:',num_mem_type])
178 log(['option_byte:', option_size])
179
180 r = struct.pack('<HH', num_mem_type, option_size)
181 for x in mem:
182 r = r + x
183
184 return r
185
186
187# open object file
188fd=open(step2o_fname, 'rb')
189
190# get information from object
191num_mem_type = getElementListByAddr(getAddrBySymbol(b'_mdmp_num_mem_type'), fd, '=I')[0][0]
192num_region_option = getElementListByAddr(getAddrBySymbol(b'_mdmp_num_region_option'), fd, '=I')[0][0]
193
194profile = []
195pid = 0
196for p in getElementListByAddr(getAddrBySymbol(b'mdmp_profile_list'), fd, '=III'):
197 log('Profile #{}: +0x{:X} -0x{:X}'.format(pid, p[0], p[1]))
198 genBinObj(p[0], buildRegionTable, num_mem_type, num_region_option, getElementListByAddr(p[0], fd, '=I'+'I'*num_region_option))
199 genBinObj(p[1], buildSelectiveTable, getElementListByAddr(p[1], fd, '=IIII'))
200 profile.append((p[0],p[1],p[2]))
201 pid = pid+1
202
203fd.close()
204
205# Write to binary file
206fd_bin = open(sys.argv[1], 'wb+')
207
208profile_info_size = 8 + len(profile)*8
209fd_bin.seek(profile_info_size)
210
211bin_obj_offset = {0:0}
212for b in bin_obj:
213 bin_obj_offset[b] = fd_bin.tell()
214 fd_bin.write(bin_obj[b])
215
216# write eof pattern
217fd_bin.write(b'\x99\x17\x71\xCB')
218
219# Read build info
220try:
221 sym = readSymbolTableV2(elf_file, (b'RELEASE_VERNO_RW', b'BUILD_TIME_RW'))
222 build_verno = readFromFileV2(elf_file, sym[b'RELEASE_VERNO_RW$$Base']['val'], sym[b'RELEASE_VERNO_RW$$Length']['val'], isNullTerminated = True)
223 build_time = readFromFileV2(elf_file, sym[b'BUILD_TIME_RW$$Base']['val'], sym[b'BUILD_TIME_RW$$Length']['val'], isNullTerminated = True)
224 signature = bytearray(build_verno + b'_' + build_time)
225except Exception as err:
226 print("Cannot read build information!", err)
227
228signature_pos = fd_bin.tell()
229fd_bin.write(struct.pack('<H', len(signature)))
230fd_bin.write(signature)
231
232# from the end of binary
233fd_bin.write(struct.pack('<I', signature_pos))
234fd_bin.seek(0)
235
236profile_binary_magic = 0x1A424650
237fd_bin.write(struct.pack('<II', profile_binary_magic, len(profile)))
238for p in profile:
239 fd_bin.write(struct.pack('<HHI', bin_obj_offset[p[0]], bin_obj_offset[p[1]], p[2]))
240
241# add crc32 at file end
242fd_bin.seek(0)
243buf = fd_bin.read()
244crc32 = binascii.crc32(buf, profile_binary_magic) & 0xFFFFFFFF
245fd_bin.write(struct.pack('<I', crc32))
246output_size = fd_bin.tell()
247fd_bin.close()
248
249os.remove(step1o_fname)
250os.remove(step2o_fname)
251print ("Memory dump profile %s created. File size %d. CRC32 0x%08X"%(sys.argv[1], output_size, crc32))