跨模块边界的ReadProcessMemory

时间:2018-12-11 00:43:28

标签: java winapi jna readprocessmemory

我正在使用ReadProcessMemory来读取进程的内存。似乎当我在模块末尾读取时,其余字节未成功读取。我也收到以下内核错误:

299: Only part of a ReadProcessMemory or WriteProcessMemory request was completed.

如果我列出所有带有EnumProcessModules的模块,则它们都不包含我要读取的地址,但是Cheat Engine可以很好地显示所有内存内容。 Cheat Engine表示模块的大小为0xE000,这恰好是我在停止之前可以读取的字节数,仅将0x00个字节放入缓冲区中是不正确的,并不代表实际的字节数内存内容。

以下代码是否不适合跨模块边界读取(即使它们是连续的)?

static Memory getOutputMemory(Pointer openedProcess, long baseAddress, int length)
{
    val outputMemory = new Memory(length);
    val intByReference = new IntByReference();
    if (!MY_KERNEL_32.ReadProcessMemory(openedProcess, baseAddress,
            outputMemory, (int) outputMemory.size(), intByReference))
    {
        checkForKernelError();
    }

    return outputMemory;
}

1 个答案:

答案 0 :(得分:0)

事实证明,分别读取内存页面是如何做到的,例如类似于以下代码:

public byte[] readBytes(long address, int length)
{
    val byteBuffer = allocate(length);

    var totalRemainingLength = length;
    var currentAddress = address;

    while (totalRemainingLength > 0)
    {
        val memoryBasicInformation = new MEMORY_BASIC_INFORMATION();
        val process = new HANDLE(processHandle);
        val pointer = new Pointer(currentAddress);
        val memoryPageQueryResult = KERNEL_32.VirtualQueryEx(process, pointer, memoryBasicInformation,
                new BaseTSD.SIZE_T(memoryBasicInformation.size()));
        if (memoryPageQueryResult.equals(new SIZE_T(0)))
        {
            throw new IllegalStateException("Memory not contiguous");
        }

        val memoryPageBaseAddress = nativeValue(memoryBasicInformation.baseAddress);
        val memoryPageSize = memoryBasicInformation.regionSize.longValue();
        val memoryPageEndAddress = memoryPageBaseAddress + memoryPageSize;

        val remainingMemoryPageBytes = memoryPageEndAddress - address;
        val currentLength = (int) min(totalRemainingLength, remainingMemoryPageBytes);
        val outputMemory = getOutputMemory(processHandle, currentAddress, currentLength);
        val byteArray = outputMemory.getByteArray(0, currentLength);
        byteBuffer.put(byteArray);

        currentAddress += currentLength;
        totalRemainingLength -= currentLength;
    }

    return byteBuffer.array();
}

static Memory getOutputMemory(Pointer openedProcess, long baseAddress, int length)
{
    val outputMemory = new Memory(length);
    val intByReference = new IntByReference();
    if (!MY_KERNEL_32.ReadProcessMemory(openedProcess, baseAddress,
            outputMemory, (int) outputMemory.size(), intByReference))
    {
        checkForKernelError();
    }

    return outputMemory;
}