基於visual c++之windows核心編程程式碼分析(19)枚舉進程以及進程載入模組資訊

來源:互聯網
上載者:User

我們進行Windows安全編程的時候,經常需要檢測進程,我們來實踐一下枚舉進程與進程載入模組。請見代碼實現與注釋分析。

 

 

/* 標頭檔 */#include <Windows.h>#include <Psapi.h>#include <Tlhelp32.h>#include <stdio.h>/* 預先處理聲明 */#pragma comment (lib, "psapi.lib")/* 函式宣告 */VOID WINAPI EnumProcess1();VOID WINAPI EnumProcess2();VOID ListProcessModules1( DWORD dwPID );VOID ListProcessModules2( DWORD dwPID);VOID PrintMemoryInfo( DWORD dwPID );VOID ShowProcessMemoryInfo( DWORD dwPID );VOID ListHeapInfo( DWORD dwPID );VOID ListProcessThreads( DWORD dwPID );VOID PrintError( LPTSTR msg );/************************************** VOID WINAPI EnumProcess1()* 功能調用EnumProcesses遍曆進程,*並調用ListProcessModules1函數和*ListProcessThreads函數列舉模組和線程** 無參數,無傳回值**************************************/VOID WINAPI EnumProcess1(){// 假設不超過1024個進程DWORD aProcesses[1024], cbNeeded, cProcesses;unsigned int i;// 調用EnumProcessesif ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )return;// 進程數cProcesses = cbNeeded / sizeof(DWORD);for ( i = 0; i < cProcesses; i++ ){// 顯示進程資訊printf( "\n\n**************************************************" );printf("\nPROCESS : %u\n\n",aProcesses[i]);printf( "\n****************************************************" );// 列舉模組資訊和線程資訊ListProcessModules1( aProcesses[i] );ListProcessThreads( aProcesses[i] );}}/************************************** VOID WINAPI EnumProcess2()* 功能調用Process32First和Process32Next遍曆進程,*並調用ListProcessModules2函數列舉模組,*調用ShowProcessMemoryInfo函數顯示記憶體使用量情況** 無參數,無傳回值**************************************/VOID WINAPI EnumProcess2(){HANDLE hProcessSnap;HANDLE hProcess;PROCESSENTRY32 pe32;DWORD dwPriorityClass;// SnapshothProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );if( hProcessSnap == INVALID_HANDLE_VALUE ){PrintError( "CreateToolhelp32Snapshot (of processes)" );return ;}// 設定輸入參數,結構的大小pe32.dwSize = sizeof( PROCESSENTRY32 );// 開始列舉進程if( !Process32First( hProcessSnap, &pe32 ) ){PrintError( "Process32First" );  // 出錯資訊CloseHandle( hProcessSnap );return ;}do{// 列印進程名printf( "\n\n=====================================================" );printf( "\nPROCESS NAME:  %s", pe32.szExeFile );printf( "\n-----------------------------------------------------" );// 擷取優先順序dwPriorityClass = 0;hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );if( hProcess == NULL )PrintError( "OpenProcess" );else{dwPriorityClass = GetPriorityClass( hProcess );if( !dwPriorityClass )PrintError( "GetPriorityClass" );CloseHandle( hProcess );}// 列印進程相關資訊printf( "\n  process ID        = 0x%08X", pe32.th32ProcessID );printf( "\n  thread count      = %d",   pe32.cntThreads );printf( "\n  parent process ID = 0x%08X", pe32.th32ParentProcessID );printf( "\n  Priority Base     = %d", pe32.pcPriClassBase );if( dwPriorityClass )printf( "\n  Priority Class    = %d", dwPriorityClass );// 擷取模組資訊,顯示記憶體使用量情況ListProcessModules2( pe32.th32ProcessID );PrintMemoryInfo(pe32.th32ProcessID);ListHeapInfo(pe32.th32ProcessID);} while( Process32Next( hProcessSnap, &pe32 ) );CloseHandle( hProcessSnap );//關閉控制代碼return ;}/************************************** VOID ListProcessModules1( DWORD dwPID )* 功能調用EnumProcessModules函數*列舉和顯示進程載入的模組** 參數DWORD dwPID進程PID**************************************/VOID ListProcessModules1( DWORD dwPID ){HMODULE hMods[1024];HANDLE hProcess;DWORD cbNeeded;unsigned int i;printf( "\nListProcessModules1 Process ID %u\n", dwPID );// 開啟進程,獲得控制代碼hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |PROCESS_VM_READ,FALSE, dwPID );if (NULL == hProcess)return;// 調用EnumProcessModulesif( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)){for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ ){TCHAR szModName[MAX_PATH];// 擷取擷取的路徑if ( GetModuleFileNameEx( hProcess, hMods[i], szModName,sizeof(szModName)/sizeof(TCHAR))){// 列印printf( TEXT("\t%s (0x%08X)\n"), szModName, hMods[i] );}}}CloseHandle( hProcess );// 關閉進程控制代碼}/************************************** VOID ListProcessModules2( DWORD dwPID )* 功能調用Module32First和Module32Next函數*列舉和顯示進程載入的模組** 參數DWORD dwPID進程PID**************************************/VOID ListProcessModules2( DWORD dwPID){HANDLE hModuleSnap = INVALID_HANDLE_VALUE;MODULEENTRY32 me32;printf( "\nListProcessModules2 Process ID %u\n", dwPID );// SnapshothModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID );if( hModuleSnap == INVALID_HANDLE_VALUE ){PrintError( "CreateToolhelp32Snapshot (of modules)" );return ;}// 設定輸入參數,結構的大小me32.dwSize = sizeof( MODULEENTRY32 );// 開始擷取模組資訊if( !Module32First( hModuleSnap, &me32 ) ){PrintError( "Module32First" );  // Show cause of failureCloseHandle( hModuleSnap );     // Must clean up the snapshot object!return ;}do{printf( "\n\n     MODULE NAME:     %s",             me32.szModule );printf( "\n     executable     = %s",             me32.szExePath );printf( "\n     process ID     = 0x%08X",         me32.th32ProcessID );printf( "\n     ref count (g)  =     0x%04X",     me32.GlblcntUsage );printf( "\n     ref count (p)  =     0x%04X",     me32.ProccntUsage );printf( "\n     base address   = 0x%08X", (DWORD) me32.modBaseAddr );printf( "\n     base size      = %d",             me32.modBaseSize );} while( Module32Next( hModuleSnap, &me32 ) );CloseHandle( hModuleSnap );// 關閉控制代碼return ;}/************************************** VOID PrintMemoryInfo( DWORD dwPID )* 功能顯示進程的記憶體使用量情況** 參數DWORD dwPID進程PID**************************************/VOID PrintMemoryInfo( DWORD dwPID ){HANDLE hProcess;PROCESS_MEMORY_COUNTERS pmc;printf( "\nProcess ID: %u\n", dwPID );hProcess = OpenProcess(  PROCESS_QUERY_INFORMATION |PROCESS_VM_READ,FALSE, dwPID );if (NULL == hProcess)return;if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ){printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );printf( "\tPeakWorkingSetSize: 0x%08X\n", pmc.PeakWorkingSetSize );printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakPagedPoolUsage );printf( "\tQuotaPagedPoolUsage: 0x%08X\n", pmc.QuotaPagedPoolUsage );printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakNonPagedPoolUsage );printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n", pmc.QuotaNonPagedPoolUsage );printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage ); printf( "\tPeakPagefileUsage: 0x%08X\n", pmc.PeakPagefileUsage );}CloseHandle( hProcess );}/************************************** VOID ListHeapInfo( DWORD dwPID )* 功能顯示進程的堆分配情況** 參數DWORD dwPID進程PID**************************************/VOID ListHeapInfo( DWORD dwPID ){HEAPLIST32 hl;HEAPENTRY32 he;HANDLE hSnapshot = INVALID_HANDLE_VALUE;printf( "\\ListHeapInfo Process ID %u\n", dwPID );//  SnapshothSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST , dwPID ); if( hSnapshot == INVALID_HANDLE_VALUE ) { PrintError( "CreateToolhelp32Snapshot (of heaplist)" ); return ; }// 設定輸入參數,結構的大小hl.dwSize = sizeof( HEAPLIST32 ); // 開始擷取資訊if( !Heap32ListFirst( hSnapshot, &hl ) ) { PrintError( "Heap32ListFirst" );  CloseHandle( hSnapshot );     return ; } do { printf( "\n\tHeap ID     =%u", hl.th32HeapID ); printf( "\tHeap Flags     = %u", hl.dwFlags ); he.dwSize = sizeof(HEAPENTRY32);if( !Heap32First(&he,dwPID,hl.th32HeapID) ) { PrintError( "Heap32First" );// 出錯CloseHandle( hSnapshot );     return ; }do { // 顯示資訊printf( "\n\t\t Heap Address\t= %u",he.dwAddress ); printf( "\t Heap Size\t= %u",he.dwBlockSize); printf( "\t Heap Flags\t= %u",he.dwFlags);printf( "\t Heap Handle\t= %u",he.hHandle);} while( Heap32Next(&he )); } while( Heap32ListNext( hSnapshot, &hl ) ); CloseHandle( hSnapshot );// 關閉控制代碼return ; }/************************************** VOID ListProcessThreads( DWORD dwPID )* 功能調用Thread32First和Thread32Next*顯示一個進程的線程** 參數DWORD dwPID進程PID**************************************/VOID ListProcessThreads( DWORD dwPID ){HANDLE hThreadSnap = INVALID_HANDLE_VALUE; THREADENTRY32 te32; printf( "\\ListProcessThreads Process ID %u\n", dwPID );// SnapshothThreadSnap = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ); if( hThreadSnap == INVALID_HANDLE_VALUE ) return ; // 設定輸入參數,結構的大小te32.dwSize = sizeof(THREADENTRY32 ); // 開始擷取資訊if( !Thread32First( hThreadSnap, &te32 ) ) {PrintError( "Thread32First" );  // Show cause of failureCloseHandle( hThreadSnap );     // Must clean up the snapshot object!return ;}do { if( te32.th32OwnerProcessID == dwPID ){// 顯示相關資訊printf( "\n   THREAD ID = 0x%08X", te32.th32ThreadID ); printf( "\t   base priority = %d", te32.tpBasePri ); printf( "\t   delta priority = %d", te32.tpDeltaPri ); }} while( Thread32Next(hThreadSnap, &te32 ) ); CloseHandle( hThreadSnap );return ;}// 列印出錯資訊VOID PrintError( LPTSTR msg ){DWORD eNum;TCHAR sysMsg[256];TCHAR* p;eNum = GetLastError( );FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,NULL, eNum,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), sysMsg, 256, NULL );p = sysMsg;while( ( *p > 31 ) || ( *p == 9 ) )++p;do { *p-- = 0; } while( ( p >= sysMsg ) &&( ( *p == '.' ) || ( *p < 33 ) ) );printf( "\n  WARNING: %s failed with error %d (%s)", msg, eNum, sysMsg );}void main(){printf("EnumProcess1 \n");EnumProcess1();printf("\n\n\nEnumProcess2 \n");EnumProcess2();}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.