Created
March 15, 2015 20:45
-
-
Save tp7/e12143e48503f19398f0 to your computer and use it in GitHub Desktop.
Add two numbers in x86 assembly in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import mmap | |
import ctypes | |
def run(): | |
code_stream = mmap.mmap(-1, 4096, mmap.MAP_PRIVATE, | |
mmap.PROT_EXEC | mmap.PROT_READ | mmap.PROT_WRITE) | |
code_stream.write(b"\x01\xf7") # add edi, esi | |
code_stream.write(b"\x89\xf8") # mov eax, edi | |
code_stream.write(b"\xc3") # ret | |
code_address = ctypes.addressof(ctypes.c_void_p.from_buffer(code_stream)) | |
function_type = ctypes.CFUNCTYPE(ctypes.c_uint32, ctypes.c_int32, ctypes.c_int32) | |
add_numbers = function_type(code_address) | |
assert add_numbers(121, 27) == 148 | |
if __name__ == "__main__": | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment