Rob Rob - 5 months ago 27
Node.js Question

Node addon unable to snapshot (CreateToolhelp32Snapshot) modules

I'm trying to learn C++ but can't quite understand why when I attempt to snapshot modules via a Node add-on different results are returned to when I run the program through VS on the desktop.

Using this source from MSDN I can list all modules within a process:

void fm(LPSTR name) {
HANDLE hModuleSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 5844);
MODULEENTRY32 mEntry;

// check invalid handle value...
// check module32first...

mEntry.dwSize = sizeof(mEntry);

do {
if (!strcmp(mEntry.szModule, name)) {
CloseHandle(hModuleSnapshot);
cout << mEntry.szModule << endl;
}
} while (Module32Next(hModuleSnapshot, &mEntry));
}


This works as intended and will find/print the module information (error checking omitted) - however, when I try and port this functionality over to a Node add-on it does not list the same modules as the code above (the code is nearly identical, I don't know why attempting to implement the function inside a custom Node add-on affects the result):

void fm() {
HANDLE hModuleSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 5844);
MODULEENTRY32 mEntry;

// check invalid handle value...
// check module32first...

mEntry.dwSize = sizeof(mEntry);

do {
cout << mEntry.szModule << endl;
} while (Module32Next(hModuleSnapshot, &mEntry));

CloseHandle(hModuleSnapshot);
}


After using node-gyp to compile the add-on I can call it successfully (after requiring, it simply runs a function that calls
fm
).

If I try to snapshot the process with the PID
5844
(VS Code) it prints out:

Code.exe
ntdll.dll
wow64.dll
wow64win.dll
wow64cpu.dll


If I try the process with the PID
6540
(Chrome) it prints out:

chrome.exe
ntdll.dll
wow64.dll
wow64win.dll
wow64cpu.dll


This is obviously not correct, it prints out the same modules even though the PID (hard coded) is differing.

If I use the first block of code and run it with VS, I get:

chrome.exe
ntdll.dll
KERNEL32.DLL
KERNELBASE.dll
apphelp.dll
ADVAPI32.dll
msvcrt.dll
sechost.dll
RPCRT4.dll
SspiCli.dll
CRYPTBASE.dll...

There's a lot more modules, but you can see this is what the second block of code should print.

I do not know why running the code through a custom Node add-on would affect the outcome unless I'm missing or not understanding something about Node add-ons.

I can open and collect information about all processes correctly using
CreateToolhelp32Snapshot
with the Node add-on, but I can not seem to collect information on the modules within a process.

Answer

Using TH32CS_SNAPMODULE within a x64 process(Node.exe) on x86 process will give you only the 64 bit modules, use TH32CS_SNAPMODULE32 to get the 32 bit modules - TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32 for all modules.