Skip to content

Instantly share code, notes, and snippets.

@hasherezade
Created April 5, 2017 17:31
Show Gist options
  • Select an option

  • Save hasherezade/55c4e18e1e4b9748e33726d563bd6182 to your computer and use it in GitHub Desktop.

Select an option

Save hasherezade/55c4e18e1e4b9748e33726d563bd6182 to your computer and use it in GitHub Desktop.
Enumerates all the modules in the process with a given PID
// Enumerates all the modules in the process with a given PID
// saves the list in the log with the given format:
// <module_start>,<module_end>,<module_name>
// CC-BY: hasherezade
#include <stdio.h>
#include <Windows.h>
#include <TlHelp32.h>
void log_info(FILE *f, MODULEENTRY32 &module_entry)
{
BYTE* mod_end = module_entry.modBaseAddr + module_entry.modBaseSize;
fprintf(f, "%p,%p,%s\n", module_entry.modBaseAddr, mod_end, module_entry.szModule);
fflush(f);
}
size_t enum_modules_in_process(DWORD process_id, FILE *f)
{
HANDLE hProcessSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, process_id);
MODULEENTRY32 module_entry = { 0 };
module_entry.dwSize = sizeof(module_entry);
if (!Module32First(hProcessSnapShot, &module_entry)) {
return 0;
}
size_t modules = 1;
log_info(f, module_entry);
while (Module32Next(hProcessSnapShot, &module_entry)) {
log_info(f, module_entry);
modules++;
}
// Close the handle
CloseHandle(hProcessSnapShot);
return modules;
}
int main(int argc, char *argv[])
{
DWORD pid = GetCurrentProcessId();
if (argc >= 2) {
pid = atoi(argv[1]);
printf("PID: %d\n", pid);
}
char filename[MAX_PATH] = { 0 };
sprintf(filename,"PID_%d_modules.txt", pid);
FILE *f = fopen(filename, "w");
if (!f) {
printf("[ERROR] Cannot open file!\n");
system("pause");
return -1;
}
int num = enum_modules_in_process(pid, f);
fclose(f);
printf("Found modules: %d saved to the file: %s\n", num, filename);
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment