Free mag vol1 | Page 689

CHAPTER 17  PROCESSES, APPDOMAINS, AND OBJECT CONTEXTS Investigating a Process’s Module Set Next up, let’s check out how to iterate over the number of loaded modules that are hosted within a given process. When talking about processes, a module is a general term used to describe a given *.dll (or the *.exe itself) that is hosted by a specific process. When you access the ProcessModuleCollection via the Process.Modules property, you are able to enumerate over all modules hosted within a process: .NETbased, COM-based, or traditional C-based libraries. Ponder the following additional helper function that will enumerate the modules in a specific process based on the PID: static void EnumModsForPid(int pID) { Process theProc = null; try { theProc = Process.GetProcessById(pID); } catch(ArgumentException ex) { Console.WriteLine(ex.Message); return; } Console.WriteLine("Here are the loaded modules for: {0}", theProc.ProcessName); ProcessModuleCollection theMods = theProc.Modules; foreach(ProcessModule pm in theMods) { string info = string.Format("-> Mod Name: {0}", pm.ModuleName); Console.WriteLine(info); } Console.WriteLine("************************************\n"); } To see some possible output, let’s check out the loaded modules for the process hosting the current example program (ProcessManipulator). To do so, run the application, identify the PID assigned to ProcessManipulator.exe (via the Task Manager), and pass this value to the EnumModsForPid() method (be sure to update your Main() method accordingly). Once you do, you might be surprised to see the list of *.dlls used for a simple Console Application (GDI32.dll, USER32.dll, ole32.dll, and so forth). Consider the following output: Here are the -> Mod Name: -> Mod Name: -> Mod Name: -> Mod Name: -> Mod Name: -> Mod Name: -> Mod Name: -> Mod Name: -> Mod Name: -> Mod Name: 632 loaded modules for: ProcessManipulator ProcessManipulator.exe ntdll.dll MSCOREE.DLL KERNEL32.dll KERNELBASE.dll ADVAPI32.dll msvcrt.dll sechost.dll RPCRT4.dll SspiCli.dll