PE-sieve
Scans all running processes. Recognizes and dumps a variety of potentially malicious implants (replaced/implanted PEs, shellcodes, hooks, in-memory patches).
Loading...
Searching...
No Matches
modules_enum.cpp
Go to the documentation of this file.
1#include "modules_enum.h"
2
3#include <psapi.h>
4#pragma comment(lib,"psapi.lib")
5
6namespace {
7 size_t _enum_modules(IN HANDLE hProcess, IN OUT HMODULE hMods[], DWORD hModsMax, IN DWORD filters) //throws exceptions
8 {
9 if (hProcess == nullptr) {
10 return 0;
11 }
12 const char err_msg[] = "Could not enumerate modules. ";
13 DWORD cbNeeded = 0;
14#ifdef _WIN64
15 if (!EnumProcessModulesEx(hProcess, hMods, hModsMax, &cbNeeded, filters)) {
16 throw std::runtime_error(err_msg);
17 return 0;
18 }
19#else
20 /*
21 Some old, 32-bit versions of Windows do not have EnumProcessModulesEx,
22 but we can use EnumProcessModules for the 32-bit version: it will work the same and prevent the compatibility issues.
23 */
24 if (!EnumProcessModules(hProcess, hMods, hModsMax, &cbNeeded)) {
25 throw std::runtime_error(err_msg);
26 return 0;
27 }
28#endif
29 const size_t modules_count = cbNeeded / sizeof(HMODULE);
30 return modules_count;
31 }
32};
33
34size_t pesieve::util::enum_modules(IN HANDLE hProcess, IN OUT std::vector<HMODULE>& modules, IN DWORD filters) //throws exceptions
35{
36 if (hProcess == nullptr) {
37 return 0;
38 }
39 const size_t max_count = 1024 * 3;
40 size_t capacity = 1024;
41
42 while (true) {
43 modules.assign(capacity, nullptr);
44
45 const size_t size_in_bytes = modules.size() * sizeof(HMODULE);
46 if (size_in_bytes > MAXDWORD) {
47 throw std::runtime_error("Module buffer too large.");
48 }
49 const size_t count = _enum_modules(
50 hProcess,
51 modules.data(),
52 static_cast<DWORD>(size_in_bytes),
53 filters
54 );
55
56 if (count <= modules.size()) {
57 modules.resize(count);
58 return count;
59 }
60 if (count > max_count) {
61 throw std::runtime_error("Too many modules to enumerate safely.");
62 }
63 capacity = count;
64 }
65}
size_t enum_modules(IN HANDLE hProcess, OUT std::vector< HMODULE > &hMods, IN DWORD filters)
DWORD(__stdcall *_PssCaptureSnapshot)(HANDLE ProcessHandle