0

I had written a program that enumerates all the memory regions of a process with the following attributes: MEM_COMMIT and PAGE_READWRITE, and that at the end of the program prints the total size of all the regions found, everything seems to work well, then I tried it on programs at 64 bits and it turned out that the total regions size was greater than the RAM available on my PC. On my PC there are 15.9GB of RAM available while one of the scans that I made was 18.363.846.656 Byte (18.3 GB). I wonder, how is it possible? is it a mistake in my code, or are they using some memory management methods that I am not aware of?

#include <iostream>
#include <Windows.h>

int main()
{
   // Get an handle to the process
   HWND hWnd = FindWindowA(NULL, "WindowName");
   DWORD pid; GetWindowThreadProcessId(hWnd, &pid);
   HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

   // Declaration of some variables
   char* Ptr(0);
   MEMORY_BASIC_INFORMATION Mem;
   size_t totalSize = 0;

   // Start querying
   while (VirtualQueryEx(hProcess, Ptr, &Mem, sizeof(MEMORY_BASIC_INFORMATION)))
   {
      if (Mem.State == MEM_COMMIT && Mem.Protect == PAGE_READWRITE)
      {
         totalSize += Mem.RegionSize;
         std::cout << std::hex << Mem.BaseAddress << " - " << (LPVOID)(Mem.RegionSize + (INT64)Mem.BaseAddress) << " - size:(" << std::dec << Mem.RegionSize << ")\n";
      }

      Ptr += Mem.RegionSize;
   }

   std::cout << "[" << totalSize << "]";
   CloseHandle(hProcess);
   return 0;
}
DanyDollaro
  • 5
  • 1
  • 4
  • You are walking virtual memory, not physical memory. Regions of virtual memory could be swapped to disk at any given time, and not backed by physical memory. – Igor Tandetnik May 03 '20 at 01:39
  • Does this answer your question? [What is the difference between virtual memory and physical memory?](https://stackoverflow.com/q/14347206/62576) – Ken White May 03 '20 at 02:06
  • Thanks, but I was wondering how could I go about considering only physical memory? in the MEMORY_BASIC_INFORMATION structure I don't see any value that helps me understand if it is in physical memory or not – DanyDollaro May 03 '20 at 14:15

1 Answers1

1

You cannot query physical memory using any normal documented Windows API functions. Virtual Memory is intended to be an abstraction, the Operating System is meant to handle all this in the background for you.

There is RAMMap from SysInternals which can display information regarding physical memory but the source code is not public. RAMMap is explained in this video from Microsoft

To learn more about how the system works you can look up "physical memory" in the Windows Internals book.

There is some code in this answer which claims to be able to query physical memory from usermode here using NtOpenSection and NtMapViewOfSection.

To interact with physical memory from a kernel driver you can read this source code

GuidedHacking
  • 3,628
  • 1
  • 9
  • 59