game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
process_manager_linux.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#include "platform/platform.h"
4
5#ifdef PLATFORM_LINUX
6
7#include <algorithm>
8#include <array>
9#include <chrono>
10#include <cstdlib>
11#include <cstring>
12#include <filesystem>
13#include <fstream>
14#include <regex>
15#include <sstream>
16#include <thread>
17
18#include <cerrno>
19#include <climits>
20#include <dirent.h>
21#include <fcntl.h>
22#include <poll.h>
23#include <signal.h>
24#include <sys/types.h>
25#include <sys/wait.h>
26#include <unistd.h>
27
28// POSIX `environ` is a global C symbol — declared at file scope (not inside
29// `namespace platform`) and with C linkage so the lookup resolves to the
30// libc-provided ::environ. Previously the declaration sat inside the
31// LinuxProcessManager::launch function body, which placed it under
32// `namespace platform` and produced an unresolved `platform::environ` that
33// only linked by accident through a transitive shared-library symbol when
34// building the full launcher; the static-only test build link surfaced
35// the missing reference.
36extern "C" char** environ;
37
38namespace platform
39{
40
41class LinuxProcessManager : public ProcessManager
42{
43 public:
44 std::optional<uint64_t> launch(const std::string& executable,
45 const std::vector<std::string>& args,
46 const std::string& workingDir,
47 const std::map<std::string, std::string>& env,
48 bool detached) override
49 {
50 // Build the child's environment BEFORE fork to avoid calling setenv()
51 // (which uses malloc internally) in the child of a multi-threaded parent.
52 // Inherit the parent environment, then overlay with caller-supplied entries.
53 // ::environ is declared at file scope above (extern "C") so this
54 // resolves to libc's POSIX environ, not platform::environ.
55 std::vector<std::string> envStrings;
56 for (char** ep = ::environ; ep && *ep; ++ep)
57 envStrings.emplace_back(*ep);
58 for (const auto& kv : env)
59 {
60 const std::string& key = kv.first;
61 const std::string& value = kv.second;
62 std::string entry = key + "=" + value;
63 // std::find_if + branched move keeps the move/non-move paths
64 // mutually exclusive at the language level. The previous
65 // `replaced=true; break;` flag was correct but clang-tidy
66 // (bugprone-use-after-move) couldn't prove the move on the
67 // matched branch never aliased the post-loop push_back's move.
68 // Avoiding structured-binding capture here also keeps the
69 // lambda C++17-conformant (capturing structured bindings is
70 // C++20).
71 auto it = std::find_if(envStrings.begin(), envStrings.end(),
72 [&key](const std::string& e)
73 {
74 return e.size() > key.size() && e[key.size()] == '=' &&
75 e.compare(0, key.size(), key) == 0;
76 });
77 if (it != envStrings.end())
78 *it = std::move(entry);
79 else
80 envStrings.push_back(std::move(entry));
81 }
82 std::vector<char*> envp;
83 envp.reserve(envStrings.size() + 1);
84 for (auto& s : envStrings)
85 envp.push_back(s.data());
86 envp.push_back(nullptr);
87
88 pid_t pid = fork();
89
90 if (pid < 0)
91 {
92 // Fork failed
93 return std::nullopt;
94 }
95
96 if (pid == 0)
97 {
98 // First-level child.
99 //
100 // Detached path uses a double-fork so the eventual grandchild
101 // becomes init's (PID 1's) child and gets auto-reaped by init,
102 // avoiding the zombie-accumulation problem if the caller never
103 // waits. Non-detached path runs in this process so the caller
104 // can waitpid() the returned pid.
105 if (detached)
106 {
107 // setsid() detaches from controlling terminal; required
108 // before the second fork so the grandchild can never
109 // re-acquire a tty.
110 setsid();
111
112 pid_t inner = fork();
113 if (inner < 0)
114 {
115 // Inner fork failed; abort the child without running
116 // the user binary. _exit() not exit() — atexit()
117 // handlers from libc/Qt are not safe across fork.
118 _exit(127);
119 }
120 if (inner > 0)
121 {
122 // Intermediate child exits immediately. The original
123 // parent's waitpid (below) reaps it; the grandchild
124 // is now an orphan and will be reaped by init.
125 _exit(0);
126 }
127 // Grandchild falls through to exec the user binary.
128 }
129
130 // Change working directory if specified
131 if (!workingDir.empty())
132 {
133 if (chdir(workingDir.c_str()) != 0)
134 {
135 _exit(127);
136 }
137 }
138
139 // Environment already built in envp; do NOT call setenv() here.
140
141 // Build persistent copies to avoid dangling pointers from const_cast
142 std::vector<std::string> argStrings;
143 argStrings.reserve(args.size() + 1);
144 argStrings.push_back(executable);
145 argStrings.insert(argStrings.end(), args.begin(), args.end());
146 std::vector<char*> argv;
147 argv.reserve(argStrings.size() + 1);
148 for (auto& s : argStrings)
149 {
150 argv.push_back(s.data());
151 }
152 argv.push_back(nullptr);
153
154 // Close all inherited file descriptors except stdin/stdout/stderr.
155 //
156 // Prefer closing via /proc/self/fd so we only iterate fds the
157 // process actually has open. The fallback is the bounded
158 // sysconf(_SC_OPEN_MAX) loop, capped at 65536 to avoid the
159 // 1M-syscall storm on systemd setups (which default to
160 // LimitNOFILE=infinity / 1048576 on modern distros).
161 //
162 // glibc 2.34+ has closefrom(3) but we don't depend on that
163 // version yet — the /proc/self/fd path is portable across
164 // every Linux that mounts procfs.
165 DIR* fdDir = opendir("/proc/self/fd");
166 if (fdDir != nullptr)
167 {
168 int dirFd = dirfd(fdDir);
169 struct dirent* entry;
170 while ((entry = readdir(fdDir)) != nullptr)
171 {
172 if (entry->d_name[0] == '.')
173 continue;
174 // Kernel guarantees /proc/self/fd entries are decimal
175 // ints; strtol over atoi to silence clang-tidy and
176 // skip any unparseable entry defensively.
177 char* endp = nullptr;
178 long fd = std::strtol(entry->d_name, &endp, 10);
179 if (endp == entry->d_name || *endp != '\0')
180 continue;
181 if (fd > 2 && fd <= INT_MAX && static_cast<int>(fd) != dirFd)
182 {
183 close(static_cast<int>(fd));
184 }
185 }
186 closedir(fdDir);
187 }
188 else
189 {
190 // /proc not available (e.g. minimal sandbox). Fall back to
191 // the bounded loop with a sanity cap.
192 long maxFd = sysconf(_SC_OPEN_MAX);
193 if (maxFd < 0)
194 maxFd = 1024;
195 if (maxFd > 65536)
196 maxFd = 65536;
197 for (long fd = 3; fd < maxFd; ++fd)
198 {
199 close(static_cast<int>(fd));
200 }
201 }
202
203 // Redirect stdin/stdout/stderr to /dev/null if detached
204 if (detached)
205 {
206 int devNull = open("/dev/null", O_RDWR);
207 if (devNull >= 0)
208 {
209 dup2(devNull, STDIN_FILENO);
210 dup2(devNull, STDOUT_FILENO);
211 dup2(devNull, STDERR_FILENO);
212 close(devNull);
213 }
214 }
215
216 // Execute with pre-built environment (GNU extension, Linux-only — acceptable here).
217 execvpe(executable.c_str(), argv.data(), envp.data());
218
219 // If we get here, exec failed
220 _exit(127);
221 }
222
223 // Parent process.
224 if (detached)
225 {
226 // Reap the intermediate child immediately so it doesn't sit as
227 // a zombie. The grandchild has already been re-parented to
228 // init by the time waitpid returns. The reported pid is the
229 // intermediate child's; the grandchild's pid is unknown to
230 // us, which is acceptable for fully-detached launches (the
231 // caller can't track it anyway). Use WNOHANG-with-loop in
232 // case the intermediate child isn't quite gone yet.
233 int status = 0;
234 for (int attempts = 0; attempts < 50; ++attempts)
235 {
236 pid_t r = ::waitpid(pid, &status, WNOHANG);
237 if (r == pid || r < 0)
238 break;
239 std::this_thread::sleep_for(std::chrono::milliseconds(1));
240 }
241 return static_cast<uint64_t>(pid);
242 }
243 else
244 {
245 return static_cast<uint64_t>(pid);
246 }
247 }
248
249 std::optional<uint64_t> launchShell(const std::string& command, const std::string& workingDir,
250 bool detached) override
251 {
252 std::vector<std::string> args = {"-c", command};
253 return launch("/bin/sh", args, workingDir, {}, detached);
254 }
255
256 bool isRunning(uint64_t pid) const override
257 {
258 // Check if /proc/<pid> exists
259 std::filesystem::path procPath = "/proc/" + std::to_string(pid);
260 return std::filesystem::exists(procPath);
261 }
262
263 std::optional<ProcessInfo> getProcessInfo(uint64_t pid) const override
264 {
265 std::filesystem::path procPath = "/proc/" + std::to_string(pid);
266
267 if (!std::filesystem::exists(procPath))
268 {
269 return std::nullopt;
270 }
271
272 ProcessInfo info;
273 info.pid = pid;
274
275 // Read comm (process name)
276 std::ifstream commFile(procPath / "comm");
277 if (commFile)
278 {
279 std::getline(commFile, info.name);
280 }
281
282 // Read cmdline — null-separated args, convert to space-separated
283 std::ifstream cmdlineFile(procPath / "cmdline");
284 if (cmdlineFile)
285 {
286 std::string arg;
287 bool first = true;
288 while (std::getline(cmdlineFile, arg, '\0'))
289 {
290 if (arg.empty())
291 continue;
292 if (!first)
293 info.cmdLine += ' ';
294 info.cmdLine += arg;
295 first = false;
296 }
297 }
298
299 // Read exe link
300 std::filesystem::path exeLink = procPath / "exe";
301 std::error_code ec;
302 auto exePath = std::filesystem::read_symlink(exeLink, ec);
303 if (!ec)
304 {
305 info.executablePath = exePath.string();
306 }
307
308 // Read parent PID from stat
309 std::ifstream statFile(procPath / "stat");
310 if (statFile)
311 {
312 std::string stat;
313 std::getline(statFile, stat);
314 // Format: pid (comm) state ppid ...
315 // Find last ) to handle process names with spaces/parens
316 auto lastParen = stat.rfind(')');
317 if (lastParen != std::string::npos && lastParen + 2 < stat.size())
318 {
319 std::istringstream iss(stat.substr(lastParen + 2));
320 char state;
321 uint64_t ppid;
322 iss >> state >> ppid;
323 info.parentPid = ppid;
324 }
325 }
326
327 return info;
328 }
329
330 std::vector<ProcessInfo> findByName(const std::string& name) const override
331 {
332 std::vector<ProcessInfo> results;
333
334 DIR* procDir = opendir("/proc");
335 if (!procDir)
336 return results;
337
338 struct dirent* entry;
339 while ((entry = readdir(procDir)) != nullptr)
340 {
341 // Check if this is a PID directory
342 char* endptr;
343 long pid = strtol(entry->d_name, &endptr, 10);
344 if (*endptr != '\0' || pid <= 0)
345 continue;
346
347 auto info = getProcessInfo(static_cast<uint64_t>(pid));
348 if (info && info->name == name)
349 {
350 results.push_back(*info);
351 }
352 }
353
354 closedir(procDir);
355 return results;
356 }
357
358 std::vector<ProcessInfo> findByCommandLine(const std::string& pattern) const override
359 {
360 std::vector<ProcessInfo> results;
361 std::regex re(pattern, std::regex::icase);
362
363 DIR* procDir = opendir("/proc");
364 if (!procDir)
365 return results;
366
367 struct dirent* entry;
368 while ((entry = readdir(procDir)) != nullptr)
369 {
370 char* endptr;
371 long pid = strtol(entry->d_name, &endptr, 10);
372 if (*endptr != '\0' || pid <= 0)
373 continue;
374
375 auto info = getProcessInfo(static_cast<uint64_t>(pid));
376 if (info && std::regex_search(info->cmdLine, re))
377 {
378 results.push_back(*info);
379 }
380 }
381
382 closedir(procDir);
383 return results;
384 }
385
386 std::vector<ProcessInfo> getChildren(uint64_t parentPid) const override
387 {
388 std::vector<ProcessInfo> results;
389
390 DIR* procDir = opendir("/proc");
391 if (!procDir)
392 return results;
393
394 struct dirent* entry;
395 while ((entry = readdir(procDir)) != nullptr)
396 {
397 char* endptr;
398 long pid = strtol(entry->d_name, &endptr, 10);
399 if (*endptr != '\0' || pid <= 0)
400 continue;
401
402 auto info = getProcessInfo(static_cast<uint64_t>(pid));
403 if (info && info->parentPid == parentPid)
404 {
405 results.push_back(*info);
406 }
407 }
408
409 closedir(procDir);
410 return results;
411 }
412
413 std::vector<ProcessInfo> getAllProcesses() const override
414 {
415 std::vector<ProcessInfo> results;
416
417 DIR* procDir = opendir("/proc");
418 if (!procDir)
419 return results;
420
421 struct dirent* entry;
422 while ((entry = readdir(procDir)) != nullptr)
423 {
424 char* endptr;
425 long pid = strtol(entry->d_name, &endptr, 10);
426 if (*endptr != '\0' || pid <= 0)
427 continue;
428
429 auto info = getProcessInfo(static_cast<uint64_t>(pid));
430 if (info)
431 {
432 results.push_back(*info);
433 }
434 }
435
436 closedir(procDir);
437 return results;
438 }
439
440 bool terminate(uint64_t pid, bool force) override
441 {
442 int sig = force ? SIGKILL : SIGTERM;
443 return kill(static_cast<pid_t>(pid), sig) == 0;
444 }
445
446 bool terminateTree(uint64_t pid) override
447 {
448 // First, terminate all children recursively
449 auto children = getChildren(pid);
450 for (const auto& child : children)
451 {
452 terminateTree(child.pid);
453 }
454
455 // Then terminate the process itself
456 return terminate(pid, false);
457 }
458
459 int waitForExit(uint64_t pid, uint32_t timeoutMs) override
460 {
461 auto start = std::chrono::steady_clock::now();
462
463 while (true)
464 {
465 int status;
466 pid_t result = waitpid(static_cast<pid_t>(pid), &status, WNOHANG);
467
468 if (result == static_cast<pid_t>(pid))
469 {
470 // Process exited
471 if (WIFEXITED(status))
472 {
473 return WEXITSTATUS(status);
474 }
475 else if (WIFSIGNALED(status))
476 {
477 return 128 + WTERMSIG(status);
478 }
479 return -1;
480 }
481 else if (result < 0)
482 {
483 // Error or not our child
484 if (!isRunning(pid))
485 {
486 return 0; // Process no longer exists
487 }
488 }
489
490 // Check timeout
491 if (timeoutMs > 0)
492 {
493 auto elapsed = std::chrono::steady_clock::now() - start;
494 if (std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count() >=
495 timeoutMs)
496 {
497 return -1; // Timeout
498 }
499 }
500
501 // Sleep a bit before checking again
502 std::this_thread::sleep_for(std::chrono::milliseconds(50));
503 }
504 }
505
506 std::pair<int, std::string> executeAndCapture(const std::string& command,
507 uint32_t timeoutMs) override
508 {
509 // Run `command` via `/bin/sh -c` (popen semantics) but with a manual
510 // fork/exec so the child runs in its OWN process group. That is what
511 // makes timeoutMs enforceable: on deadline we kill(-pid, …) the whole
512 // group and reap with waitpid(). popen() hides the child pid, so the
513 // previous timeout path called tcgetpgrp() on a pipe fd — which always
514 // fails with ENOTTY — sent no signal, then blocked in pclose(). The
515 // child only calls async-signal-safe functions before exec, so the
516 // fork is safe even when this is invoked from a worker thread.
517 std::array<char, 4096> buffer;
518 std::string output;
519
520 int pipefd[2];
521 if (::pipe(pipefd) != 0)
522 return {-1, ""};
523
524 const pid_t pid = ::fork();
525 if (pid < 0)
526 {
527 ::close(pipefd[0]);
528 ::close(pipefd[1]);
529 return {-1, ""};
530 }
531
532 if (pid == 0)
533 {
534 // Child: own process group, stdout+stderr → pipe, exec the shell.
535 ::setpgid(0, 0);
536 ::dup2(pipefd[1], STDOUT_FILENO);
537 ::dup2(pipefd[1], STDERR_FILENO);
538 ::close(pipefd[0]);
539 ::close(pipefd[1]);
540 ::execl("/bin/sh", "sh", "-c", command.c_str(), static_cast<char*>(nullptr));
541 _exit(127); // exec failed
542 }
543
544 // Parent.
545 ::close(pipefd[1]);
546 ::setpgid(pid, pid); // set here too to close the fork/exec race (ok if it fails)
547 const int fd = pipefd[0];
548
549 // Non-blocking so a stalled child can't trap us in read().
550 int flags = ::fcntl(fd, F_GETFL, 0);
551 if (flags >= 0)
552 ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
553
554 const bool hasDeadline = (timeoutMs != 0);
555 const auto deadline =
556 std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
557 bool timedOut = false;
558 while (true)
559 {
560 int waitMs = 250;
561 if (hasDeadline)
562 {
563 const auto now = std::chrono::steady_clock::now();
564 if (now >= deadline)
565 {
566 timedOut = true;
567 break;
568 }
569 waitMs = std::min(
570 250, static_cast<int>(
571 std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now)
572 .count()));
573 }
574
575 struct pollfd pfd{};
576 pfd.fd = fd;
577 pfd.events = POLLIN | POLLHUP;
578 int pr = ::poll(&pfd, 1, waitMs);
579 if (pr < 0)
580 {
581 if (errno == EINTR)
582 continue;
583 break; // hard poll error
584 }
585 if (pr == 0)
586 continue; // re-check deadline
587 ssize_t n = ::read(fd, buffer.data(), buffer.size());
588 if (n > 0)
589 {
590 output.append(buffer.data(), static_cast<size_t>(n));
591 }
592 else if (n == 0)
593 {
594 break; // EOF — child closed stdout
595 }
596 else
597 {
598 if (errno == EAGAIN || errno == EWOULDBLOCK)
599 continue;
600 break; // read error
601 }
602 }
603
604 ::close(fd);
605
606 if (timedOut)
607 {
608 // Kill the whole process group: SIGTERM, brief grace, then SIGKILL.
609 ::kill(-pid, SIGTERM);
610 bool reaped = false;
611 for (int i = 0; i < 20; ++i) // ~200 ms grace
612 {
613 int st = 0;
614 pid_t r = ::waitpid(pid, &st, WNOHANG);
615 if (r == pid || (r < 0 && errno == ECHILD))
616 {
617 reaped = true;
618 break;
619 }
620 std::this_thread::sleep_for(std::chrono::milliseconds(10));
621 }
622 if (!reaped)
623 {
624 ::kill(-pid, SIGKILL);
625 int st = 0;
626 ::waitpid(pid, &st, 0);
627 }
628 return {-1, output};
629 }
630
631 int status = 0;
632 if (::waitpid(pid, &status, 0) < 0)
633 return {-1, output};
634 int exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
635 return {exitCode, output};
636 }
637};
638
639// Factory implementation
640std::unique_ptr<ProcessManager> ProcessManager::create()
641{
642 return std::make_unique<LinuxProcessManager>();
643}
644
645} // namespace platform
646
647#endif // PLATFORM_LINUX
static std::unique_ptr< ProcessManager > create()