C ++ VirtualQueryEx无限循环

时间:2012-09-01 15:05:40

标签: c++ memory

我目前正在使用C ++重新创建一个内存修饰符应用程序,原始版本是在C#中。

所有的归功于“gimmeamilk”,我曾在YouTube(video 1 of 8)上关注过这些教程。对于试图创建类似应用程序的任何人,我强烈推荐这些教程。

我遇到的问题是我的VirtualQueryEx似乎永远运行。我正在扫描的进程是“notepad.exe”,我通过命令行参数传递给应用程序。

std::cout<<"Create scan started\n";
#define WRITABLE (PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) //These are all the flags that will be used to determin if a memory block is writable.
MEMBLOCK * mb_list = NULL;          //pointer to the head of the link list to be returned
MEMORY_BASIC_INFORMATION meminfo;   //holder for the VirtualQueryEx return struct
unsigned char *addr = 0;            //holds the value to pass to VirtualQueryEx

HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS,false, pid);
if(hProc) 
{
    while(1)
    {
        if(VirtualQueryEx(hProc,addr, &meminfo, sizeof(meminfo)) == 0) 
        {
            break;
        }


        if((meminfo.State & MEM_COMMIT) && (meminfo.Protect & WRITABLE)) //((binary comparison of meminfos state and MEM_COMMIT, this is basically filtering out memory that the process has reserved but not used)())
        {
            MEMBLOCK * mb = create_memblock(hProc, &meminfo);
            if(mb)
            {
                mb->next = mb_list;
                mb_list = mb;
            }
        }
        addr = (unsigned char *)meminfo.BaseAddress + meminfo.RegionSize;//move the adress along by adding on the length of the current block

    }
}
else
{
    std::cout<<"Failed to open process\n";
}
std::cout<<"Create scan finished\n";

return mb_list;

此代码的输出结果为

Create scan started on process:7228

然后它不会向控制台返回任何其他内容。不幸的是,通过Youtube视频链接的示例源代码不再可用。 (7228将根据notepad.exe的当前pid进行更改)

编辑回复问题@Hans Passant 我仍然不明白,我认为我在做什么

Starting a infinite loop
{
   Testing using vqx if the address is valid and populating my MEM_BASIC_etc..
   {
        (has the process commited to using that addr of memory)(is the memory writeable)
        {
            create memblock etc
        } 
   }
   move the address along by the size of the current block
}

我的程序是x32,记事本也是如此(据我所知)。

我的问题是因为我正在使用x64位操作系统,我实际上正在检查一半块(这里的块意味着内存中OS分配的单元)并导致它循环?

非常感谢您的帮助!我想了解我的问题并解决它。

1 个答案:

答案 0 :(得分:0)

您的问题是您正在编译32位程序,并使用它来解析64位程序的内存。您将“ addr”定义为无符号字符指针,在这种情况下,其大小为32位。它不能包含64位地址,这是导致您出现问题的原因。

如果目标进程是64位,则也将程序编译为64位。对于32位目标进程,请编译为32位。通常,这是处理外部进程内存的最佳技术,也是最快的解决方案。

根据您的工作,还可以使用#ifdef和其他条件根据目标使用64位变量,但是原始解决方案通常更容易。