void GetProcessName(DWORD PID, PTSTR szProcessName, size_t cchSize) { /* Opens an existing local process object. */ HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, PID); if (hProcess == NULL) { _tcscpy_s(szProcessName, cchSize, TEXT("???")); return; } DWORD dwSize = (DWORD)cchSize; /* Retrieves the full name of the executable image * for the specified process. */ QueryFullProcessImageName( hProcess, 0, szProcessName, &dwSize); /* Don't forget to close the process handle */ CloseHandle(hProcess); }
static char *proc_filename(DWORD pid) { HANDLE proc; DWORD s = 1000; char* filename; proc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); if (proc == INVALID_HANDLE_VALUE) { printf("err:%d.", GetLastError()); return NULL; } filename = (char*)calloc(1000, sizeof(char)); /* For the best results use the following table to convert paths. Windows 2000 = GetModuleFileNameEx() Windows XP x32 = GetProcessImageFileName() Windows XP x64 = GetProcessImageFileName() Windows Vista = QueryFullProcessImageName() Windows 7 = QueryFullProcessImageName() */ /* GetModuleFileNameEx(proc, NULL, (LPSTR)filename, 1000); */ if (!QueryFullProcessImageName(proc, 0, filename, &s)) printf("err:%d.", GetLastError()); return filename; }
/* Vista Or Above */ BOOL GetProcessPathByPID4(DWORD dwProcessID, LPTSTR szFullPath, DWORD nSize) { HANDLE hProcess; _QueryFullProcessImageName QueryFullProcessImageName; #ifdef UNICODE QueryFullProcessImageName = (_QueryFullProcessImageName)GetProcAddress( GetModuleHandle(_T("kernel32.dll")), "QueryFullProcessImageNameW"); #else QueryFullProcessImageName = (_QueryFullProcessImageName)GetProcAddress( GetModuleHandle(_T("kernel32.dll")), "QueryFullProcessImageNameA"); #endif if (QueryFullProcessImageName == NULL) { ODS(_T("QueryFullProcessImageName address error!")); return FALSE; } hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessID); if (hProcess == NULL) { return FALSE; } if (!QueryFullProcessImageName(hProcess, 0, szFullPath, &nSize)) { CloseHandle(hProcess); return FALSE; } CloseHandle(hProcess); return TRUE; }
BOOL CALLBACK GraphicsCaptureFindWindow(HWND hwnd, LPARAM lParam) { TCHAR windowClass[256]; TCHAR windowExecutable[MAX_PATH]; windowClass[_countof(windowClass)-1] = windowExecutable[MAX_PATH-1] = 0; FindWindowData *fwd = (FindWindowData *)lParam; if (!IsWindowVisible(hwnd)) return TRUE; if (GetClassName(hwnd, windowClass, _countof(windowClass) - 1) && !scmp(windowClass, fwd->classname)) { //handle old sources which lack an exe name if (fwd->exename.IsEmpty()) return TRUE; DWORD processID; GetWindowThreadProcessId(hwnd, &processID); HANDLE hProc = fwd->pOpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID); if (hProc) { DWORD wLen = _countof(windowExecutable) - 1; if (QueryFullProcessImageName(hProc, 0, windowExecutable, &wLen)) { TCHAR *p; p = wcsrchr(windowExecutable, '\\'); if (p) p++; else p = windowExecutable; slwr(p); if (!scmp(p, fwd->exename)) { CloseHandle(hProc); fwd->hwnd = hwnd; return FALSE; } } else { RUNONCE Log(TEXT("OpenProcess worked but QueryFullProcessImageName returned %d for pid %d?"), GetLastError(), processID); } CloseHandle(hProc); } } return TRUE; }
void TaskButton::OpenTaskProcess() { DWORD processId; GetWindowThreadProcessId(mWindow, &processId); HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId); if (process) { wchar_t processPath[MAX_PATH]; DWORD size = MAX_PATH; if (QueryFullProcessImageName(process, 0, processPath, &size)) { ShellExecute(nullptr, L"open", processPath, L"", L"", SW_SHOW); } CloseHandle(process); } }
Application::string_list_512 Application::searchActiveGameLogFolders() { string_list_512 pathList; DWORD pids[1024]; DWORD readed = 0; BOOL bRet = EnumProcesses(pids, sizeof(pids), &readed); if(!bRet) { Log(LOG_ERROR, "error: EnumProcesses, errCode:%d", GetLastError()); return pathList; } char buf[512]; int n = (int)(readed/sizeof(DWORD)); for(int i=0; i<n; i++) { DWORD pid = pids[i]; HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); if(!hProc) { Log(LOG_DEBUG, "debug: fail open process pid:%u, errCode:%u", pid, GetLastError()); continue; } DWORD len = sizeof(buf); BOOL bRet = QueryFullProcessImageName(hProc, 0, buf, &len); if(!bRet) { CloseHandle(hProc); Log(LOG_DEBUG, "debug: fail GetProcessImageFileName pid:%u, errCode:%u", pid, GetLastError()); continue; } const char* shortName = JG_F::KFileUtil::basename_r(buf); if(g_pApp->isProcessCared(shortName)) { char dirName[512]; JG_F::KFileUtil::dirname_r(buf, dirName); strcat(dirName, "\\log"); if(JG_F::KFileUtil::IsDir(dirName)) { pathList.push_back(dirName); } } CloseHandle(hProc); } return pathList; }
//Check these only once at the start void Engine::Global_Cks(){ Process * RT_ActionRunner = new Process(ProcN); //Check for 64 bit system int ProcessorType = GetPrcessorInfo(); if (ProcessorType == 0 || ProcessorType == -1){ ///Termminate Client & program //HANDLE C = OpenProcess(PROCESS_TERMINATE, FALSE, PreLoaderINFO->Pinfo.Process_ID); //TerminateProcess(C, NULL); //exit(0); } //Check USN //std::wstring Test0 = L"TEST.exe"; //USN_RECORD * usn_record = GetUSN(Test0); //Check DNS //std::wstring Test1 = L"www.test.com"; //DNSCACHEENTRY * dns_record = GetDNS(Test1); HANDLE Query = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, RT_ActionRunner->Pinfo.Process_ID); LPSTR NameP = new CHAR[MAX_PATH]; DWORD charsCarried = MAX_PATH; //Win32 path format if (QueryFullProcessImageName(Query, 0, NameP, &charsCarried) == 0) { //Check the executable file GetPeInfo(NameP); } CloseHandle(Query); delete[] NameP; //Create hash CheckSegmentCount(RT_ActionRunner, FALSE); delete RT_ActionRunner; return; }
FString FWindowsPlatformProcess::GetApplicationName( uint32 ProcessId ) { FString Output = TEXT(""); HANDLE ProcessHandle = ::OpenProcess(PROCESS_QUERY_INFORMATION, false, ProcessId); if (ProcessHandle != NULL) { const int32 ProcessNameBufferSize = 4096; TCHAR ProcessNameBuffer[ProcessNameBufferSize]; int32 InOutSize = ProcessNameBufferSize; static_assert(sizeof(::DWORD) == sizeof(int32), "DWORD size doesn't match int32. Is it the future or the past?"); #if WINVER == 0x0502 GetProcessImageFileName(ProcessHandle, ProcessNameBuffer, InOutSize); #else QueryFullProcessImageName(ProcessHandle, 0, ProcessNameBuffer, (PDWORD)(&InOutSize)); #endif Output = ProcessNameBuffer; } return Output; }
void RefreshWindowList(HWND hwndCombobox, StringList &classList) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); classList.Clear(); BOOL bCurrentProcessIsWow64 = FALSE; IsWow64Process(GetCurrentProcess(), &bCurrentProcessIsWow64); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if( (exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 && hwndParent == NULL) { String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); //------- DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { BOOL bTargetProcessIsWow64 = FALSE; IsWow64Process(hProcess, &bTargetProcessIsWow64); DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); CloseHandle(hProcess); if(bCurrentProcessIsWow64 != bTargetProcessIsWow64) continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName) << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strWindowName.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); classList << strClassName; } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); }
void CZRegHelper::ParseReg(wchar_t **arg,int num) { wchar_t szApplication[MAX_PATH]; DWORD cchLength = _countof(szApplication); QueryFullProcessImageName(GetCurrentProcess(), 0, szApplication, &cchLength); CString appPath; appPath.Format(L"%s",szApplication); if(2 == num) { if(0 == _wcsnicmp(arg[1],L"/reg",4) && wcslen(arg[1]) > 4) { CString para(arg[1]); para = para.Right(para.GetLength()-4); int index = 0; int last = 0; CString tmp; CString icoIndex ; icoIndex.Format(L"%s,0",appPath); while(-1 != (index = para.Find('|'))) { tmp = para.Left(index); para = para.Right(para.GetLength() - index -1); if(0 == tmp.CompareNoCase(L"flac")) { RegisterFileRelation(L".FLAC",appPath,L"ZLP.FLAC",icoIndex,L"FLAC"); } else if(0 == tmp.CompareNoCase(L"ape")) { RegisterFileRelation(L".APE",appPath,L"ZLP.APE",icoIndex,L"APE"); } else if(0 == tmp.CompareNoCase(L"wav")) { RegisterFileRelation(L".WAV",appPath,L"ZLP.WAV",icoIndex,L"WAV"); } else if(0 == tmp.CompareNoCase(L"mp3")) { RegisterFileRelation(L".MP3",appPath,L"ZLP.MP3",icoIndex,L"MP3"); } else if(0 == tmp.CompareNoCase(L"cue")) { RegisterFileRelation(L".CUE",appPath,L"ZLP.CUE",icoIndex,L"CUE"); } else if(0 == tmp.CompareNoCase(L"ofr")) { RegisterFileRelation(L".OFR",appPath,L"ZLP.OFR",icoIndex,L"OFR"); } else if(0 == tmp.CompareNoCase(L"ogg")) { RegisterFileRelation(L".OGG",appPath,L"ZLP.OGG",icoIndex,L"OGG"); } else if(0 == tmp.CompareNoCase(L"tak")) { RegisterFileRelation(L".TAK",appPath,L"ZLP.TAK",icoIndex,L"TAK"); } else if(0 == tmp.CompareNoCase(L"wv")) { RegisterFileRelation(L".WV",appPath,L"ZLP.WV",icoIndex,L"WV"); } else if(0 == tmp.CompareNoCase(L"aac")) { RegisterFileRelation(L".AAC",appPath,L"ZLP.AAC",icoIndex,L"AAC"); } else if(0 == tmp.CompareNoCase(L"m4a")) { RegisterFileRelation(L".M4A",appPath,L"ZLP.M4A",icoIndex,L"M4A"); } else if(0 == tmp.CompareNoCase(L"tta")) { RegisterFileRelation(L".TTA",appPath,L"ZLP.TTA",icoIndex,L"TTA"); } tmp.Empty(); } tmp.Empty(); while(-1!=(index = para.Find(','))) { tmp = para.Left(index); para = para.Right(para.GetLength() - index -1); if(0 == tmp.CompareNoCase(L"flac")) { UnRegisterFileRelation(L".FLAC",L"ZLP.FLAC"); } else if(0 == tmp.CompareNoCase(L"ape")) { UnRegisterFileRelation(L".APE",L"ZLP.APE"); } else if(0 == tmp.CompareNoCase(L"wav")) { UnRegisterFileRelation(L".WAV",L"ZLP.WAV"); } else if(0 == tmp.CompareNoCase(L"mp3")) { UnRegisterFileRelation(L".MP3",L"ZLP.MP3"); } else if(0 == tmp.CompareNoCase(L"cue")) { UnRegisterFileRelation(L".CUE",L"ZLP.CUE"); } else if(0 == tmp.CompareNoCase(L"ofr")) { UnRegisterFileRelation(L".OFR",L"ZLP.OFR"); } else if(0 == tmp.CompareNoCase(L"ogg")) { UnRegisterFileRelation(L".OGG",L"ZLP.OGG"); } else if(0 == tmp.CompareNoCase(L"tak")) { UnRegisterFileRelation(L".TAK",L"ZLP.TAK"); } else if(0 == tmp.CompareNoCase(L"wv")) { UnRegisterFileRelation(L".WV",L"ZLP.WV"); } else if(0 == tmp.CompareNoCase(L"aac")) { UnRegisterFileRelation(L".AAC",L"ZLP.AAC"); } else if(0 == tmp.CompareNoCase(L"m4a")) { UnRegisterFileRelation(L".M4A",L"ZLP.M4A"); } else if(0 == tmp.CompareNoCase(L"tta")) { UnRegisterFileRelation(L".TTA",L"ZLP.TTA"); } tmp.Empty(); } icoIndex.Empty(); para.Empty(); tmp.Empty(); SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); appPath.Empty(); } } }
void RefreshWindowList(HWND hwndCombobox, ConfigDialogData &configData) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); configData.ClearData(); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if (strWindowName.IsValid() && sstri(strWindowName, L"battlefield") != nullptr) exStyles &= ~WS_EX_TOOLWINDOW; if((exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 /*&& hwndParent == NULL*/) { BOOL bFoundModule = true; DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); for (int i=0; i<11; i++) pOPStr[i] ^= i^1; OPPROC pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); HANDLE hProcess = (*pOpenProcess)(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if(hProcess) { DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); StringList moduleList; if (OSGetLoadedModuleList(hProcess, moduleList) && moduleList.Num()) { //note: this doesn't actually work cross-bit, but we may as well make as much use of //the data we can get. bFoundModule = false; for(UINT i=0; i<moduleList.Num(); i++) { CTSTR moduleName = moduleList[i]; if (!scmp(moduleName, TEXT("d3d9.dll")) || !scmp(moduleName, TEXT("d3d10.dll")) || !scmp(moduleName, TEXT("d3d10_1.dll")) || !scmp(moduleName, TEXT("d3d11.dll")) || !scmp(moduleName, TEXT("dxgi.dll")) || !scmp(moduleName, TEXT("d3d8.dll")) || !scmp(moduleName, TEXT("opengl32.dll"))) { bFoundModule = true; break; } } if (!bFoundModule) { CloseHandle(hProcess); continue; } } CloseHandle(hProcess); } else { hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { configData.adminWindows << strWindowName; CloseHandle(hProcess); } continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName); strText << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); TCHAR *baseExeName; baseExeName = wcsrchr(fileName, '\\'); if (!baseExeName) baseExeName = fileName; else baseExeName++; WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = strClassName; info.strExecutable = baseExeName; info.bRequiresAdmin = false; //todo: add later info.bFoundHookableModule = bFoundModule; info.strExecutable.MakeLower(); } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); if(OSGetVersion() < 8) { BOOL isCompositionEnabled = FALSE; DwmIsCompositionEnabled(&isCompositionEnabled); if(isCompositionEnabled) { String strText; strText << TEXT("[DWM]: ") << Str("Sources.SoftwareCaptureSource.MonitorCapture"); int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)NULL); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = TEXT("Dwm"); info.strExecutable = TEXT("dwm.exe"); info.bRequiresAdmin = false; //todo: add later info.bFoundHookableModule = true; } } // preserve the last used settings in case the target isn't open any more, prevents // Properties -> OK selecting a new random target. String oldWindow = configData.data->GetString(TEXT("window")); String oldClass = configData.data->GetString(TEXT("windowClass")); String oldExe = configData.data->GetString(TEXT("executable")); UINT windowID = (UINT)SendMessage(hwndCombobox, CB_FINDSTRINGEXACT, -1, (LPARAM)oldWindow.Array()); if (windowID == CB_ERR && oldWindow.IsValid() && oldClass.IsValid()) { int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)oldWindow.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)NULL); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = oldClass; info.strExecutable = oldExe; info.bRequiresAdmin = false; //todo: add later info.bFoundHookableModule = true; } }
void Dlg_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { static BOOL s_fProcesses = TRUE; switch (id) { case IDCANCEL: EndDialog(hwnd, id); break; /* Restart the application when we are not running * as Elevated Administrator. */ case IDC_BTN_SYSTEM_PROCESSES: { /* Hide ourself before trying to start the same application * but with elevated privileges. */ ShowWindow(hwnd, SW_HIDE); TCHAR szApplication[MAX_PATH]; DWORD cchLength = _countof(szApplication); /* Retrieves the full name of the executable * image for the specified process. * hProcess [in] * A handle to the process. * This handle must be created with the PROCESS_QUERY_INFORMATION * or PROCESS_QUERY_LIMITED_INFORMATION access right. * For more information, see Process Security and Access Rights. * dwFlags [in] * This parameter can be one of the following values. * 0 The name should use the Win32 path format. * The name should use the native system path format. * lpExeName [out] * The path to the executable image. * If the function succeeds, this string is null-terminated. * lpdwSize [in, out] * On input, specifies the size of the lpExeName buffer, in characters. * On success, receives the number of characters written to the buffer, * not including the null-terminating character. */ QueryFullProcessImageName( GetCurrentProcess(), 0, szApplication, &cchLength); DWORD dwStatus = StartElevatedProcess(szApplication, NULL); if (dwStatus == S_OK) { /* not need to keep on working under lower privileges. */ ExitProcess(0); } /* In case of error, show up again. */ ShowWindow(hwnd, SW_SHOWNORMAL); } break; case ID_PROCESSES: s_fProcesses = TRUE; EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_ENABLED); DrawMenuBar(hwnd); Dlg_PopulateProcessList(hwnd); break; case ID_MODULES: EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_GRAYED); DrawMenuBar(hwnd); s_fProcesses = FALSE; Dlg_PopulateModuleList(hwnd); break; case IDC_PROCESSMODULELIST: if (codeNotify == CBN_SELCHANGE) { DWORD dw = ComboBox_GetCurSel(hwndCtl); if (s_fProcesses) { dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); // Process ID ShowProcessInfo(GetDlgItem(hwnd, IDC_RESULTS), dw); } else { // Index in helper listbox of full path dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); TCHAR szModulePath[1024]; ListBox_GetText(GetDlgItem(hwnd, IDC_MODULEHELP), dw, szModulePath); ShowModuleInfo(GetDlgItem(hwnd, IDC_RESULTS), szModulePath); } } break; case ID_VMMAP: { TCHAR szCmdLine[32]; HWND hwndCB = GetDlgItem(hwnd, IDC_PROCESSMODULELIST); DWORD dwProcessId = (DWORD) ComboBox_GetItemData(hwndCB, ComboBox_GetCurSel(hwndCB)); StringCchPrintf(szCmdLine, _countof(szCmdLine), TEXT("%d"), dwProcessId); DWORD dwStatus = StartElevatedProcess(TEXT("\"14-VMMap.exe\""), szCmdLine); if (dwStatus == ERROR_CANCELLED) { chMB("Failed to run 14-VMMap.exe: you refused access."); } } break; } }
DWORD WINAPI BMF_MonitorProcess (LPVOID user) { BMF_InitCOM (); EnterCriticalSection (&com_cs); process_stats_t& proc = process_stats; const double update = config.mem.interval; HRESULT hr; if (FAILED (hr = CoCreateInstance ( CLSID_WbemRefresher, NULL, CLSCTX_INPROC_SERVER, IID_IWbemRefresher, (void**) &proc.pRefresher ) ) ) { dll_log.Log(L" [WMI]: Failed to create Refresher Instance (%s:%d) -- 0x%X", __FILEW__, __LINE__, hr); goto PROC_CLEANUP; } if (FAILED (hr = proc.pRefresher->QueryInterface ( IID_IWbemConfigureRefresher, (void **)&proc.pConfig ) ) ) { dll_log.Log(L" [WMI]: Failed to Query Refresher Interface (%s:%d) -- 0x%X", __FILEW__, __LINE__, hr); goto PROC_CLEANUP; } IWbemClassObject *pClassObj = nullptr; HANDLE hProc = GetCurrentProcess (); DWORD dwProcessSize = MAX_PATH; wchar_t wszProcessName [MAX_PATH]; QueryFullProcessImageName (hProc, 0, wszProcessName, &dwProcessSize); wchar_t* pwszShortName = wcsrchr (wszProcessName, L'\\') + 1; wchar_t* pwszTruncName = wcsrchr (pwszShortName, L'.'); if (pwszTruncName != nullptr) *pwszTruncName = L'\0'; wchar_t wszInstance [512]; wsprintf ( wszInstance, L"Win32_PerfFormattedData_PerfProc_Process.Name='%ws'", pwszShortName ); if (FAILED (hr = proc.pConfig->AddObjectByPath ( pNameSpace, wszInstance, 0, 0, &pClassObj, 0 ) ) ) { dll_log.Log(L" [WMI]: Failed to AddObjectByPath (%s:%d) -- 0x%X", __FILEW__, __LINE__, hr); goto PROC_CLEANUP; } if (FAILED (hr = pClassObj->QueryInterface ( IID_IWbemObjectAccess, (void **)(&proc.pAccess ) ) ) ) { dll_log.Log(L" [WMI]: Failed to Query WbemObjectAccess Interface (%s:%d)" L" -- 0x%X", __FILEW__, __LINE__, hr); pClassObj->Release (); pClassObj = nullptr; goto PROC_CLEANUP; } pClassObj->Release (); pClassObj = nullptr; CIMTYPE variant; if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"PageFileBytes", &variant, &proc.hPageFileBytes ) ) ) { goto PROC_CLEANUP; } if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"PageFileBytesPeak", &variant, &proc.hPageFileBytesPeak ) ) ) { goto PROC_CLEANUP; } if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"ThreadCount", &variant, &proc.hThreadCount ) ) ) { goto PROC_CLEANUP; } if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"PrivateBytes", &variant, &proc.hPrivateBytes ) ) ) { goto PROC_CLEANUP; } if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"WorkingSetPeak", &variant, &proc.hWorkingSetPeak ) ) ) { goto PROC_CLEANUP; } if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"WorkingSet", &variant, &proc.hWorkingSet ) ) ) { goto PROC_CLEANUP; } if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"VirtualBytesPeak", &variant, &proc.hVirtualBytesPeak ) ) ) { goto PROC_CLEANUP; } if (FAILED (hr = proc.pAccess->GetPropertyHandle ( L"VirtualBytes", &variant, &proc.hVirtualBytes ) ) ) { goto PROC_CLEANUP; } proc.pConfig->Release (); proc.pConfig = nullptr; int iter = 0; proc.lID = 1; LeaveCriticalSection (&com_cs); while (proc.lID != 0) { // Sleep until ready Sleep (DWORD (update * 1000.0)); // Only poll WMI while the data view is visible if (! config.mem.show) continue; EnterCriticalSection (&com_cs); if (FAILED (hr = proc.pRefresher->Refresh (0L))) { goto PROC_CLEANUP; } proc.pAccess->ReadQWORD ( proc.hVirtualBytes, &proc.memory.virtual_bytes ); proc.pAccess->ReadQWORD ( proc.hVirtualBytesPeak, &proc.memory.virtual_bytes_peak ); proc.pAccess->ReadQWORD ( proc.hWorkingSet, &proc.memory.working_set ); proc.pAccess->ReadQWORD ( proc.hWorkingSetPeak, &proc.memory.working_set_peak ); proc.pAccess->ReadQWORD ( proc.hPrivateBytes, &proc.memory.private_bytes ); proc.pAccess->ReadDWORD ( proc.hThreadCount, (DWORD *)&proc.tasks.thread_count ); proc.pAccess->ReadQWORD ( proc.hPageFileBytes, &proc.memory.page_file_bytes ); proc.pAccess->ReadQWORD ( proc.hPageFileBytesPeak, &proc.memory.page_file_bytes_peak ); ++iter; LeaveCriticalSection (&com_cs); } EnterCriticalSection (&com_cs); PROC_CLEANUP: // dll_log.Log (L" >> PROC_CLEANUP"); if (proc.pAccess != nullptr) { proc.pAccess->Release (); proc.pAccess = nullptr; } if (proc.pConfig != nullptr) { proc.pConfig->Release (); proc.pConfig = nullptr; } if (proc.pRefresher != nullptr) { proc.pRefresher->Release (); proc.pRefresher = nullptr; } CoUninitialize (); LeaveCriticalSection (&com_cs); return 0; }
void RefreshWindowList(HWND hwndCombobox, ConfigDialogData &configData) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); configData.ClearData(); BOOL bWindows64bit = Is64BitWindows(); BOOL bCurrentProcessIsWow64 = FALSE; IsWow64Process(GetCurrentProcess(), &bCurrentProcessIsWow64); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if( (exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 /*&& hwndParent == NULL*/) { String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); bool b64bit = false; //------- DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if(hProcess) { BOOL bTargetProcessIsWow64 = FALSE; IsWow64Process(hProcess, &bTargetProcessIsWow64); DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); StringList moduleList; OSGetLoadedModuleList(hProcess, moduleList); CloseHandle(hProcess); //todo: remove later if(bCurrentProcessIsWow64 != bTargetProcessIsWow64) { configData.opposingBitWindows << strWindowName; continue; } BOOL bFoundModule = FALSE; for(UINT i=0; i<moduleList.Num(); i++) { CTSTR moduleName = moduleList[i]; if (!scmp(moduleName, TEXT("d3d9.dll")) || !scmp(moduleName, TEXT("d3d10.dll")) || !scmp(moduleName, TEXT("d3d10_1.dll")) || !scmp(moduleName, TEXT("d3d11.dll")) || !scmp(moduleName, TEXT("opengl32.dll"))) { bFoundModule = true; break; } } if (!bFoundModule) continue; b64bit = (bWindows64bit && !bTargetProcessIsWow64); } else { hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { BOOL bTargetProcessIsWow64 = FALSE; IsWow64Process(hProcess, &bTargetProcessIsWow64); if(bCurrentProcessIsWow64 != bTargetProcessIsWow64) configData.opposingBitWindows << strWindowName; configData.adminWindows << strWindowName; CloseHandle(hProcess); } continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName); strText << (b64bit ? TEXT("*64") : TEXT("*32")); strText << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = strClassName; info.b64bit = b64bit; info.bRequiresAdmin = false; //todo: add later } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); }
void RefreshWindowList(HWND hwndCombobox, ConfigDialogData &configData) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); configData.ClearData(); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if (strWindowName.IsValid() && sstri(strWindowName, L"battlefield") != nullptr) exStyles &= ~WS_EX_TOOLWINDOW; if((exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 /*&& hwndParent == NULL*/) { DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); for (int i=0; i<11; i++) pOPStr[i] ^= i^1; OPPROC pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); HANDLE hProcess = (*pOpenProcess)(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if(hProcess) { DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); StringList moduleList; OSGetLoadedModuleList(hProcess, moduleList); CloseHandle(hProcess); //note: this doesn't actually work cross-bit /*BOOL bFoundModule = FALSE; for(UINT i=0; i<moduleList.Num(); i++) { CTSTR moduleName = moduleList[i]; if (!scmp(moduleName, TEXT("d3d9.dll")) || !scmp(moduleName, TEXT("d3d10.dll")) || !scmp(moduleName, TEXT("d3d10_1.dll")) || !scmp(moduleName, TEXT("d3d11.dll")) || !scmp(moduleName, TEXT("opengl32.dll"))) { bFoundModule = true; break; } } if (!bFoundModule) continue;*/ } else { hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { configData.adminWindows << strWindowName; CloseHandle(hProcess); } continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName); strText << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = strClassName; info.bRequiresAdmin = false; //todo: add later } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); if(OSGetVersion() < 8) { BOOL isCompositionEnabled = FALSE; DwmIsCompositionEnabled(&isCompositionEnabled); if(isCompositionEnabled) { String strText; strText << TEXT("[DWM]: ") << Str("Sources.SoftwareCaptureSource.MonitorCapture"); int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)NULL); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = TEXT("Dwm"); info.bRequiresAdmin = false; //todo: add later } } }
int APIENTRY _tWinMain( HINSTANCE handleToInstance, HINSTANCE handleToPreviousInstance, LPTSTR commandLine, int showCommand) { LPTSTR commandLineReader = commandLine; int argc = 0; while (*commandLineReader) { if (*commandLineReader == _T(' ')) argc++; commandLineReader++; } /*if (argc < 2) { return 0; }*/ TCHAR targetExecutableBuffer[MaxExeNameLength]; _tcscpy_s<MaxExeNameLength>(targetExecutableBuffer, commandLine); LPTSTR targetExecutable = targetExecutableBuffer; if (*targetExecutable == TEXT('"')) { targetExecutable++; *_tcschr(targetExecutable, TEXT('"')) = TEXT('\0'); } // See if the app is already running; if so, activate it // Get all running process ids DWORD processIds[MaxProcessIds]; DWORD bytesNeeded; EnumProcesses(processIds, MaxProcessIds * sizeof(DWORD), &bytesNeeded); DWORD processCount = bytesNeeded / sizeof(DWORD); for (DWORD i = 0; i < processCount; i++) { // Get the image name of the process TCHAR exeName[MaxExeNameLength]; DWORD length = MaxExeNameLength * sizeof(TCHAR); HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processIds[i]); BOOL result = QueryFullProcessImageName(processHandle, 0, exeName, &length); CloseHandle(processHandle); // If the image name is the same as the one we are trying to start if (result && _tcsicmp(targetExecutable, exeName) == 0) { // Get its window handle targetProcessId = processIds[i]; EnumWindows(EnumWindowsProc, 0); // Restore the window if it is minimized BOOL isMinimized = !IsMaximized(targetWindowHandle); if (isMinimized) { ShowWindow(targetWindowHandle, SW_RESTORE); } // Bring the window to the front (activate it) DWORD currentThreadId = GetCurrentThreadId(); DWORD targetThreadId = GetWindowThreadProcessId(targetWindowHandle, NULL); AttachThreadInput(currentThreadId, targetThreadId, TRUE); SetActiveWindow(targetWindowHandle); AttachThreadInput(currentThreadId, targetThreadId, FALSE); return 0; } } // App wasn't found, so start it STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); CreateProcess( NULL, commandLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); return 0; }
process::process(DWORD pid) : _process_id(pid) { // NT API Support: // 5.0 GetModuleFileNameEx // 5.1 GetProcessImageFileName // 5.0 GetProcessTimes // 5.0 GetTokenInformation // 5.0 LookupAccountSid // 5.0 OpenProcess // 5.0 OpenProcessToken // 6.0 QueryFullProcessImageName #if _WIN32_WINNT < 0x0600 //HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); #else //HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); #endif HANDLE hProcess = OpenProcess(MAXIMUM_ALLOWED, FALSE, pid); if (NULL != hProcess) { FILETIME ctime = { 0, 0 }; FILETIME etime = { 0, 0 }; FILETIME ktime = { 0, 0 }; FILETIME utime = { 0, 0 }; if (GetProcessTimes(hProcess, &ctime, &etime, &ktime, &utime)) { _creation_time = ctime; } else { std::tcerr << std::dec << pid << ": GetProcessTimes failed: " << std::hex << std::setw(8) << std::setfill(_T('0')) << GetLastError() << std::endl; } #if _WIN32_WINNT < 0x0600 std::tstring image(MAX_PATH, '\0'); // This needs PROCESS_VM_READ. DWORD image_length = GetModuleFileNameEx(hProcess, NULL, &image[0], image.size()); if (image_length > 0) { image.resize(image_length); } else { std::tcerr << std::dec << pid << ": GetModuleFileNameEx failed: " << std::hex << std::setw(8) << std::setfill(_T('0')) << GetLastError() << std::endl; } #else std::tstring image(MAX_PATH, '\0'); DWORD image_length = image.size(); // This needs PROCESS_QUERY_LIMITED_INFORMATION. if (QueryFullProcessImageName(hProcess, 0, &image[0], &image_length)) { image.resize(image_length); } else { std::tcerr << std::dec << pid << ": QueryFullProcessImageName failed: " << std::hex << std::setw(8) << std::setfill(_T('0')) << GetLastError() << std::endl; } #endif _image_filepath.assign(image); std::tstring::size_type last_slash = _image_filepath.rfind('\\'); if (last_slash != std::tstring::npos) { _image_filename = _image_filepath.substr(++last_slash, _image_filepath.size()); } HANDLE hProcessToken; if (OpenProcessToken(hProcess, TOKEN_QUERY, &hProcessToken)) { DWORD data_length = 0; if (!GetTokenInformation(hProcessToken, TokenUser, NULL, 0, &data_length) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { void* data = new byte[data_length]; if (GetTokenInformation(hProcessToken, TokenUser, data, data_length, &data_length)) { TOKEN_USER* user = static_cast<TOKEN_USER*>(data); std::tstring name(MAX_NAME, '\0'); DWORD name_length = name.size(); std::tstring domain(MAX_NAME, '\0'); DWORD domain_length = domain.size(); SID_NAME_USE type; if (LookupAccountSid(NULL, user->User.Sid, &name[0], &name_length, &domain[0], &domain_length, &type)) { name.resize(name_length); domain.resize(domain_length); _username = _T(""); if (domain.size()) { _username += domain; _username += _T("\\"); } _username += name; } else { std::tcerr << std::dec << pid << ": LookupAccountSid failed: " << std::hex << std::setw(8) << std::setfill(_T('0')) << GetLastError() << std::endl; } } else { std::tcerr << std::dec << pid << ": GetTokenInformation(2) failed: " << std::hex << std::setw(8) << std::setfill(_T('0')) << GetLastError() << std::endl; } delete data; } else { std::tcerr << std::dec << pid << ": GetTokenInformation failed: " << std::hex << std::setw(8) << std::setfill(_T('0')) << GetLastError() << std::endl; } CloseHandle(hProcessToken); } else { std::tcerr << std::dec << pid << ": OpenProcessToken failed: " << std::hex << std::setw(8) << std::setfill(_T('0')) << GetLastError() << std::endl; } CloseHandle(hProcess); } }
void RefreshWindowList(HWND hwndCombobox, ConfigDialogData &configData) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); configData.ClearData(); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if( (exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 /*&& hwndParent == NULL*/) { String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); bool b64bit = false; //------- DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if(hProcess) { DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); } else { hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { CloseHandle(hProcess); } continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName); strText << (b64bit ? TEXT("*64") : TEXT("*32")); strText << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = strClassName; info.strProcess = fileName; } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); }
void GraphicsCaptureSource::AttemptCapture() { OSDebugOut(TEXT("attempting to capture..\n")); if (scmpi(strWindowClass, L"dwm") == 0) { hwndTarget = FindWindow(strWindowClass, NULL); } else { FindWindowData fwd; //FIXME: duplicated code, but we need OpenProcess here char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated for (int i = 0; i<11; i++) pOPStr[i] ^= i ^ 1; fwd.pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); fwd.classname = strWindowClass; fwd.exename = strExecutable; fwd.hwnd = nullptr; EnumWindows(GraphicsCaptureFindWindow, (LPARAM)&fwd); hwndTarget = fwd.hwnd; } // use foregroundwindow as fallback (should be NULL if not using hotkey capture) if (!hwndTarget) hwndTarget = hwndNextTarget; hwndNextTarget = nullptr; OSDebugOut(L"Window: %s: ", strWindowClass.Array()); if (hwndTarget) { OSDebugOut(L"Valid window\n"); targetThreadID = GetWindowThreadProcessId(hwndTarget, &targetProcessID); if (!targetThreadID || !targetProcessID) { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: GetWindowThreadProcessId failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; return; } } else { OSDebugOut(L"Bad window\n"); if (!bUseHotkey && !warningID) { //Log(TEXT("GraphicsCaptureSource::AttemptCapture: Window '%s' [%s] not found."), strWindowClass.Array(), strExecutable.Array()); //warningID = API->AddStreamInfo(Str("Sources.SoftwareCaptureSource.WindowNotFound"), StreamInfoPriority_High); } bCapturing = false; return; } if (injectHelperProcess && WaitForSingleObject(injectHelperProcess, 0) == WAIT_TIMEOUT) return; if(warningID) { //API->RemoveStreamInfo(warningID); warningID = 0; } //------------------------------------------- // see if we already hooked the process. if not, inject DLL char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated for (int i=0; i<11; i++) pOPStr[i] ^= i^1; OPPROC pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); DWORD permission = useSafeHook ? (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ) : (PROCESS_ALL_ACCESS); HANDLE hProcess = (*pOpenProcess)(permission, FALSE, targetProcessID); if(hProcess) { DWORD dwSize = MAX_PATH; wchar_t processName[MAX_PATH]; memset(processName, 0, sizeof(processName)); QueryFullProcessImageName(hProcess, 0, processName, &dwSize); if (dwSize != 0 && scmpi(processName, lastProcessName) != 0) { if (processName[0]) { wchar_t *fileName = srchr(processName, '\\'); Log(L"Trying to hook process: %s", (fileName ? fileName+1 : processName)); } scpy_n(lastProcessName, processName, MAX_PATH-1); } //------------------------------------------- // load keepalive event hOBSIsAlive = CreateEvent(NULL, FALSE, FALSE, String() << OBS_KEEPALIVE_EVENT << UINT(targetProcessID)); //------------------------------------------- hwndCapture = hwndTarget; hSignalRestart = OpenEvent(EVENT_ALL_ACCESS, FALSE, String() << RESTART_CAPTURE_EVENT << UINT(targetProcessID)); if(hSignalRestart) { OSDebugOut(L"Setting signal for process ID %u\n", targetProcessID); SetEvent(hSignalRestart); bCapturing = true; captureWaitCount = 0; } else { BOOL bSameBit = TRUE; BOOL b32bit = TRUE; if (Is64BitWindows()) { BOOL bCurrentProcessWow64, bTargetProcessWow64; IsWow64Process(GetCurrentProcess(), &bCurrentProcessWow64); IsWow64Process(hProcess, &bTargetProcessWow64); bSameBit = (bCurrentProcessWow64 == bTargetProcessWow64); } if(Is64BitWindows()) IsWow64Process(hProcess, &b32bit); //verify the hook DLL is accessible String strDLL; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLL.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLL); strDLL << TEXT("\\plugins\\GraphicsCapture\\GraphicsCaptureHook"); if (!b32bit) strDLL << TEXT("64"); strDLL << TEXT(".dll"); if (!CheckFileIntegrity(strDLL.Array())) { OSDebugOut(L"Error acquiring\n"); bErrorAcquiring = true; } else { if (bSameBit && !useSafeHook) { if (InjectLibrary(hProcess, strDLL)) { captureWaitCount = 0; OSDebugOut(L"Inject successful\n"); bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: Failed to inject library, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } } else { String strDLLPath; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLLPath.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLLPath); strDLLPath << TEXT("\\plugins\\GraphicsCapture"); String strHelper = strDLLPath; strHelper << ((b32bit) ? TEXT("\\injectHelper.exe") : TEXT("\\injectHelper64.exe")); if (!CheckFileIntegrity(strHelper.Array())) { bErrorAcquiring = true; } else { String strCommandLine; strCommandLine << TEXT("\"") << strHelper << TEXT("\" "); if (useSafeHook) strCommandLine << UIntString(targetThreadID) << " 1"; else strCommandLine << UIntString(targetProcessID) << " 0"; //--------------------------------------- PROCESS_INFORMATION pi; STARTUPINFO si; zero(&pi, sizeof(pi)); zero(&si, sizeof(si)); si.cb = sizeof(si); if (CreateProcess(strHelper, strCommandLine, NULL, NULL, FALSE, 0, NULL, strDLLPath, &si, &pi)) { int exitCode = 0; CloseHandle(pi.hThread); if (!useSafeHook) { WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, (DWORD*)&exitCode); CloseHandle(pi.hProcess); } else { injectHelperProcess = pi.hProcess; } if (exitCode == 0) { captureWaitCount = 0; bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: Failed to inject library, error code = %d"), exitCode); bErrorAcquiring = true; } } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: Could not create inject helper, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } } } } } //save a copy of the process handle which we injected into, this lets us check for process exit in Tick() if (!hTargetProcess) { if (!DuplicateHandle(GetCurrentProcess(), hProcess, GetCurrentProcess(), &hTargetProcess, 0, FALSE, DUPLICATE_SAME_ACCESS)) { Log(TEXT("Warning: Couldn't DuplicateHandle, %d"), GetLastError()); } } CloseHandle(hProcess); if (!bCapturing) { CloseHandle(hOBSIsAlive); hOBSIsAlive = NULL; } } else { AppWarning(TEXT("GraphicsCaptureSource::AttemptCapture: OpenProcess failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } }
CProcess *CProcess::FindByName (const TCHAR *pszExecutable) { #ifdef _WIN32 DWORD cdwProcesses = 512; DWORD cbProcesses; PDWORD pdwProcesses = NULL; do { if (pdwProcesses) { delete pdwProcesses; } cdwProcesses <<= 1; pdwProcesses = new DWORD[cdwProcesses]; if (!pdwProcesses) { LOGFATAL (TEXT ("Out of memory")); return NULL; } LOGDEBUG (TEXT ("Calling EnumProcesses with ") << cdwProcesses << TEXT (" slots")); if (!EnumProcesses (pdwProcesses, cdwProcesses * sizeof (DWORD), &cbProcesses)) { LOGWARN (TEXT ("Couldn't enumerate active processes, error ") << GetLastError ()); delete pdwProcesses; return NULL; } } while (cbProcesses == cdwProcesses * sizeof (DWORD)); cdwProcesses = cbProcesses / sizeof (DWORD); LOGDEBUG (TEXT ("Checking ") << cdwProcesses << TEXT (" processes")); HANDLE hProcess = NULL; // Lookup correct rights mask - PROCESS_QUERY_INFORMATION on XP/W2K, PROCESS_QUERY_LIMITED_INFORMATION on newer OSVERSIONINFO version; ZeroMemory (&version, sizeof (version)); version.dwOSVersionInfoSize = sizeof (version); GetVersionEx (&version); DWORD dwRights = ((version.dwMajorVersion < 6) ? PROCESS_QUERY_INFORMATION : PROCESS_QUERY_LIMITED_INFORMATION) | PROCESS_TERMINATE | SYNCHRONIZE; while (cdwProcesses) { DWORD dwProcessID = pdwProcesses[--cdwProcesses]; if (!dwProcessID) continue; hProcess = OpenProcess (dwRights, FALSE, dwProcessID); if (hProcess) { TCHAR sz[MAX_PATH]; DWORD cch = MAX_PATH; if (QueryFullProcessImageName (hProcess, 0, sz, &cch)) { LOGDEBUG (TEXT ("Checking process ") << dwProcessID << TEXT (", executable ") << sz); if (!_tcsicmp (pszExecutable, sz)) { DWORD dwExitCode; if (GetExitCodeProcess (hProcess, &dwExitCode)) { if (dwExitCode == STILL_ACTIVE) { LOGINFO (TEXT ("Found process ") << dwProcessID << TEXT (" with executable ") << sz); break; } else { LOGINFO (TEXT ("Found terminated process ") << dwProcessID << TEXT (" with executable ") << sz); } } else { LOGWARN (TEXT ("Couldn't get exit code for process ") << dwProcessID << TEXT (", error ") << GetLastError ()); } } } else { DWORD dwError = GetLastError (); // Note: sometimes get ec 6 for the process we've just launched; should we pause and retry? if (dwError == ERROR_PARTIAL_COPY) { LOGDEBUG (TEXT ("Partial copy only of process ") << dwProcessID); } else { LOGWARN (TEXT ("Couldn't get filename for process ") << dwProcessID << TEXT (", error ") << dwError); } } CloseHandle (hProcess); hProcess = NULL; } else { DWORD dwError = GetLastError (); if (dwError == ERROR_ACCESS_DENIED) { LOGDEBUG (TEXT ("Access denied to process ") << dwProcessID); } else { LOGWARN (TEXT ("Error opening process ") << dwProcessID << TEXT (", error ") << dwError); } } } delete pdwProcesses; return hProcess ? new CProcess (hProcess) : NULL; #else /* ifdef _WIN32 */ DIR *dir = opendir ("/proc"); if (!dir) { LOGWARN (TEXT ("Couldn't open /proc, error ") << GetLastError ()); return NULL; } struct dirent *dp; while ((dp = readdir (dir)) != NULL) { if (dp->d_name[0] == '.') { continue; } if (dp->d_type & DT_DIR) { int pid = atoi (dp->d_name); if (pid > 0) { TCHAR sz[16], szExecutable[256]; StringCbPrintf (sz, sizeof (sz), TEXT ("/proc/%d/exe"), pid); int cb = readlink (sz, szExecutable, (sizeof (szExecutable) / sizeof (TCHAR)) - 1); if (cb > 0) { szExecutable[cb] = 0; LOGDEBUG (TEXT ("Checking ") << pid << TEXT (" with executable ") << szExecutable); if (!_tcscmp (szExecutable, pszExecutable)) { LOGINFO (TEXT ("Found process ") << pid << TEXT (" with executable ") << szExecutable); closedir (dir); return new CProcess (pid); } } else { LOGDEBUG (TEXT ("Couldn't read process ") << pid << TEXT (" info, error ") << GetLastError ()); } } } } closedir (dir); return NULL; #endif /* ifdef _WIN32 */ }
void Dlg_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { static BOOL s_fProcesses = TRUE; switch (id) { case IDCANCEL: EndDialog(hwnd, id); break; // Restart the application when we are not running // as Elevated Administrator. case IDC_BTN_SYSTEM_PROCESSES: { // Hide ourself before trying to start the same application // but with elevated privileges. ShowWindow(hwnd, SW_HIDE); TCHAR szApplication[MAX_PATH]; DWORD cchLength = _countof(szApplication); QueryFullProcessImageName( GetCurrentProcess(), 0, szApplication, &cchLength); DWORD dwStatus = StartElevatedProcess(szApplication, NULL); if (dwStatus == S_OK) { // not need to keep on working under lower privileges. ExitProcess(0); } // In case of error, show up again. ShowWindow(hwnd, SW_SHOWNORMAL); } break; case ID_PROCESSES: s_fProcesses = TRUE; EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_ENABLED); DrawMenuBar(hwnd); Dlg_PopulateProcessList(hwnd); break; case ID_MODULES: EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_GRAYED); DrawMenuBar(hwnd); s_fProcesses = FALSE; Dlg_PopulateModuleList(hwnd); break; case IDC_PROCESSMODULELIST: if (codeNotify == CBN_SELCHANGE) { DWORD dw = ComboBox_GetCurSel(hwndCtl); if (s_fProcesses) { dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); // Process ID ShowProcessInfo(GetDlgItem(hwnd, IDC_RESULTS), dw); } else { // Index in helper listbox of full path dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); TCHAR szModulePath[1024]; ListBox_GetText(GetDlgItem(hwnd, IDC_MODULEHELP), dw, szModulePath); ShowModuleInfo(GetDlgItem(hwnd, IDC_RESULTS), szModulePath); } } break; case ID_VMMAP: { TCHAR szCmdLine[32]; HWND hwndCB = GetDlgItem(hwnd, IDC_PROCESSMODULELIST); DWORD dwProcessId = (DWORD) ComboBox_GetItemData(hwndCB, ComboBox_GetCurSel(hwndCB)); StringCchPrintf(szCmdLine, _countof(szCmdLine), TEXT("%d"), dwProcessId); DWORD dwStatus = StartElevatedProcess(TEXT("\"14-VMMap.exe\""), szCmdLine); if (dwStatus == ERROR_CANCELLED) { chMB("Failed to run 14-VMMap.exe: you refused access."); } } break; } }