'CreateToolhelp32Snapshot fails when enumerating a 32bit process from a 32 bit process

I am writing a basic debugger in c++. I am trying to get a list of the loaded modules of the debugged process from the debugger process. My OS is 64bit windows 7, but both the debugger and the debuggee are compiled 32 bit (when looked at in task manager, they have *32 next to their names).

Whenever I try to call CreateToolhelpSnapshot on the debuggee from the debugger, I get a 299 error. MSDN says that this should only happen if querying a 64 bit process from a 32 bit on or vice versa. Both of my processes are 32 bit as far as I can tell.

Here is my snapshot code:

HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32, pid);
if( hModuleSnap == INVALID_HANDLE_VALUE )
{
    std::cout << "CreateToolhelp32Snapshot Error: " << GetLastError() << std::endl;
}


Solution 1:[1]

Use TH32CS_SNAPMODULE instead of TH32CS_SNAPMODULE32.

Another cause may be that the process that you want to enumerate is just starting up and is not yet ready with loading it's modules. So what I do is calling CreateToolhelp32Snapshot in a loop and when getting error ERROR_PARTIAL_COPY (299) I wait a 200 milliseconds and then try again to enumerate the modules until I don't get this error anymore.

If this does not work for you will have to use another API to enumerate the modules. Have a look at this article: http://www.codeproject.com/Articles/19685/Get-Process-Info-with-NtQueryInformationProcess

The PEB_LDR_DATA structure contains information about the loaded modules for the process.

More details here: https://msdn.microsoft.com/en-us/library/aa813708.aspx

EDIT: I found a case where the above does not solve the problem. I finally found that enumerating modules in a 64 bit process works only correctly if CreateToolHelpSnapshot is running also in a 64 bit process. A shame that Microsoft implemented this so buggy.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1