MEMORY_BASIC_INFORMATION.AllocationBase IMAGE_DOS_HEADER有效性检查

时间:2017-07-06 01:27:15

标签: c++ winapi

我使用VirtualQueryEx来循环进程内的内存分配。但是,由于某些奇怪的原因,将分配库与有效的IMAGE_DOS_HEADER签名/' MZ'进行比较。我遇到了访问冲突...有人能指出我的代码中有什么不正确吗?

MEMORY_BASIC_INFORMATION mbi;
do 
{
   if (VirtualQueryEx(handle, currentAddress, &mbi, sizeof(mbi)) == 0) 
   {
      continue;
   }

   if (mbi.State & MEM_COMMIT && !(mbi.Protect & PAGE_NOACCESS) && 
         !(mbi.Protect & PAGE_PROTECT))
   {
      if (mbi.AllocationBase != nullptr)
      { 
         bool hasValidDosHeader = *(WORD*)mbi.AllocationBase == 
         IMAGE_DOS_SIGNATURE; //THIS CAUSES AN ACCESS VIOLATION 
      }
   }
   currentAddress += mbi.RegionSize;
} while(currentAddress < endAddress);

PS:我还尝试将AllocationBase转换为IMAGE_DOS_HEADER *,然后使用IMAGE_DOS_SIGNATURE检查e_magic,这也会导致访问冲突......

1 个答案:

答案 0 :(得分:1)

VirtualQueryEx返回有关远程内存的信息,但不会为您读取。

您需要msdn: ReadProcessMemory将内存从远程进程实际复制到进程才能读取内存。

MEMORY_BASIC_INFORMATION mbi;
do 
{
   if (VirtualQueryEx(handle, currentAddress, &mbi, sizeof(mbi)) == 0) 
   {
      break; // we can't continue in the loop, as we don't know the size.
   }

   if (mbi.State & MEM_COMMIT && !(mbi.Protect & PAGE_NOACCESS) && 
         !(mbi.Protect & PAGE_PROTECT))
   {
       if (mbi.AllocationBase != nullptr)
       { 
          IMAGE_DOS_HEADER dosHeader; 
          if (ReadProcessMemory(handle, mbi.AllocationBase, &dosHeader, mbi.RegionSize, NULL)) {

              bool hasValidDosHeader = dosHeader.e_magic == IMAGE_DOS_SIGNATURE; 
          }
       }
   }
   currentAddress += mbi.RegionSize;
} while(currentAddress < endAddress);