gamemode.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /*
  2. Copyright (c) 2017-2018, Feral Interactive
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of Feral Interactive nor the names of its contributors
  12. may be used to endorse or promote products derived from this software
  13. without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  18. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #define _GNU_SOURCE
  27. #include "gamemode.h"
  28. #include "daemon_config.h"
  29. #include "governors-query.h"
  30. #include "governors.h"
  31. #include "helpers.h"
  32. #include "logging.h"
  33. #include <ctype.h>
  34. #include <fcntl.h>
  35. #include <pthread.h>
  36. #include <signal.h>
  37. #include <stdatomic.h>
  38. #include <systemd/sd-daemon.h>
  39. /* SCHED_ISO may not be defined as it is a reserved value not yet
  40. * implemented in official kernel sources, see linux/sched.h.
  41. */
  42. #ifndef SCHED_ISO
  43. #define SCHED_ISO 4
  44. #endif
  45. /**
  46. * The GameModeClient encapsulates the remote connection, providing a list
  47. * form to contain the pid and credentials.
  48. */
  49. typedef struct GameModeClient {
  50. pid_t pid; /**< Process ID */
  51. struct GameModeClient *next; /**<Next client in the list */
  52. char *executable; /**<Process executable */
  53. } GameModeClient;
  54. struct GameModeContext {
  55. pthread_rwlock_t rwlock; /**<Guard access to the client list */
  56. _Atomic int refcount; /**<Allow cycling the game mode */
  57. GameModeClient *client; /**<Pointer to first client */
  58. GameModeConfig *config; /**<Pointer to config object */
  59. char initial_cpu_mode[64]; /**<Only updates when we can */
  60. /* Reaper control */
  61. struct {
  62. pthread_t thread;
  63. bool running;
  64. pthread_mutex_t mutex;
  65. pthread_cond_t condition;
  66. } reaper;
  67. };
  68. static GameModeContext instance = { 0 };
  69. /* Maximum number of concurrent processes we'll sanely support */
  70. #define MAX_GAMES 256
  71. /**
  72. * Protect against signals
  73. */
  74. static volatile bool had_context_init = false;
  75. static GameModeClient *game_mode_client_new(pid_t pid, char *exe);
  76. static void game_mode_client_free(GameModeClient *client);
  77. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client);
  78. static int game_mode_context_num_clients(GameModeContext *self);
  79. static void *game_mode_context_reaper(void *userdata);
  80. static void game_mode_context_enter(GameModeContext *self);
  81. static void game_mode_context_leave(GameModeContext *self);
  82. static char *game_mode_context_find_exe(pid_t pid);
  83. void game_mode_context_init(GameModeContext *self)
  84. {
  85. if (had_context_init) {
  86. LOG_ERROR("Context already initialised\n");
  87. return;
  88. }
  89. had_context_init = true;
  90. self->refcount = ATOMIC_VAR_INIT(0);
  91. /* clear the initial string */
  92. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  93. /* Initialise the config */
  94. self->config = config_create();
  95. config_init(self->config);
  96. pthread_rwlock_init(&self->rwlock, NULL);
  97. pthread_mutex_init(&self->reaper.mutex, NULL);
  98. pthread_cond_init(&self->reaper.condition, NULL);
  99. /* Get the reaper thread going */
  100. self->reaper.running = true;
  101. if (pthread_create(&self->reaper.thread, NULL, game_mode_context_reaper, self) != 0) {
  102. FATAL_ERROR("Couldn't construct a new thread");
  103. }
  104. }
  105. void game_mode_context_destroy(GameModeContext *self)
  106. {
  107. if (!had_context_init) {
  108. return;
  109. }
  110. /* Leave game mode now */
  111. if (game_mode_context_num_clients(self) > 0) {
  112. game_mode_context_leave(self);
  113. }
  114. had_context_init = false;
  115. game_mode_client_free(self->client);
  116. self->reaper.running = false;
  117. /* We might be stuck waiting, so wake it up again */
  118. pthread_mutex_lock(&self->reaper.mutex);
  119. pthread_cond_signal(&self->reaper.condition);
  120. pthread_mutex_unlock(&self->reaper.mutex);
  121. /* Join the thread as soon as possible */
  122. pthread_join(self->reaper.thread, NULL);
  123. pthread_cond_destroy(&self->reaper.condition);
  124. pthread_mutex_destroy(&self->reaper.mutex);
  125. /* Destroy the config object */
  126. config_destroy(self->config);
  127. pthread_rwlock_destroy(&self->rwlock);
  128. }
  129. /**
  130. * Pivot into game mode.
  131. *
  132. * This is only possible after game_mode_context_init has made a GameModeContext
  133. * usable, and should always be followed by a game_mode_context_leave.
  134. */
  135. static void game_mode_context_enter(GameModeContext *self)
  136. {
  137. LOG_MSG("Entering Game Mode...\n");
  138. sd_notifyf(0, "STATUS=%sGameMode is now active.%s\n", "\x1B[1;32m", "\x1B[0m");
  139. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  140. memset(scripts, 0, sizeof(scripts));
  141. config_get_gamemode_start_scripts(self->config, scripts);
  142. unsigned int i = 0;
  143. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  144. LOG_MSG("Executing script [%s]\n", scripts[i]);
  145. int err;
  146. if ((err = system(scripts[i])) != 0) {
  147. /* Log the failure, but this is not fatal */
  148. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  149. }
  150. i++;
  151. }
  152. /* Read the initial governor state so we can revert it correctly */
  153. const char *initial_state = get_gov_state();
  154. if (initial_state) {
  155. /* store the initial cpu governor mode */
  156. strncpy(self->initial_cpu_mode, initial_state, sizeof(self->initial_cpu_mode) - 1);
  157. self->initial_cpu_mode[sizeof(self->initial_cpu_mode) - 1] = '\0';
  158. LOG_MSG("governor was initially set to [%s]\n", initial_state);
  159. /* Choose the desired governor */
  160. char desired[CONFIG_VALUE_MAX] = { 0 };
  161. config_get_desired_governor(self->config, desired);
  162. const char *desiredGov = desired[0] != '\0' ? desired : "performance";
  163. /* set the governor to performance */
  164. if (!set_governors(desiredGov)) {
  165. /* if the set fails, clear the initial mode so we don't try and reset it back and fail
  166. * again, presumably */
  167. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  168. }
  169. }
  170. }
  171. /**
  172. * Pivot out of game mode.
  173. *
  174. * Should only be called after both init and game_mode_context_enter have
  175. * been performed.
  176. */
  177. static void game_mode_context_leave(GameModeContext *self)
  178. {
  179. LOG_MSG("Leaving Game Mode...\n");
  180. sd_notifyf(0, "STATUS=%sGameMode is currently deactivated.%s\n", "\x1B[1;36m", "\x1B[0m");
  181. /* Reset the governer state back to initial */
  182. if (self->initial_cpu_mode[0] != '\0') {
  183. /* Choose the governor to reset to, using the config to override */
  184. char defaultgov[CONFIG_VALUE_MAX] = { 0 };
  185. config_get_default_governor(self->config, defaultgov);
  186. const char *gov_mode = defaultgov[0] != '\0' ? defaultgov : self->initial_cpu_mode;
  187. set_governors(gov_mode);
  188. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  189. }
  190. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  191. memset(scripts, 0, sizeof(scripts));
  192. config_get_gamemode_end_scripts(self->config, scripts);
  193. unsigned int i = 0;
  194. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  195. LOG_MSG("Executing script [%s]\n", scripts[i]);
  196. int err;
  197. if ((err = system(scripts[i])) != 0) {
  198. /* Log the failure, but this is not fatal */
  199. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  200. }
  201. i++;
  202. }
  203. }
  204. /**
  205. * Automatically expire all dead processes
  206. *
  207. * This has to take special care to ensure thread safety and ensuring that our
  208. * pointer is never cached incorrectly.
  209. */
  210. static void game_mode_context_auto_expire(GameModeContext *self)
  211. {
  212. bool removing = true;
  213. while (removing) {
  214. pthread_rwlock_rdlock(&self->rwlock);
  215. removing = false;
  216. /* Each time we hit an expired game, start the loop back */
  217. for (GameModeClient *client = self->client; client; client = client->next) {
  218. if (kill(client->pid, 0) != 0) {
  219. LOG_MSG("Removing expired game [%i]...\n", client->pid);
  220. pthread_rwlock_unlock(&self->rwlock);
  221. game_mode_context_unregister(self, client->pid);
  222. removing = true;
  223. break;
  224. }
  225. }
  226. if (!removing) {
  227. pthread_rwlock_unlock(&self->rwlock);
  228. break;
  229. }
  230. if (game_mode_context_num_clients(self) == 0)
  231. LOG_MSG("Properly cleaned up all expired games.\n");
  232. }
  233. }
  234. /**
  235. * Determine if the client is already known to the context
  236. */
  237. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client)
  238. {
  239. const GameModeClient *found = NULL;
  240. pthread_rwlock_rdlock(&self->rwlock);
  241. /* Walk all clients and find a matching pid */
  242. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  243. if (cl->pid == client) {
  244. found = cl;
  245. break;
  246. }
  247. }
  248. pthread_rwlock_unlock(&self->rwlock);
  249. return found;
  250. }
  251. /**
  252. * Helper to grab the current number of clients we know about
  253. */
  254. static int game_mode_context_num_clients(GameModeContext *self)
  255. {
  256. return atomic_load(&self->refcount);
  257. }
  258. bool game_mode_context_register(GameModeContext *self, pid_t client)
  259. {
  260. /* Construct a new client if we can */
  261. GameModeClient *cl = NULL;
  262. char *executable = NULL;
  263. /* Cap the total number of active clients */
  264. if (game_mode_context_num_clients(self) + 1 > MAX_GAMES) {
  265. LOG_ERROR("Max games (%d) reached, not registering %d\n", MAX_GAMES, client);
  266. return false;
  267. }
  268. errno = 0;
  269. /* Check the PID first to spare a potentially expensive lookup for the exe */
  270. pthread_rwlock_rdlock(&self->rwlock); // ensure our pointer is sane
  271. const GameModeClient *existing = game_mode_context_has_client(self, client);
  272. if (existing) {
  273. static int once = 0;
  274. const char *additional_message =
  275. (once++
  276. ? ""
  277. : " -- This may happen due to using exec or shell wrappers. You may want to\n"
  278. " -- blacklist this client so GameMode can see its final name here.\n");
  279. LOG_ERROR("Addition requested for already known client %d [%s].\n%s",
  280. existing->pid,
  281. existing->executable,
  282. additional_message);
  283. pthread_rwlock_unlock(&self->rwlock);
  284. goto error_cleanup;
  285. }
  286. pthread_rwlock_unlock(&self->rwlock);
  287. /* Lookup the executable first */
  288. executable = game_mode_context_find_exe(client);
  289. if (!executable)
  290. goto error_cleanup;
  291. /* Check our blacklist and whitelist */
  292. if (!config_get_client_whitelisted(self->config, executable)) {
  293. LOG_MSG("Client [%s] was rejected (not in whitelist)\n", executable);
  294. goto error_cleanup;
  295. } else if (config_get_client_blacklisted(self->config, executable)) {
  296. LOG_MSG("Client [%s] was rejected (in blacklist)\n", executable);
  297. goto error_cleanup;
  298. }
  299. /* From now on we depend on the client, initialize it */
  300. cl = game_mode_client_new(client, executable);
  301. if (cl)
  302. executable = NULL; // ownership has been delegated
  303. else
  304. goto error_cleanup;
  305. /* Begin a write lock now to insert our new client at list start */
  306. pthread_rwlock_wrlock(&self->rwlock);
  307. LOG_MSG("Adding game: %d [%s]\n", client, cl->executable);
  308. /* Update the list */
  309. cl->next = self->client;
  310. self->client = cl;
  311. pthread_rwlock_unlock(&self->rwlock);
  312. /* First add, init */
  313. if (atomic_fetch_add_explicit(&self->refcount, 1, memory_order_seq_cst) == 0) {
  314. game_mode_context_enter(self);
  315. }
  316. /* Apply scheduler policies */
  317. game_mode_apply_renice(self, client);
  318. game_mode_apply_scheduling(self, client);
  319. /* Apply io priorities */
  320. game_mode_apply_ioprio(self, client);
  321. return true;
  322. error_cleanup:
  323. if (errno != 0)
  324. LOG_ERROR("Failed to register client [%d]: %s\n", client, strerror(errno));
  325. free(executable);
  326. game_mode_client_free(cl);
  327. return false;
  328. }
  329. bool game_mode_context_unregister(GameModeContext *self, pid_t client)
  330. {
  331. GameModeClient *cl = NULL;
  332. GameModeClient *prev = NULL;
  333. bool found = false;
  334. /* Requires locking. */
  335. pthread_rwlock_wrlock(&self->rwlock);
  336. for (prev = cl = self->client; cl; cl = cl->next) {
  337. if (cl->pid != client) {
  338. prev = cl;
  339. continue;
  340. }
  341. LOG_MSG("Removing game: %d [%s]\n", client, cl->executable);
  342. /* Found it */
  343. found = true;
  344. prev->next = cl->next;
  345. if (cl == self->client) {
  346. self->client = cl->next;
  347. }
  348. cl->next = NULL;
  349. game_mode_client_free(cl);
  350. break;
  351. }
  352. /* Unlock here, potentially yielding */
  353. pthread_rwlock_unlock(&self->rwlock);
  354. if (!found) {
  355. static int once = 0;
  356. const char *additional_message =
  357. (once++
  358. ? ""
  359. : " -- The parent process probably forked and tries to unregister from the\n"
  360. " -- wrong process now. We cannot work around this. This message will\n"
  361. " -- likely be paired with a nearby 'Removing expired game' which means we\n"
  362. " -- cleaned up properly (we will log this event).\n");
  363. LOG_ERROR("Removal requested for unknown process [%d].\n%s", client, additional_message);
  364. return false;
  365. }
  366. /* When we hit bottom then end the game mode */
  367. if (atomic_fetch_sub_explicit(&self->refcount, 1, memory_order_seq_cst) == 1) {
  368. game_mode_context_leave(self);
  369. }
  370. return true;
  371. }
  372. int game_mode_context_query_status(GameModeContext *self, pid_t client)
  373. {
  374. GameModeClient *cl = NULL;
  375. int ret = 0;
  376. /*
  377. * Check the current refcount on gamemode, this equates to whether gamemode is active or not,
  378. * see game_mode_context_register and game_mode_context_unregister
  379. */
  380. if (atomic_load_explicit(&self->refcount, memory_order_seq_cst)) {
  381. ret++;
  382. /* Check if the current client is registered */
  383. /* Requires locking. */
  384. pthread_rwlock_rdlock(&self->rwlock);
  385. for (cl = self->client; cl; cl = cl->next) {
  386. if (cl->pid != client) {
  387. continue;
  388. }
  389. /* Found it */
  390. ret++;
  391. break;
  392. }
  393. /* Unlock here, potentially yielding */
  394. pthread_rwlock_unlock(&self->rwlock);
  395. }
  396. return ret;
  397. }
  398. /**
  399. * Construct a new GameModeClient for the given process ID
  400. *
  401. * This is deliberately OOM safe
  402. */
  403. static GameModeClient *game_mode_client_new(pid_t pid, char *executable)
  404. {
  405. GameModeClient c = {
  406. .executable = executable,
  407. .next = NULL,
  408. .pid = pid,
  409. };
  410. GameModeClient *ret = NULL;
  411. ret = calloc(1, sizeof(struct GameModeClient));
  412. if (!ret) {
  413. return NULL;
  414. }
  415. *ret = c;
  416. return ret;
  417. }
  418. /**
  419. * Free a client and the next element in the list.
  420. */
  421. static void game_mode_client_free(GameModeClient *client)
  422. {
  423. if (!client) {
  424. return;
  425. }
  426. if (client->next) {
  427. game_mode_client_free(client->next);
  428. }
  429. if (client->executable) {
  430. free(client->executable);
  431. }
  432. free(client);
  433. }
  434. /**
  435. * We continuously run until told otherwise.
  436. */
  437. static void *game_mode_context_reaper(void *userdata)
  438. {
  439. /* Stack, not allocated, won't disappear. */
  440. GameModeContext *self = userdata;
  441. long reaper_interval = 0.0f;
  442. config_get_reaper_thread_frequency(self->config, &reaper_interval);
  443. struct timespec ts = { 0, 0 };
  444. ts.tv_sec = time(NULL) + reaper_interval;
  445. while (self->reaper.running) {
  446. /* Wait for condition */
  447. pthread_mutex_lock(&self->reaper.mutex);
  448. pthread_cond_timedwait(&self->reaper.condition, &self->reaper.mutex, &ts);
  449. pthread_mutex_unlock(&self->reaper.mutex);
  450. /* Highly possible the main thread woke us up to exit */
  451. if (!self->reaper.running) {
  452. return NULL;
  453. }
  454. /* Expire remaining entries */
  455. game_mode_context_auto_expire(self);
  456. ts.tv_sec = time(NULL) + reaper_interval;
  457. }
  458. return NULL;
  459. }
  460. GameModeContext *game_mode_context_instance()
  461. {
  462. return &instance;
  463. }
  464. GameModeConfig *game_mode_config_from_context(const GameModeContext *context)
  465. {
  466. return context ? context->config : NULL;
  467. }
  468. /**
  469. * Attempt to resolve the exe for wine-preloader.
  470. * This function is used if game_mode_context_find_exe() identified the
  471. * process as wine-preloader. Returns NULL when resolve fails.
  472. */
  473. static char *game_mode_resolve_wine_preloader(pid_t pid)
  474. {
  475. char buffer[PATH_MAX];
  476. char *proc_path = NULL, *wine_exe = NULL, *wineprefix = NULL;
  477. /* Open the directory, we are potentially reading multiple files from it */
  478. procfd_t proc_fd = game_mode_open_proc(pid);
  479. if (proc_fd == INVALID_PROCFD)
  480. goto fail_proc;
  481. /* Open the command line */
  482. int fd = openat(proc_fd, "cmdline", O_RDONLY | O_CLOEXEC);
  483. if (fd != -1) {
  484. FILE *stream = fdopen(fd, "r");
  485. if (stream) {
  486. char *argv = NULL;
  487. size_t args = 0;
  488. int argc = 0;
  489. while (!wine_exe && (argc++ < 2) && (getdelim(&argv, &args, 0, stream) != -1)) {
  490. /* If we see the wine loader here, we have to use the next argument */
  491. if (strtail(argv, "/wine") || strtail(argv, "/wine64"))
  492. continue;
  493. free(wine_exe); // just in case
  494. /* Check presence of the drive letter, we assume that below */
  495. wine_exe = args > 2 && argv[1] == ':' ? strndup(argv, args) : NULL;
  496. }
  497. free(argv);
  498. fclose(stream);
  499. } else
  500. close(fd);
  501. }
  502. /* Did we get wine exe from cmdline? */
  503. if (wine_exe)
  504. LOG_MSG("Detected wine exe for client %d [%s].\n", pid, wine_exe);
  505. else
  506. goto fail_cmdline;
  507. /* Open the process environment and find the WINEPREFIX */
  508. errno = 0;
  509. if (!(wineprefix = game_mode_lookup_proc_env(proc_fd, "WINEPREFIX"))) {
  510. /* Lookup user home instead only if there was no error */
  511. char *home = NULL;
  512. if (errno == 0)
  513. home = game_mode_lookup_user_home();
  514. /* Append "/.wine" if we found the user home */
  515. if (home)
  516. wineprefix = safe_snprintf(buffer, "%s/.wine", home);
  517. /* Cleanup and check result */
  518. free(home);
  519. if (!wineprefix)
  520. goto fail_env;
  521. }
  522. /* Wine prefix was detected, log this for diagnostics */
  523. LOG_MSG("Detected wine prefix for client %d: '%s'\n", pid, wineprefix);
  524. /* Convert Windows to Unix path separators */
  525. char *ix = wine_exe;
  526. while (ix != NULL)
  527. (ix = strchr(ix, '\\')) && (*ix++ = '/');
  528. /* Convert the drive letter to lcase because wine handles it this way in the prefix */
  529. wine_exe[0] = (char)tolower(wine_exe[0]);
  530. /* Convert relative wine exe path to full unix path */
  531. char *wine_path = buffered_snprintf(buffer, "%s/dosdevices/%s", wineprefix, wine_exe);
  532. free(wine_exe);
  533. wine_exe = wine_path ? realpath(wine_path, NULL) : NULL;
  534. /* Fine? Successo? Fortuna! */
  535. if (wine_exe)
  536. LOG_MSG("Successfully mapped wine client %d [%s].\n", pid, wine_exe);
  537. else
  538. goto fail;
  539. error_cleanup:
  540. game_mode_close_proc(proc_fd);
  541. free(wineprefix);
  542. free(proc_path);
  543. return wine_exe;
  544. fail:
  545. LOG_ERROR("Unable to find wine executable for client %d: %s\n", pid, strerror(errno));
  546. goto error_cleanup;
  547. fail_cmdline:
  548. LOG_ERROR("Wine loader has no accepted cmdline for client %d yet, deferring.\n", pid);
  549. goto error_cleanup;
  550. fail_env:
  551. LOG_ERROR("Failed to access process environment in '%s': %s\n", proc_path, strerror(errno));
  552. goto error_cleanup;
  553. fail_proc:
  554. LOG_ERROR("Failed to access process data in '%s': %s\n", proc_path, strerror(errno));
  555. goto error_cleanup;
  556. }
  557. /**
  558. * Attempt to locate the exe for the process.
  559. * We might run into issues if the process is running under an odd umask.
  560. */
  561. static char *game_mode_context_find_exe(pid_t pid)
  562. {
  563. char buffer[PATH_MAX];
  564. char *proc_path = NULL, *wine_exe = NULL;
  565. if (!(proc_path = buffered_snprintf(buffer, "/proc/%d/exe", pid)))
  566. goto fail;
  567. /* Allocate the realpath if possible */
  568. char *exe = realpath(proc_path, NULL);
  569. if (!exe)
  570. goto fail;
  571. /* Detect if the process is a wine loader process */
  572. if (strtail(exe, "/wine-preloader") || strtail(exe, "/wine64-preloader")) {
  573. LOG_MSG("Detected wine preloader for client %d [%s].\n", pid, exe);
  574. goto wine_preloader;
  575. }
  576. if (strtail(exe, "/wine") || strtail(exe, "/wine64")) {
  577. LOG_MSG("Detected wine loader for client %d [%s].\n", pid, exe);
  578. goto wine_preloader;
  579. }
  580. return exe;
  581. wine_preloader:
  582. wine_exe = game_mode_resolve_wine_preloader(pid);
  583. if (wine_exe) {
  584. free(exe);
  585. exe = wine_exe;
  586. return exe;
  587. }
  588. /* We have to ignore this because the wine process is in some sort
  589. * of respawn mode
  590. */
  591. free(exe);
  592. fail:
  593. if (errno != 0) // otherwise a proper message was logged before
  594. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  595. return NULL;
  596. }