简体   繁体   中英

Java read memory of other process with JNA

I'm trying to read a part from the memory of a Notepad instance, but I'm always getting system error 299 when calling kernel32's ReadProcessMemory() .

This is the code I have so far:

package memreadtest;

import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;

public class MemReader {

    private final static Kernel32 kernel32 = Native.load("kernel32", Kernel32.class, W32APIOptions.DEFAULT_OPTIONS);
    private final static User32 user32 = Native.load("user32", User32.class, W32APIOptions.DEFAULT_OPTIONS);

    private final static int PROCESS_VM_READ = 0x0010;

    public static void main(String[] args) {
        int bytesToRead = 1024;

        Memory notepadDump = readProcessMemory("*Untitled - Notepad", bytesToRead);

        Memory.disposeAll();
    }

    private static Memory readProcessMemory(String winTitle, int bytesToRead) {
        Memory output = new Memory(bytesToRead);

        IntByReference pid = new IntByReference(0);

        user32.GetWindowThreadProcessId(user32.FindWindow(null, winTitle), pid);

        HANDLE handle = kernel32.OpenProcess(PROCESS_VM_READ, true, pid.getValue());

        if (!kernel32.ReadProcessMemory(handle, handle.getPointer(), output, bytesToRead, null)) {
            System.err.println("Failed to read memory of process " + pid.getValue() + ". System Error Code: " + kernel32.GetLastError());
            return null;
        }

        return output;
    }
}

What am I doing wrong?

You are reading an address that there is no reason to expect is valid in the external process. A process handle is not expected to be a valid address in the process.

I'm not sure what you are trying to read from this process, but l whatever it is you will need to somehow find an appropriate address.

You clarify in comments that you want to read from the module base address. For instance see: Get base address of process

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM