I’m using VirtualQueryEx to enumerate a module’s memory pages with the following code:
unsigned char *p = (unsigned char *)module;
MEMORY_BASIC_INFORMATION info;
unsigned long usage = 0;
for ( ;VirtualQueryEx(hProcess, p, &info, sizeof(info)) == sizeof(info);
p += info.RegionSize )
{
printf("%#10.10x (%6uK)\t", info.BaseAddress, info.RegionSize/1024);
switch (info.State) {
case MEM_COMMIT:
printf("Committed");
break;
case MEM_RESERVE:
printf("Reserved");
break;
case MEM_FREE:
printf("Free");
break;
}
printf("\t");
switch (info.Type) {
case MEM_IMAGE:
printf("Code Module");
break;
case MEM_MAPPED:
printf("Mapped ");
break;
case MEM_PRIVATE:
printf("Private ");
}
printf("\t");
if ((info.State == MEM_COMMIT) && (info.Type == MEM_PRIVATE))
usage +=info.RegionSize;
int guard = 0, nocache = 0;
if ( info.AllocationProtect & PAGE_NOCACHE)
nocache = 1;
if ( info.AllocationProtect & PAGE_GUARD )
guard = 1;
info.AllocationProtect &= ~(PAGE_GUARD | PAGE_NOCACHE);
switch (info.AllocationProtect) {
case PAGE_READONLY:
printf("Read Only");
break;
case PAGE_READWRITE:
printf("Read/Write");
break;
case PAGE_WRITECOPY:
printf("Copy on Write");
break;
case PAGE_EXECUTE:
printf("Execute only");
break;
case PAGE_EXECUTE_READ:
printf("Execute/Read");
break;
case PAGE_EXECUTE_READWRITE:
printf("Execute/Read/Write");
break;
case PAGE_EXECUTE_WRITECOPY:
printf("COW Executable");
break;
}
if (guard)
printf("\tguard page");
if (nocache)
printf("\tnon-cachable");
printf("\n");
}
The code was taken from another post here.
The problem is: VirtualQueryEx won’t stop enumerating pages at the current module (it just stops when memory is out of process) and the results are wrong
Here’s my output and VMMap’s one

As you can see starting from the address highlighted the pages are all wrong and VirtualQueryEx won’t even stop enumerating them.
Where am I getting wrong?
VMMap knows about pe file format (sections .data, .text, ext), VirtualQueryEx don’t. MEMORY_BASIC_INFORMATION.RegionSize – the size of the region in which all pages have identical protection attributes (RW in screenshot). That is why mismatch in calculating regions VMMap and VirtualQueryEx.
VirtualQueryEx won’t even stop enumerating them.
scans the entire user mode virtual memory address space. If you want to stop the scanning, check the AllocationBase field.