Created
December 22, 2018 10:07
-
-
Save marcan/6ff215135d38eced7bc7d7d46d60e979 to your computer and use it in GitHub Desktop.
Python module to assemble snippets of code
This file contains hidden or 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 python | |
import os, tempfile, shutil, subprocess | |
class AsmException(Exception): | |
pass | |
class BaseAsm(object): | |
def __init__(self, source, addr = 0): | |
self.source = source | |
self._tmp = tempfile.mkdtemp() + os.sep | |
self.addr = addr | |
self.compile(source) | |
def compile(self, source): | |
self.sfile = self._tmp + "b.S" | |
with open(self.sfile, "w") as fd: | |
fd.write(self.HEADER + "\n") | |
fd.write(source + "\n") | |
fd.write(self.FOOTER + "\n") | |
self.elffile = self._tmp + "b.elf" | |
self.bfile = self._tmp + "b.b" | |
self.nfile = self._tmp + "b.n" | |
subprocess.check_call("%sgcc %s -Ttext=0x%x -o %s %s" % (self.PREFIX, self.CFLAGS, self.addr, self.elffile, self.sfile), shell=True) | |
subprocess.check_call("%sobjcopy -j.text -O binary %s %s" % (self.PREFIX, self.elffile, self.bfile), shell=True) | |
subprocess.check_call("%snm %s > %s" % (self.PREFIX, self.elffile, self.nfile), shell=True) | |
with open(self.bfile, "rb") as fd: | |
self.data = fd.read() | |
with open(self.nfile) as fd: | |
for line in fd: | |
line = line.replace("\n", "") | |
addr, type, name = line.split() | |
addr = int(addr, 16) | |
setattr(self, name, addr) | |
self.start = self._start | |
self.len = len(self.data) | |
self.end = self.start + self.len | |
def objdump(self): | |
subprocess.check_call("%sobjdump -rd %s" % (self.PREFIX, self.elffile), shell=True) | |
def __del__(self): | |
if self._tmp: | |
shutil.rmtree(self._tmp) | |
self._tmp = None | |
class ARMAsm(BaseAsm): | |
PREFIX = os.path.join("arm-none-eabi-") | |
CFLAGS = "-mcpu=cortex-m3 -pipe -Wall -nostartfiles -nodefaultlibs" | |
HEADER = """ | |
.text | |
.arm | |
.globl _start | |
_start: | |
""" | |
FOOTER = """ | |
.pool | |
""" | |
class THUMBAsm(ARMAsm): | |
HEADER = ARMAsm.HEADER.replace(".arm", ".thumb") | |
CFLAGS = ARMAsm.CFLAGS + " -mthumb" | |
if __name__ == "__main__": | |
code = """ | |
ldr r0, =0xDEADBEEF | |
b test | |
svc 1 | |
test: | |
b test | |
""" | |
c = ARMAsm(code, 0x1234) | |
c.objdump() | |
assert c.start == 0x1234 | |
assert c.test == 0x1240 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment