| 1 | |
| 2 | import os |
| 3 | import tempfile |
| 4 | |
| 5 | as = "/usr/ccs/bin/as" |
| 6 | dis = "/usr/ccs/bin/dis" |
| 7 | grep = "/bin/egrep" |
| 8 | |
| 9 | class AssemblerError(Exception): |
| 10 | def __init__(self,*args): |
| 11 | Exception.__init__(self,args) |
| 12 | |
| 13 | |
| 14 | def asm(instr): |
| 15 | """ |
| 16 | asm() takes a string of assembly code and produces a list of |
| 17 | instruction words. When asm() is passed a list of strings it |
| 18 | will produce a list of list of instruction words. For example |
| 19 | asm('done;nop') returns [0x81f00000,0x1000000] and |
| 20 | asm(['done','nop']) returns [[0x81f00000],[0x1000000]]. |
| 21 | """ |
| 22 | if type(instr) == list: |
| 23 | result = [] |
| 24 | [result.append(asm_instr(i)) for i in instr] |
| 25 | else: |
| 26 | result = asm_instr(instr) |
| 27 | return result |
| 28 | |
| 29 | |
| 30 | def asm_instr(instr): |
| 31 | s_list = [] |
| 32 | |
| 33 | s_name = tempfile.mktemp(suffix=".s") |
| 34 | o_name = tempfile.mktemp(suffix=".o") |
| 35 | d_name = tempfile.mktemp(suffix=".d") |
| 36 | e_name = tempfile.mktemp(suffix=".2") |
| 37 | t_name = tempfile.mktemp(suffix=".t") |
| 38 | |
| 39 | s_file = open(s_name,'w') |
| 40 | s_file.writelines([ |
| 41 | ".register %g2,#scratch\n", |
| 42 | ".register %g3,#scratch\n", |
| 43 | ".register %g6,#scratch\n", |
| 44 | ".register %g7,#scratch\n", |
| 45 | "main:\n", |
| 46 | instr]) |
| 47 | s_file.write("\n") |
| 48 | s_file.close() |
| 49 | |
| 50 | s_exec = "%s -xarch=v9c -o %s %s 2> %s" % (as,o_name,s_name,e_name) |
| 51 | if os.system(s_exec) == 0: |
| 52 | d_exec = "%s %s | /bin/awk '{print $2$3$4$5}' | %s '^[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]' > %s 2> /dev/null" % (dis,o_name,grep,d_name) |
| 53 | if os.system(d_exec) == 0: |
| 54 | d_file = open(d_name) |
| 55 | s_list = [int(nr,16) for nr in d_file.readlines()] |
| 56 | d_file.close() |
| 57 | os.unlink(d_name) |
| 58 | os.unlink(s_name) |
| 59 | os.unlink(o_name) |
| 60 | else: |
| 61 | os.unlink(s_name) |
| 62 | t_exec = "/bin/sed -e 's/[^:]*:[^:]*:\ //g' %s > %s" % (e_name,t_name) |
| 63 | os.system(t_exec) |
| 64 | t_file = open(t_name,'r') |
| 65 | x = t_file.readlines() |
| 66 | t_file.close() |
| 67 | raise AssemblerError(x) |
| 68 | return s_list |
| 69 | |
| 70 | |
| 71 | if __name__ == '__main__': |
| 72 | print asm("adx %g0, %g1, %g2") |
| 73 | print asm("add %g4, %g5, %g3\nadd %g0, %g1, %g2") |
| 74 | try: |
| 75 | print asm(['add %g0, %g1, %o6', 'asd %g7, %g6, %g2']) |
| 76 | except AssemblerError, e: |
| 77 | print e |
| 78 | |
| 79 | |
| 80 | |
| 81 | |