Created
April 29, 2012 05:21
-
-
Save 7shi/2533658 to your computer and use it in GitHub Desktop.
PythonでJIT
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
from ctypes import * | |
libc = cdll.LoadLibrary("libc.dylib") | |
mmap = libc.mmap | |
mmap.restype = c_void_p | |
munmap = libc.munmap | |
munmap.argtype = [c_void_p, c_size_t] | |
PROT_READ = 1 | |
PROT_WRITE = 2 | |
PROT_EXEC = 4 | |
MAP_PRIVATE = 2 | |
MAP_ANON = 0x1000 | |
codes = (c_ubyte * 32)( | |
0x48, 0x89, 0xf8, # mov rax, rdi | |
0x48, 0x01, 0xf0, # add rax, rsi | |
0xc3, # ret | |
) | |
buflen = len(codes) | |
p = mmap(0, buflen, | |
PROT_READ | PROT_WRITE | PROT_EXEC, | |
MAP_PRIVATE | MAP_ANON, -1, 0) | |
memmove(p, addressof(codes), buflen) | |
f = CFUNCTYPE(c_int, c_int, c_int)(p) | |
print "f(1, 2) = %d" % f(1, 2) | |
munmap(p, buflen) |
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
from ctypes import * | |
import sys | |
VirtualAlloc = windll.kernel32.VirtualAlloc | |
VirtualFree = windll.kernel32.VirtualFree | |
MEM_COMMIT = 0x1000 | |
MEM_RELEASE = 0x8000 | |
PAGE_EXECUTE_READWRITE = 0x40 | |
putchar = CFUNCTYPE(None, c_int)( | |
lambda ch: sys.stdout.write(chr(ch))) | |
codes = (c_ubyte * 32)( | |
0x6a, 0x41, # push 65 | |
0xff, 0x54, 0x24, 0x08, # call [esp+8] | |
0x83, 0xc4, 0x04, # add esp, 4 | |
0xc3, # ret | |
) | |
buflen = len(codes) | |
p = VirtualAlloc(0, buflen, MEM_COMMIT, PAGE_EXECUTE_READWRITE) | |
memmove(p, addressof(codes), buflen) | |
f = CFUNCTYPE(None, c_void_p)(p) | |
f(putchar) | |
VirtualFree(p, 0, MEM_RELEASE) |
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
from ctypes import * | |
VirtualAlloc = windll.kernel32.VirtualAlloc | |
VirtualFree = windll.kernel32.VirtualFree | |
MEM_COMMIT = 0x1000 | |
MEM_RELEASE = 0x8000 | |
PAGE_EXECUTE_READWRITE = 0x40 | |
codes = (c_ubyte * 32)( | |
0x8b, 0x44, 0x24, 0x04, # mov eax, [esp+4] | |
0x03, 0x44, 0x24, 0x08, # add eax, [esp+8] | |
0xc3, # ret | |
) | |
buflen = len(codes) | |
p = VirtualAlloc(0, buflen, MEM_COMMIT, PAGE_EXECUTE_READWRITE) | |
memmove(p, addressof(codes), buflen) | |
f = CFUNCTYPE(c_int, c_int, c_int)(p) | |
print "f(1, 2) = %d" % f(1, 2) | |
VirtualFree(p, 0, MEM_RELEASE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment