gamemode.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. /*
  2. Copyright (c) 2017-2019, 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 "config.h"
  29. #include "daemon_config.h"
  30. #include "dbus_messaging.h"
  31. #include "external-helper.h"
  32. #include "governors-query.h"
  33. #include "helpers.h"
  34. #include "logging.h"
  35. #include <pthread.h>
  36. #include <signal.h>
  37. #include <stdatomic.h>
  38. #include <systemd/sd-daemon.h>
  39. /**
  40. * The GameModeClient encapsulates the remote connection, providing a list
  41. * form to contain the pid and credentials.
  42. */
  43. typedef struct GameModeClient {
  44. pid_t pid; /**< Process ID */
  45. struct GameModeClient *next; /**<Next client in the list */
  46. char *executable; /**<Process executable */
  47. } GameModeClient;
  48. struct GameModeContext {
  49. pthread_rwlock_t rwlock; /**<Guard access to the client list */
  50. _Atomic int refcount; /**<Allow cycling the game mode */
  51. GameModeClient *client; /**<Pointer to first client */
  52. GameModeConfig *config; /**<Pointer to config object */
  53. char initial_cpu_mode[64]; /**<Only updates when we can */
  54. struct GameModeGPUInfo *stored_gpu; /**<Stored GPU info for the current GPU */
  55. struct GameModeGPUInfo *target_gpu; /**<Target GPU info for the current GPU */
  56. /* Reaper control */
  57. struct {
  58. pthread_t thread;
  59. bool running;
  60. pthread_mutex_t mutex;
  61. pthread_cond_t condition;
  62. } reaper;
  63. };
  64. static GameModeContext instance = { 0 };
  65. /* Maximum number of concurrent processes we'll sanely support */
  66. #define MAX_GAMES 256
  67. /**
  68. * Protect against signals
  69. */
  70. static volatile bool had_context_init = false;
  71. static GameModeClient *game_mode_client_new(pid_t pid, char *exe);
  72. static void game_mode_client_free(GameModeClient *client);
  73. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client);
  74. static int game_mode_context_num_clients(GameModeContext *self);
  75. static void *game_mode_context_reaper(void *userdata);
  76. static void game_mode_context_enter(GameModeContext *self);
  77. static void game_mode_context_leave(GameModeContext *self);
  78. static char *game_mode_context_find_exe(pid_t pid);
  79. static void game_mode_execute_scripts(char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX], int timeout);
  80. void game_mode_context_init(GameModeContext *self)
  81. {
  82. if (had_context_init) {
  83. LOG_ERROR("Context already initialised\n");
  84. return;
  85. }
  86. had_context_init = true;
  87. self->refcount = ATOMIC_VAR_INIT(0);
  88. /* clear the initial string */
  89. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  90. /* Initialise the config */
  91. self->config = config_create();
  92. config_init(self->config);
  93. /* Initialise the current GPU info */
  94. game_mode_initialise_gpu(self->config, &self->stored_gpu);
  95. game_mode_initialise_gpu(self->config, &self->target_gpu);
  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 gpu object */
  126. game_mode_free_gpu(&self->stored_gpu);
  127. game_mode_free_gpu(&self->target_gpu);
  128. /* Destroy the config object */
  129. config_destroy(self->config);
  130. pthread_rwlock_destroy(&self->rwlock);
  131. }
  132. /**
  133. * Pivot into game mode.
  134. *
  135. * This is only possible after game_mode_context_init has made a GameModeContext
  136. * usable, and should always be followed by a game_mode_context_leave.
  137. */
  138. static void game_mode_context_enter(GameModeContext *self)
  139. {
  140. LOG_MSG("Entering Game Mode...\n");
  141. sd_notifyf(0, "STATUS=%sGameMode is now active.%s\n", "\x1B[1;32m", "\x1B[0m");
  142. /* Read the initial governor state so we can revert it correctly */
  143. const char *initial_state = get_gov_state();
  144. if (initial_state) {
  145. /* store the initial cpu governor mode */
  146. strncpy(self->initial_cpu_mode, initial_state, sizeof(self->initial_cpu_mode) - 1);
  147. self->initial_cpu_mode[sizeof(self->initial_cpu_mode) - 1] = '\0';
  148. LOG_MSG("governor was initially set to [%s]\n", initial_state);
  149. /* Choose the desired governor */
  150. char desired[CONFIG_VALUE_MAX] = { 0 };
  151. config_get_desired_governor(self->config, desired);
  152. const char *desiredGov = desired[0] != '\0' ? desired : "performance";
  153. const char *const exec_args[] = {
  154. "/usr/bin/pkexec", LIBEXECDIR "/cpugovctl", "set", desiredGov, NULL,
  155. };
  156. LOG_MSG("Requesting update of governor policy to %s\n", desiredGov);
  157. if (run_external_process(exec_args, NULL, -1) != 0) {
  158. LOG_ERROR("Failed to update cpu governor policy\n");
  159. /* if the set fails, clear the initial mode so we don't try and reset it back and fail
  160. * again, presumably */
  161. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  162. }
  163. }
  164. /* Inhibit the screensaver */
  165. if (config_get_inhibit_screensaver(self->config))
  166. game_mode_inhibit_screensaver(true);
  167. /* Apply GPU optimisations by first getting the current values, and then setting the target */
  168. game_mode_get_gpu(self->stored_gpu);
  169. game_mode_apply_gpu(self->target_gpu);
  170. /* Run custom scripts last - ensures the above are applied first and these scripts can react to
  171. * them if needed */
  172. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  173. memset(scripts, 0, sizeof(scripts));
  174. config_get_gamemode_start_scripts(self->config, scripts);
  175. long timeout = config_get_script_timeout(self->config);
  176. game_mode_execute_scripts(scripts, (int)timeout);
  177. }
  178. /**
  179. * Pivot out of game mode.
  180. *
  181. * Should only be called after both init and game_mode_context_enter have
  182. * been performed.
  183. */
  184. static void game_mode_context_leave(GameModeContext *self)
  185. {
  186. LOG_MSG("Leaving Game Mode...\n");
  187. sd_notifyf(0, "STATUS=%sGameMode is currently deactivated.%s\n", "\x1B[1;36m", "\x1B[0m");
  188. /* Remove GPU optimisations */
  189. game_mode_apply_gpu(self->stored_gpu);
  190. /* UnInhibit the screensaver */
  191. if (config_get_inhibit_screensaver(self->config))
  192. game_mode_inhibit_screensaver(false);
  193. /* Reset the governer state back to initial */
  194. if (self->initial_cpu_mode[0] != '\0') {
  195. /* Choose the governor to reset to, using the config to override */
  196. char defaultgov[CONFIG_VALUE_MAX] = { 0 };
  197. config_get_default_governor(self->config, defaultgov);
  198. const char *gov_mode = defaultgov[0] != '\0' ? defaultgov : self->initial_cpu_mode;
  199. const char *const exec_args[] = {
  200. "/usr/bin/pkexec", LIBEXECDIR "/cpugovctl", "set", gov_mode, NULL,
  201. };
  202. LOG_MSG("Requesting update of governor policy to %s\n", gov_mode);
  203. if (run_external_process(exec_args, NULL, -1) != 0) {
  204. LOG_ERROR("Failed to update cpu governor policy\n");
  205. }
  206. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  207. }
  208. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  209. memset(scripts, 0, sizeof(scripts));
  210. config_get_gamemode_end_scripts(self->config, scripts);
  211. long timeout = config_get_script_timeout(self->config);
  212. game_mode_execute_scripts(scripts, (int)timeout);
  213. }
  214. /**
  215. * Automatically expire all dead processes
  216. *
  217. * This has to take special care to ensure thread safety and ensuring that our
  218. * pointer is never cached incorrectly.
  219. */
  220. static void game_mode_context_auto_expire(GameModeContext *self)
  221. {
  222. bool removing = true;
  223. while (removing) {
  224. pthread_rwlock_rdlock(&self->rwlock);
  225. removing = false;
  226. /* Each time we hit an expired game, start the loop back */
  227. for (GameModeClient *client = self->client; client; client = client->next) {
  228. if (kill(client->pid, 0) != 0) {
  229. LOG_MSG("Removing expired game [%i]...\n", client->pid);
  230. pthread_rwlock_unlock(&self->rwlock);
  231. game_mode_context_unregister(self, client->pid, client->pid);
  232. removing = true;
  233. break;
  234. }
  235. }
  236. if (!removing) {
  237. pthread_rwlock_unlock(&self->rwlock);
  238. break;
  239. }
  240. if (game_mode_context_num_clients(self) == 0)
  241. LOG_MSG("Properly cleaned up all expired games.\n");
  242. }
  243. }
  244. /**
  245. * Determine if the client is already known to the context
  246. */
  247. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client)
  248. {
  249. const GameModeClient *found = NULL;
  250. pthread_rwlock_rdlock(&self->rwlock);
  251. /* Walk all clients and find a matching pid */
  252. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  253. if (cl->pid == client) {
  254. found = cl;
  255. break;
  256. }
  257. }
  258. pthread_rwlock_unlock(&self->rwlock);
  259. return found;
  260. }
  261. /**
  262. * Helper to grab the current number of clients we know about
  263. */
  264. static int game_mode_context_num_clients(GameModeContext *self)
  265. {
  266. return atomic_load(&self->refcount);
  267. }
  268. int game_mode_context_register(GameModeContext *self, pid_t client, pid_t requester)
  269. {
  270. errno = 0;
  271. /* Construct a new client if we can */
  272. GameModeClient *cl = NULL;
  273. char *executable = NULL;
  274. /* Check our requester config first */
  275. if (requester != client) {
  276. /* Lookup the executable first */
  277. executable = game_mode_context_find_exe(requester);
  278. if (!executable) {
  279. return -1;
  280. }
  281. /* Check our blacklist and whitelist */
  282. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  283. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  284. free(executable);
  285. return -2;
  286. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  287. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  288. free(executable);
  289. return -2;
  290. }
  291. } else if (config_get_require_supervisor(self->config)) {
  292. LOG_ERROR("Direct request made but require_supervisor was set, rejecting request!\n");
  293. return -2;
  294. }
  295. /* Cap the total number of active clients */
  296. if (game_mode_context_num_clients(self) + 1 > MAX_GAMES) {
  297. LOG_ERROR("Max games (%d) reached, not registering %d\n", MAX_GAMES, client);
  298. goto error_cleanup;
  299. }
  300. /* Check the PID first to spare a potentially expensive lookup for the exe */
  301. pthread_rwlock_rdlock(&self->rwlock); // ensure our pointer is sane
  302. const GameModeClient *existing = game_mode_context_has_client(self, client);
  303. if (existing) {
  304. LOG_HINTED(ERROR,
  305. "Addition requested for already known client %d [%s].\n",
  306. " -- This may happen due to using exec or shell wrappers. You may want to\n"
  307. " -- blacklist this client so GameMode can see its final name here.\n",
  308. existing->pid,
  309. existing->executable);
  310. pthread_rwlock_unlock(&self->rwlock);
  311. goto error_cleanup;
  312. }
  313. pthread_rwlock_unlock(&self->rwlock);
  314. /* Lookup the executable first */
  315. executable = game_mode_context_find_exe(client);
  316. if (!executable)
  317. goto error_cleanup;
  318. /* Check our blacklist and whitelist */
  319. if (!config_get_client_whitelisted(self->config, executable)) {
  320. LOG_MSG("Client [%s] was rejected (not in whitelist)\n", executable);
  321. goto error_cleanup;
  322. } else if (config_get_client_blacklisted(self->config, executable)) {
  323. LOG_MSG("Client [%s] was rejected (in blacklist)\n", executable);
  324. goto error_cleanup;
  325. }
  326. /* From now on we depend on the client, initialize it */
  327. cl = game_mode_client_new(client, executable);
  328. if (cl)
  329. executable = NULL; // ownership has been delegated
  330. else
  331. goto error_cleanup;
  332. /* Begin a write lock now to insert our new client at list start */
  333. pthread_rwlock_wrlock(&self->rwlock);
  334. LOG_MSG("Adding game: %d [%s]\n", client, cl->executable);
  335. /* Update the list */
  336. cl->next = self->client;
  337. self->client = cl;
  338. pthread_rwlock_unlock(&self->rwlock);
  339. /* First add, init */
  340. if (atomic_fetch_add_explicit(&self->refcount, 1, memory_order_seq_cst) == 0) {
  341. game_mode_context_enter(self);
  342. }
  343. /* Apply scheduler policies */
  344. game_mode_apply_renice(self, client);
  345. game_mode_apply_scheduling(self, client);
  346. /* Apply io priorities */
  347. game_mode_apply_ioprio(self, client);
  348. return 0;
  349. error_cleanup:
  350. if (errno != 0)
  351. LOG_ERROR("Failed to register client [%d]: %s\n", client, strerror(errno));
  352. free(executable);
  353. game_mode_client_free(cl);
  354. return -1;
  355. }
  356. int game_mode_context_unregister(GameModeContext *self, pid_t client, pid_t requester)
  357. {
  358. GameModeClient *cl = NULL;
  359. GameModeClient *prev = NULL;
  360. bool found = false;
  361. /* Check our requester config first */
  362. if (requester != client) {
  363. /* Lookup the executable first */
  364. char *executable = game_mode_context_find_exe(requester);
  365. if (!executable) {
  366. return -1;
  367. }
  368. /* Check our blacklist and whitelist */
  369. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  370. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  371. free(executable);
  372. return -2;
  373. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  374. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  375. free(executable);
  376. return -2;
  377. }
  378. free(executable);
  379. } else if (config_get_require_supervisor(self->config)) {
  380. LOG_ERROR("Direct request made but require_supervisor was set, rejecting request!\n");
  381. return -2;
  382. }
  383. /* Requires locking. */
  384. pthread_rwlock_wrlock(&self->rwlock);
  385. for (prev = cl = self->client; cl; cl = cl->next) {
  386. if (cl->pid != client) {
  387. prev = cl;
  388. continue;
  389. }
  390. LOG_MSG("Removing game: %d [%s]\n", client, cl->executable);
  391. /* Found it */
  392. found = true;
  393. prev->next = cl->next;
  394. if (cl == self->client) {
  395. self->client = cl->next;
  396. }
  397. cl->next = NULL;
  398. game_mode_client_free(cl);
  399. break;
  400. }
  401. /* Unlock here, potentially yielding */
  402. pthread_rwlock_unlock(&self->rwlock);
  403. if (!found) {
  404. LOG_HINTED(
  405. ERROR,
  406. "Removal requested for unknown process [%d].\n",
  407. " -- The parent process probably forked and tries to unregister from the wrong\n"
  408. " -- process now. We cannot work around this. This message will likely be paired\n"
  409. " -- with a nearby 'Removing expired game' which means we cleaned up properly\n"
  410. " -- (we will log this event). This hint will be displayed only once.\n",
  411. client);
  412. return -1;
  413. }
  414. /* When we hit bottom then end the game mode */
  415. if (atomic_fetch_sub_explicit(&self->refcount, 1, memory_order_seq_cst) == 1) {
  416. game_mode_context_leave(self);
  417. }
  418. return 0;
  419. }
  420. int game_mode_context_query_status(GameModeContext *self, pid_t client, pid_t requester)
  421. {
  422. GameModeClient *cl = NULL;
  423. int ret = 0;
  424. /* First check the requester settings if appropriate */
  425. if (client != requester) {
  426. char *executable = game_mode_context_find_exe(requester);
  427. if (!executable) {
  428. return -1;
  429. }
  430. /* Check our blacklist and whitelist */
  431. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  432. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  433. free(executable);
  434. return -2;
  435. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  436. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  437. free(executable);
  438. return -2;
  439. }
  440. free(executable);
  441. }
  442. /*
  443. * Check the current refcount on gamemode, this equates to whether gamemode is active or not,
  444. * see game_mode_context_register and game_mode_context_unregister
  445. */
  446. if (atomic_load_explicit(&self->refcount, memory_order_seq_cst)) {
  447. ret++;
  448. /* Check if the current client is registered */
  449. /* Requires locking. */
  450. pthread_rwlock_rdlock(&self->rwlock);
  451. for (cl = self->client; cl; cl = cl->next) {
  452. if (cl->pid != client) {
  453. continue;
  454. }
  455. /* Found it */
  456. ret++;
  457. break;
  458. }
  459. /* Unlock here, potentially yielding */
  460. pthread_rwlock_unlock(&self->rwlock);
  461. }
  462. return ret;
  463. }
  464. /**
  465. * Construct a new GameModeClient for the given process ID
  466. *
  467. * This is deliberately OOM safe
  468. */
  469. static GameModeClient *game_mode_client_new(pid_t pid, char *executable)
  470. {
  471. GameModeClient c = {
  472. .executable = executable,
  473. .next = NULL,
  474. .pid = pid,
  475. };
  476. GameModeClient *ret = NULL;
  477. ret = calloc(1, sizeof(struct GameModeClient));
  478. if (!ret) {
  479. return NULL;
  480. }
  481. *ret = c;
  482. return ret;
  483. }
  484. /**
  485. * Free a client and the next element in the list.
  486. */
  487. static void game_mode_client_free(GameModeClient *client)
  488. {
  489. if (!client) {
  490. return;
  491. }
  492. if (client->next) {
  493. game_mode_client_free(client->next);
  494. }
  495. if (client->executable) {
  496. free(client->executable);
  497. }
  498. free(client);
  499. }
  500. /**
  501. * We continuously run until told otherwise.
  502. */
  503. static void *game_mode_context_reaper(void *userdata)
  504. {
  505. /* Stack, not allocated, won't disappear. */
  506. GameModeContext *self = userdata;
  507. long reaper_interval = config_get_reaper_frequency(self->config);
  508. struct timespec ts = { 0, 0 };
  509. ts.tv_sec = time(NULL) + reaper_interval;
  510. while (self->reaper.running) {
  511. /* Wait for condition */
  512. pthread_mutex_lock(&self->reaper.mutex);
  513. pthread_cond_timedwait(&self->reaper.condition, &self->reaper.mutex, &ts);
  514. pthread_mutex_unlock(&self->reaper.mutex);
  515. /* Highly possible the main thread woke us up to exit */
  516. if (!self->reaper.running) {
  517. return NULL;
  518. }
  519. /* Expire remaining entries */
  520. game_mode_context_auto_expire(self);
  521. ts.tv_sec = time(NULL) + reaper_interval;
  522. }
  523. return NULL;
  524. }
  525. GameModeContext *game_mode_context_instance(void)
  526. {
  527. return &instance;
  528. }
  529. GameModeConfig *game_mode_config_from_context(const GameModeContext *context)
  530. {
  531. return context ? context->config : NULL;
  532. }
  533. /**
  534. * Attempt to locate the exe for the process.
  535. * We might run into issues if the process is running under an odd umask.
  536. */
  537. static char *game_mode_context_find_exe(pid_t pid)
  538. {
  539. char buffer[PATH_MAX];
  540. char *proc_path = NULL, *wine_exe = NULL;
  541. if (!(proc_path = buffered_snprintf(buffer, "/proc/%d/exe", pid)))
  542. goto fail;
  543. /* Allocate the realpath if possible */
  544. char *exe = realpath(proc_path, NULL);
  545. if (!exe)
  546. goto fail;
  547. /* Detect if the process is a wine loader process */
  548. if (game_mode_detect_wine_preloader(exe)) {
  549. LOG_MSG("Detected wine preloader for client %d [%s].\n", pid, exe);
  550. goto wine_preloader;
  551. }
  552. if (game_mode_detect_wine_loader(exe)) {
  553. LOG_MSG("Detected wine loader for client %d [%s].\n", pid, exe);
  554. goto wine_preloader;
  555. }
  556. return exe;
  557. wine_preloader:
  558. wine_exe = game_mode_resolve_wine_preloader(pid);
  559. if (wine_exe) {
  560. free(exe);
  561. exe = wine_exe;
  562. return exe;
  563. }
  564. /* We have to ignore this because the wine process is in some sort
  565. * of respawn mode
  566. */
  567. free(exe);
  568. fail:
  569. if (errno != 0) // otherwise a proper message was logged before
  570. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  571. return NULL;
  572. }
  573. /* Executes a set of scripts */
  574. static void game_mode_execute_scripts(char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX], int timeout)
  575. {
  576. unsigned int i = 0;
  577. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  578. LOG_MSG("Executing script [%s]\n", scripts[i]);
  579. int err;
  580. const char *args[] = { "/bin/sh", "-c", scripts[i], NULL };
  581. if ((err = run_external_process(args, NULL, timeout)) != 0) {
  582. /* Log the failure, but this is not fatal */
  583. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  584. }
  585. i++;
  586. }
  587. }