| 1 |
import os, sys |
| 2 |
from rpython.tool.udir import udir |
| 3 |
import tempfile |
| 4 |
|
| 5 |
class ASMInstruction(object): |
| 6 |
|
| 7 |
asm_opts = '-march=armv8-a' |
| 8 |
body = """.section .text |
| 9 |
_start: .global _start |
| 10 |
.global main |
| 11 |
b main |
| 12 |
main: |
| 13 |
.ascii "START " |
| 14 |
%s |
| 15 |
.ascii "END " |
| 16 |
""" |
| 17 |
begin_tag = 'START ' |
| 18 |
end_tag = 'END ' |
| 19 |
base_name = 'test_%d.asm' |
| 20 |
index = 0 |
| 21 |
|
| 22 |
def __init__(self, instr): |
| 23 |
self.instr = instr |
| 24 |
self.file = udir.join(self.base_name % self.index) |
| 25 |
while self.file.check(): |
| 26 |
self.index += 1 |
| 27 |
self.file = udir.join(self.base_name % self.index) |
| 28 |
|
| 29 |
def encode(self): |
| 30 |
f = open("%s/a.out" % (udir),'rb') |
| 31 |
data = f.read() |
| 32 |
f.close() |
| 33 |
i = data.find(self.begin_tag) |
| 34 |
assert i>=0 |
| 35 |
j = data.find(self.end_tag, i) |
| 36 |
assert j>=0 |
| 37 |
as_code = data[i+len(self.begin_tag):j] |
| 38 |
return as_code |
| 39 |
|
| 40 |
def assemble(self, *args): |
| 41 |
res = self.body % (self.instr) |
| 42 |
self.file.write(res) |
| 43 |
if sys.platform == 'darwin': |
| 44 |
fatal_warnings = '' |
| 45 |
else: |
| 46 |
fatal_warnings = '--fatal-warnings' |
| 47 |
os.system("as " + fatal_warnings + " %s %s -o %s/a.out" % (self.asm_opts, self.file, udir)) |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
def assemble(instr): |
| 53 |
a = ASMInstruction(instr) |
| 54 |
a.assemble(instr) |
| 55 |
return a.encode() |