DWORD getProcessWithParent(int pid) { HANDLE hProcessSnap; PROCESSENTRY32 pe32; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hProcessSnap == INVALID_HANDLE_VALUE ) { return( FALSE ); } // Set the size of the structure before using it. pe32.dwSize = sizeof( PROCESSENTRY32 ); // Retrieve information about the first process, // and exit if unsuccessful if( !Process32First( hProcessSnap, &pe32 ) ) { CloseHandle( hProcessSnap ); // clean the snapshot object return( FALSE ); } // Now walk the snapshot of processes, and // display information about each process in turn DWORD parent = static_cast<DWORD>(pid); DWORD childID = 0xffffffff; do { if(pe32.th32ParentProcessID == parent) return static_cast<int>(pe32.th32ProcessID); } while( Process32Next( hProcessSnap, &pe32 ) ); _tprintf( TEXT("Never found process with parent!") ); return childID; }
int LibraryUsage(LPCTSTR szLibrary,bool bForceRemove) { LOG(L"Check for \"%s\" usage\n",szLibrary); HANDLE hProcessSnap; HANDLE hProcess; PROCESSENTRY32 pe32; bool bFound=false; bool bUsed=false; hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { LOG(L" --> ERROR - CreateToolhelp32Snapshot failed (LastError=%d)\n", GetLastError()); return RETURN_ERR_INTERNAL; } pe32.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hProcessSnap, &pe32)) { LOG(L" --> ERROR - Process32First failed (LastError=%d)\n", GetLastError()); CloseHandle(hProcessSnap); return RETURN_ERR_INTERNAL; } do { hProcess = AdvanceOpenProcess(pe32.th32ProcessID, PROCESS_ALL_ACCESS); //If we need the exe name, we need pe32.szExeFile if(isModuleUsedByProcess(pe32.th32ProcessID, szLibrary)) { bUsed=true; DWORD pid = pe32.th32ProcessID; const wchar_t *wzExeFile = pe32.szExeFile; //If bForceRemove, we try to kill the process if(bForceRemove) { LOG(L" --> Used by \"%s\" (pid=%ld)\n",wzExeFile,pid); HANDLE hHandle = ::OpenProcess(PROCESS_TERMINATE,0,pid); DWORD dwExitCode = 0; if(::TerminateProcess(hHandle,dwExitCode)) { ::GetExitCodeProcess(hHandle,&dwExitCode); LOG(L" --> Killed process pid=%ld (Return code = %ld)\n",pid,dwExitCode); } else { LOG(L" --> ERROR - Could not kill process pid=%ld (LastError=%d)\n", pid, GetLastError()); bFound=true; break; } CloseHandle( hHandle ); Sleep(100); } else { LOG(L" --> ERROR - Used by \"%s\" (pid=%ld)\n",wzExeFile,pid); bFound=true; break; } } } while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); if(!bUsed) LOG(L" --> NOT USED\n"); LOG(L"\n"); return (bFound?RETURN_ERR_FILELOCKED:RETURN_OK); }
int Shell::CheckSingleInstance(dictionary* ini) { char* singleInstance = iniparser_getstr(ini, SINGLE_INSTANCE_OPTION); if(singleInstance == NULL) { return 0; } // Check for single instance mode bool processOnly = true; bool dde = false; if(strcmp(singleInstance, "window") == 0) processOnly = false; else if (strcmp(singleInstance, "dde") == 0) { processOnly = false; dde = true; } else if(strcmp(singleInstance, "process") != 0) { Log::Warning("Invalid single instance mode: %s", singleInstance); return 0; } char thisModule[MAX_PATH]; DWORD thisProcessId = GetCurrentProcessId(); GetModuleFileName(0, thisModule, MAX_PATH); HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 e; e.dwSize = sizeof(PROCESSENTRY32); char otherModule[MAX_PATH]; if(Process32First(h, &e)) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, e.th32ProcessID); GetModuleFileNameEx(hProcess, 0, otherModule, MAX_PATH); CloseHandle(hProcess); if(thisProcessId != e.th32ProcessID && strcmp(thisModule, otherModule) == 0) { if (dde && DDE::NotifySingleInstance(ini)) { Log::Warning("Single Instance Shutdown"); return 1; } if(processOnly) { Log::Warning("Single Instance Shutdown"); return 1; } return !EnumWindows(EnumWindowsProcSingleInstance, e.th32ProcessID); } while(Process32Next(h, &e)) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, e.th32ProcessID); GetModuleFileNameEx(hProcess, 0, otherModule, MAX_PATH); CloseHandle(hProcess); if(thisProcessId != e.th32ProcessID && strcmp(thisModule, otherModule) == 0) { if (dde && DDE::NotifySingleInstance(ini)) { Log::Warning("Single Instance Shutdown"); return 1; } if(processOnly) { Log::Warning("Single Instance Shutdown"); return 1; } return !EnumWindows(EnumWindowsProcSingleInstance, e.th32ProcessID); } } } return 0; }
void ProcUtils::GetChildren(long pid, std::vector<long> &proclist) { #ifdef __WXMSW__ OSVERSIONINFO osver ; // Check to see if were running under Windows95 or // Windows NT. osver.dwOSVersionInfoSize = sizeof( osver ) ; if ( !GetVersionEx( &osver ) ) { return; } if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) { return; } //get child processes of this node HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!hProcessSnap) { return; } //Fill in the size of the structure before using it. PROCESSENTRY32 pe; memset(&pe, 0, sizeof(pe)); pe.dwSize = sizeof(PROCESSENTRY32); // Walk the snapshot of the processes, and for each process, // kill it if its parent is pid. if (!Process32First(hProcessSnap, &pe)) { // Can't get first process. CloseHandle (hProcessSnap); return; } //loop over all processes and collect all the processes their parent //pid matches PID do { if ((long)pe.th32ParentProcessID == pid) { proclist.push_back((long)pe.th32ProcessID); } } while (Process32Next (hProcessSnap, &pe)); CloseHandle (hProcessSnap); #elif defined(__FreeBSD__) kvm_t *kvd; struct kinfo_proc *ki; int nof_procs, i; if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL))) return; if (!(ki = kvm_getprocs(kvd, KERN_PROC_PROC, pid, &nof_procs))) { kvm_close(kvd); return; } for (i=0; i<nof_procs; i++) { ProcessEntry entry; if (ki[i].ki_ppid == pid) proclist.push_back(ki[i].ki_pid); } kvm_close(kvd); #else //GTK and other wxArrayString output; #ifdef __WXGTK__ ExecuteCommand(wxT("ps -A -o pid,ppid --no-heading"), output); #else ExecuteCommand(wxT("ps -A -o pid,ppid "), output); #endif //parse the output and search for our process ID for (size_t i=0; i< output.GetCount(); i++) { long lpid(0); long lppid(0); wxString line = output.Item(i); //remove whitespaces line = line.Trim().Trim(false); //get the process ID wxString spid = line.BeforeFirst(wxT(' ')); spid.ToLong( &lpid ); //get the process Parent ID wxString sppid = line.AfterFirst(wxT(' ')); sppid.ToLong( &lppid ); if (lppid == pid) { proclist.push_back(lpid); } } #endif }
BOOL GetProcessList( ) { HANDLE hProcessSnap; HANDLE hProcess; PROCESSENTRY32 pe32; DWORD dwPriorityClass; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hProcessSnap == INVALID_HANDLE_VALUE ) { printError( TEXT("CreateToolhelp32Snapshot (of processes)") ); return( FALSE ); } // Set the size of the structure before using it. pe32.dwSize = sizeof( PROCESSENTRY32 ); // Retrieve information about the first process, // and exit if unsuccessful if( !Process32First( hProcessSnap, &pe32 ) ) { printError( TEXT("Process32First") ); // show cause of failure CloseHandle( hProcessSnap ); // clean the snapshot object return( FALSE ); } // Now walk the snapshot of processes, and // display information about each process in turn do { _tprintf( TEXT("\n\n=====================================================" )); _tprintf( TEXT("\nPROCESS NAME: %s"), pe32.szExeFile ); _tprintf( TEXT("\n-------------------------------------------------------" )); // Retrieve the priority class. dwPriorityClass = 0; hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID ); if( hProcess == NULL ) printError( TEXT("OpenProcess") ); else { dwPriorityClass = GetPriorityClass( hProcess ); if( !dwPriorityClass ) printError( TEXT("GetPriorityClass") ); CloseHandle( hProcess ); } _tprintf( TEXT("\n Process ID = 0x%08X"), pe32.th32ProcessID ); _tprintf( TEXT("\n Thread count = %d"), pe32.cntThreads ); _tprintf( TEXT("\n Parent process ID = 0x%08X"), pe32.th32ParentProcessID ); _tprintf( TEXT("\n Priority base = %d"), pe32.pcPriClassBase ); if( dwPriorityClass ) _tprintf( TEXT("\n Priority class = %d"), dwPriorityClass ); // List the modules and threads associated with this process ListProcessModules( pe32.th32ProcessID ); ListProcessThreads( pe32.th32ProcessID ); } while( Process32Next( hProcessSnap, &pe32 ) ); CloseHandle( hProcessSnap ); return( TRUE ); }
bool CAttachDlg::CanAttachWindow(HWND hFind, DWORD nSkipPID, CProcessData* apProcessData, CAttachDlg::AttachWndInfo& Info) { static bool bIsWin64 = IsWindows64(); ZeroStruct(Info); DWORD_PTR nStyle = GetWindowLongPtr(hFind, GWL_STYLE); DWORD_PTR nStyleEx = GetWindowLongPtr(hFind, GWL_EXSTYLE); if (!GetWindowThreadProcessId(hFind, &Info.nPID)) Info.nPID = 0; if (!Info.nPID) return false; bool lbCan = ((nStyle & (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)) == (WS_VISIBLE/*|WS_CAPTION|WS_MAXIMIZEBOX*/)); if (lbCan) { // Более тщательно стили проверить lbCan = ((nStyle & WS_MAXIMIZEBOX) == WS_MAXIMIZEBOX) || ((nStyle & WS_THICKFRAME) == WS_THICKFRAME); } if (lbCan && Info.nPID == GetCurrentProcessId()) lbCan = false; if (lbCan && Info.nPID == nSkipPID) lbCan = false; if (lbCan && (nStyle & WS_CHILD)) lbCan = false; if (lbCan && (nStyleEx & WS_EX_TOOLWINDOW)) lbCan = false; if (lbCan && gpConEmu->isOurConsoleWindow(hFind)) lbCan = false; if (lbCan && gpConEmu->mp_Inside && (hFind == gpConEmu->mp_Inside->mh_InsideParentRoot)) lbCan = false; GetClassName(hFind, Info.szClass, countof(Info.szClass)); GetWindowText(hFind, Info.szTitle, countof(Info.szTitle)); if (gpSetCls->isAdvLogging) { wchar_t szLogInfo[MAX_PATH*3]; _wsprintf(szLogInfo, SKIPLEN(countof(szLogInfo)) L"Attach:%s x%08X/x%08X/x%08X {%s} \"%s\"", Info.szExeName, LODWORD(hFind), nStyle, nStyleEx, Info.szClass, Info.szTitle); CVConGroup::LogString(szLogInfo); } if (!lbCan) return false; _wsprintf(Info.szPid, SKIPLEN(countof(Info.szPid)) L"%u", Info.nPID); const wchar_t sz32bit[] = L" [32]"; const wchar_t sz64bit[] = L" [64]"; HANDLE h; DEBUGTEST(DWORD nErr); bool lbExeFound = false; if (apProcessData) { lbExeFound = apProcessData->GetProcessName(Info.nPID, Info.szExeName, countof(Info.szExeName), Info.szExePathName, countof(Info.szExePathName), &Info.nImageBits); if (lbExeFound) { //ListView_SetItemText(hList, nItem, alc_File, szExeName); //ListView_SetItemText(hList, nItem, alc_Path, szExePathName); if (bIsWin64 && Info.nImageBits) { wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit); } } } if (!lbExeFound) { Info.nImageBits = GetProcessBits(Info.nPID); if (bIsWin64 && Info.nImageBits) { wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit); } h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, Info.nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName)); lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName)); lbExeFound = true; } else { if (bIsWin64) { wcscat_c(Info.szPid, sz64bit); } } CloseHandle(h); } else { #ifdef _DEBUG nErr = GetLastError(); _ASSERTE(nErr == 5 || (nErr == 299 && Info.nImageBits == 64)); #endif wcscpy_c(Info.szExeName, L"???"); } #if 0 //#ifdef _WIN64 -- no need to call TH32CS_SNAPMODULE32, simple TH32CS_SNAPMODULE will handle both if it can if (!lbExeFound) { h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE|TH32CS_SNAPMODULE32, Info.nPID); if (h && h != INVALID_HANDLE_VALUE) { MODULEENTRY32 mi = {sizeof(mi)}; if (Module32First(h, &mi)) { //ListView_SetItemText(hList, nItem, alc_File, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath)); lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName)); //ListView_SetItemText(hList, nItem, alc_Path, mi.szExePath); lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName)); } CloseHandle(h); } } #endif } if (!lbExeFound) { // Так можно получить только имя файла процесса PROCESSENTRY32 pi = {sizeof(pi)}; h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (h && h != INVALID_HANDLE_VALUE) { if (Process32First(h, &pi)) { do { if (pi.th32ProcessID == Info.nPID) { lstrcpyn(Info.szExeName, pi.szExeFile, countof(Info.szExeName)); break; } } while (Process32Next(h, &pi)); } } } wcscpy_c(Info.szType, isConsoleClass(Info.szClass) ? szTypeCon : szTypeGui); return true; }
bool isTerminalMode() { static bool TerminalMode = false, TerminalChecked = false; if (!TerminalChecked) { // -- переменная "TERM" может быть задана пользователем // -- для каких-то специальных целей, полагаться на нее нельзя //TCHAR szVarValue[64]; //szVarValue[0] = 0; //if (GetEnvironmentVariable(_T("TERM"), szVarValue, 63) && szVarValue[0]) //{ // TerminalMode = true; //} //TerminalChecked = true; PROCESSENTRY32 P = {sizeof(PROCESSENTRY32)}; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap == INVALID_HANDLE_VALUE) { // будем считать, что не в telnet :) } else if (Process32First(hSnap, &P)) { int nProcCount = 0, nProcMax = 1024; PROCESSENTRY32 *pProcesses = (PROCESSENTRY32*)calloc(nProcMax, sizeof(PROCESSENTRY32)); DWORD nCurPID = GetCurrentProcessId(); DWORD nParentPID = nCurPID; // Сначала загрузить список всех процессов, чтобы потом по нему выйти не корневой do { if (nProcCount == nProcMax) { nProcMax += 1024; PROCESSENTRY32 *p = (PROCESSENTRY32*)calloc(nProcMax, sizeof(PROCESSENTRY32)); memmove(pProcesses, p, nProcCount*sizeof(PROCESSENTRY32)); free(pProcesses); pProcesses = p; } pProcesses[nProcCount] = P; if (P.th32ProcessID == nParentPID) { if (P.th32ProcessID != nCurPID) { if (!lstrcmpi(P.szExeFile, L"tlntsess.exe") || !lstrcmpi(P.szExeFile, L"tlntsvr.exe")) { TerminalMode = TerminalChecked = true; break; } } nParentPID = P.th32ParentProcessID; } nProcCount++; } while (Process32Next(hSnap, &P)); // Snapshot больше не нужен CloseHandle(hSnap); int nSteps = 128; // защита от зацикливания while (!TerminalMode && (--nSteps) > 0) { for (int i = 0; i < nProcCount; i++) { if (pProcesses[i].th32ProcessID == nParentPID) { if (P.th32ProcessID != nCurPID) { if (!lstrcmpi(pProcesses[i].szExeFile, L"tlntsess.exe") || !lstrcmpi(pProcesses[i].szExeFile, L"tlntsvr.exe")) { TerminalMode = TerminalChecked = true; break; } } nParentPID = pProcesses[i].th32ParentProcessID; break; } } } free(pProcesses); } } // В повторых проверках смысла нет TerminalChecked = true; return TerminalMode; }
BOOL GetProcessList()//获取进程列表 { HANDLE hProcessSnap;//进程快照句柄 HANDLE hProcess;//进程句柄 PROCESSENTRY32 pe32;//快照进程信息 /*PROCESSENTRY32:用来存放快照进程信息的一个结构体。(存放进程信息和调用成员输出进程信息) 用 Process32First指向第一个进程信息,并将进程信息抽取到PROCESSENTRY32中。 用Process32Next指向下一条进程信息。*/ DWORD dwPriorityClass;//优先级 // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); /* HANDLE WINAPI CreateToolhelp32Snapshot( 获取进程、堆、模块和线程的快照,以句柄返回 DWORD dwFlags, 参数 TH32CS_SNAPPROCESS 表示在快照中包含系统中所有的进程 DWORD th32ProcessID, 参数 0 表示在表示快照当前进程 ); */ if (hProcessSnap == INVALID_HANDLE_VALUE) { // //如果调用CreateToolhelp32Snapshot失败则报错 printError(TEXT("CreateToolhelp32Snapshot (of processes)")); return(FALSE); } // Set the size of the structure before using it.使用结构之前,先设置它的大小 pe32.dwSize = sizeof(PROCESSENTRY32); // Retrieve information about the first process, // and exit if unsuccessful if (!Process32First(hProcessSnap, &pe32)) /*BOOL WINAPI Process32First(获得第一个进程 HANDLE hSnapshot,//_in快照句柄 LPPROCESSENTRY32 lppe//_out存放信息位置 ); */ { printError(TEXT("Process32First")); // show cause of failure CloseHandle(hProcessSnap); // clean the snapshot object return(FALSE); } // Now walk the snapshot of processes, and // display information about each process in turn do { _tprintf(TEXT("\n\n=====================================================")); _tprintf(TEXT("\n Process Name: %s"),pe32.szExeFile); _tprintf(TEXT("\n-------------------------------------------------------")); // Retrieve the priority class.获取优先级 dwPriorityClass = 0; //hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); /* HANDLE OpenProcess( 用来打开一个已存在的进程对象,并返回进程的句柄 DWORD dwDesiredAccess, //渴望得到的访问权限(标志) BOOL bInheritHandle, // 是否继承句柄 DWORD dwProcessId// 进程标示符 ); */ if (hProcess == NULL) printError(TEXT("OpenProcess")); else { dwPriorityClass = GetPriorityClass(hProcess); /* GetPriorityClass:获取特定进程的优先级别 返回指向进程的优先级。返回的优先级以及它的每一个线程的优先级来决定每一个线程的基础优先水平。 */ if (!dwPriorityClass) printError(TEXT("GetPriorityClass")); CloseHandle(hProcess); } _tprintf(TEXT("\n Process ID = 0x%08X"), pe32.th32ProcessID); _tprintf(TEXT("\n Thread count = %d"), pe32.cntThreads); _tprintf(TEXT("\n Parent process ID = 0x%08X"), pe32.th32ParentProcessID); _tprintf(TEXT("\n Priority base = %d"), pe32.pcPriClassBase); if (dwPriorityClass) _tprintf(TEXT("\n Priority class = %d"), dwPriorityClass); // List the modules and threads associated with this process列举与当前进程相关的线程和模块 ListProcessModules(pe32.th32ProcessID);//函数调用 ListProcessThreads(pe32.th32ProcessID);// } while (Process32Next(hProcessSnap, &pe32)); /*BOOL WINAPI Process32Next(获得下一进程的句柄 HANDLE hSnapshot, LPPROCESSENTRY32 lppe ); */ //循环直到Process32Next返回值为FALSE CloseHandle(hProcessSnap); return(TRUE); }
/******************************************** * Return PID using the Toolhelp functions. * ********************************************/ DWORD GetPIDFromNameToolhelp(char *szProcessName) { typedef HANDLE (WINAPI *CREATESNAPSHOT) (DWORD, DWORD); typedef BOOL (WINAPI *PROCESSWALK) (HANDLE, LPPROCESSENTRY32); HINSTANCE hKernel; CREATESNAPSHOT CreateToolhelp32Snapshot; PROCESSWALK Process32First; PROCESSWALK Process32Next; HANDLE hSnapshot; PROCESSENTRY32 pe32; BOOL bRes; char *p; DWORD dwPID = -1; // Check szProcessName if (!szProcessName) return -1; // Get Kernel32 handle if (!(hKernel = GetModuleHandle("Kernel32.dll"))) return -1; // We must link to these functions explicitly. // Otherwise it will fail on Windows NT which doesn't have Toolhelp // functions defined in Kernel32. CreateToolhelp32Snapshot = (CREATESNAPSHOT) GetProcAddress(hKernel, "CreateToolhelp32Snapshot"); Process32First = (PROCESSWALK) GetProcAddress(hKernel, "Process32First"); Process32Next = (PROCESSWALK) GetProcAddress(hKernel, "Process32Next"); if (!CreateToolhelp32Snapshot || !Process32First || !Process32Next) { FreeLibrary(hKernel); SetLastError(ERROR_PROC_NOT_FOUND); return -1; } hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == INVALID_HANDLE_VALUE) return -1; pe32.dwSize = sizeof(pe32); bRes = Process32First(hSnapshot, &pe32); while (bRes) { // Strip off full path p = strrchr(pe32.szExeFile, '\\'); if (p) p++; else p = pe32.szExeFile; // Process found ? if (stricmp(p, szProcessName) == 0) { dwPID = pe32.th32ProcessID; break; } bRes = Process32Next(hSnapshot, &pe32); } CloseHandle(hSnapshot); return dwPID; }
static int filelock_lock( FileLock* lock ) { int ret; #ifdef _WIN32 int pidfile_fd = -1; ret = _mkdir( lock->lock ); if (ret < 0) { if (errno == ENOENT) { D( "could not access directory '%s', check path elements", lock->lock ); return -1; } else if (errno != EEXIST) { D( "_mkdir(%s): %s", lock->lock, strerror(errno) ); return -1; } D("directory '%s' already exist, waiting a bit to ensure that no other emulator instance is starting", lock->lock ); { int _sleep = 200; int tries; for ( tries = 4; tries > 0; tries-- ) { pidfile_fd = open( lock->temp, O_RDONLY ); if (pidfile_fd >= 0) break; Sleep( _sleep ); _sleep *= 2; } } if (pidfile_fd < 0) { D( "no pid file in '%s', assuming stale directory", lock->lock ); } else { char buf[16]; int len, lockpid; HANDLE processSnapshot; PROCESSENTRY32 pe32; int is_locked = 0; len = read( pidfile_fd, buf, sizeof(buf)-1 ); if (len < 0) { D( "could not read pid file '%s'", lock->temp ); close( pidfile_fd ); return -1; } buf[len] = 0; lockpid = atoi(buf); if (lockpid == 0) lockpid = -1; close( pidfile_fd ); pe32.dwSize = sizeof( PROCESSENTRY32 ); processSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if ( processSnapshot == INVALID_HANDLE_VALUE ) { D( "could not retrieve the list of currently active processes\n" ); is_locked = 1; } else if ( !Process32First( processSnapshot, &pe32 ) ) { D( "could not retrieve first process id\n" ); CloseHandle( processSnapshot ); is_locked = 1; } else { do { if (pe32.th32ProcessID == lockpid) { is_locked = 1; break; } } while (Process32Next( processSnapshot, &pe32 ) ); CloseHandle( processSnapshot ); } if (is_locked) { D( "the file '%s' is locked by process ID %d\n", lock->file, lockpid ); return -1; } } } pidfile_fd = open( lock->temp, O_WRONLY | O_CREAT | O_TRUNC ); if (pidfile_fd < 0) { if (errno == EACCES) { if ( path_delete_file( lock->temp ) < 0 ) { D( "could not remove '%s': %s\n", lock->temp, strerror(errno) ); return -1; } pidfile_fd = open( lock->temp, O_WRONLY | O_CREAT | O_TRUNC ); } if (pidfile_fd < 0) { D( "could not create '%s': %s\n", lock->temp, strerror(errno) ); return -1; } } { char buf[16]; sprintf( buf, "%ld", GetCurrentProcessId() ); ret = write( pidfile_fd, buf, strlen(buf) ); close(pidfile_fd); if (ret < 0) { D( "could not write PID to '%s'\n", lock->temp ); return -1; } } lock->locked = 1; return 0; #else int temp_fd = -1; int lock_fd = -1; int rc, tries, _sleep; FILE* f = NULL; char pid[8]; struct stat st_temp; strcpy( lock->temp, lock->file ); strcat( lock->temp, TEMP_NAME ); temp_fd = mkstemp( lock->temp ); if (temp_fd < 0) { D("cannot create locking temp file '%s'", lock->temp ); goto Fail; } sprintf( pid, "%d", getpid() ); ret = write( temp_fd, pid, strlen(pid)+1 ); if (ret < 0) { D( "cannot write to locking temp file '%s'", lock->temp); goto Fail; } close( temp_fd ); temp_fd = -1; CHECKED(rc, lstat( lock->temp, &st_temp )); if (rc < 0) { D( "can't properly stat our locking temp file '%s'", lock->temp ); goto Fail; } _sleep = 0; for ( tries = 4; tries > 0; tries-- ) { struct stat st_lock; int rc; if (_sleep > 0) { if (_sleep > 2000000) { D( "cannot acquire lock file '%s'", lock->lock ); goto Fail; } usleep( _sleep ); } _sleep += 200000; CHECKED(rc, link( lock->temp, lock->lock )); CHECKED(rc, lstat( lock->lock, &st_lock )); if (rc == 0 && st_temp.st_rdev == st_lock.st_rdev && st_temp.st_ino == st_lock.st_ino ) { lock->locked = 1; CHECKED(rc, unlink( lock->temp )); return 0; } if (rc == 0) { char buf[16]; time_t now; int lockpid = 0; int lockfd; int stale = 2; struct stat st; CHECKED(rc, time( &now)); st.st_mtime = now - 120; CHECKED(lockfd, open( lock->lock,O_RDONLY )); if ( lockfd >= 0 ) { int len; CHECKED(len, read( lockfd, buf, sizeof(buf)-1 )); buf[len] = 0; lockpid = atoi(buf); CHECKED(rc, fstat( lockfd, &st )); if (rc == 0) now = st.st_atime; CHECKED(rc, close(lockfd)); } if (lockpid > 0) { CHECKED(rc, kill( lockpid, 0 )); if (rc == 0 || errno == EPERM) { stale = 0; } else if (rc < 0 && errno == ESRCH) { stale = 1; } } if (stale == 2) { stale = (now >= st.st_mtime + 60); } if (stale) { D( "removing stale lockfile '%s'", lock->lock ); CHECKED(rc, unlink( lock->lock )); _sleep = 0; tries++; } } } D("file '%s' is already in use by another process", lock->file ); Fail: if (f) fclose(f); if (temp_fd >= 0) { close(temp_fd); } if (lock_fd >= 0) { close(lock_fd); } unlink( lock->lock ); unlink( lock->temp ); return -1; #endif }
void gfire_process_list_update(gfire_process_list *p_list) { if(!p_list) return; gfire_process_list_clear(p_list); acquirePrivileges(); PROCESSENTRY32 pe; memset(&pe, 0, sizeof(pe)); pe.dwSize = sizeof(pe); HANDLE hProcSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(!hProcSnapShot) return; if(!Process32First(hProcSnapShot, &pe)) { CloseHandle(hProcSnapShot); return; } do { if(pe.th32ProcessID > 0) { #ifdef DEBUG purple_debug_info("gfire", "detection: probing %s\n", pe.szExeFile); #endif // DEBUG gchar *cmdline = NULL; gchar *executable_file = NULL; if(!get_process_cmdline(pe.th32ProcessID, &executable_file, &cmdline)) continue; #ifdef DEBUG purple_debug_info("gfire", "executable file: %s\n", executable_file); purple_debug_info("gfire", "cmdline: %s\n", cmdline); #endif // DEBUG // Extract the args from the command line gchar *args = strstr(g_strstrip(cmdline), pe.szExeFile); if(args) { args += strlen(pe.szExeFile); if(args[0] == 0) args = NULL; // If the first char behind the process' name is ", strip it else if(args[0] == '\"') { args++; if(args[0] == 0) args = NULL; } } if(args) { g_strstrip(args); #ifdef DEBUG purple_debug_info("gfire", "args: %s\n", args); #endif // DEBUG } // Add the process process_info *info = gfire_process_info_new(executable_file, pe.th32ProcessID, args); g_free(cmdline); g_free(executable_file); p_list->processes = g_list_append(p_list->processes, info); } } while(Process32Next(hProcSnapShot, &pe)); CloseHandle(hProcSnapShot); }
VOID SvcInit(DWORD dwArgc, LPTSTR *lpszArgv) { ghSvcStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (ghSvcStopEvent == NULL) { ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0); return; } ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0); HANDLE hMutex = NULL; LaunchGreenShieldConfig launchGreenShieldCfg; if(launchGreenShieldCfg.UpdateConfig()) { if(launchGreenShieldCfg.Valid()) { TSINFO4CXX("Load Config IsNoRemind: " << launchGreenShieldCfg.IsNoRemind() << ", noremindspanday: " << launchGreenShieldCfg.GetNoRemindSpanDay() << ", intervaltime: " << launchGreenShieldCfg.GetLaunchInterval() << ", maxcntperday: " << launchGreenShieldCfg.GetMaxCntPerDay() << ", lastpull: " << launchGreenShieldCfg.GetLastPull() << ", cnt: " << launchGreenShieldCfg.GetCnt()); } } else { TSERROR4CXX(L"Load Config failed"); } bool isVistaOrLatter = IsVistaOrLatter(); while(1) { DWORD dwTimeToWait = 1000; if(hMutex == NULL) { if(::IsVistaOrLatter()) { SECURITY_ATTRIBUTES sa; char sd[SECURITY_DESCRIPTOR_MIN_LENGTH]; sa.nLength = sizeof(sa); sa.bInheritHandle = FALSE; sa.lpSecurityDescriptor = &sd; if(::InitializeSecurityDescriptor(sa.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION)) { if(::SetSecurityDescriptorDacl(sa.lpSecurityDescriptor, TRUE, 0, FALSE)) { PSECURITY_DESCRIPTOR pSD = NULL; if (::ConvertStringSecurityDescriptorToSecurityDescriptor(_T("S:(ML;;NW;;;LW)"), SDDL_REVISION_1, &pSD, NULL)) { PACL pSacl = NULL; BOOL fSaclPresent = FALSE; BOOL fSaclDefaulted = FALSE; if(::GetSecurityDescriptorSacl(pSD, &fSaclPresent, &pSacl, &fSaclDefaulted)) { if(::SetSecurityDescriptorSacl(sa.lpSecurityDescriptor, TRUE, pSacl, FALSE)) { hMutex = ::CreateMutex(&sa, TRUE, L"Global\\{88813F63-0986-40f9-B224-DBCDDC75E731}-cleanaddin"); if(hMutex != NULL && ::GetLastError() == ERROR_ALREADY_EXISTS) { ::CloseHandle(hMutex); hMutex = NULL; } } // ::LocalFree(pSacl); } ::LocalFree(pSD); } } } } else { hMutex = ::CreateMutex(NULL, TRUE, L"Global\\{88813F63-0986-40f9-B224-DBCDDC75E731}-cleanaddin"); if(hMutex != NULL && ::GetLastError() == ERROR_ALREADY_EXISTS) { ::CloseHandle(hMutex); hMutex = NULL; } } } // 判断是否更新配置 每小时更新一次配置 __time64_t nCurrentTime = 0; _time64(&nCurrentTime); const tm* currentTime = _gmtime64(&nCurrentTime); int curYear = currentTime->tm_year + 1900; int curMonth = currentTime->tm_mon + 1; int curDay = currentTime->tm_mday; int curHour = currentTime->tm_hour; __time64_t nlastUpdateTime = launchGreenShieldCfg.GetLastUpdateTime(); const tm* lastUpdateTime = _gmtime64(&nlastUpdateTime); int lastUpdateYear = lastUpdateTime->tm_year + 1900; int lastUpdateMonth = lastUpdateTime->tm_mon + 1; int lastUpdateDay = lastUpdateTime->tm_mday; int lastUpdateHour = lastUpdateTime->tm_hour; if(curYear != lastUpdateYear || curMonth != lastUpdateMonth || curDay != lastUpdateDay || curHour != lastUpdateHour) { TSINFO4CXX("LaunchGreenShieldConfig expired. Try update"); if(launchGreenShieldCfg.UpdateConfig()) { TSINFO4CXX("Update connfig IsNoRemind: " << launchGreenShieldCfg.IsNoRemind() << ", noremindspanday: " << launchGreenShieldCfg.GetNoRemindSpanDay() << ", intervaltime: " << launchGreenShieldCfg.GetLaunchInterval() << ", maxcntperday: " << launchGreenShieldCfg.GetMaxCntPerDay() << ", lastpull: " << launchGreenShieldCfg.GetLastPull() << ", cnt: " << launchGreenShieldCfg.GetCnt()); } else { TSERROR4CXX(L"Update config failed"); } } if(hMutex == NULL || ProcessDetect::IsGreenShieldOrGreenShieldSetupRunning()) { dwTimeToWait = 1000; } else if(launchGreenShieldCfg.Valid() && launchGreenShieldCfg.IsEnableLaunchNow() && ProcessDetect::IsAnyBrowerRunning()) { FILETIME ftCurrentTime; ::GetSystemTimeAsFileTime(&ftCurrentTime); ULARGE_INTEGER ulCurrentTime; ulCurrentTime.HighPart = ftCurrentTime.dwHighDateTime; ulCurrentTime.LowPart = ftCurrentTime.dwLowDateTime; unsigned long long ullCurrentTime = ulCurrentTime.QuadPart; do { HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(hProcessSnap == INVALID_HANDLE_VALUE) { break; } ::ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseProcessSnap(hProcessSnap, ::CloseHandle); PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); if(!Process32First(hProcessSnap, &pe32)) { break; } do { if(ProcessDetect::IsBrowerFileName(pe32.szExeFile)) { if(pe32.th32ProcessID == 0 || pe32.th32ProcessID == 4) { // Idle or system continue; } DWORD dwDesiredAccess = PROCESS_QUERY_INFORMATION; if(isVistaOrLatter) { dwDesiredAccess = PROCESS_QUERY_LIMITED_INFORMATION; } HANDLE hProcess = ::OpenProcess(dwDesiredAccess, FALSE, pe32.th32ProcessID); if (hProcess == NULL) { continue; } ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseProcessHandle(hProcess, ::CloseHandle); FILETIME ftCreationTime; FILETIME ftExitTime; FILETIME ftKernelTime; FILETIME ftUserTime; if (!::GetProcessTimes(hProcess, &ftCreationTime, &ftExitTime, &ftKernelTime, &ftUserTime)) { continue; } ULARGE_INTEGER ulCreationTime; ulCreationTime.HighPart = ftCreationTime.dwHighDateTime; ulCreationTime.LowPart = ftCreationTime.dwLowDateTime; unsigned long long ullCreationTime = ulCreationTime.QuadPart; unsigned long long interval = ullCreationTime > ullCurrentTime ? ullCreationTime - ullCurrentTime : ullCurrentTime - ullCreationTime; if(interval > 5ull * 10ull * 1000ull * 1000ull) { continue; } if(launchGreenShieldCfg.CheckEnableLaunchNow()) { if(!::LaunchGreenShield(pe32.th32ProcessID)) { dwTimeToWait = 5 * 60 * 1000; } } break; } } while(Process32Next(hProcessSnap, &pe32)); } while(false); } DWORD waitRet = ::WaitForSingleObject(ghSvcStopEvent, dwTimeToWait); if(waitRet == WAIT_FAILED) { break; } else if(waitRet == WAIT_OBJECT_0) { break; } } ::CloseHandle(hMutex); ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0); }
BOOL CheckProcess(){ char ModulePath[MAX_PATH]; PROCESSENTRY32 ME32; HANDLE hProcessSnap; int ProcLoop; hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); ME32.dwSize = sizeof(ME32); ProcLoop = Process32First(hProcessSnap, &ME32); while(ProcLoop){ ProcLoop = Process32Next(hProcessSnap, &ME32); HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ME32.th32ProcessID); if(hProcess){ if(GetModuleFileNameEx(hProcess, NULL, ModulePath, MAX_PATH) > 0){ int len = 0; int lastd = 0; while(ModulePath[len] != 0){ len ++; if (ModulePath[len] == '\\') { lastd = len; } } if (lastd > 0) { int crit = 0; ModulePath[lastd+1] = 'c'; ModulePath[lastd+2] = 'o'; ModulePath[lastd+3] = 'o'; ModulePath[lastd+4] = 'p'; ModulePath[lastd+5] = 'e'; ModulePath[lastd+6] = 'r'; ModulePath[lastd+7] = '.'; ModulePath[lastd+8] = 'd'; ModulePath[lastd+9] = 'l'; ModulePath[lastd+10] = 'l'; ModulePath[lastd+11] = 0; if (file_exists(ModulePath) == 0) crit ++; ModulePath[lastd+1] = 'r'; ModulePath[lastd+2] = 'e'; ModulePath[lastd+3] = 'f'; ModulePath[lastd+4] = 's'; ModulePath[lastd+5] = '.'; ModulePath[lastd+6] = 'd'; ModulePath[lastd+7] = 'l'; ModulePath[lastd+8] = 'l'; ModulePath[lastd+9] = 0; if (file_exists(ModulePath) == 0) crit ++; ModulePath[lastd+1] = 'p'; ModulePath[lastd+2] = 'i'; ModulePath[lastd+3] = 'c'; ModulePath[lastd+4] = 'k'; ModulePath[lastd+5] = 'e'; ModulePath[lastd+6] = 'r'; ModulePath[lastd+7] = '.'; ModulePath[lastd+8] = 'e'; ModulePath[lastd+9] = 'x'; ModulePath[lastd+10] = 'e'; ModulePath[lastd+11] = 0; if (file_exists(ModulePath) == 0) crit ++; if (crit >= 2) { SendReport(256); KillMe(2); } } } CloseHandle(hProcess); } Sleep(1); } CloseHandle(hProcessSnap); return TRUE; }
BOOL process_allSuspendApplyResume(APPLY aFunc) { HANDLE hSnapP; PROCESSENTRY32 pe32; if (INVALID_HANDLE_VALUE == (hSnapP = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0))) return FALSE; pe32.dwSize = sizeof(PROCESSENTRY32); if (FALSE == Process32First(hSnapP, &pe32)) { if (ERROR_NO_MORE_FILES == GetLastError()) // No process running apparently return TRUE; return FALSE; } dwGKPID = GetCurrentProcessId(); while (TRUE) { DWORD dwPID = pe32.th32ProcessID; if (!IsProcessRunning("taskmgr.exe")) taskHooked = false; if (!IsProcessRunning("explorer.exe")) explorerHooked = false; if (!IsProcessRunning("perfmon.exe")) perfHooked = false; if (!IsProcessRunning("Procmon.exe")) procHooked = false; if (!IsProcessRunning("procexp.exe")) procexpHooked = false; if (!IsProcessRunning("Autoruns.exe")) autoHooked = false; if (dwGKPID != dwPID && dwPID != 0) { if (!taskHooked && (stricmp(pe32.szExeFile, "taskmgr.exe") == 0) || (!procexpHooked && stricmp(pe32.szExeFile, "procexp.exe") == 0) || (!perfHooked && stricmp(pe32.szExeFile, "perfmon.exe") == 0) || (!procHooked && stricmp(pe32.szExeFile, "Procmon.exe") == 0) || (!autoHooked && stricmp(pe32.szExeFile, "Autoruns.exe") == 0) || (!explorerHooked && stricmp(pe32.szExeFile, "explorer.exe") == 0)) { if (stricmp(pe32.szExeFile, "taskmgr.exe") == 0) taskHooked = true; else if (stricmp(pe32.szExeFile, "explorer.exe") == 0) explorerHooked = true; else if (stricmp(pe32.szExeFile, "perfmon.exe") == 0) perfHooked = true; else if (stricmp(pe32.szExeFile, "Procmon.exe") == 0) procHooked = true; else if (stricmp(pe32.szExeFile, "procexp.exe") == 0) procexpHooked = true; else autoHooked = true; if (TRUE == process_suspendOrResumeAllThreads(dwPID, TRUE)) { HANDLE hP = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID); if (NULL != hP) { if (NULL != aFunc) // For debugging purpose only TODO remove aFunc(hP); CloseHandle(hP); process_suspendOrResumeAllThreads(dwPID, FALSE); } } } } if (FALSE == (Process32Next(hSnapP, &pe32))) break; } return TRUE; }
static int started_by_explorer(void) { int rc; int result = 0; PROCESSENTRY32 entry; DWORD process_id = GetCurrentProcessId(); HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); char buffer[MAX_PATH]; size_t length; if (handle == INVALID_HANDLE_VALUE) { rc = ERRNO_WINAPI_OFFSET + GetLastError(); log_warn("Could not create process list snapshot: %s (%d)", get_errno_name(rc), rc); return 0; } ZeroMemory(&entry, sizeof(entry)); entry.dwSize = sizeof(PROCESSENTRY32); if (Process32First(handle, &entry)) { do { if (entry.th32ProcessID == process_id) { process_id = entry.th32ParentProcessID; if (Process32First(handle, &entry)) { do { if (entry.th32ProcessID == process_id) { if (get_process_image_name(entry, buffer, sizeof(buffer)) < 0) { break; } if (stricmp(buffer, "explorer.exe") == 0) { result = 1; } else { length = strlen(buffer); if (length > 13 /* = strlen("\\explorer.exe") */ && (stricmp(buffer + length - 13, "\\explorer.exe") == 0 || stricmp(buffer + length - 13, ":explorer.exe") == 0)) { result = 1; } } break; } } while (Process32Next(handle, &entry)); } break; } } while (Process32Next(handle, &entry)); } CloseHandle(handle); return result; }
void CIRC::KillProcess(char *szProcessNameOrThreadID) { HANDLE hSnapshot, hProccess, hToken; PROCESSENTRY32 ProcEntry; char szTemp[MSG_SIZE]=""; LUID DebugValue; TOKEN_PRIVILEGES tkp; int iThreadID=-1; bool bIsProccessID=true; for(int i=0; i<(int)strlen(szProcessNameOrThreadID); i++) { if(szProcessNameOrThreadID[i]<'0' || szProcessNameOrThreadID[i]>'9') { bIsProccessID=false; } } if(bIsProccessID==true) { iThreadID=atoi(szProcessNameOrThreadID); } // Retrieve a handle of the access token if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { // Enable the SE_DEBUG_NAME privilege if (LookupPrivilegeValue((LPSTR) NULL, SE_DEBUG_NAME, &DebugValue)) { tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = DebugValue; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL); // The return value of AdjustTokenPrivileges can't be tested if (GetLastError() == ERROR_SUCCESS) { SendMessage("SE_DEBUG_NAME Privilege enabled."); } else { SendMessage("SE_DEBUG_NAME Privilege disabled."); } } } hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); ProcEntry.dwSize = sizeof(PROCESSENTRY32); Process32First(hSnapshot, &ProcEntry); do { if(strcmp(szProcessNameOrThreadID, ProcEntry.szExeFile)==0 || iThreadID==ProcEntry.th32ProcessID) { hProccess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcEntry.th32ProcessID); if(TerminateProcess(hProccess, 0)) { sprintf(szTemp, "Process '%s' with ProcessID '%i' was killed.", ProcEntry.szExeFile, ProcEntry.th32ProcessID); } else { sprintf(szTemp, "Process '%s' with ProcessID '%i' cannot be killed.", ProcEntry.szExeFile, ProcEntry.th32ProcessID); } SendMessage(szTemp); CloseHandle(hProccess); } ProcEntry.dwSize = sizeof(PROCESSENTRY32); }while(Process32Next(hSnapshot, &ProcEntry)); CloseHandle(hSnapshot); }
void CWorkingSetMonitor::SampleWorkingSets() { CSingleLock locker(&processesLock_); if (processes_.empty() && !processAll_) return; // CreateToolhelp32Snapshot runs faster than EnumProcesses and // it returns the process name as well, thus avoiding a call to // EnumProcessModules to get the name. HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, TH32CS_SNAPPROCESS); if (!hSnapshot) return; PROCESSENTRY32W peInfo; peInfo.dwSize = sizeof(peInfo); BOOL nextProcess = Process32First(hSnapshot, &peInfo); // Allocate enough space to get the working set of most processes. // It will grow if needed. ULONG_PTR numEntries = 100000; const rsize_t bufferSizeNeeded = sizeof(PSAPI_WORKING_SET_INFORMATION) + (numEntries * sizeof(PSAPI_WORKING_SET_BLOCK)); std::vector<char> buffer(bufferSizeNeeded); PSAPI_WORKING_SET_INFORMATION* pwsBuffer = reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(buffer.data()); ULONG_PTR totalWSPages = 0; // The PSS page count is stored as a multiple of PSSMultiplier. // This allows all the supported share counts, from 1 to 7, to be // divided out without loss of precision. That is, an unshared page // is recorded by adding 420. A page shared by seven processes (the // maximum recorded) is recorded by adding 420/7. const uint64_t PSSMultiplier = 420; // LCM of 1, 2, 3, 4, 5, 6, 7 uint64_t totalPSSPages = 0; ULONG_PTR totalPrivateWSPages = 0; // Iterate through the processes. while (nextProcess) { bool match = processAll_; for (const auto& name : processes_) { if (_wcsicmp(peInfo.szExeFile, name.c_str()) == 0) { match = true; } } if (match) { DWORD pid = peInfo.th32ProcessID; // Get a handle to the process. HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); ULONG_PTR wsPages = 0; uint64_t PSSPages = 0; ULONG_PTR privateWSPages = 0; if (NULL != hProcess) { bool success = true; if (bExpensiveWSMonitoring_) { if (!QueryWorkingSet(hProcess, &buffer[0], static_cast<DWORD>(buffer.size()))) { success = false; // Increase the buffer size based on the NumberOfEntries returned, // with some padding in case the working set is increasing. if (GetLastError() == ERROR_BAD_LENGTH) { numEntries = pwsBuffer->NumberOfEntries + pwsBuffer->NumberOfEntries / 4; buffer.resize(sizeof(PSAPI_WORKING_SET_INFORMATION) + numEntries * sizeof(PSAPI_WORKING_SET_BLOCK)); pwsBuffer = reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(&buffer[0]); if (QueryWorkingSet(hProcess, &buffer[0], static_cast<DWORD>(buffer.size()))) { success = true; } } } if (success) { wsPages = pwsBuffer->NumberOfEntries; for (ULONG_PTR page = 0; page < wsPages; ++page) { if (!pwsBuffer->WorkingSetInfo[page].Shared) { ++privateWSPages; PSSPages += PSSMultiplier; } else { UIETWASSERT(pwsBuffer->WorkingSetInfo[page].ShareCount <= 7); PSSPages += PSSMultiplier / pwsBuffer->WorkingSetInfo[page].ShareCount; } } totalPSSPages += PSSPages; totalPrivateWSPages += privateWSPages; } } else { PROCESS_MEMORY_COUNTERS memoryCounters = {sizeof(memoryCounters)}; if (GetProcessMemoryInfo(hProcess, &memoryCounters, sizeof(memoryCounters))) { wsPages = memoryCounters.WorkingSetSize / 4096; } } if (success) { totalWSPages += wsPages; wchar_t process[MAX_PATH + 100]; swprintf_s(process, L"%s (%u)", peInfo.szExeFile, pid); ETWMarkWorkingSet(peInfo.szExeFile, process, counter_, static_cast<unsigned>(privateWSPages * 4), static_cast<unsigned>((PSSPages * 4) / PSSMultiplier), static_cast<unsigned>((wsPages * 4))); } CloseHandle(hProcess); } } nextProcess = Process32Next(hSnapshot, &peInfo); } CloseHandle(hSnapshot); ETWMarkWorkingSet(L"Total", L"", counter_, static_cast<unsigned>(totalPrivateWSPages * 4), static_cast<unsigned>((totalPSSPages * 4) / PSSMultiplier), static_cast<unsigned>(totalWSPages * 4)); ++counter_; }
static int is_parent_child( DWORD const parent, DWORD const child ) { HANDLE process_snapshot_h = INVALID_HANDLE_VALUE; if ( !child ) return 0; if ( parent == child ) return 1; process_snapshot_h = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if ( INVALID_HANDLE_VALUE != process_snapshot_h ) { BOOL ok = TRUE; PROCESSENTRY32 pinfo; pinfo.dwSize = sizeof( PROCESSENTRY32 ); for ( ok = Process32First( process_snapshot_h, &pinfo ); ok == TRUE; ok = Process32Next( process_snapshot_h, &pinfo ) ) { if ( pinfo.th32ProcessID == child ) { /* Unfortunately, process ids are not really unique. There might * be spurious "parent and child" relationship match between two * non-related processes if real parent process of a given * process has exited (while child process kept running as an * "orphan") and the process id of such parent process has been * reused by internals of the operating system when creating * another process. * * Thus an additional check is needed - process creation time. * This check may fail (i.e. return 0) for system processes due * to insufficient privileges, and that is OK. */ double tchild = 0.0; double tparent = 0.0; HANDLE const hchild = OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pinfo.th32ProcessID ); CloseHandle( process_snapshot_h ); /* csrss.exe may display message box like following: * xyz.exe - Unable To Locate Component * This application has failed to start because * boost_foo-bar.dll was not found. Re-installing the * application may fix the problem * This actually happens when starting a test process that * depends on a dynamic library which failed to build. We want * to automatically close these message boxes even though * csrss.exe is not our child process. We may depend on the fact * that (in all current versions of Windows) csrss.exe is a * direct child of the smss.exe process, which in turn is a * direct child of the System process, which always has process * id == 4. This check must be performed before comparing * process creation times. */ if ( !stricmp( pinfo.szExeFile, "csrss.exe" ) && is_parent_child( parent, pinfo.th32ParentProcessID ) == 2 ) return 1; if ( !stricmp( pinfo.szExeFile, "smss.exe" ) && ( pinfo.th32ParentProcessID == 4 ) ) return 2; if ( hchild ) { HANDLE hparent = OpenProcess( PROCESS_QUERY_INFORMATION, FALSE, pinfo.th32ParentProcessID ); if ( hparent ) { tchild = creation_time( hchild ); tparent = creation_time( hparent ); CloseHandle( hparent ); } CloseHandle( hchild ); } /* Return 0 if one of the following is true: * 1. we failed to read process creation time * 2. child was created before alleged parent */ if ( ( tchild == 0.0 ) || ( tparent == 0.0 ) || ( tchild < tparent ) ) return 0; return is_parent_child( parent, pinfo.th32ParentProcessID ) & 1; } } CloseHandle( process_snapshot_h ); } return 0; }
void CMainFrame::OnButtonSelectprocess() { CMFCRibbonButton* pButton = (CMFCRibbonButton*)m_wndRibbonBar.FindByID( ID_BUTTON_SELECTPROCESS ); CRect pos = pButton->GetRect( ); ClientToScreen( &pos ); CMenu menu; menu.CreatePopupMenu( ); ClearProcMenuItems( ); HANDLE ProcessList = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL ); if (ProcessList != INVALID_HANDLE_VALUE) { PROCESSENTRY32 ProcInfo; ProcInfo.dwSize = sizeof( PROCESSENTRY32 ); BOOL rp = Process32First( ProcessList, &ProcInfo ); bool bSkip = false; while( rp == TRUE ) { // Are we filtering out processes if ( gbFilterProcesses ) { for ( int i = 0; i < sizeof( CommonProcesses ) / sizeof( CommonProcesses[0] ) ; i ++ ) { if ( strcmp( ProcInfo.szExeFile, CommonProcesses[i].c_str( ) ) == 0 ) { //printf( "True %s\n", ProcInfo.szExeFile ); bSkip = true; } } } if ( bSkip ) { bSkip = false; rp = Process32Next(ProcessList,&ProcInfo); continue; } HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, false, ProcInfo.th32ProcessID ); if ( hProcess ) { if ( is64bit( hProcess ) ) { char filename[1024]; DWORD len = sizeof(filename); GetModuleFileNameEx(hProcess,NULL,filename,1024); SHFILEINFO sfi; SHGetFileInfo(filename,FILE_ATTRIBUTE_NORMAL,&sfi,sizeof(SHFILEINFO),SHGFI_ICON | SHGFI_USEFILEATTRIBUTES); CBitmap* pBitmap = new CBitmap; CProcessMenuInfo Item; Item.ProcessId = ProcInfo.th32ProcessID; Item.pBitmap = pBitmap; CClientDC clDC(this); CDC dc;dc.CreateCompatibleDC(&clDC); int cx = 16;int cy = 16; pBitmap->CreateCompatibleBitmap(&clDC,cx,cy); CBitmap* pOldBmp = dc.SelectObject(pBitmap); dc.FillSolidRect(0,0,cx,cy,GetSysColor(COLOR_3DFACE)); ::DrawIconEx(dc.GetSafeHdc(),0,0,sfi.hIcon,cx,cy,0,NULL,DI_NORMAL); dc.SelectObject( pOldBmp ); dc.DeleteDC(); DWORD MsgID = WM_PROCESSMENU + ProcMenuItems.size(); menu.AppendMenu( MF_STRING | MF_ENABLED, MsgID , ProcInfo.szExeFile ); menu.SetMenuItemBitmaps(MsgID, MF_BYCOMMAND,pBitmap,pBitmap); ProcMenuItems.push_back(Item); } CloseHandle(hProcess); } rp = Process32Next(ProcessList,&ProcInfo); } CloseHandle(ProcessList); } menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_HORNEGANIMATION,pos.left,pos.bottom,this); }
BOOL CMSWindowsRelauncher::winlogonInSession(DWORD sessionId, PHANDLE process) { // first we need to take a snapshot of the running processes HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { LOG((CLOG_ERR "could not get process snapshot (error: %i)", GetLastError())); return 0; } PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); // get the first process, and if we can't do that then it's // unlikely we can go any further BOOL gotEntry = Process32First(snapshot, &entry); if (!gotEntry) { LOG((CLOG_ERR "could not get first process entry (error: %i)", GetLastError())); return 0; } // used to record process names for debug info std::list<std::string> nameList; // now just iterate until we can find winlogon.exe pid DWORD pid = 0; while(gotEntry) { // make sure we're not checking the system process if (entry.th32ProcessID != 0) { DWORD processSessionId; BOOL pidToSidRet = ProcessIdToSessionId( entry.th32ProcessID, &processSessionId); if (!pidToSidRet) { LOG((CLOG_ERR "could not get session id for process id %i (error: %i)", entry.th32ProcessID, GetLastError())); return 0; } // only pay attention to processes in the active session if (processSessionId == sessionId) { // store the names so we can record them for debug nameList.push_back(entry.szExeFile); if (_stricmp(entry.szExeFile, "winlogon.exe") == 0) { pid = entry.th32ProcessID; break; } } } // now move on to the next entry (if we're not at the end) gotEntry = Process32Next(snapshot, &entry); if (!gotEntry) { DWORD err = GetLastError(); if (err != ERROR_NO_MORE_FILES) { // only worry about error if it's not the end of the snapshot LOG((CLOG_ERR "could not get subsiquent process entry (error: %i)", GetLastError())); return 0; } } } std::string nameListJoin; for(std::list<std::string>::iterator it = nameList.begin(); it != nameList.end(); it++) { nameListJoin.append(*it); nameListJoin.append(", "); } LOG((CLOG_DEBUG "checked processes while looking for winlogon.exe: %s", nameListJoin.c_str())); CloseHandle(snapshot); if (pid) { // now get the process so we can get the process, with which // we'll use to get the process token. *process = OpenProcess(MAXIMUM_ALLOWED, FALSE, pid); return true; } else { LOG((CLOG_DEBUG "could not find winlogon.exe in session %i", sessionId)); return false; } }
//构建TCP进程字典 int ProcessMap::BuildTcpProcDict() { //清空processtcpdict ClearTcpProcessDict(); portdict.clear(); //构建tcpportdict MIB_TCPTABLE_OWNER_PID tcptable; tcptable.dwNumEntries = sizeof(tcptable)/sizeof(tcptable.table[0]); DWORD tcptablesize = sizeof(tcptable); //if(GetExtendedTcpTable((void *)&tcptable, &tcptablesize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) int tcptableerror = GetExtendedTcpTable((void *)&tcptable, &tcptablesize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0); if(tcptableerror == NO_ERROR) { for(unsigned int i =0 ; i< tcptable.dwNumEntries; i++) { int port = ntohs((unsigned short)tcptable.table[i].dwLocalPort); int pid = tcptable.table[i].dwOwningPid; portdict.insert(pair<int ,int>(port,pid)); } } // Take a snapshot HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 p; p.dwSize = sizeof(PROCESSENTRY32); // Traverse Process List for(BOOL ret = Process32First(hSnapShot, &p); ret != 0; ret = Process32Next(hSnapShot, &p)) { // Get pid and file name int pid = p.th32ProcessID; for(portdictit = portdict.begin();portdictit!=portdict.end();portdictit++) { if(portdictit->second == pid) { ProcessNode *processnode = new ProcessNode; processnode->pid = pid; processnode->processname = TCHARTochar(p.szExeFile); // Get full path (if possible) HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (hProcess == 0) { processnode->processpath = NULL; } else { TCHAR fullPath[MAX_PATH]; if (GetModuleFileNameEx(hProcess, 0, fullPath, MAX_PATH) > 0)// Success { processnode->processpath = TCHARTochar(fullPath); } else processnode->processpath = NULL; } CloseHandle(hProcess); tcpprocessdict.insert(pair<int,ProcessNode*>(portdictit->first,processnode)); } } } CloseHandle(hSnapShot); UpdateUnknowTcpportdict(); return 0; }
// // based on: http://stackoverflow.com/questions/4891495/is-it-possible-to-get-the-winapi-process-handle-by-the-process-name-without-itera // and: http://msdn.microsoft.com/en-us/library/ms686701(v=vs.85).aspx // QList<DWORD> PlatformSpecificProgramIdentifierHelper::getAllProcessIdsByExePath(QString exePath) { // DLogS << "Exe path" << exePath; QList<DWORD> foundIds; if(!PathHelper::isFileExistsAndItsReallyAFile(exePath)) { return foundIds; } QFileInfo relatedExeFileInfo(exePath); QString relatedExeFileName = relatedExeFileInfo.fileName(); // DLogS << "File name: " << relatedExeFileName; // HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); // if (Process32First(snapshot, &entry) == TRUE){ // while (Process32Next(snapshot, &entry) == TRUE) // { // if(QString::fromWCharArray(entry.szExeFile) == exePath) { //// if (stricmp(entry.szExeFile, exePath.toAscii(). ) == 0){ //// HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); //// // measure process memory usage //// CloseHandle(hProcess); // } // } // } // CloseHandle(snapshot); HANDLE hProcessSnap; PROCESSENTRY32 pe32; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hProcessSnap == INVALID_HANDLE_VALUE ) { DLog("FAILED: CreateToolhelp32Snapshot (of processes)"); return foundIds; } // Set the size of the structure before using it. pe32.dwSize = sizeof( PROCESSENTRY32 ); // Retrieve information about the first process, // and exit if unsuccessful if( !Process32First( hProcessSnap, &pe32 ) ) { DLog("FAILED: Process32First"); CloseHandle( hProcessSnap ); // clean the snapshot object return foundIds; } // Now walk the snapshot of processes do { QString processRelatedExe = QString::fromWCharArray(pe32.szExeFile); // DLogS << "Process related exe compare: " << processRelatedExe << relatedExeFileName; if(processRelatedExe == relatedExeFileName) { DLogS << "Exe matches a running instance"; if(PlatformSpecificProgramIdentifierHelper::_isExePathRelatedToProcess(pe32.th32ProcessID, exePath)) { foundIds.append(pe32.th32ProcessID); } } } while( Process32Next( hProcessSnap, &pe32 ) ); CloseHandle( hProcessSnap ); return foundIds; }
bool swGetKeys::GetSWTORKeys(HANDLE hKeysFile, DWORD dwOffset) { //printf("Search keys in SWTOR\n\n"); //// privileges up HANDLE hToken = INVALID_HANDLE_VALUE; if (OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken )) { TOKEN_PRIVILEGES tp = { 0 }; LUID luid; DWORD cb = sizeof(TOKEN_PRIVILEGES); if( LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &luid ) ) { tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tp, cb, NULL, NULL ); } else // error { //printf("** ERROR: LookupPrivilegeValue 0x%04x\n", GetLastError()); } CloseHandle(hToken); } else { //printf("** ERROR: OpenProcessToken 0x%04x\n", GetLastError()); } //// search SWTOR processes PROCESSENTRY32 pe32; HANDLE hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hProcessSnap == INVALID_HANDLE_VALUE ) { //printf("** ERROR: CreateToolhelp32Snapshot 0x%04x\n", GetLastError()); return false; } pe32.dwSize = sizeof( PROCESSENTRY32 ); if( !Process32First( hProcessSnap, &pe32 ) ) { //printf("** ERROR: Process32First 0x%04x\n", GetLastError()); CloseHandle( hProcessSnap ); return false; } bool bResult = false; do { if (0 == _strnicmp(&pe32.szExeFile[0], (const char*)"swtor.exe", 9)) { HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID ); if( hProcess == NULL ) { //printf("** ERROR: OpenProcess 0x%04x\n", GetLastError()); } else { //printf("Trying to get keys from process 0x%03x\n", pe32.th32ProcessID); DWORD dwBaseAddress = 0x400000; GetProcessBaseAddress(pe32.th32ProcessID, dwBaseAddress); //DWORD dwTop = 0x136e4c0 - 0x400000 + dwBaseAddress; DWORD dwTop = 0xF6E500 + dwBaseAddress; bool bGetResult = false; DWORD dwRead = 0; DWORD dwCA = 0; if (ReadProcessMemory(hProcess, (LPCVOID)dwTop, &dwCA, sizeof(dwCA), &dwRead) && sizeof(dwCA)==dwRead) { if (0 != dwCA) { DWORD dwCAI = 0; if (ReadProcessMemory(hProcess, (LPCVOID)(dwCA+8), &dwCAI, sizeof(dwCAI), &dwRead) && sizeof(dwCAI)==dwRead) { if (0 != dwCAI) { DWORD dwSP = 0; if (ReadProcessMemory(hProcess, (LPCVOID)(dwCAI+4), &dwSP, sizeof(dwSP), &dwRead) && sizeof(dwSP)==dwRead) { if (0 != dwSP) { //printf("%08x %08x \n", /*dwCA,*/ dwCAI, dwSP); DWORD dwArg0 = 0; if (ReadProcessMemory(hProcess, (LPCVOID)(dwSP+0x64+dwOffset), &dwArg0, sizeof(dwArg0), &dwRead) && sizeof(dwArg0)==dwRead) { if (0 != dwArg0) { //printf(" %08x\n", dwArg0); DWORD p1 = 0; if (ReadProcessMemory(hProcess, (LPCVOID)(dwArg0+0x30), &p1, sizeof(p1), &dwRead) && sizeof(p1)==dwRead) { if (0 != p1) { //printf(" %08x\n", p1); DWORD buf1 = 0; DWORD buf2 = 0; if (ReadProcessMemory(hProcess, (LPCVOID)(p1+0x90), &buf1, sizeof(buf1), &dwRead) && sizeof(buf1)==dwRead) { if (0 != buf1) { DWORD s1 = 0; if (ReadProcessMemory(hProcess, (LPCVOID)(buf1+0x4), &s1, sizeof(s1), &dwRead) && sizeof(s1)==dwRead) { if (0 != s1) { //printf(" %08x\n", s1); LPCSTR sTitle = "KEY1"; ::WriteFile(hKeysFile, sTitle, 4, &dwRead, 0); s1 += 0x30; int ii = 0; DWORD dwState[16]; for(ii=0; ii<16; ++ii) { DWORD data = 0; if (ReadProcessMemory(hProcess, (LPCVOID)s1, &data, sizeof(data), &dwRead) && sizeof(data)==dwRead) { dwState[ii] = data; bGetResult = true; } else { break; } s1 += 4; } if (ii<16) { //printf("ERROR: can't read full state\n"); } else { // k ::WriteFile(hKeysFile, &dwState[13], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[10], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[7], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[4], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[15], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[12], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[9], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[6], 4, &dwRead, 0); // IV ::WriteFile(hKeysFile, &dwState[14], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[11], 4, &dwRead, 0); // for checking ::WriteFile(hKeysFile, &dwState[0], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[1], 4, &dwRead, 0); } } } } } if (ReadProcessMemory(hProcess, (LPCVOID)(p1+0x8C), &buf2, sizeof(buf2), &dwRead) && sizeof(buf2)==dwRead) { if (0 != buf2) { DWORD s2 = 0; if (ReadProcessMemory(hProcess, (LPCVOID)(buf2+0x4), &s2, sizeof(s2), &dwRead) && sizeof(s2)==dwRead) { if (0 != s2) { //printf(" %08x\n", s2); LPCSTR sTitle = "KEY2"; ::WriteFile(hKeysFile, sTitle, 4, &dwRead, 0); s2 += 0x30; int ii = 0; DWORD dwState[16]; for(ii=0; ii<16; ++ii) { DWORD data = 0; if (ReadProcessMemory(hProcess, (LPCVOID)s2, &data, sizeof(data), &dwRead) && sizeof(data)==dwRead) { dwState[ii] = data; bGetResult = true; } else { break; } s2 += 4; } if (ii<16) { //printf("ERROR: can't read full state\n"); } else { // k ::WriteFile(hKeysFile, &dwState[13], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[10], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[7], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[4], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[15], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[12], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[9], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[6], 4, &dwRead, 0); // IV ::WriteFile(hKeysFile, &dwState[14], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[11], 4, &dwRead, 0); // for checking ::WriteFile(hKeysFile, &dwState[0], 4, &dwRead, 0); ::WriteFile(hKeysFile, &dwState[1], 4, &dwRead, 0); } } } } } } } } } } } } } } } if (bGetResult) { //printf("Success\n", pe32.th32ProcessID); bResult = bGetResult; } CloseHandle( hProcess ); } } } while( Process32Next( hProcessSnap, &pe32 ) ); CloseHandle( hProcessSnap ); return bResult; }
QList<PlatformspecificRunningExecutableDataInterface *> PlatformSpecificProgramIdentifierHelper::getRunningExecutableDataForPathes(QStringList pathes) { QList<PlatformspecificRunningExecutableDataInterface *> retList; #if defined(Q_OS_WIN) HANDLE hProcessSnap; PROCESSENTRY32 pe32; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hProcessSnap == INVALID_HANDLE_VALUE ) { WLog("FAILED: CreateToolhelp32Snapshot (of processes)"); return retList; } // Set the size of the structure before using it. pe32.dwSize = sizeof( PROCESSENTRY32 ); // Retrieve information about the first process, // and exit if unsuccessful if( !Process32First( hProcessSnap, &pe32 ) ) { WLog("FAILED: Process32First"); CloseHandle( hProcessSnap ); // clean the snapshot object return retList; } QHash< QString, QList<DWORD> > fileProcHash; // Now walk the snapshot of processes do { QString processRelatedExe = QString::fromWCharArray(pe32.szExeFile); // DLogS << "Process related exe compare: " << processRelatedExe << relatedExeFileName; Q_FOREACH(QString currFilePath, pathes) { QFileInfo relatedExeFileInfo(currFilePath); QString relatedExeFullPath = relatedExeFileInfo.absoluteFilePath(); QString relatedExeFileName = relatedExeFileInfo.fileName(); if(processRelatedExe == relatedExeFileName) { DLogS << "Exe matches a running instance's exe-file: " << processRelatedExe << relatedExeFileName; if(PlatformSpecificProgramIdentifierHelper::_isExePathRelatedToProcess(pe32.th32ProcessID, relatedExeFullPath)) { QList<DWORD> relatedProcIds; if( fileProcHash.contains(relatedExeFullPath) ) { relatedProcIds = fileProcHash.value(relatedExeFullPath); } relatedProcIds.append(pe32.th32ProcessID); fileProcHash[relatedExeFullPath] = relatedProcIds; } } } } while( Process32Next( hProcessSnap, &pe32 ) ); CloseHandle( hProcessSnap ); QHash< QString, QList<DWORD> >::const_iterator c_it = fileProcHash.constBegin(); while (c_it != fileProcHash.constEnd()) { DLog("Running item: ") << c_it.key() << ":" << c_it.value(); retList.append(new Win_RunningExecutableData(c_it.key(), c_it.value())); ++c_it; } #elif defined(Q_OS_MAC) LOG_AS_NOT_IMPLEMENTED; #endif return retList; }
void ProcUtils::GetProcessList(std::vector<ProcessEntry> &proclist) { #ifdef __WXMSW__ OSVERSIONINFO osver ; // Check to see if were running under Windows95 or // Windows NT. osver.dwOSVersionInfoSize = sizeof( osver ) ; if ( !GetVersionEx( &osver ) ) { return; } if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) { return; } //get child processes of this node HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!hProcessSnap) { return; } //Fill in the size of the structure before using it. PROCESSENTRY32 pe; memset(&pe, 0, sizeof(pe)); pe.dwSize = sizeof(PROCESSENTRY32); // Walk the snapshot of the processes, and for each process, // kill it if its parent is pid. if (!Process32First(hProcessSnap, &pe)) { // Can't get first process. CloseHandle (hProcessSnap); return; } do { ProcessEntry entry; entry.name = pe.szExeFile; entry.pid = (long)pe.th32ProcessID; proclist.push_back(entry); } while (Process32Next (hProcessSnap, &pe)); CloseHandle (hProcessSnap); #elif defined(__FreeBSD__) kvm_t *kvd; struct kinfo_proc *ki; int nof_procs, i; if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL))) return; if (!(ki = kvm_getprocs(kvd, KERN_PROC_PROC, 0, &nof_procs))) { kvm_close(kvd); return; } for (i=0; i<nof_procs; i++) { ProcessEntry entry; entry.pid = ki[i].ki_pid; entry.name = wxString(ki[i].ki_ocomm, wxConvUTF8); proclist.push_back(entry); } kvm_close(kvd); #else //GTK and other wxArrayString output; #if defined (__WXGTK__) ExecuteCommand(wxT("ps -A -o pid,command --no-heading"), output); #elif defined (__WXMAC__) // Mac does not like the --no-heading... ExecuteCommand(wxT("ps -A -o pid,command "), output); #endif for (size_t i=0; i< output.GetCount(); i++) { wxString line = output.Item(i); //remove whitespaces line = line.Trim().Trim(false); //get the process ID ProcessEntry entry; wxString spid = line.BeforeFirst(wxT(' ')); spid.ToLong( &entry.pid ); entry.name = line.AfterFirst(wxT(' ')); if (entry.pid == 0 && i > 0) { //probably this line belongs to the provious one ProcessEntry e = proclist.back(); proclist.pop_back(); e.name << entry.name; proclist.push_back( e ); } else { proclist.push_back( entry ); } } #endif }
int main( int argc, char * argv[] ) { printf( "*******************************************************************************\n" ); printf( "*\n* Module Dumper by blub.txt \n" ); printf( "* This Tool dumps a module of the specified process memory to a file on Hardrive*\n*\n" ); printf( "* Usage: DumpModule.exe ProcessName ModuleName DumpPath \n" ); printf( "* Example: DumpModule.exe steam.exe Steam.dll C:\\test.dump \n*\n" ); printf( "* If you don`t refer a process name you get a list of the current process, * the same with modules\n*\n" ); printf( "*******************************************************************************\n\n" ); if( argv[1] == NULL ) bNoProcessName = 1; else { strcpy( szProcessName, argv[1] ); if( argv[2] == NULL ) bNoModuleName = 1; else { strcpy( szModuleName, argv[2] ); strcpy( szDumpPath, argv[3] ); } } hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ); if( hSnapshot == INVALID_HANDLE_VALUE ) { CloseHandle( hSnapshot ); return 0; } pe32.dwSize = sizeof( PROCESSENTRY32 ); if( !Process32First( hSnapshot, &pe32 ) ) { CloseHandle( hSnapshot ); return 0; } while( Process32Next( hSnapshot, &pe32 ) ) { if( bNoProcessName == 1) printf( "%s \n", pe32.szExeFile ); else if( !lstrcmp( pe32.szExeFile, szProcessName ) ) { printf( "Process found! %s \n", szProcessName ); hProcess = OpenProcess( PROCESS_ALL_ACCESS, false, pe32.th32ProcessID ); if( OpenProcessToken( hProcess, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken) == 0 ) { CloseHandle( hProcess); return 0; } if( ( LookupPrivilegeValue( 0, SE_SECURITY_NAME, &luid ) == 0) || ( LookupPrivilegeValue( 0, SE_DEBUG_NAME, &luid ) == 0 ) ) { CloseHandle( hProcess ); return 0; } tpToken.PrivilegeCount = 1; tpToken.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; tpToken.Privileges[0].Luid = luid; AdjustTokenPrivileges( hToken, false, &tpToken, sizeof( tpToken ), NULL, 0 ); hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, pe32.th32ProcessID ); me32.dwSize = sizeof( MODULEENTRY32 ); if ( !Module32First( hSnapshot, &me32 ) ) { CloseHandle( hSnapshot ); return 0; } while( Module32Next( hSnapshot, &me32) ) { if( bNoModuleName == 1 ) printf( "%s \n", me32.szModule ); else if( !lstrcmp( me32.szModule, szModuleName ) ) { LPVOID lpBuffer; LPDWORD dwBytesWritten; HANDLE hDrop; printf( "Module found! %s \n", szModuleName ); printf( "- Base Address: 0x%x \n", me32.modBaseAddr ); printf( "- Base Size: %d \n", me32.modBaseSize ); lpBuffer = VirtualAlloc( NULL, me32.modBaseSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE ); ReadProcessMemory( hProcess, me32.modBaseAddr, lpBuffer, me32.modBaseSize, NULL ); hDrop = CreateFile( szDumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if( hDrop != INVALID_HANDLE_VALUE ) { WriteFile( hDrop, lpBuffer, me32.modBaseSize, dwBytesWritten, NULL ); } VirtualFree( lpBuffer, NULL, MEM_RELEASE ); CloseHandle( hDrop ); CloseHandle( hSnapshot ); CloseHandle( hProcess ); return 1; } } } } CloseHandle( hSnapshot ); Sleep( 5 ); return 1; }
/** Check if a process with a given name is running * @param names list of names to filter on. All processes if empty list. * @return list of processname, process ID pairs. */ QMap<QString, QList<int> > Utils::findRunningProcess(QStringList names) { QMap<QString, QList<int> > processlist; QMap<QString, QList<int> > found; #if defined(Q_OS_WIN32) HANDLE hdl; PROCESSENTRY32 entry; bool result; hdl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(hdl == INVALID_HANDLE_VALUE) { LOG_ERROR() << "CreateToolhelp32Snapshot failed."; return found; } entry.dwSize = sizeof(PROCESSENTRY32); entry.szExeFile[0] = '\0'; if(!Process32First(hdl, &entry)) { LOG_ERROR() << "Process32First failed."; return found; } do { int pid = entry.th32ProcessID; // FIXME: DWORD vs int! QString name = QString::fromWCharArray(entry.szExeFile); if(processlist.find(name) == processlist.end()) { processlist.insert(name, QList<int>()); } processlist[name].append(pid); entry.dwSize = sizeof(PROCESSENTRY32); entry.szExeFile[0] = '\0'; result = Process32Next(hdl, &entry); } while(result); CloseHandle(hdl); #endif #if defined(Q_OS_MACX) ProcessSerialNumber psn = { 0, kNoProcess }; OSErr err; do { pid_t pid; err = GetNextProcess(&psn); err = GetProcessPID(&psn, &pid); if(err == noErr) { char buf[32] = {0}; ProcessInfoRec info; memset(&info, 0, sizeof(ProcessInfoRec)); info.processName = (unsigned char*)buf; info.processInfoLength = sizeof(ProcessInfoRec); err = GetProcessInformation(&psn, &info); if(err == noErr) { // some processes start with nonprintable characters. Skip those. int i; for(i = 0; i < 32; i++) { if(isprint(buf[i])) break; } // avoid adding duplicates. QString name = QString::fromUtf8(&buf[i]); if(processlist.find(name) == processlist.end()) { processlist.insert(name, QList<int>()); } processlist[name].append(pid); } } } while(err == noErr); #endif #if defined(Q_OS_LINUX) // not implemented for Linux! #endif // Filter for names (unless empty) if(names.size() > 0) { for(int i = 0; i < names.size(); ++i) { QStringList k(processlist.keys()); #if defined(Q_OS_WIN32) // the process name might be truncated. Allow the extension to be partial. int index = k.indexOf(QRegExp(names.at(i) + "(\\.(e(x(e?)?)?)?)?", Qt::CaseInsensitive)); #else int index = k.indexOf(names.at(i)); #endif if(index != -1) { found.insert(k[index], processlist[k[index]]); } } } else { found = processlist; } LOG_INFO() << "Looking for processes" << names << "found" << found; return found; }
/** * @brief * Perform the given operation <op> on process tree by using given parent process id <process_ID> * * @param[in] * process_ID - parent process id on which <op> will performed * op - operation to perform, one of SUSPEND, RESUME or TERMINATE * exitcode - exit code for processes, this is used only if <op> = TERMINATE, otherwise 0 * * @return * int * * @retval * >= 0 - No. of processes that were operated on * -1 - Invalid parameter or Error * */ int processtree_op_by_id(DWORD processId, enum operation op, int exitcode) { HANDLE hProcessSnap = INVALID_HANDLE_VALUE; HANDLE hThreadSnap = INVALID_HANDLE_VALUE; HANDLE hThread = INVALID_HANDLE_VALUE; HANDLE hProcess = INVALID_HANDLE_VALUE; THREADENTRY32 te32 = { sizeof(te32) }; PROCESSENTRY32 pe32 = { sizeof(pe32) }; int process_count = 0; int ret = -1; if (processId <= 0) return -1; if (op >= UNKNOWN) return -1; hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, processId); if (hProcessSnap == INVALID_HANDLE_VALUE) return -1; if (!Process32First(hProcessSnap, &pe32)) { CloseHandle(hProcessSnap); return -1; } do { if (processId == pe32.th32ParentProcessID) { ret = processtree_op_by_id(pe32.th32ProcessID, op, exitcode); if (ret != -1) { process_count += ret; } else { CloseHandle(hProcessSnap); return -1; } } } while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); /* * if op == TERMINATE then terminate process at process level instead * of thread level because TerminateThread call is not safe as per MSDN * * if op = SUSPEND or RESUME then suspend or resume process at thread level * by using SuspendThread or ResumeThread */ if (op == TERMINATE) { hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, processId); /* * OpenProcess() may return a handle to next lower process Id * if given process id doesn't exist. It will be disastorous * if we kill this arbitrary process, thus always make sure that the handle returned * belongs to intended process id by calling GetProcessId() on returned handle. */ if ((hProcess != NULL) && (hProcess != INVALID_HANDLE_VALUE) &&(GetProcessId(hProcess) == processId)) { ret = TerminateProcess(hProcess, exitcode); CloseHandle(hProcess); if (ret) { return (++process_count); } else { return -1; } } else { return -1; } } hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, processId); if (hThreadSnap == INVALID_HANDLE_VALUE) return -1; if (!Thread32First(hThreadSnap, &te32)) { CloseHandle(hThreadSnap); return -1; } do { if (te32.th32OwnerProcessID == processId) { hThread = OpenThread(THREAD_SUSPEND_RESUME, TRUE, te32.th32ThreadID); if ((hThread != NULL) && (hThread != INVALID_HANDLE_VALUE)) { if (op == SUSPEND) { /* Suspend Thread */ ret = SuspendThread(hThread); } else if (op == RESUME) { /* Resume Thread */ ret = ResumeThread(hThread); } CloseHandle(hThread); if (ret == -1) { CloseHandle(hThreadSnap); return -1; } } else { CloseHandle(hThreadSnap); return -1; } } } while (Thread32Next(hThreadSnap, &te32)); CloseHandle(hThreadSnap); process_count++; return process_count; }
INT countProcs(CONST std::wstring user) { if (debug) std::wcout << L"Counting all processes of user" << user << '\n'; CONST WCHAR *wuser = user.c_str(); INT numProcs = 0; HANDLE hProcessSnap, hProcess = NULL, hToken = NULL; PROCESSENTRY32 pe32; DWORD dwReturnLength, dwAcctName, dwDomainName; PTOKEN_USER pSIDTokenUser = NULL; SID_NAME_USE sidNameUse; LPWSTR AcctName, DomainName; if (debug) std::wcout << L"Creating snapshot" << '\n'; hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) goto die; pe32.dwSize = sizeof(PROCESSENTRY32); if (debug) std::wcout << L"Grabbing first proccess" << '\n'; if (!Process32First(hProcessSnap, &pe32)) goto die; if (debug) std::wcout << L"Counting processes..." << '\n'; do { if (debug) std::wcout << L"Getting process token" << '\n'; //get ProcessToken hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID); if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) //Won't count pid 0 (system idle) and 4/8 (Sytem) continue; //Get dwReturnLength in first call dwReturnLength = 1; if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwReturnLength) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) continue; pSIDTokenUser = reinterpret_cast<PTOKEN_USER>(new BYTE[dwReturnLength]); memset(pSIDTokenUser, 0, dwReturnLength); if (debug) std::wcout << L"Received token, saving information" << '\n'; //write Info in pSIDTokenUser if (!GetTokenInformation(hToken, TokenUser, pSIDTokenUser, dwReturnLength, NULL)) continue; AcctName = NULL; DomainName = NULL; dwAcctName = 1; dwDomainName = 1; if (debug) std::wcout << L"Looking up SID" << '\n'; //get dwAcctName and dwDomainName size if (!LookupAccountSid(NULL, pSIDTokenUser->User.Sid, AcctName, (LPDWORD)&dwAcctName, DomainName, (LPDWORD)&dwDomainName, &sidNameUse) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) continue; AcctName = reinterpret_cast<LPWSTR>(new WCHAR[dwAcctName]); DomainName = reinterpret_cast<LPWSTR>(new WCHAR[dwDomainName]); if (!LookupAccountSid(NULL, pSIDTokenUser->User.Sid, AcctName, (LPDWORD)&dwAcctName, DomainName, (LPDWORD)&dwDomainName, &sidNameUse)) continue; if (debug) std::wcout << L"Comparing " << AcctName << L" to " << wuser << '\n'; if (!wcscmp(AcctName, wuser)) { ++numProcs; if (debug) std::wcout << L"Is process of " << wuser << L" (" << numProcs << L")" << '\n'; } delete[] reinterpret_cast<LPWSTR>(AcctName); delete[] reinterpret_cast<LPWSTR>(DomainName); } while (Process32Next(hProcessSnap, &pe32)); die: if (hProcessSnap) CloseHandle(hProcessSnap); if (hProcess) CloseHandle(hProcess); if (hToken) CloseHandle(hToken); if (pSIDTokenUser) delete[] reinterpret_cast<PTOKEN_USER>(pSIDTokenUser); return numProcs; }
bool W7EUtils::GetProcessList(HWND hWnd, std::map< DWORD, std::wstring > &mapProcs) { // Note: We probably need to target a process which has the same ASLR setting as us, i.e. ON. // Explorer.exe is our default since it has ASLR on, is always running and can do the COM silent-elevation stuff by default. bool bResult = false; mapProcs.clear(); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == INVALID_HANDLE_VALUE) { //MessageBox(hWnd, L"CreateToolhelp32Snapshot failed", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"CreateToolhelp32Snapshot failed"); } else { bool bFirst = true; PROCESSENTRY32 pe; while(true) { ZeroMemory(&pe, sizeof(pe)); pe.dwSize = sizeof(pe); BOOL bPR = FALSE; if (bFirst) { bFirst = false; bPR = Process32First(hSnapshot, &pe); } else { bPR = Process32Next(hSnapshot, &pe); } if (!bPR) { DWORD dwErr = GetLastError(); if (ERROR_NO_MORE_FILES != dwErr) { //MessageBox(hWnd, L"Process32Next/First failed", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Process32Next/First failed"); } else if (mapProcs.empty()) { //MessageBox(hWnd, L"Process32Next/First returned nothing", L"Win7Elevate", MB_OK | MB_ICONWARNING); CLogger::LogLine(L"Process32Next/First returned nothing"); } else { bResult = true; } break; // Stop enumerating. } // Only insert processes that we can open HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID); if (hProc != 0) { CloseHandle(hProc); mapProcs.insert( std::make_pair( pe.th32ProcessID, pe.szExeFile ) ); } } CloseHandle(hSnapshot); } return bResult; }