Created
February 9, 2019 13:00
-
-
Save mic-e/5e2007c820e17c0911c34c3b7039cad2 to your computer and use it in GitHub Desktop.
Machine code <-> Assembly translator using binutils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import re | |
import subprocess | |
def tmppath(what): | |
return "/tmp/machcode-" + what | |
def tool(which, prefix="arm-none-eabi-"): | |
return prefix + which | |
def call_tool(which, *args): | |
subprocess.check_call([tool(which)] + list(args)) | |
def init_readline(): | |
import readline | |
import atexit | |
import os | |
readline.set_history_length(1000) | |
history = os.path.expanduser("~/.machcode_history") | |
def save_history(): | |
readline.write_history_file(history) | |
atexit.register(save_history) | |
if os.path.exists(history): | |
readline.read_history_file(history) | |
def disassemble(code): | |
code = code.replace(' ', '').replace('\n', '').replace('\t', '').lower() | |
if len(code) % 2 != 0: | |
raise ValueError("not an even number of nibbles") | |
blob = bytes(int(code[i:i+2], 16) for i in range(0, len(code), 2)) | |
with open(tmppath("blob"), "wb") as fileobj: | |
fileobj.write(blob) | |
call_tool("objdump", "-D", "-marm", "-Mforce-thumb", "-b", "binary", tmppath("blob")) | |
def assemble(code): | |
code = code.replace('\\n', '\n') | |
with open(tmppath("code.S"), "w") as fileobj: | |
fileobj.write(code) | |
fileobj.write("\n") | |
call_tool("as", "-mthumb", "-o", tmppath("obj.o"), tmppath("code.S")) | |
call_tool("objdump", "-d", tmppath("obj.o")) | |
def handle(code): | |
machinecode_re = re.compile("^[\s0-9a-fA-F]+$") | |
try: | |
if machinecode_re.match(code) is not None: | |
disassemble(code) | |
else: | |
assemble(code) | |
except Exception as exc: | |
print("\x1b[31;1m%s\x1b[m" % (exc,)) | |
def main(): | |
init_readline() | |
while True: | |
try: | |
code = input("\x01\x1b[36m\x02(code)\x01\x1b[m\x02 ") | |
except EOFError: | |
print("") | |
break | |
except KeyboardInterrupt: | |
print("^C") | |
break | |
handle(code) | |
print("") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment