game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
process_manager_windows.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#include "platform/platform.h"
4
5#ifdef PLATFORM_WINDOWS
6
7#include <array>
8#include <chrono>
9#include <psapi.h>
10#include <sstream>
11#include <thread>
12#include <tlhelp32.h>
13#include <windows.h>
14
15#pragma comment(lib, "psapi.lib")
16
17namespace platform
18{
19
20namespace
21{
22
23std::wstring toWideString(const std::string& str)
24{
25 if (str.empty())
26 return L"";
27 int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
28 std::wstring result(len - 1, L'\0');
29 MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, result.data(), len);
30 return result;
31}
32
33std::string toNarrowString(const std::wstring& wstr)
34{
35 if (wstr.empty())
36 return "";
37 int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
38 std::string result(len - 1, '\0');
39 WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, result.data(), len, nullptr, nullptr);
40 return result;
41}
42
43} // anonymous namespace
44
45class WindowsProcessManager : public ProcessManager
46{
47 public:
48 std::optional<uint64_t> launch(const std::string& executable,
49 const std::vector<std::string>& args,
50 const std::string& workingDir,
51 const std::map<std::string, std::string>& env,
52 bool detached) override
53 {
54 // Build command line
55 std::wstring cmdLine = L"\"" + toWideString(executable) + L"\"";
56 for (const auto& arg : args)
57 {
58 cmdLine += L" \"" + toWideString(arg) + L"\"";
59 }
60
61 // Prepare environment block if needed
62 std::wstring envBlock;
63 if (!env.empty())
64 {
65 for (const auto& [key, value] : env)
66 {
67 envBlock += toWideString(key) + L"=" + toWideString(value) + L'\0';
68 }
69 envBlock += L'\0';
70 }
71
72 STARTUPINFOW si = {sizeof(si)};
73 PROCESS_INFORMATION pi = {};
74
75 DWORD flags = detached ? CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS : 0;
76
77 std::wstring wideWorkingDir = toWideString(workingDir);
78
79 BOOL success =
80 CreateProcessW(nullptr, cmdLine.data(), nullptr, nullptr, FALSE, flags,
81 env.empty() ? nullptr : envBlock.data(),
82 workingDir.empty() ? nullptr : wideWorkingDir.c_str(), &si, &pi);
83
84 if (success)
85 {
86 uint64_t pid = static_cast<uint64_t>(pi.dwProcessId);
87 CloseHandle(pi.hThread);
88 CloseHandle(pi.hProcess);
89 return pid;
90 }
91
92 return std::nullopt;
93 }
94
95 std::optional<uint64_t> launchShell(const std::string& command, const std::string& workingDir,
96 bool detached) override
97 {
98 return launch("cmd.exe", {"/c", command}, workingDir, {}, detached);
99 }
100
101 bool isRunning(uint64_t pid) const override
102 {
103 HANDLE hProcess =
104 OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, static_cast<DWORD>(pid));
105 if (hProcess)
106 {
107 DWORD exitCode;
108 bool running = GetExitCodeProcess(hProcess, &exitCode) && exitCode == STILL_ACTIVE;
109 CloseHandle(hProcess);
110 return running;
111 }
112 return false;
113 }
114
115 std::optional<ProcessInfo> getProcessInfo(uint64_t pid) const override
116 {
117 HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE,
118 static_cast<DWORD>(pid));
119 if (!hProcess)
120 return std::nullopt;
121
122 ProcessInfo info;
123 info.pid = pid;
124
125 // Get executable path
126 wchar_t exePath[MAX_PATH];
127 DWORD size = MAX_PATH;
128 if (QueryFullProcessImageNameW(hProcess, 0, exePath, &size))
129 {
130 info.executablePath = toNarrowString(exePath);
131 // Extract just the name
132 std::filesystem::path p(info.executablePath);
133 info.name = p.filename().string();
134 }
135
136 // Get command line (requires higher privileges, may fail)
137 // For simplicity, just use the executable name
138 info.cmdLine = info.executablePath;
139
140 // Get parent PID using snapshot
141 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
142 if (hSnapshot != INVALID_HANDLE_VALUE)
143 {
144 PROCESSENTRY32W pe = {sizeof(pe)};
145 if (Process32FirstW(hSnapshot, &pe))
146 {
147 do
148 {
149 if (pe.th32ProcessID == static_cast<DWORD>(pid))
150 {
151 info.parentPid = pe.th32ParentProcessID;
152 break;
153 }
154 } while (Process32NextW(hSnapshot, &pe));
155 }
156 CloseHandle(hSnapshot);
157 }
158
159 CloseHandle(hProcess);
160 return info;
161 }
162
163 std::vector<ProcessInfo> findByName(const std::string& name) const override
164 {
165 std::vector<ProcessInfo> results;
166 std::wstring wideName = toWideString(name);
167
168 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
169 if (hSnapshot == INVALID_HANDLE_VALUE)
170 return results;
171
172 PROCESSENTRY32W pe = {sizeof(pe)};
173 if (Process32FirstW(hSnapshot, &pe))
174 {
175 do
176 {
177 if (_wcsicmp(pe.szExeFile, wideName.c_str()) == 0)
178 {
179 ProcessInfo info;
180 info.pid = pe.th32ProcessID;
181 info.name = toNarrowString(pe.szExeFile);
182 info.parentPid = pe.th32ParentProcessID;
183 results.push_back(info);
184 }
185 } while (Process32NextW(hSnapshot, &pe));
186 }
187
188 CloseHandle(hSnapshot);
189 return results;
190 }
191
192 std::vector<ProcessInfo> findByCommandLine(const std::string& pattern) const override
193 {
194 // On Windows, getting command lines requires elevated privileges
195 // For now, search by executable name as fallback
196 std::vector<ProcessInfo> results;
197
198 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
199 if (hSnapshot == INVALID_HANDLE_VALUE)
200 return results;
201
202 PROCESSENTRY32W pe = {sizeof(pe)};
203 if (Process32FirstW(hSnapshot, &pe))
204 {
205 do
206 {
207 std::string exeName = toNarrowString(pe.szExeFile);
208 if (exeName.find(pattern) != std::string::npos)
209 {
210 ProcessInfo info;
211 info.pid = pe.th32ProcessID;
212 info.name = exeName;
213 info.parentPid = pe.th32ParentProcessID;
214 results.push_back(info);
215 }
216 } while (Process32NextW(hSnapshot, &pe));
217 }
218
219 CloseHandle(hSnapshot);
220 return results;
221 }
222
223 std::vector<ProcessInfo> getChildren(uint64_t parentPid) const override
224 {
225 std::vector<ProcessInfo> results;
226
227 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
228 if (hSnapshot == INVALID_HANDLE_VALUE)
229 return results;
230
231 PROCESSENTRY32W pe = {sizeof(pe)};
232 if (Process32FirstW(hSnapshot, &pe))
233 {
234 do
235 {
236 if (pe.th32ParentProcessID == static_cast<DWORD>(parentPid))
237 {
238 ProcessInfo info;
239 info.pid = pe.th32ProcessID;
240 info.name = toNarrowString(pe.szExeFile);
241 info.parentPid = pe.th32ParentProcessID;
242 results.push_back(info);
243 }
244 } while (Process32NextW(hSnapshot, &pe));
245 }
246
247 CloseHandle(hSnapshot);
248 return results;
249 }
250
251 std::vector<ProcessInfo> getAllProcesses() const override
252 {
253 std::vector<ProcessInfo> results;
254
255 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
256 if (hSnapshot == INVALID_HANDLE_VALUE)
257 return results;
258
259 PROCESSENTRY32W pe = {sizeof(pe)};
260 if (Process32FirstW(hSnapshot, &pe))
261 {
262 do
263 {
264 ProcessInfo info;
265 info.pid = pe.th32ProcessID;
266 info.name = toNarrowString(pe.szExeFile);
267 info.parentPid = pe.th32ParentProcessID;
268 results.push_back(info);
269 } while (Process32NextW(hSnapshot, &pe));
270 }
271
272 CloseHandle(hSnapshot);
273 return results;
274 }
275
276 bool terminate(uint64_t pid, bool force) override
277 {
278 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, static_cast<DWORD>(pid));
279 if (hProcess)
280 {
281 BOOL result = TerminateProcess(hProcess, 1);
282 CloseHandle(hProcess);
283 return result != 0;
284 }
285 return false;
286 }
287
288 bool terminateTree(uint64_t pid) override
289 {
290 // First terminate children
291 auto children = getChildren(pid);
292 for (const auto& child : children)
293 {
294 terminateTree(child.pid);
295 }
296 return terminate(pid, true);
297 }
298
299 int waitForExit(uint64_t pid, uint32_t timeoutMs) override
300 {
301 HANDLE hProcess = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
302 static_cast<DWORD>(pid));
303 if (!hProcess)
304 return -1;
305
306 DWORD waitResult = WaitForSingleObject(hProcess, timeoutMs == 0 ? INFINITE : timeoutMs);
307
308 if (waitResult == WAIT_OBJECT_0)
309 {
310 DWORD exitCode;
311 if (GetExitCodeProcess(hProcess, &exitCode))
312 {
313 CloseHandle(hProcess);
314 return static_cast<int>(exitCode);
315 }
316 }
317
318 CloseHandle(hProcess);
319 return -1;
320 }
321
322 std::pair<int, std::string> executeAndCapture(const std::string& command,
323 uint32_t timeoutMs) override
324 {
325 SECURITY_ATTRIBUTES sa = {sizeof(sa), nullptr, TRUE};
326 HANDLE hReadPipe, hWritePipe;
327
328 if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0))
329 {
330 return {-1, ""};
331 }
332
333 SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);
334
335 STARTUPINFOW si = {sizeof(si)};
336 si.dwFlags = STARTF_USESTDHANDLES;
337 si.hStdOutput = hWritePipe;
338 si.hStdError = hWritePipe;
339 si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
340
341 PROCESS_INFORMATION pi = {};
342
343 std::wstring cmdLine = L"cmd.exe /c " + toWideString(command);
344
345 BOOL success = CreateProcessW(nullptr, cmdLine.data(), nullptr, nullptr, TRUE,
346 CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi);
347
348 CloseHandle(hWritePipe);
349
350 if (!success)
351 {
352 CloseHandle(hReadPipe);
353 return {-1, ""};
354 }
355
356 std::string output;
357 std::array<char, 4096> buffer;
358 DWORD bytesRead;
359
360 while (ReadFile(hReadPipe, buffer.data(), static_cast<DWORD>(buffer.size()), &bytesRead,
361 nullptr) &&
362 bytesRead > 0)
363 {
364 output.append(buffer.data(), bytesRead);
365 }
366
367 CloseHandle(hReadPipe);
368
369 WaitForSingleObject(pi.hProcess, timeoutMs == 0 ? INFINITE : timeoutMs);
370
371 DWORD exitCode;
372 GetExitCodeProcess(pi.hProcess, &exitCode);
373
374 CloseHandle(pi.hThread);
375 CloseHandle(pi.hProcess);
376
377 return {static_cast<int>(exitCode), output};
378 }
379};
380
381// Factory implementation
382std::unique_ptr<ProcessManager> ProcessManager::create()
383{
384 return std::make_unique<WindowsProcessManager>();
385}
386
387} // namespace platform
388
389#endif // PLATFORM_WINDOWS
static std::unique_ptr< ProcessManager > create()