3 takes powerpc assembly instructions and turns them into LE/BE binary
4 data. calls powerpc64-linux-gnu-as, ld and objcopy to do so.
12 from io
import BytesIO
15 filedir
= os
.path
.dirname(os
.path
.realpath(__file__
))
16 memmap
= os
.path
.join(filedir
, "memmap")
20 def __init__(self
, instructions
, bigendian
):
21 self
.bigendian
= bigendian
23 self
.endian_fmt
= "elf64-big"
28 self
.endian_fmt
= "elf64-little"
31 if isinstance(instructions
, bytes
): # actual bytes
32 self
.binfile
= BytesIO(instructions
)
33 self
.binfile
.name
= "assembly"
34 self
.assembly
= '' # noo disassemble number fiiive
35 elif isinstance(instructions
, str): # filename
36 # read instructions into a BytesIO to avoid "too many open files"
37 with
open(instructions
, "rb") as f
:
39 self
.binfile
= BytesIO(b
)
40 self
.assembly
= '' # noo disassemble number fiiive
41 print("program", self
.binfile
)
43 if isinstance(instructions
, list):
44 instructions
= '\n'.join(instructions
)
45 self
.assembly
= instructions
+ '\n' # plus final newline
47 self
._instructions
= list(self
._get
_instructions
())
52 def __exit__(self
, type, value
, traceback
):
55 def _get_binary(self
, elffile
):
56 self
.binfile
= tempfile
.NamedTemporaryFile(suffix
=".bin")
57 args
= ["powerpc64-linux-gnu-objcopy",
59 "-I", self
.endian_fmt
,
62 subprocess
.check_output(args
)
64 def _link(self
, ofile
):
65 with tempfile
.NamedTemporaryFile(suffix
=".elf") as elffile
:
66 args
= ["powerpc64-linux-gnu-ld",
71 subprocess
.check_output(args
)
72 self
._get
_binary
(elffile
)
75 with tempfile
.NamedTemporaryFile(suffix
=".o") as outfile
:
76 args
= ["powerpc64-linux-gnu-as",
81 p
= subprocess
.Popen(args
, stdin
=subprocess
.PIPE
)
82 p
.communicate(self
.assembly
.encode('utf-8'))
84 print("Error in program:")
89 def _get_instructions(self
):
91 data
= self
.binfile
.read(4)
94 yield struct
.unpack('<I', data
)[0] # unsigned int
96 def generate_instructions(self
):
97 yield from self
._instructions
103 curpos
= self
.binfile
.tell()
104 self
.binfile
.seek(0, 2) # Seek to end of file
105 size
= self
.binfile
.tell()
106 self
.binfile
.seek(curpos
, 0)