github.com/cowsed/Parser@v0.0.0-20211216032244-48b10019d380/Other/testmain.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"syscall"
     6  	"unsafe"
     7  )
     8  
     9  func PrintHexBytes(s []byte) {
    10  	fmt.Print("[")
    11  	for i := range s {
    12  		fmt.Printf("0x%x ", s[i])
    13  	}
    14  	fmt.Println("]")
    15  }
    16  
    17  func main() {
    18  	mathFunction2 := []uint8{
    19  		//Setup stuff
    20  		0x48, 0x83, 0xec, 0x18, 0x48, 0x89, 0x6c, 0x24, 0x10, 0x48, 0x8d, 0x6c, 0x24, 0x10, 0x48, 0x89,
    21  		0x44, 0x24, 0x20, 0x48, 0x85, 0xdb, 0x76, 0x43,
    22  
    23  		//data[3]+data[0]+data[1]
    24  		0xf2, 0x0f, 0x10, 0x00, //MOVESD
    25  
    26  		//Returning stuff
    27  		0x48, 0x8b, 0x6c, 0x24, 0x10,
    28  		0x48, 0x83, 0xc4, 0x18, 0x90, 0xc3, 0xb8, 0x02, 0x00, 0x00, 0x00, 0x48, 0x89, 0xd9, 0xe8,
    29  	}
    30  	data := []float64{2, 2, 3, -8008, -8008}
    31  
    32  	f := MakeMathFunc(mathFunction2)
    33  
    34  	fmt.Println(f(data))
    35  }
    36  func MakeMathFunc(mathFunction []uint8) func([]float64) float64 {
    37  	type floatFunc func([]float64) float64
    38  
    39  	fmt.Println("function length", len(mathFunction))
    40  	if len(mathFunction) > 128 {
    41  		panic(fmt.Errorf("function too long for memory alloted"))
    42  	}
    43  	PrintHexBytes(mathFunction)
    44  
    45  	executablePrintFunc, err := syscall.Mmap(
    46  		-1,
    47  		0,
    48  		128,
    49  		syscall.PROT_READ|syscall.PROT_WRITE|syscall.PROT_EXEC,
    50  		syscall.MAP_PRIVATE|syscall.MAP_ANONYMOUS)
    51  	if err != nil {
    52  		fmt.Printf("mmap err: %v", err)
    53  	}
    54  
    55  	copy(executablePrintFunc, mathFunction) ///When going back this is where it gets switched out for debug function
    56  
    57  	PrintHexBytes(executablePrintFunc)
    58  
    59  	unsafePrintFunc := (uintptr)(unsafe.Pointer(&executablePrintFunc))
    60  	function := *(*floatFunc)(unsafe.Pointer(&unsafePrintFunc))
    61  	return function
    62  }