Skip to content

Instantly share code, notes, and snippets.

@jayendra13
Created December 24, 2021 03:33
Show Gist options
  • Save jayendra13/2c007e5b1f2ee91e240ebeeebe070138 to your computer and use it in GitHub Desktop.
Save jayendra13/2c007e5b1f2ee91e240ebeeebe070138 to your computer and use it in GitHub Desktop.
import mmap
from cffi import FFI
"""
add.c
double add(double a, double b) {
return a+b
}
~$ gcc -O3 -c add.c
~$ objdump -d add.o
add.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <add>:
0: f2 0f 58 c1 addsd %xmm1,%xmm0
4: c3 retq
"""
# put binary code in buffer
code = b"\xf2\x0f\x58\xc1\xc3"
buf = mmap.mmap(-1, len(code), mmap.MAP_PRIVATE, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
# make ffi
ffi = FFI()
ffi.cdef("typedef double (*fn)(double, double);")
# get pointer to the code
fptr = ffi.cast("fn", ffi.from_buffer(buf))
# execute the code
print(fptr(4,4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment