oisc8asm.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import argparse
  2. import sys
  3. import math
  4. from os import path, mkdir
  5. import asm_compiler as compiler
  6. from asm_compiler import InstructionError, CompilingError
  7. class Compiler(compiler.Compiler):
  8. def compile(self, file, code):
  9. sections = super(Compiler, self).compile(file, code)
  10. return sections
  11. # if '.text' in sections:
  12. # width, length, size, data = sections['.text']
  13. def decompile(self, binary):
  14. addr = 0
  15. res = []
  16. ibin = iter(binary)
  17. for data in ibin:
  18. src = int(next(ibin))
  19. imm = ((data & 16) >> 4) == 1
  20. dst = data & 15
  21. dst_name = None
  22. for instr in self.instr_db.values():
  23. if instr.opcode == dst:
  24. dst_name = instr.name.upper()
  25. if dst_name is None:
  26. dst_name = "0x" + format(dst, '02x')
  27. asm = f'{addr:04x}: {dst_name.ljust(6)}'
  28. src_name = "0x" + format(src, '02x')
  29. if not imm and src in instrSrc:
  30. src_name = instrSrc[src][-1]
  31. line = asm + ' ' + src_name
  32. tabs = ' ' * (27 - int(len(line)))
  33. raw = format(data, '02x') + format(src, '02x')
  34. res.append(f'{line}{tabs}[{raw}]')
  35. addr += 1
  36. return '\n'.join(res)
  37. asmc = Compiler(byte_order='big')
  38. instrSrc = {
  39. 0: ["NULL"],
  40. 1: ["ALUACC0R", "ALU0"],
  41. 2: ["ALUACC1R", "ALU1"],
  42. 3: ["ADD"],
  43. 4: ["ADDC"],
  44. 5: ["SUB"],
  45. 6: ["SUBC"],
  46. 7: ["AND"],
  47. 8: ["OR"],
  48. 9: ["XOR"],
  49. 10: ["SLL"],
  50. 11: ["SRL"],
  51. 12: ["EQ"],
  52. 13: ["GT"],
  53. 14: ["GE"],
  54. 15: ["NE"],
  55. 16: ["LT"],
  56. 17: ["LE"],
  57. 18: ["MULLO"],
  58. 19: ["MULHI"],
  59. 20: ["DIV"],
  60. 21: ["MOD"],
  61. 22: ["BRPT0R", "BR0"],
  62. 23: ["BRPT1R", "BR1"],
  63. 24: ["PC0"],
  64. 25: ["PC1"],
  65. 26: ["MEMPT0R", "MEM0"],
  66. 27: ["MEMPT1R", "MEM1"],
  67. 28: ["MEMPT2R", "MEM2"],
  68. 29: ["MEMLWHI", "LWHI", "MEMHI"],
  69. 40: ["MEMLWLO", "LWLO", "MEMLO"],
  70. 31: ["STACKR", "STACK"],
  71. 32: ["STACKPT0", "STPT0"],
  72. 33: ["STACKPT1", "STPT1"],
  73. 34: ["COMAR", "COMA"],
  74. 35: ["COMDR", "COMD"],
  75. 36: ["REG0R", "REG0"],
  76. 37: ["REG1R", "REG1"],
  77. 38: ["ADC"],
  78. 39: ["SBC"],
  79. }
  80. instrMap = {}
  81. for i, v in instrSrc.items():
  82. for n in v:
  83. instrMap[n.lower()] = i
  84. class InstructionDest:
  85. def __init__(self, name: str, opcode: int, alias=None):
  86. name = name.strip().lower()
  87. if not name or not name.isalnum():
  88. raise InstructionError(f"Invalid instruction name '{name}'")
  89. self.name = name.strip()
  90. self.alias = alias or []
  91. self.opcode = opcode
  92. self.imm_operands = 1
  93. self.reg_operands = 0
  94. self.compiler = None
  95. @property
  96. def length(self):
  97. return 1
  98. def __len__(self):
  99. return 1
  100. def compile(self, operands, scope):
  101. if len(operands) != 1:
  102. raise CompilingError(f"Instruction has invalid amount of operands")
  103. if operands[0].lower() in instrMap:
  104. src = instrMap[operands[0].lower()]
  105. immediate = 0
  106. else:
  107. imm = self.compiler.decode_with_labels(operands, scope)
  108. if len(imm) != 1:
  109. raise CompilingError(f"Instruction immediate is {len(imm)} in length. It must be 1.")
  110. immediate = 1
  111. src = imm[0]
  112. return (immediate << 12 | self.opcode << 8 | src).to_bytes(2, self.compiler.order)
  113. asmc.add_instr(InstructionDest("ALU0", 0, alias=["ALUACC0"]))
  114. asmc.add_instr(InstructionDest("ALU1", 1, alias=["ALUACC1"]))
  115. asmc.add_instr(InstructionDest("BR0", 2, alias=["BRPT0"]))
  116. asmc.add_instr(InstructionDest("BR1", 3, alias=["BRPT1"]))
  117. asmc.add_instr(InstructionDest("BRZ", 4))
  118. asmc.add_instr(InstructionDest("STACK", 5))
  119. asmc.add_instr(InstructionDest("MEM0", 6, alias=["MEMPT0"]))
  120. asmc.add_instr(InstructionDest("MEM1", 7, alias=["MEMPT1"]))
  121. asmc.add_instr(InstructionDest("MEM2", 8, alias=["MEMPT2"]))
  122. asmc.add_instr(InstructionDest("SWHI", 9, alias=["MEMSWHI", "MEMHI"]))
  123. asmc.add_instr(InstructionDest("SWLO", 10, alias=["MEMSWLO", "MEMLO"]))
  124. asmc.add_instr(InstructionDest("COMA", 11))
  125. asmc.add_instr(InstructionDest("COMD", 12))
  126. asmc.add_instr(InstructionDest("REG0", 13))
  127. asmc.add_instr(InstructionDest("REG1", 14))
  128. if __name__ == '__main__':
  129. parser = argparse.ArgumentParser(description='Assembly compiler', add_help=True)
  130. parser.add_argument('file', help='Files to compile')
  131. parser.add_argument('-t', '--output_type', choices=['bin', 'mem', 'binary', 'mif', 'uhex'], default='mem',
  132. help='Output type')
  133. parser.add_argument('-S', '--slice', default=-1, type=int, help='Slice output for section')
  134. parser.add_argument('-o', '--output', help='Output directory')
  135. parser.add_argument('-f', '--force', action='store_true', help='Force override output file')
  136. parser.add_argument('-s', '--stdout', action='store_true', help='Print to stdout')
  137. parser.add_argument('-D', '--decompile', action='store_true', help='Print decompiled')
  138. parser.add_argument('section', help='Section')
  139. args = parser.parse_args(sys.argv[1:])
  140. if not path.isfile(args.file):
  141. print(f'No file {args.file}!')
  142. sys.exit(1)
  143. output_dir = args.output or path.dirname(args.file)
  144. if not path.exists(output_dir):
  145. mkdir(output_dir)
  146. if args.output_type == 'mem':
  147. ext = '.mem'
  148. elif args.output_type == 'bin':
  149. ext = '.bin'
  150. elif args.output_type == 'mif':
  151. ext = '.mif'
  152. elif args.output_type == 'uhex':
  153. ext = '.uhex'
  154. else:
  155. ext = '.out'
  156. bname = path.basename(args.file).rsplit('.', 1)[0]
  157. sformat = f'01d'
  158. outputs = []
  159. if args.slice > 0:
  160. sformat = f'0{int(math.log10(args.slice)) + 1}d'
  161. for i in range(0, args.slice):
  162. outputs.append(path.join(output_dir, f'{bname}{args.section}_{format(i, sformat)}{ext}'))
  163. else:
  164. outputs = [path.join(output_dir, bname + args.section + ext)]
  165. if not args.stdout and not args.force:
  166. for output in outputs:
  167. if path.isfile(output):
  168. print(f'Output file already exists {output}!')
  169. sys.exit(1)
  170. data = asmc.compile_file(args.file)
  171. if data is not None:
  172. section = args.section
  173. if section in data:
  174. width, length, size, bdata = data[section]
  175. asize = len(bdata)
  176. if size > 0:
  177. bdataf = bdata + (size - len(bdata)) * bytearray(b'\x00')
  178. else:
  179. bdataf = bdata
  180. for i, output in enumerate(outputs):
  181. y = bdataf[i::len(outputs)]
  182. if args.output_type == 'binary':
  183. x = compiler.convert_to_binary(y)
  184. elif args.output_type == 'mem':
  185. x = compiler.convert_to_mem(y, width=width)
  186. elif args.output_type == 'mif':
  187. x = compiler.convert_to_mif(y, width=width, depth=len(y)/width)
  188. elif args.output_type == 'uhex':
  189. x = compiler.convert_to_mem(y, width=width, uhex=True)
  190. else:
  191. x = bytes(y)
  192. op = 'Printing' if args.stdout else 'Saving'
  193. print(f"{op} {args.output_type} {section} data '{output}' [Size: {len(y)}B Slice: {format(i + 1, sformat)}/{len(outputs)}]")
  194. if args.stdout:
  195. if args.decompile:
  196. print(asmc.decompile(bdata))
  197. else:
  198. print(x.decode())
  199. else:
  200. with open(output, 'wb') as of:
  201. of.write(x)
  202. print(f"Total {section} size: {len(bdata) / len(bdataf) * 100:.1f}% [{len(bdata)}B/{len(bdataf)}B]")
  203. else:
  204. print(f'No such section {section}!')
  205. else:
  206. print(f'Failed to compile {args.file}!')
  207. sys.exit(1)
  208. sys.exit(0)