0

I generated a list of modules from the EnumProcessModules() result and the try to get filenames of modules of that list via GetModuleFilename() function.

auto sizeInBytes = getModulesSize();
std::vector<HMODULE> hmodules(sizeInBytes / sizeof(HMODULE), 0);
if (!EnumProcessModules(d_process, hmodules.data(), sizeInBytes, &sizeInBytes))
{
  CUSTOM_THROW("failed to load process modules);
}

WCHAR buffer[MAX_PATH];
std::vector<std::wstring> result;
for (auto hmod : hmodules)
{
  DWORD size = GetModuleFileName(hmod, buffer, MAX_PATH);
  if (!size)
  {
    CUSTOM_THROW("failed to get module path");
  }
}

But sporadically, with unknown reason, sometimes the exception "failed to get module path" is thrown. How can I investigate which modules cause that exception in runtime or else?

Another question is what can cause that module is loaded and available via EnumProcessModules, but become unavailable via GetModuleFileName?

zaulan
  • 1
  • 2
  • You have set yourself up for a [TOCTOU](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use) race. Not much you can do other than ignoring the failure, or suspending the target process. – IInspectable Aug 24 '20 at 16:07
  • CUSTOM_THROW inside call GetLastError() and log 126 error – zaulan Aug 24 '20 at 16:11
  • 1
    EnumProcessModules is intended to implement a debugger, the kind of scenario where you can be reasonably sure that you can prevent or detect a process terminating. Use CreateToolhelp32Snapshot() instead. – Hans Passant Aug 24 '20 at 16:21
  • 2
    `GetModuleFileName` search module in your current process, when `EnumProcessModules` in the `d_process` – RbMm Aug 24 '20 at 16:28
  • in the problem's context, d_process is the current process – zaulan Aug 24 '20 at 16:34
  • I cannot reproduce your error. Which api did you use to get `d_process`? And what is the definition of `getModulesSize`? If possible, please post a Minimal, Reproducible Example. – Strive Sun Aug 25 '20 at 05:53
  • It is not simply reproducible by a copy-pasting a code. There is an environmental problem. Something happens outside the code so the code become producing error 126. Mostly, that code producing no errors and working OK. – zaulan Aug 25 '20 at 08:18
  • Here is [MSDN sample](https://learn.microsoft.com/en-us/windows/win32/psapi/enumerating-all-modules-for-a-process). Maybe you can copy the sample and pass your d_process as the parameter to see if the error 126 appears. – Strive Sun Aug 25 '20 at 10:06

0 Answers0