github.com/undefinedlabs/go-mpatch@v1.0.8-0.20230904093002-fbac8a0d7853/patcher_windows.go (about)

     1  //go:build windows
     2  // +build windows
     3  
     4  package mpatch
     5  
     6  import (
     7  	"syscall"
     8  	"unsafe"
     9  )
    10  
    11  const pageExecuteReadAndWrite = 0x40
    12  
    13  var virtualProtectProc = syscall.NewLazyDLL("kernel32.dll").NewProc("VirtualProtect")
    14  
    15  func callVirtualProtect(lpAddress unsafe.Pointer, dwSize int, flNewProtect uint32, lpflOldProtect unsafe.Pointer) error {
    16  	ret, _, _ := virtualProtectProc.Call(uintptr(lpAddress), uintptr(dwSize), uintptr(flNewProtect), uintptr(lpflOldProtect))
    17  	if ret == 0 {
    18  		return syscall.GetLastError()
    19  	}
    20  	return nil
    21  }
    22  
    23  func writeDataToPointer(ptr unsafe.Pointer, data []byte) error {
    24  	var oldPerms, tmp uint32
    25  	dataLength := len(data)
    26  	ptrByteSlice := getMemorySliceFromPointer(ptr, len(data))
    27  	if err := callVirtualProtect(ptr, dataLength, pageExecuteReadAndWrite, unsafe.Pointer(&oldPerms)); err != nil {
    28  		return err
    29  	}
    30  	copy(ptrByteSlice, data[:])
    31  	if err := callVirtualProtect(ptr, dataLength, oldPerms, unsafe.Pointer(&tmp)); err != nil {
    32  		return err
    33  	}
    34  	return nil
    35  }