asm_compiler.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. #!/usr/bin/python3
  2. import re
  3. import math
  4. import traceback
  5. from typing import Dict, List
  6. label_re = re.compile(r"^[\w$#@~.?]+$", re.IGNORECASE)
  7. hex_re = re.compile(r"^[0-9a-f]+$", re.IGNORECASE)
  8. bin_re = re.compile(r"^[0-1_]+$", re.IGNORECASE)
  9. oct_re = re.compile(r"^[0-8]+$", re.IGNORECASE)
  10. args_re = re.compile("(?:^|,)(?=[^\"]|(\")?)\"?((?(1)[^\"]*|[^,\"]*))\"?(?=,|$)", re.IGNORECASE)
  11. func_re = re.compile("^([\w$#@~.?]+)\s*([|^<>+\-*/%@]{1,2})\s*([\w$#@~.?]+)$", re.IGNORECASE)
  12. secs_re = re.compile("^([\d]+)x([\d]+)x([\d]+)$", re.IGNORECASE)
  13. funcc_re = re.compile("^([\w$#@~.?]+)\(([\w,]+)\)(.*)", re.IGNORECASE)
  14. MAX_INT_BYTES = 12
  15. def args2operands(args):
  16. operands = ['"' + a[1] + '"' if a[0] == '"' else a[1] for a in args_re.findall(args or '') if a[1]]
  17. return operands
  18. def match(regex, s):
  19. return regex.match(s) is not None
  20. class CompilingError(Exception):
  21. def __init__(self, message):
  22. self.message = message
  23. class InstructionError(Exception):
  24. def __init__(self, message):
  25. self.message = message
  26. class Instruction:
  27. def __init__(self, name: str, opcode: str, operands=0, alias=None):
  28. name = name.strip().lower()
  29. if not name or not name.isalnum():
  30. raise InstructionError(f"Invalid instruction name '{name}'")
  31. self.name = name.strip()
  32. self.alias = alias or []
  33. self.reg_operands = 0
  34. opcode = opcode.replace('_', '')
  35. if len(opcode) == 8:
  36. if opcode[4:6] == '??':
  37. self.reg_operands += 1
  38. if opcode[6:8] == '??':
  39. self.reg_operands += 1
  40. else:
  41. raise CompilingError("Invalid opcode: " + opcode)
  42. self.opcode = int(opcode.replace('?', '0'), 2)
  43. self.imm_operands = operands
  44. self.compiler = None
  45. @property
  46. def length(self):
  47. return self.imm_operands + 1
  48. def __len__(self):
  49. return self.length
  50. def _gen_instr(self, regs):
  51. instr = self.opcode
  52. if len(regs) != self.reg_operands:
  53. raise CompilingError(f"Invalid number of registers: set {len(regs)}, required: {self.reg_operands}")
  54. if len(regs) == 2:
  55. if regs[1] is None:
  56. raise CompilingError(f"Unable to decode register name {regs[1]}")
  57. if regs[0] is None:
  58. raise CompilingError(f"Unable to decode register name {regs[0]}")
  59. instr |= regs[0] << 2 | regs[1]
  60. elif len(regs) == 1:
  61. if regs[0] is None:
  62. raise CompilingError(f"Unable to decode register name {regs[0]}")
  63. instr |= regs[0] << 2
  64. return instr.to_bytes(1, 'little') # Order does not matter with 1 byte
  65. def compile(self, operands, scope):
  66. regs = []
  67. for reg in operands[:self.reg_operands]:
  68. regs.append(self.compiler.decode_reg(reg))
  69. imm = self.compiler.decode_with_labels(operands[self.reg_operands:], scope)
  70. if len(imm) != self.imm_operands:
  71. raise CompilingError(f"Instruction {self.name} has invalid argument size {len(imm)} != {self.imm_operands},"
  72. f" supplied args: 0x{imm.hex()}")
  73. instr = self._gen_instr(regs)
  74. return instr + imm
  75. class Section:
  76. def __init__(self):
  77. self.instr = []
  78. self.data = b''
  79. self.count = 0
  80. self.width = 1
  81. self.length = 1
  82. self.size = 2**8
  83. class Compiler:
  84. def __init__(self, address_size=2, byte_order='little'):
  85. self.instr_db: Dict[str, Instruction] = {}
  86. self.data = []
  87. self.labels = {}
  88. self.macros = {}
  89. self.order = byte_order
  90. self.regnames = {}
  91. self.address_size = address_size
  92. def decode_reg(self, s: str):
  93. s = s.strip()
  94. if s in self.regnames:
  95. return self.regnames[s]
  96. raise CompilingError(f"Unrecognised register name: {s}")
  97. def decode_bytes(self, s: str):
  98. s = s.strip()
  99. typ = ""
  100. # Decimal numbers
  101. if (s.startswith('+') or s.startswith('-')) and s[1:].isnumeric():
  102. typ = 'int'
  103. elif s.isnumeric():
  104. typ = 'uint'
  105. elif s.endswith('d') and s[:-1].isnumeric():
  106. s = s[:-1]
  107. typ = 'uint'
  108. elif s.startswith('0d') and s[2:].isnumeric():
  109. s = s[2:]
  110. typ = 'uint'
  111. # Hexadecimal numbers
  112. elif s.startswith('0') and s.endswith('h') and match(hex_re, s[1:-1]):
  113. s = s[1:-1]
  114. typ = 'hex'
  115. elif (s.startswith('$0') or s.startswith('0x') or s.startswith('$0')) and match(hex_re, s[2:]):
  116. s = s[2:]
  117. typ = 'hex'
  118. # Octal numbers
  119. elif (s.endswith('q') or s.endswith('o')) and match(oct_re, s[:-1]):
  120. s = s[:-1]
  121. typ = 'oct'
  122. elif (s.startswith('0q') or s.startswith('0o')) and match(oct_re, s[2:]):
  123. s = s[2:]
  124. typ = 'oct'
  125. # Binary number
  126. elif (s.endswith('b') or s.endswith('y')) and match(bin_re, s[:-1]):
  127. s = s[:-1].replace('_', '')
  128. typ = 'bin'
  129. elif (s.startswith('0b') or s.startswith('0y')) and match(bin_re, s[2:]):
  130. s = s[2:].replace('_', '')
  131. typ = 'bin'
  132. # ASCII
  133. elif s.startswith("'") and s.endswith("'") and len(s) == 3:
  134. s = ord(s[1:-1]).to_bytes(1, self.order)
  135. typ = 'ascii'
  136. elif (s.startswith("'") and s.endswith("'")) or (s.startswith('"') and s.endswith('"')):
  137. s = s[1:-1].encode('utf-8').decode("unicode_escape").encode('utf-8')
  138. typ = 'string'
  139. # Convert with limits
  140. if typ == 'uint':
  141. numb = int(s)
  142. for i in range(1, MAX_INT_BYTES+1):
  143. if numb < 2 ** (i * 8):
  144. return numb.to_bytes(i, self.order)
  145. elif typ == 'int':
  146. numb = int(s)
  147. for i in range(1, MAX_INT_BYTES+1):
  148. if -2 ** (i * 7) < numb < 2 ** (i * 7):
  149. return numb.to_bytes(i, self.order)
  150. elif typ == 'hex':
  151. numb = int(s, 16)
  152. return numb.to_bytes(int(len(s) / 2) + len(s) % 2, self.order)
  153. elif typ == 'oct':
  154. numb = int(s, 8)
  155. for i in range(1, 9):
  156. if -2 ** (i * 7) < i < 2 ** (i * 8):
  157. return numb.to_bytes(i, self.order)
  158. elif typ == 'bin':
  159. numb = int(s, 2)
  160. return numb.to_bytes(int(len(s) / 8) + len(s) % 8, self.order)
  161. else:
  162. return s
  163. def _decode_labels(self, arg, scope):
  164. immx = self.decode_bytes(arg)
  165. if isinstance(immx, str):
  166. if immx.startswith('.'):
  167. immx = scope + immx
  168. if immx in self.labels:
  169. return self.labels[immx]
  170. else:
  171. raise CompilingError(f"Unknown label: {immx}")
  172. elif isinstance(immx, bytes):
  173. return immx
  174. def decode_with_labels(self, args, scope):
  175. data = b''
  176. for arg in args:
  177. if isinstance(arg, str):
  178. funcm = func_re.match(arg)
  179. if funcm is not None:
  180. g = funcm.groups()
  181. left = self._decode_labels(g[0], scope)
  182. right = self._decode_labels(g[2], scope)
  183. data += self.proc_func(left, right, g[1])
  184. continue
  185. data += self._decode_labels(arg, scope)
  186. return data
  187. def add_reg(self, name, val):
  188. self.regnames[name] = val
  189. self.regnames['$' + name] = val
  190. def add_instr(self, instr: Instruction):
  191. instr.compiler = self
  192. operands = instr.reg_operands + instr.imm_operands
  193. if instr.name in self.instr_db:
  194. raise InstructionError(f"Instruction {instr.name} operands={operands} duplicate!")
  195. self.instr_db[instr.name] = instr
  196. for alias in instr.alias:
  197. if alias.lower() in self.instr_db:
  198. raise InstructionError(f"Instruction alias {alias} operands={operands} duplicate!")
  199. self.instr_db[alias.lower()] = instr
  200. def proc_func(self, left, right, op):
  201. leftInt = int.from_bytes(left, self.order)
  202. rightInt = int.from_bytes(right, self.order)
  203. if op == '|':
  204. result = leftInt | rightInt
  205. elif op == '^':
  206. result = leftInt ^ rightInt
  207. elif op == '&':
  208. result = leftInt & rightInt
  209. elif op == '<<':
  210. result = leftInt << rightInt
  211. elif op == '>>':
  212. result = leftInt >> rightInt
  213. elif op == '+':
  214. result = leftInt + rightInt
  215. elif op == '-':
  216. result = leftInt - rightInt
  217. elif op == '*':
  218. result = leftInt * rightInt
  219. elif op == '/' or op == '//':
  220. result = leftInt // rightInt
  221. elif op == '%' or op == '%%':
  222. result = leftInt % rightInt
  223. elif op == '@':
  224. return bytes([left[len(left)-rightInt-1]])
  225. else:
  226. raise CompilingError(f"Invalid function operation {op}")
  227. return result.to_bytes(len(left), self.order)
  228. def __code_compiler(self, file, lnum, line_args, csect, scope):
  229. builtin_cmds = {'db', 'dbe'}
  230. if line_args[0].endswith(':') and label_re.match(line_args[0][:-1]) is not None:
  231. # Must be label
  232. label = line_args[0][:-1]
  233. line_args = line_args[1:]
  234. if label.startswith('.'):
  235. if scope is None:
  236. raise CompilingError(f"No local scope for {label}!")
  237. label = scope + label
  238. else:
  239. scope = label
  240. if label in self.labels:
  241. raise CompilingError(f"Label {label} duplicate")
  242. self.labels[label] = csect.count.to_bytes(csect.length, self.order)
  243. if len(line_args) == 0:
  244. return scope
  245. elif len(line_args) == 1:
  246. args = None
  247. else:
  248. args = line_args[1]
  249. instr_name = line_args[0].lower()
  250. # Builtin instructions
  251. if instr_name == 'db':
  252. data = self.decode_with_labels(args2operands(args), scope)
  253. if len(data) % csect.width != 0:
  254. fill = csect.width - (len(data) % csect.width)
  255. data += b'\x00' * fill
  256. csect.instr.append(data)
  257. csect.count += len(data) // csect.width
  258. return scope
  259. if instr_name == 'dbe':
  260. try:
  261. fill = int(args[0])
  262. except ValueError:
  263. raise CompilingError(f"Instruction 'dbe' invalid argument, must be a number")
  264. except IndexError:
  265. raise CompilingError(f"Instruction 'dbe' invalid argument count! Must be 1")
  266. if fill % csect.width != 0:
  267. fill += csect.width - (fill % csect.width)
  268. data = b'\x00' * fill
  269. csect.instr.append(data)
  270. csect.count += len(data) // csect.width
  271. return scope
  272. if instr_name in self.macros:
  273. argsp = args2operands(args)
  274. if len(argsp) != self.macros[instr_name][0]:
  275. raise CompilingError(f"Invalid macro argument count!")
  276. for slnum, sline in enumerate(self.macros[instr_name][1]):
  277. slnum += 1
  278. for i in range(len(argsp)):
  279. sline = [l.replace(f'%{i+1}', argsp[i]) for l in sline]
  280. try:
  281. scope = self.__code_compiler(file, lnum, sline, csect, scope)
  282. except CompilingError as e:
  283. print(f"ERROR {file}:{self.macros[instr_name][2] + slnum}: {e.message}")
  284. raise CompilingError(f"Previous error")
  285. return scope
  286. if instr_name not in self.instr_db:
  287. raise CompilingError(f"Instruction '{instr_name}' not recognised!")
  288. instr_obj = self.instr_db[instr_name.lower()]
  289. csect.instr.append((instr_obj, args, lnum, scope))
  290. csect.count += instr_obj.length
  291. return scope
  292. @staticmethod
  293. def __line_generator(code):
  294. for lnum, line in enumerate(code):
  295. lnum += 1
  296. line = line.split(';', 1)[0]
  297. line = re.sub(' +', ' ', line) # replace multiple spaces
  298. line = line.strip()
  299. line_args = [l.strip() for l in line.split(' ', 2)]
  300. # line_args = list(filter(lambda x: len(x) > 0, line_args))
  301. if len(line_args) == 0 or line_args[0] == '':
  302. continue
  303. yield lnum, line_args
  304. def compile_file(self, file):
  305. try:
  306. with open(file, 'r') as f:
  307. data = self.compile(file, f.readlines())
  308. return data
  309. except IOError:
  310. return None
  311. def compile(self, file, code):
  312. failure = False
  313. sections: Dict[str, Section] = {}
  314. csect = None
  315. scope = None
  316. macro = None
  317. for lnum, line_args in self.__line_generator(code):
  318. try:
  319. # Inside macro
  320. if macro is not None:
  321. if line_args[0].lower() == '%endmacro':
  322. macro = None
  323. continue
  324. self.macros[macro][1].append(line_args)
  325. continue
  326. # Section
  327. if line_args[0].lower() == 'section':
  328. if len(line_args) < 2:
  329. raise CompilingError(f"Invalid section arguments!")
  330. section_name = line_args[1].lower()
  331. if section_name not in sections:
  332. s = Section()
  333. if len(line_args) == 3:
  334. m = secs_re.match(line_args[2])
  335. if m is not None:
  336. g = m.groups()
  337. s.width = int(g[0])
  338. s.length = int(g[1])
  339. s.size = int(g[2])
  340. else:
  341. raise CompilingError(f"Invalid section argument: {line_args[2]}")
  342. sections[section_name] = s
  343. csect = sections[section_name]
  344. continue
  345. # Macros
  346. elif line_args[0].lower() == '%define':
  347. if len(line_args) != 3:
  348. raise CompilingError(f"Invalid %define arguments!")
  349. self.labels[line_args[1]] = self.decode_bytes(line_args[2])
  350. continue
  351. elif line_args[0].lower() == '%macro':
  352. if len(line_args) != 3:
  353. raise CompilingError(f"Invalid %macro arguments!")
  354. if line_args[1] in self.macros:
  355. raise CompilingError(f"Macro '{line_args[1]}' already in use")
  356. if not line_args[2].isdigit():
  357. raise CompilingError(f"%macro argument 2 must be a number")
  358. macro = line_args[1].lower()
  359. self.macros[macro] = (int(line_args[2]), [], lnum)
  360. continue
  361. elif line_args[0].lower() == '%include':
  362. if len(line_args) != 2:
  363. raise CompilingError(f"Invalid %include arguments!")
  364. raise CompilingError(f"%include is not implemented yet") # TODO: Complete
  365. continue
  366. if csect is None:
  367. raise CompilingError(f"No section defined!")
  368. scope = self.__code_compiler(file, lnum, line_args, csect, scope)
  369. except CompilingError as e:
  370. failure = True
  371. print(f"ERROR {file}:{lnum}: {e.message}")
  372. for section in sections.values():
  373. for instr_tuple in section.instr:
  374. if isinstance(instr_tuple, bytes):
  375. section.data += instr_tuple
  376. continue
  377. instr, args, lnum, scope = instr_tuple
  378. try:
  379. operands = args2operands(args)
  380. section.data += instr.compile(operands, scope)
  381. except CompilingError as e:
  382. failure = True
  383. print(f"ERROR {file}:{lnum}: {e.message}")
  384. if failure:
  385. return None
  386. return {k: (v.width, v.length, v.size, v.data) for k, v in sections.items()}
  387. def decompile(self, binary):
  388. addr = 0
  389. res = []
  390. ibin = iter(binary)
  391. for data in ibin:
  392. norm0 = int(data)
  393. norm1 = norm0 & int('11110011', 2)
  394. norm2 = norm0 & int('11110000', 2)
  395. for instr in self.instr_db.values():
  396. if not ((instr.reg_operands == 0 and norm0 == instr.opcode) or
  397. (instr.reg_operands == 1 and norm1 == instr.opcode) or
  398. (instr.reg_operands == 2 and norm2 == instr.opcode)):
  399. continue
  400. asm = f'{addr:04x}: {instr.name.upper().ljust(6)}'
  401. args = []
  402. raw = format(norm0, '02x')
  403. if instr.reg_operands > 0:
  404. args.append(f'r{(norm0 & 12) >> 2}')
  405. if instr.reg_operands > 1:
  406. args.append(f'r{(norm0 & 3)}')
  407. if instr.imm_operands > 0:
  408. b = '0x'
  409. for i in range(instr.imm_operands):
  410. try:
  411. bi = format(int(next(ibin)), '02x')
  412. except StopIteration:
  413. break
  414. b += bi
  415. raw += bi
  416. addr += 1
  417. args.append(b)
  418. line = asm + ', '.join(args)
  419. tabs = ' ' * (27 - int(len(line)))
  420. res.append(f'{line}{tabs}[{raw}]')
  421. break
  422. addr += 1
  423. return '\n'.join(res)
  424. def convert_to_binary(data):
  425. a = '\n'.join([format(i, '08b') for i in data])
  426. return a.encode()
  427. def convert_to_mem(data, width=1, uhex=False):
  428. x = b''
  429. if uhex:
  430. if width == 2:
  431. for i in range(int(len(data)/2)):
  432. x += format(data[-(i*2) - 2], f'02x').upper().encode()
  433. x += format(data[-(i*2) - 1], f'02x').upper().encode()
  434. else:
  435. for i in range(len(data)):
  436. x += format(data[-i-1], f'02x').upper().encode()
  437. return x
  438. if width == 2:
  439. datax = [(x << 8) | y for x, y in zip(data[0::2], data[1::2])]
  440. if len(data) % 2 == 1:
  441. datax.append(data[-1] << 8)
  442. else:
  443. datax = data
  444. fa = f'0{math.ceil(math.ceil(math.log2(len(datax))) / 4)}x'
  445. a = [format(d, f'0{width*2}x') for d in datax]
  446. for i in range(int(len(a) / 8) + 1):
  447. y = a[i * 8:(i + 1) * 8]
  448. if len(y) > 0:
  449. x += (' '.join(y) + ' ' * ((8 - len(y)) * 3) + ' // ' + format((i * 8 - 1) + len(y), fa) + '\n').encode()
  450. return x
  451. def convert_to_mif(data, depth=32, width=1):
  452. x = f'''-- auto-generated memory initialisation file
  453. DEPTH = {math.ceil(depth)};
  454. WIDTH = {width*8};
  455. ADDRESS_RADIX = HEX;
  456. DATA_RADIX = HEX;
  457. CONTENT
  458. BEGIN
  459. '''.encode()
  460. addr_format = f'0{math.ceil(int(math.log2(len(data))) / 4)}x'
  461. if width == 2:
  462. datax = [(x << 8) | y for x, y in zip(data[0::2], data[1::2])]
  463. if len(data) % 2 == 1:
  464. datax.append(data[-1] << 8)
  465. else:
  466. datax = data
  467. a = [format(i, f'0{width*2}x') for i in datax]
  468. for i in range(int(len(a*width) / 8) + 1):
  469. y = a[i * 8:(i + 1) * 8]
  470. if len(y) > 0:
  471. x += (format(i * 8, addr_format) + ' : ' + ' '.join(y) + ';\n').encode()
  472. x += b"END;"
  473. return x