github.com/gbl08ma/monkey@v1.1.0/replace_unix.go (about)

     1  //+build !windows
     2  
     3  package monkey
     4  
     5  import (
     6  	"syscall"
     7  )
     8  
     9  func mprotectCrossPage(addr uintptr, length int, prot int) {
    10  	pageSize := syscall.Getpagesize()
    11  	for p := pageStart(addr); p < addr + uintptr(length); p += uintptr(pageSize) {
    12  		page := rawMemoryAccess(p, pageSize)
    13  		err := syscall.Mprotect(page, prot)
    14  		if err != nil {
    15  			panic(err)
    16  		}
    17  	}
    18  }
    19  
    20  // this function is super unsafe
    21  // aww yeah
    22  // It copies a slice to a raw memory location, disabling all memory protection before doing so.
    23  func copyToLocation(location uintptr, data []byte) {
    24  	f := rawMemoryAccess(location, len(data))
    25  
    26  	mprotectCrossPage(location, len(data), syscall.PROT_READ|syscall.PROT_WRITE|syscall.PROT_EXEC)
    27  	copy(f, data[:])
    28  	mprotectCrossPage(location, len(data), syscall.PROT_READ|syscall.PROT_EXEC)
    29  }