Ich suche bitte den Fehler in dieser Demo , weil bei :
r = f(42)
print (r)
der Wert "5" rauskommt oder ein anderer Wert der hier drin steht : b'\x83\xc0\x05'
statt 42+5
Wer kann bitte helfen?
Python 3.... und WIN10
Danke.
Code: Alles auswählen
import ctypes
asm_function = (
b'\x8b\xc1' # mov eax, ecx
b'\x83\xc0\x05' # add eax, 5
b'\xc3' # ret
)
# https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc#MEM_COMMIT
MEM_COMMIT = 0x00001000
# https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc#MEM_RESERVE
MEM_RESERVE = 0x00002000
# https://learn.microsoft.com/en-us/windows/win32/memory/memory-protection-constants#PAGE_EXECUTE_READWRITE
PAGE_EXECUTE_READWRITE = 0x40
# https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc
ctypes.windll.kernel32.VirtualAlloc.argtypes = (
ctypes.c_void_p, # LPVOID
ctypes.c_size_t, # SIZE_T
ctypes.c_long, # DWORD
ctypes.c_long, # DWORD
)
ctypes.windll.kernel32.VirtualAlloc.restype = ctypes.c_void_p # LPVOID
memory_buffer = ctypes.windll.kernel32.VirtualAlloc(
0, # lpAddress - NULL
len(asm_function), # dwSize
MEM_COMMIT | MEM_RESERVE, # flAllocationType
PAGE_EXECUTE_READWRITE # flProtect
)
if not memory_buffer: # VirtualAlloc returned NULL
print("VirtualAlloc call failed. Error code:", ctypes.GetLastError())
exit(-1)
c_buffer = ctypes.c_char_p(asm_function)
# https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlmovememory
ctypes.windll.kernel32.RtlMoveMemory.argtypes = (
ctypes.c_void_p, # VOID*
ctypes.c_void_p, # VOID*
ctypes.c_size_t # SIZE_T
)
ctypes.windll.kernel32.RtlMoveMemory(
memory_buffer, # Destination
c_buffer, # Source
len(asm_function) # Length
)
f = ctypes.cast(
memory_buffer,
ctypes.CFUNCTYPE(
ctypes.c_int, # return type
ctypes.c_int # argument type
)
)
r = f(42)
print(r)