首页 > 解决方案 > 是否存在 ReadProcessMemory 失败的情况?

问题描述

我目前正在编写一个程序,该程序ReadProcessMemory用于将一块内存作为文本保存到文件中。在程序中,用户将指定内存块的基地址和大小。输入验证在调用之前完成,ReadProcessMemory以确保没有与参数相关的错误。内存边界也仅限于预分配的区域,以确保用户不会尝试读取未分配的内存。由于所有分配的内存都是可读的,我认为不需要对ReadProcessMemory. 我这样说正确吗?当然,假设所有参数都是有效的。我过去曾ReadProcessMemory多次使用过适当的错误检查,但发现它是不必要的,因为该功能总是成功的。

示例也将不胜感激。提前致谢!

标签: windowswinapierror-handlingprocessreadprocessmemory

解决方案


I assume that all parameters are valid:

  • The handle have PROCESS_VM_READ access to the process;
  • lpBaseAddress is valid;
  • nSize <= the size of lpBuffer.
  • ...

I think the only factor that will cause ReadProcessMemory failure is Memory Protection attributes.

As @IInspectable: "memory is allocated doesn't imply that you can read it".

After testing, I found that the following situations will get failed.

  • PAGE_NOACCESS

https://docs.microsoft.com/en-us/windows/win32/memory/reserving-and-committing-memory

lpvBase = VirtualAlloc(
                 NULL,                 // System selects address
                 PAGELIMIT*dwPageSize, // Size of allocation
                 MEM_RESERVE,          // Allocate reserved pages
                 PAGE_NOACCESS);       // Protection = no access
  • PAGE_GUARD | ...

https://docs.microsoft.com/en-us/windows/win32/memory/creating-guard-pages

lpvAddr = VirtualAlloc(NULL, dwPageSize,
                 MEM_RESERVE | MEM_COMMIT,
                 PAGE_READONLY | PAGE_GUARD);

Or modified by VirtualProtectEx:

VirtualProtectEx(hProcess, lpAddress, dwSize, PAGE_NOACCESS, &old);

and

VirtualProtectEx(hProcess, lpAddress, dwSize, PAGE_GUARD | PAGE_READONLY, &old);

GetLastError will return 299(ERROR_PARTIAL_COPY)

Use VirtualQueryEx to retrieve the The access protection of the pages in the specified region


推荐阅读