I have a simple byte array I’ve filled with a x86 -program. Which I need to execute at runtime.
"""
Produces a simple callable procedure which returns a constant.
"""
from array import array
simple = array('B')
# mov rax, 0x10
simple.extend((0x81, 0xc0, 0x10, 0x0, 0x0, 0x0))
# ret
simple.append(0xc3)
Now, to get this running, I’ll need to offload it into a memory region in my process that has PROT_EXEC flags. Also need to know the address of that memory region so I can call it. How could I do what I just described?
from ctypes import CFUNCTYPE, c_int
procedure = CFUNCTYPE(c_int)(program.address)
print "result correct: %r" % (procedure() == 0x10)
print "result: %r" % procedure()
Also, it might be useful to do this:
program[2] = 15
print "result correct: %r" % (procedure() == 15)
print "result: %r" % procedure()
I solved this on my own. Maybe there’s not much to say into it anyway.
I did a library for this. It’s a small wrapping around linux
mmap-command.mmap module provided by python weren’t sufficient. I couldn’t get the address out of an object. Instead I had to provide my own module for just doing that.
I also wrote an utility library for little-endian integers which supplements the toolchain:
It’s simple stuff. Here’s some usage example:
I think I’ll have fun with it. http://hg.boxbase.org/ will eventually host this module.
I’m Using opcode and instruction references to select instructions. Here’s few such references: