This code works on linux and prints 43, how could I code a script with similar functionality to be run on windows without errors?
import ctypes
import mmap
buf = mmap.mmap(-1, mmap.PAGESIZE, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
ftype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
fpointer = ctypes.c_void_p.from_buffer(buf)
f = ftype(ctypes.addressof(fpointer))
buf.write(
b'\x8b\xc7' # mov eax, edi
b'\x83\xc0\x01' # add eax, 1
b'\xc3' # ret
)
r = f(42)
print(r)
del fpointer
buf.close()
When I change the line:
buf = mmap.mmap(-1, mmap.PAGESIZE, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
to
buf = mmap.mmap(-1, mmap.PAGESIZE, tagname=None, access=mmap.ACCESS_DEFAULT)
the python interpreter outputs the error:
OSError: exception: access violation writing 0x00EC0000
Does anyone know how to correct this code so it runs properly? The desired output should be "43".
FILE_MAP_EXECUTE
andPAGE_EXECUTE_*
constants in Windows XP SP2. However, Python 3.5+ only supports Vista and later, so someone could submit a patch to extend theaccess
parameter to support execute access. There's nothing preventing this in principle. Note that we already have support for this kind of operation in ctypes in order to allow calling Python callbacks from C, which requires storing a small stub function assembled in executable memory that sets up the call into the interpreter. – Vindicate