Helper function to get process PEB info by PID Falls back to process name if PEB info cannot be retrieved
| 17 | // Helper function to get process PEB info by PID |
| 18 | // Falls back to process name if PEB info cannot be retrieved |
| 19 | ProcessPebInfoRet GetProcessNameByPid(DWORD pid) { |
| 20 | // First try to get the full PEB info by opening the process |
| 21 | HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); |
| 22 | if (hProcess != NULL) { |
| 23 | try { |
| 24 | ProcessPebInfoRet pebInfo = ProcessPebInfo(hProcess); |
| 25 | CloseHandle(hProcess); |
| 26 | return pebInfo; |
| 27 | } |
| 28 | catch (const std::exception& e) { |
| 29 | //LOG_A(LOG_WARNING, "GetProcessNameByPid: Exception getting PEB info for pid %lu: %s", pid, e.what()); |
| 30 | CloseHandle(hProcess); |
| 31 | } |
| 32 | //} else { |
| 33 | // LOG_A(LOG_WARNING, "GetProcessNameByPid: Could not open process %lu for command line query (error %lu), falling back to process name", pid, GetLastError()); |
| 34 | } |
| 35 | |
| 36 | // Fallback: |
| 37 | // use CreateToolhelp32Snapshot to get just the process name |
| 38 | // If we dont have the permissions for the process basically |
| 39 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); |
| 40 | if (hSnapshot == INVALID_HANDLE_VALUE) { |
| 41 | LOG_A(LOG_ERROR, "GetProcessNameByPid: Failed to create process snapshot: %lu", GetLastError()); |
| 42 | return ProcessPebInfoRet(); |
| 43 | } |
| 44 | PROCESSENTRY32W pe32; |
| 45 | pe32.dwSize = sizeof(PROCESSENTRY32W); |
| 46 | // Get the first process |
| 47 | if (!Process32FirstW(hSnapshot, &pe32)) { |
| 48 | LOG_A(LOG_ERROR, "GetProcessNameByPid: Failed to get first process: %lu", GetLastError()); |
| 49 | CloseHandle(hSnapshot); |
| 50 | return ProcessPebInfoRet(); |
| 51 | } |
| 52 | ProcessPebInfoRet result; |
| 53 | do { |
| 54 | if (pe32.th32ProcessID == pid) { |
| 55 | std::wstring processName(pe32.szExeFile); |
| 56 | result.image_path = wstring2string(processName); |
| 57 | break; |
| 58 | } |
| 59 | } while (Process32NextW(hSnapshot, &pe32)); |
| 60 | CloseHandle(hSnapshot); |
| 61 | return result; |
| 62 | } |
| 63 | |
| 64 | |
| 65 | bool Process::ObserveIfMatchesTargets(const std::vector<std::string>& targetNames) { |
no test coverage detected