Call kernel32 ReadProcessMemory in Go

I am trying to manipulate processes in Windows using the Go language, and I start by reading the memory of another process using ReadProcessMemory.

However, for most addresses I get an error Error: Only part of a ReadProcessMemory or WriteProcessMemory request was completed.. My list of arguments may be incorrect, but I cannot understand why.

Can someone point out what I'm doing wrong here?

package main

import (
  "fmt"
)

import (
  windows "golang.org/x/sys/windows"
)

func main() {
  handle, _ := windows.OpenProcess(0x0010, false, 6100) // 0x0010 PROCESS_VM_READ, PID 6100
  procReadProcessMemory := windows.MustLoadDLL("kernel32.dll").MustFindProc("ReadProcessMemory")

  var data uint   = 0
  var length uint = 0

  for i := 0; i < 0xffffffff; i += 2 {
    fmt.Printf("0x%x\n", i)

    // BOOL ReadProcessMemory(HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead)
    ret, _, e := procReadProcessMemory.Call(uintptr(handle), uintptr(i), uintptr(data), 2, uintptr(length)) // read 2 bytes
    if (ret == 0) {
        fmt.Println("  Error:", e)          
    } else {
        fmt.Println("  Length:", length)
        fmt.Println("  Data:", data)                        
    }
  }

  windows.CloseHandle(handle)
}
+4
source share
1 answer

uintptr(data)false: it takes a value from data(0 type uint) and converts it to unitptrtype - with the same value converted to another type; producing a null pointer on x86.

, Go C, , , , unsafe Pointer, void* ( - ) C.

, -

import "unsafe"

var (
    data   [2]byte
    length uint32
)
ret, _, e := procReadProcessMemory.Call(uintptr(handle), uintptr(i),
    uintptr(unsafe.Pointer(&data[0])),
    2, uintptr(unsafe.Pointer(&length))) // read 2 bytes

, :

  • ​​ " ";
  • :
  • unsafe.Pointer;
  • uintptr.

, Go :

  • Go, , GC "" , , , , , , .
  • , , — unsafe.Pointer GC "" , — .
  • uintptr GC stop . , FFI/interop.

    ,

    var data [2]byte
    a := &data[0]
    p := unsafe.Pointer(a)
    i := uintptr(p)
    

    data: , a p, i.

, , unitptr -typed: , " ". , , /.

, Go , . , , , . "" Go, " ": , uintptr(unsafe.Pointer) ( ) FFI/interop, , GC.

"" "" , encoding/binary no - , or -s ..; -)


2015-10-05, .

, ret , length.

+6

Source: https://habr.com/ru/post/1609891/


All Articles