Skip to content

Instantly share code, notes, and snippets.

@karminski
Created February 23, 2021 09:44
Show Gist options
  • Save karminski/9bc59a0c261437e553e3d83cfaad6624 to your computer and use it in GitHub Desktop.
Save karminski/9bc59a0c261437e553e3d83cfaad6624 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"syscall"
"log"
"unsafe"
)
const MMAP_FLAGS = syscall.MAP_ANONYMOUS
type sum2 func(a int, b int) (r int)
func sum2f (a int, b int) (r int) {
fmt.Printf("a: %d \n", a)
fmt.Printf("b: %d \n", b)
r = a + b
return r
}
// function prototypes
type _call func(a int, b int, f sum2) (r int)
// type sum2 func(a int, b int) (r int)
func main() {
var m = []uint8{
0x64, 0x48, 0x8b, 0x0c, 0x25, 0x00, 0x00, 0x00, 0x00, 0x48, 0x3b, 0x61, 0x10, 0x76, 0x3c, 0x48,
0x83, 0xec, 0x28, 0x48, 0x89, 0x6c, 0x24, 0x20, 0x48, 0x8d, 0x6c, 0x24, 0x20, 0x48, 0x8b, 0x44,
0x24, 0x30, 0x48, 0x89, 0x04, 0x24, 0x48, 0x8b, 0x44, 0x24, 0x38, 0x48, 0x89, 0x44, 0x24, 0x08,
0x48, 0x8b, 0x44, 0x24, 0x40, 0x48, 0x89, 0x44, 0x24, 0x48, 0x48, 0x8b, 0x44, 0x24, 0x40, 0xff,
0xd0, 0x48, 0x8b, 0x6c, 0x24, 0x20, 0x48, 0x83, 0xc4, 0x28, 0xc3, 0xe8, 0x00, 0x00, 0x00, 0x00,
0xeb, 0xae,
}
// jit part
bin, err := syscall.Mmap(
-1,
0,
len(m),
syscall.PROT_READ | syscall.PROT_WRITE | syscall.PROT_EXEC,
syscall.MAP_PRIVATE | MMAP_FLAGS,
)
if err != nil {
log.Fatalf("mmap failed: %v", err)
}
for i, b := range m {
bin[i] = b
}
unsafeFunc := (uintptr)(unsafe.Pointer(&bin))
callFunc := *(*_call)(unsafe.Pointer(&unsafeFunc))
// run
var a int
var b int
var r int
a = 7
b = 9
r = 3
r = callFunc(a, b, sum2f)
fmt.Printf("a: %d \n", a)
fmt.Printf("b: %d \n", b)
fmt.Printf("r: %d \n", r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment