-
Notifications
You must be signed in to change notification settings - Fork 2
/
unild
executable file
·409 lines (333 loc) · 14.3 KB
/
unild
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
#!/usr/bin/env python3
import os
import io
import sys
import atexit
import struct
import argparse
import hashlib
import base64
import subprocess
from typing import Tuple
parser = argparse.ArgumentParser()
parser.add_argument('path', help='path to the input UniCore32 relocatable (.o)')
parser.add_argument('-e', '--entrypoint', help='name of the entry function')
parser.add_argument('-o', '--output', default='a.out', help='path to the output RISC-V executable')
parser.add_argument('--hpm-counter', help='monitor on this counter')
parser.add_argument('--warmup', type=int, default=0, help='number of warmups before execution')
parser.add_argument('-v', '--verbose', action='store_true', help='print debugging logs')
def panic(fmt: str, *args):
sys.stderr.write(sys.argv[0] + ': ' + fmt % args + '\n')
sys.stderr.flush()
exit(1)
def debug(fmt: str, *sargs):
if args.verbose:
print('debug: ' + fmt % sargs)
class ELFHeader:
size = 52
def __init__(self, content: bytes, offset: int = 0):
(
self.e_ident,
self.e_type, self.e_machine, self.e_version,
self.e_entry, self.e_phoff, self.e_shoff,
self.e_flags,
self.e_ehsize,
self.e_phentsize, self.e_phnum,
self.e_shentsize, self.e_shnum,
self.e_shstrndx,
) = struct.unpack('16sHHIIIIIHHHHHH', content[offset:offset + self.size])
class ELFHeader64:
size = 64
def __init__(self, content: bytes, offset: int = 0):
(
self.e_ident,
self.e_type, self.e_machine, self.e_version,
self.e_entry, self.e_phoff, self.e_shoff,
self.e_flags,
self.e_ehsize,
self.e_phentsize, self.e_phnum,
self.e_shentsize, self.e_shnum,
self.e_shstrndx,
) = struct.unpack('16sHHIQQQIHHHHHH', content[offset:offset + self.size])
class SymTabEntry:
size = 16
NO_TYPE = 0
OBJECT = 1
FUNC = 2
SECTION = 3
FILE = 4
LOCAL = 0
GLOBAL = 1
def __init__(self, content: bytes, offset: int = 0):
(
self.st_name, self.st_value, self.st_size,
st_info, self.st_other, self.st_shndx,
) = struct.unpack('IIIBBH', content[offset:offset + self.size])
self.st_bind = st_info >> 4
self.st_type = st_info & 0xf
def is_global_func(self) -> bool:
return self.st_type == self.FUNC and self.st_bind == self.GLOBAL
class SymTabEntry64(SymTabEntry):
size = 24
def __init__(self, content: bytes, offset: int = 0):
(
self.st_name, st_info, self.st_other,
self.st_shndx, self.st_value, self.st_size,
) = struct.unpack('IBBHQQ', content[offset:offset + self.size])
self.st_bind = st_info >> 4
self.st_type = st_info & 0xf
class SectionHeader:
size = 40
def __init__(self, content: bytes, offset: int = 0):
(
self.sh_name, self.sh_type, self.sh_flags,
self.sh_addr, self.sh_offset, self.sh_size,
self.sh_link, self.sh_info, self.sh_addralign, self.sh_entsize,
) = struct.unpack('IIIIIIIIII', content[offset:offset + self.size])
def get_bound(self) -> Tuple[int, int]:
return self.sh_offset, self.sh_offset + self.sh_size
class SectionHeader64(SectionHeader):
size = 64
def __init__(self, content: bytes, offset: int = 0):
(
self.sh_name, self.sh_type, self.sh_flags,
self.sh_addr, self.sh_offset, self.sh_size,
self.sh_link, self.sh_info, self.sh_addralign, self.sh_entsize,
) = struct.unpack('IIQQQQIIQQ', content[offset:offset + self.size])
class ProgramHeader64:
size = 56
def __init__(self, content: bytes, offset: int = 0):
(
self.p_type, self.p_flags, self.p_offset,
self.p_vaddr, self.p_paddr, self.p_filesz,
self.p_memsz, self.p_align,
) = struct.unpack('IIQQQQQQ', content[offset:offset + self.size])
class StrTab:
def __init__(self, content: bytes):
self._content = content
def __getitem__(self, start: int) -> str:
end = self._content.find(b'\0', start)
return self._content[start:end].decode('utf-8')
class RelEntry:
size = 8
R_UNICORE32_PC24 = 1
R_UNICORE32_ABS32 = 2
def __init__(self, content: bytes, offset: int = 0):
self.r_offset, r_info = struct.unpack('II', content[offset:offset + self.size])
self.r_sym = r_info >> 8
self.r_type = r_info & 0xff
class UniCore32ELF:
def __init__(self, content: bytes):
# parse header
self.elf_header = ELFHeader(content)
self.section_headers = []
for i in range(self.elf_header.e_shnum):
offset = self.elf_header.e_shoff + self.elf_header.e_shentsize * i
self.section_headers.append(SectionHeader(content, offset))
begin, end = self.section_headers[self.elf_header.e_shstrndx].get_bound()
self.shstrtab = StrTab(content[begin:end])
self.section_header_table = {}
for i, h in enumerate(self.section_headers):
sh_name = self.shstrtab[h.sh_name]
self.section_header_table[sh_name] = h
# parse sections
self.symtab = []
begin, end = self.section_header_table['.symtab'].get_bound()
for i in range(begin, end, SymTabEntry.size):
self.symtab.append(SymTabEntry(content, i))
self.entrypoint = None
begin, end = self.section_header_table['.strtab'].get_bound()
self.strtab = StrTab(content[begin:end])
self.rel_sections = {}
self.rel_tables = {}
for h in self.section_headers:
name = self.shstrtab[h.sh_name]
if any(name.startswith(s)
for s in {'.text', '.data', '.rodata', '.bss'}):
self.rel_sections[name] = h
elif name.startswith('.rel'):
sh_name = name[len('.rel'):]
rel_table = []
begin, end = h.get_bound()
for i in range(begin, end, RelEntry.size):
rel_table.append(RelEntry(content, i))
self.rel_tables[sh_name] = rel_table
def set_entrypoint(self, name: str = None):
if name is not None:
for e in self.symtab:
if self.strtab[e.st_name] == name and e.is_global_func():
self.entrypoint = e
break
if self.entrypoint is None:
panic("No matching entrypoint named '%s'", name)
else:
for e in self.symtab:
if e.is_global_func():
if self.entrypoint is None:
self.entrypoint = e
else:
panic('Cannot decide entrypoint automatically. '
'Please specify it by hand')
if self.entrypoint is None:
panic("Cannot find any entrypoint in '%s'", args.path)
h = self.section_headers[self.entrypoint.st_shndx]
if self.shstrtab[h.sh_name] != '.text':
panic("Entrypoint should be inside '.text'")
def format_asm(self, warmup: int = 0, hpm_counter: str = None) -> str:
codes = []
code = codes.append
code('# Auto-generated by Uni-ld.')
code('# Do not modify by hand!')
code(' .local main_stack')
code(' .comm main_stack, 16, 8')
code(' .text')
code(' .global main')
code('main:')
code(' la a0, main_stack')
code(' sd sp, 0(a0)')
code(' sd ra, 8(a0)')
code(' mv x29, sp')
for _ in range(warmup):
code(' la a0, unicore32.entrypoint')
code(' add x0, x0, x1 # enter unicore')
code(' .word 0x11ffc12a # jump.l a0')
code(' add x0, x0, x2 # exit unicore')
code(' la a0, unicore32.entrypoint')
if hpm_counter:
code(' csrw %s, zero' % hpm_counter)
code(' add x0, x0, x1 # enter unicore')
code(' .word 0x11ffc12a # jump.l a0')
code(' add x0, x0, x2 # exit unicore')
code(' csrr a0, %s' % hpm_counter)
else:
code(' add x0, x0, x1 # enter unicore')
code(' .word 0x11ffc12a # jump.l a0')
code(' .word 0x1a028000 # mov a0, r0')
code(' add x0, x0, x2 # exit unicore')
code(' la sp, main_stack')
code(' ld ra, 8(sp)')
code(' ld sp, 0(sp)')
code(' ret')
for name, h in self.rel_sections.items():
debug("Accept section '%s'", name)
if name.startswith('.bss'):
code(' .local unicore32%s' % name)
code(' .comm unicore32%s, %d, %d' % (name, h.sh_size, h.sh_addralign))
continue
if name.startswith('.text'):
code(' .text')
else:
code(' .data')
code(' .align 4')
code('unicore32%s:' % name)
begin, end = h.get_bound()
for i in range(begin, end, 4):
if name == '.text' and i - begin == self.entrypoint.st_value:
code('unicore32.entrypoint:')
code(' .word 0x%08x' % struct.unpack('I', content[i:i + 4]))
code('')
return '\n'.join(codes)
class RISCV64Exe:
def __init__(self, content: bytes):
# parse header
self.elf_header = ELFHeader64(content)
self.section_headers = []
for i in range(self.elf_header.e_shnum):
offset = self.elf_header.e_shoff + self.elf_header.e_shentsize * i
self.section_headers.append(SectionHeader64(content, offset))
self.program_headers = []
for i in range(self.elf_header.e_phnum):
offset = self.elf_header.e_phoff + self.elf_header.e_phentsize * i
self.program_headers.append(ProgramHeader64(content, offset))
begin, end = self.section_headers[self.elf_header.e_shstrndx].get_bound()
self.shstrtab = StrTab(content[begin:end])
self.section_header_table = {}
for i, h in enumerate(self.section_headers):
sh_name = self.shstrtab[h.sh_name]
self.section_header_table[sh_name] = h
# parse sections
self.symtab = []
begin, end = self.section_header_table['.symtab'].get_bound()
for i in range(begin, end, SymTabEntry64.size):
self.symtab.append(SymTabEntry64(content, i))
begin, end = self.section_header_table['.strtab'].get_bound()
self.strtab = StrTab(content[begin:end])
self.symtab_table = {}
for e in self.symtab:
name = self.strtab[e.st_name]
self.symtab_table[name] = e
def get_offset(self, vaddr: int):
for h in self.program_headers:
if vaddr >= h.p_vaddr and vaddr < h.p_vaddr + h.p_memsz:
return vaddr - h.p_vaddr + h.p_offset
panic('Virtual address 0x%016x is beyond the address space', vaddr)
if __name__ == '__main__':
args = parser.parse_args()
# extract necessary sections from uc32 elf
with open(args.path, 'rb') as f:
content = f.read()
uc32_elf = UniCore32ELF(content)
uc32_elf.set_entrypoint(args.entrypoint)
asm = uc32_elf.format_asm(args.warmup, args.hpm_counter)
asm_hash = hashlib.sha256(asm.encode('utf-8')).digest()
asm_uid = base64.b64encode(asm_hash[:6], b'01').decode('utf-8')
asm_path = asm_uid + '.s'
with open(asm_path, 'w') as f:
f.write(asm)
atexit.register(os.remove, asm_path)
# compile into rv64 executable
exe_path = asm_uid + '.out'
cmd = ['riscv64-unknown-elf-gcc',
'-march=rv64g', '-mabi=lp64d', '-mcmodel=medany',
'-I.', '-O3',
'-nostdlib', '-nostartfiles', '-Tlink.ld', '-static',
'-o', exe_path, asm_path, 'lib/crt.S', 'lib/syslib.c']
p = subprocess.Popen(cmd)
if p.wait():
exit(p.returncode)
atexit.register(os.remove, exe_path)
# do relocation on rv64 executable
with open(exe_path, 'rb') as f:
content = f.read()
rv64_exe = RISCV64Exe(content)
# relocate
out = io.BytesIO(content)
for rel_name, rel_table in uc32_elf.rel_tables.items():
from_sec_vaddr = rv64_exe.symtab_table['unicore32' + rel_name].st_value
from_sec_offset = rv64_exe.get_offset(from_sec_vaddr)
for e in rel_table:
sym = uc32_elf.symtab[e.r_sym]
name = uc32_elf.strtab[sym.st_name]
try:
sec = uc32_elf.section_headers[sym.st_shndx]
except IndexError:
panic("Symbol '%s' doesn't belong to any section. Try make it static", name)
sec_name = uc32_elf.shstrtab[sec.sh_name]
to_sym = rv64_exe.symtab_table.get('unicore32' + sec_name)
if to_sym is None:
panic("Cannot relocate symbol '%s' in section '%s'", name, sec_name)
to_sym_offset = rv64_exe.get_offset(to_sym.st_value)
if e.r_type == RelEntry.R_UNICORE32_PC24:
from_vaddr = from_sec_vaddr + e.r_offset
from_offset = from_sec_offset + e.r_offset
to_vaddr = to_sym.st_value + sym.st_value
pc_offset = ((to_vaddr - from_vaddr - 4) >> 2) & 0xffffff
out.seek(from_offset)
out.write(pc_offset.to_bytes(3, 'little'))
debug('Relocate PC24 0x%08x (%s+0x%x) to 0x%08x (%s+0x%x)',
from_offset, rel_name, e.r_offset, to_vaddr, sec_name, sym.st_value)
elif e.r_type == RelEntry.R_UNICORE32_ABS32:
from_offset = from_sec_offset + e.r_offset
out.seek(from_offset)
offset, = struct.unpack('I', out.read(4))
to_vaddr = to_sym.st_value + offset
out.seek(from_offset)
out.write(to_vaddr.to_bytes(4, 'little'))
debug('Relocate ABS32 0x%08x (%s+0x%x) to 0x%08x (%s+0x%x)',
from_offset, rel_name, e.r_offset, to_vaddr, sec_name, offset)
else:
panic("Unknown relocation type: %d", e.r_type)
out.seek(0)
with open(args.output, 'wb') as f:
f.write(out.read())
os.chmod(args.output, 0o755)