platform-nix.c 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. /*
  2. * Copyright (c) 2023 Lain Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include "obsconfig.h"
  17. #if !defined(__APPLE__)
  18. #define _GNU_SOURCE
  19. #include <link.h>
  20. #include <stdlib.h>
  21. #endif
  22. #include <stdio.h>
  23. #include <errno.h>
  24. #include <sys/types.h>
  25. #include <sys/stat.h>
  26. #include <sys/statvfs.h>
  27. #include <dirent.h>
  28. #include <stdlib.h>
  29. #include <limits.h>
  30. #include <dlfcn.h>
  31. #include <unistd.h>
  32. #include <glob.h>
  33. #include <time.h>
  34. #include <signal.h>
  35. #include <uuid/uuid.h>
  36. #if !defined(__APPLE__)
  37. #include <sys/times.h>
  38. #include <sys/wait.h>
  39. #include <libgen.h>
  40. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  41. #include <sys/param.h>
  42. #include <sys/queue.h>
  43. #include <sys/socket.h>
  44. #include <sys/sysctl.h>
  45. #include <sys/user.h>
  46. #include <unistd.h>
  47. #if defined(__FreeBSD__)
  48. #include <libprocstat.h>
  49. #endif
  50. #else
  51. #include <sys/resource.h>
  52. #endif
  53. #if !defined(__OpenBSD__)
  54. #include <sys/sysinfo.h>
  55. #endif
  56. #include <spawn.h>
  57. #endif
  58. #include "darray.h"
  59. #include "dstr.h"
  60. #include "platform.h"
  61. #include "threading.h"
  62. void *os_dlopen(const char *path)
  63. {
  64. struct dstr dylib_name;
  65. if (!path)
  66. return NULL;
  67. dstr_init_copy(&dylib_name, path);
  68. #ifdef __APPLE__
  69. if (!dstr_find(&dylib_name, ".framework") && !dstr_find(&dylib_name, ".plugin") &&
  70. !dstr_find(&dylib_name, ".dylib") && !dstr_find(&dylib_name, ".so"))
  71. #else
  72. if (!dstr_find(&dylib_name, ".so"))
  73. #endif
  74. dstr_cat(&dylib_name, ".so");
  75. #ifdef __APPLE__
  76. int dlopen_flags = RTLD_LAZY | RTLD_FIRST;
  77. if (dstr_find(&dylib_name, "Python")) {
  78. dlopen_flags = dlopen_flags | RTLD_GLOBAL;
  79. } else {
  80. dlopen_flags = dlopen_flags | RTLD_LOCAL;
  81. }
  82. void *res = dlopen(dylib_name.array, dlopen_flags);
  83. #else
  84. void *res = dlopen(dylib_name.array, RTLD_LAZY);
  85. #endif
  86. if (!res)
  87. blog(LOG_ERROR, "os_dlopen(%s->%s): %s\n", path, dylib_name.array, dlerror());
  88. dstr_free(&dylib_name);
  89. return res;
  90. }
  91. void *os_dlsym(void *module, const char *func)
  92. {
  93. return dlsym(module, func);
  94. }
  95. void os_dlclose(void *module)
  96. {
  97. if (module)
  98. dlclose(module);
  99. }
  100. #if !defined(__APPLE__)
  101. int module_has_qt5_check(const char *path)
  102. {
  103. void *mod = os_dlopen(path);
  104. if (mod == NULL) {
  105. return 1;
  106. }
  107. struct link_map *list = NULL;
  108. if (dlinfo(mod, RTLD_DI_LINKMAP, &list) == 0) {
  109. for (struct link_map *ptr = list; ptr; ptr = ptr->l_next) {
  110. if (strstr(ptr->l_name, "libQt5") != NULL) {
  111. return 0;
  112. }
  113. }
  114. }
  115. return 1;
  116. }
  117. bool has_qt5_dependency(const char *path)
  118. {
  119. pid_t pid = fork();
  120. if (pid == 0) {
  121. base_set_log_handler(NULL, NULL);
  122. _exit(module_has_qt5_check(path));
  123. }
  124. if (pid < 0) {
  125. return false;
  126. }
  127. int status;
  128. if (waitpid(pid, &status, 0) < 0) {
  129. return false;
  130. }
  131. return WIFEXITED(status) && WEXITSTATUS(status) == 0;
  132. }
  133. #endif
  134. void get_plugin_info(const char *path, bool *is_obs_plugin, bool *can_load)
  135. {
  136. *is_obs_plugin = true;
  137. *can_load = true;
  138. #if !defined(__APPLE__)
  139. *can_load = !has_qt5_dependency(path);
  140. #endif
  141. UNUSED_PARAMETER(path);
  142. }
  143. bool os_is_obs_plugin(const char *path)
  144. {
  145. UNUSED_PARAMETER(path);
  146. /* not necessary on this platform */
  147. return true;
  148. }
  149. #if !defined(__APPLE__)
  150. struct os_cpu_usage_info {
  151. clock_t last_cpu_time, last_sys_time, last_user_time;
  152. int core_count;
  153. };
  154. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  155. {
  156. struct os_cpu_usage_info *info = bmalloc(sizeof(*info));
  157. struct tms time_sample;
  158. info->last_cpu_time = times(&time_sample);
  159. info->last_sys_time = time_sample.tms_stime;
  160. info->last_user_time = time_sample.tms_utime;
  161. info->core_count = sysconf(_SC_NPROCESSORS_ONLN);
  162. return info;
  163. }
  164. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  165. {
  166. struct tms time_sample;
  167. clock_t cur_cpu_time;
  168. double percent;
  169. if (!info)
  170. return 0.0;
  171. cur_cpu_time = times(&time_sample);
  172. if (cur_cpu_time <= info->last_cpu_time || time_sample.tms_stime < info->last_sys_time ||
  173. time_sample.tms_utime < info->last_user_time)
  174. return 0.0;
  175. percent =
  176. (double)(time_sample.tms_stime - info->last_sys_time + (time_sample.tms_utime - info->last_user_time));
  177. percent /= (double)(cur_cpu_time - info->last_cpu_time);
  178. percent /= (double)info->core_count;
  179. info->last_cpu_time = cur_cpu_time;
  180. info->last_sys_time = time_sample.tms_stime;
  181. info->last_user_time = time_sample.tms_utime;
  182. return percent * 100.0;
  183. }
  184. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  185. {
  186. if (info)
  187. bfree(info);
  188. }
  189. #endif
  190. bool os_sleepto_ns(uint64_t time_target)
  191. {
  192. uint64_t current = os_gettime_ns();
  193. if (time_target < current)
  194. return false;
  195. time_target -= current;
  196. struct timespec req, remain;
  197. memset(&req, 0, sizeof(req));
  198. memset(&remain, 0, sizeof(remain));
  199. req.tv_sec = time_target / 1000000000;
  200. req.tv_nsec = time_target % 1000000000;
  201. while (nanosleep(&req, &remain)) {
  202. req = remain;
  203. memset(&remain, 0, sizeof(remain));
  204. }
  205. return true;
  206. }
  207. bool os_sleepto_ns_fast(uint64_t time_target)
  208. {
  209. uint64_t current = os_gettime_ns();
  210. if (time_target < current)
  211. return false;
  212. do {
  213. uint64_t remain_us = (time_target - current + 999) / 1000;
  214. useconds_t us = remain_us >= 1000000 ? 999999 : remain_us;
  215. usleep(us);
  216. current = os_gettime_ns();
  217. } while (time_target > current);
  218. return true;
  219. }
  220. void os_sleep_ms(uint32_t duration)
  221. {
  222. usleep(duration * 1000);
  223. }
  224. #if !defined(__APPLE__)
  225. uint64_t os_gettime_ns(void)
  226. {
  227. struct timespec ts;
  228. clock_gettime(CLOCK_MONOTONIC, &ts);
  229. return ((uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec);
  230. }
  231. /* should return $HOME/.config/[name] as default */
  232. int os_get_config_path(char *dst, size_t size, const char *name)
  233. {
  234. char *xdg_ptr = getenv("XDG_CONFIG_HOME");
  235. // If XDG_CONFIG_HOME is unset,
  236. // we use the default $HOME/.config/[name] instead
  237. if (xdg_ptr == NULL) {
  238. char *home_ptr = getenv("HOME");
  239. if (home_ptr == NULL)
  240. bcrash("Could not get $HOME\n");
  241. if (!name || !*name) {
  242. return snprintf(dst, size, "%s/.config", home_ptr);
  243. } else {
  244. return snprintf(dst, size, "%s/.config/%s", home_ptr, name);
  245. }
  246. } else {
  247. if (!name || !*name)
  248. return snprintf(dst, size, "%s", xdg_ptr);
  249. else
  250. return snprintf(dst, size, "%s/%s", xdg_ptr, name);
  251. }
  252. }
  253. /* should return $HOME/.config/[name] as default */
  254. char *os_get_config_path_ptr(const char *name)
  255. {
  256. struct dstr path;
  257. char *xdg_ptr = getenv("XDG_CONFIG_HOME");
  258. /* If XDG_CONFIG_HOME is unset,
  259. * we use the default $HOME/.config/[name] instead */
  260. if (xdg_ptr == NULL) {
  261. char *home_ptr = getenv("HOME");
  262. if (home_ptr == NULL)
  263. bcrash("Could not get $HOME\n");
  264. dstr_init_copy(&path, home_ptr);
  265. dstr_cat(&path, "/.config/");
  266. dstr_cat(&path, name);
  267. } else {
  268. dstr_init_copy(&path, xdg_ptr);
  269. dstr_cat(&path, "/");
  270. dstr_cat(&path, name);
  271. }
  272. return path.array;
  273. }
  274. int os_get_program_data_path(char *dst, size_t size, const char *name)
  275. {
  276. return snprintf(dst, size, "/usr/local/share/%s", !!name ? name : "");
  277. }
  278. char *os_get_program_data_path_ptr(const char *name)
  279. {
  280. size_t len = snprintf(NULL, 0, "/usr/local/share/%s", !!name ? name : "");
  281. char *str = bmalloc(len + 1);
  282. snprintf(str, len + 1, "/usr/local/share/%s", !!name ? name : "");
  283. str[len] = 0;
  284. return str;
  285. }
  286. #if defined(__OpenBSD__)
  287. // a bit modified version of https://stackoverflow.com/a/31495527
  288. ssize_t os_openbsd_get_executable_path(char *epath)
  289. {
  290. int mib[4];
  291. char **argv;
  292. size_t len;
  293. const char *comm;
  294. int ok = 0;
  295. mib[0] = CTL_KERN;
  296. mib[1] = KERN_PROC_ARGS;
  297. mib[2] = getpid();
  298. mib[3] = KERN_PROC_ARGV;
  299. if (sysctl(mib, 4, NULL, &len, NULL, 0) < 0)
  300. abort();
  301. if (!(argv = malloc(len)))
  302. abort();
  303. if (sysctl(mib, 4, argv, &len, NULL, 0) < 0)
  304. abort();
  305. comm = argv[0];
  306. if (*comm == '/' || *comm == '.') {
  307. if (realpath(comm, epath))
  308. ok = 1;
  309. } else {
  310. char *sp;
  311. char *xpath = strdup(getenv("PATH"));
  312. char *path = strtok_r(xpath, ":", &sp);
  313. struct stat st;
  314. if (!xpath)
  315. abort();
  316. while (path) {
  317. snprintf(epath, PATH_MAX, "%s/%s", path, comm);
  318. if (!stat(epath, &st) && (st.st_mode & S_IXUSR)) {
  319. ok = 1;
  320. break;
  321. }
  322. path = strtok_r(NULL, ":", &sp);
  323. }
  324. free(xpath);
  325. }
  326. free(argv);
  327. return ok ? (ssize_t)strlen(epath) : -1;
  328. }
  329. #endif
  330. char *os_get_executable_path_ptr(const char *name)
  331. {
  332. char exe[PATH_MAX];
  333. #if defined(__FreeBSD__) || defined(__DragonFly__)
  334. int sysctlname[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
  335. size_t pathlen = PATH_MAX;
  336. ssize_t count;
  337. if (sysctl(sysctlname, nitems(sysctlname), exe, &pathlen, NULL, 0) == -1) {
  338. blog(LOG_ERROR, "sysctl(KERN_PROC_PATHNAME) failed, errno %d", errno);
  339. return NULL;
  340. }
  341. count = pathlen;
  342. #elif defined(__OpenBSD__)
  343. ssize_t count = os_openbsd_get_executable_path(exe);
  344. #else
  345. ssize_t count = readlink("/proc/self/exe", exe, PATH_MAX - 1);
  346. if (count >= 0) {
  347. exe[count] = '\0';
  348. }
  349. #endif
  350. const char *path_out = NULL;
  351. struct dstr path;
  352. if (count == -1) {
  353. return NULL;
  354. }
  355. path_out = dirname(exe);
  356. if (!path_out) {
  357. return NULL;
  358. }
  359. dstr_init_copy(&path, path_out);
  360. dstr_cat(&path, "/");
  361. if (name && *name) {
  362. dstr_cat(&path, name);
  363. }
  364. return path.array;
  365. }
  366. bool os_get_emulation_status(void)
  367. {
  368. return false;
  369. }
  370. #endif
  371. bool os_file_exists(const char *path)
  372. {
  373. return access(path, F_OK) == 0;
  374. }
  375. size_t os_get_abs_path(const char *path, char *abspath, size_t size)
  376. {
  377. size_t min_size = size < PATH_MAX ? size : PATH_MAX;
  378. char newpath[PATH_MAX];
  379. int ret;
  380. if (!abspath)
  381. return 0;
  382. if (!realpath(path, newpath))
  383. return 0;
  384. ret = snprintf(abspath, min_size, "%s", newpath);
  385. return ret >= 0 ? ret : 0;
  386. }
  387. char *os_get_abs_path_ptr(const char *path)
  388. {
  389. char *ptr = bmalloc(512);
  390. if (!os_get_abs_path(path, ptr, 512)) {
  391. bfree(ptr);
  392. ptr = NULL;
  393. }
  394. return ptr;
  395. }
  396. struct os_dir {
  397. const char *path;
  398. DIR *dir;
  399. struct dirent *cur_dirent;
  400. struct os_dirent out;
  401. };
  402. os_dir_t *os_opendir(const char *path)
  403. {
  404. struct os_dir *dir;
  405. DIR *dir_val;
  406. dir_val = opendir(path);
  407. if (!dir_val)
  408. return NULL;
  409. dir = bzalloc(sizeof(struct os_dir));
  410. dir->dir = dir_val;
  411. dir->path = path;
  412. return dir;
  413. }
  414. static inline bool is_dir(const char *path)
  415. {
  416. struct stat stat_info;
  417. if (stat(path, &stat_info) == 0)
  418. return !!S_ISDIR(stat_info.st_mode);
  419. blog(LOG_DEBUG, "is_dir: stat for %s failed, errno: %d", path, errno);
  420. return false;
  421. }
  422. struct os_dirent *os_readdir(os_dir_t *dir)
  423. {
  424. struct dstr file_path = {0};
  425. if (!dir)
  426. return NULL;
  427. dir->cur_dirent = readdir(dir->dir);
  428. if (!dir->cur_dirent)
  429. return NULL;
  430. const size_t length = strlen(dir->cur_dirent->d_name);
  431. if (sizeof(dir->out.d_name) <= length)
  432. return NULL;
  433. memcpy(dir->out.d_name, dir->cur_dirent->d_name, length + 1);
  434. dstr_copy(&file_path, dir->path);
  435. dstr_cat(&file_path, "/");
  436. dstr_cat(&file_path, dir->out.d_name);
  437. dir->out.directory = is_dir(file_path.array);
  438. dstr_free(&file_path);
  439. return &dir->out;
  440. }
  441. void os_closedir(os_dir_t *dir)
  442. {
  443. if (dir) {
  444. closedir(dir->dir);
  445. bfree(dir);
  446. }
  447. }
  448. #ifndef __APPLE__
  449. int64_t os_get_free_space(const char *path)
  450. {
  451. struct statvfs info;
  452. int64_t ret = (int64_t)statvfs(path, &info);
  453. if (ret == 0)
  454. ret = (int64_t)info.f_bsize * (int64_t)info.f_bfree;
  455. return ret;
  456. }
  457. #endif
  458. struct posix_glob_info {
  459. struct os_glob_info base;
  460. glob_t gl;
  461. };
  462. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  463. {
  464. struct posix_glob_info pgi;
  465. int ret = glob(pattern, 0, NULL, &pgi.gl);
  466. if (ret == 0) {
  467. DARRAY(struct os_globent) list;
  468. da_init(list);
  469. for (size_t i = 0; i < pgi.gl.gl_pathc; i++) {
  470. struct os_globent ent = {0};
  471. ent.path = pgi.gl.gl_pathv[i];
  472. ent.directory = is_dir(ent.path);
  473. da_push_back(list, &ent);
  474. }
  475. pgi.base.gl_pathc = list.num;
  476. pgi.base.gl_pathv = list.array;
  477. *pglob = bmemdup(&pgi, sizeof(pgi));
  478. } else {
  479. *pglob = NULL;
  480. }
  481. UNUSED_PARAMETER(flags);
  482. return ret;
  483. }
  484. void os_globfree(os_glob_t *pglob)
  485. {
  486. if (pglob) {
  487. struct posix_glob_info *pgi = (struct posix_glob_info *)pglob;
  488. globfree(&pgi->gl);
  489. bfree(pgi->base.gl_pathv);
  490. bfree(pgi);
  491. }
  492. }
  493. int os_unlink(const char *path)
  494. {
  495. return unlink(path);
  496. }
  497. int os_rmdir(const char *path)
  498. {
  499. return rmdir(path);
  500. }
  501. int os_mkdir(const char *path)
  502. {
  503. if (mkdir(path, 0755) == 0)
  504. return MKDIR_SUCCESS;
  505. return (errno == EEXIST) ? MKDIR_EXISTS : MKDIR_ERROR;
  506. }
  507. int os_rename(const char *old_path, const char *new_path)
  508. {
  509. return rename(old_path, new_path);
  510. }
  511. int os_safe_replace(const char *target, const char *from, const char *backup)
  512. {
  513. if (backup && os_file_exists(target) && rename(target, backup) != 0)
  514. return -1;
  515. return rename(from, target);
  516. }
  517. #if !defined(__APPLE__)
  518. os_performance_token_t *os_request_high_performance(const char *reason)
  519. {
  520. UNUSED_PARAMETER(reason);
  521. return NULL;
  522. }
  523. void os_end_high_performance(os_performance_token_t *token)
  524. {
  525. UNUSED_PARAMETER(token);
  526. }
  527. #endif
  528. int os_copyfile(const char *file_path_in, const char *file_path_out)
  529. {
  530. FILE *file_out = NULL;
  531. FILE *file_in = NULL;
  532. uint8_t data[4096];
  533. int ret = -1;
  534. size_t size;
  535. if (os_file_exists(file_path_out))
  536. return -1;
  537. file_in = fopen(file_path_in, "rb");
  538. if (!file_in)
  539. return -1;
  540. file_out = fopen(file_path_out, "ab+");
  541. if (!file_out)
  542. goto error;
  543. do {
  544. size = fread(data, 1, sizeof(data), file_in);
  545. if (size)
  546. size = fwrite(data, 1, size, file_out);
  547. } while (size == sizeof(data));
  548. ret = feof(file_in) ? 0 : -1;
  549. error:
  550. if (file_out)
  551. fclose(file_out);
  552. fclose(file_in);
  553. return ret;
  554. }
  555. char *os_getcwd(char *path, size_t size)
  556. {
  557. return getcwd(path, size);
  558. }
  559. int os_chdir(const char *path)
  560. {
  561. return chdir(path);
  562. }
  563. #if !defined(__APPLE__)
  564. #if defined(GIO_FOUND)
  565. struct dbus_sleep_info;
  566. struct portal_inhibit_info;
  567. extern struct dbus_sleep_info *dbus_sleep_info_create(void);
  568. extern void dbus_inhibit_sleep(struct dbus_sleep_info *dbus, const char *sleep, bool active);
  569. extern void dbus_sleep_info_destroy(struct dbus_sleep_info *dbus);
  570. extern struct portal_inhibit_info *portal_inhibit_info_create(void);
  571. extern void portal_inhibit(struct portal_inhibit_info *portal, const char *reason, bool active);
  572. extern void portal_inhibit_info_destroy(struct portal_inhibit_info *portal);
  573. #endif
  574. struct os_inhibit_info {
  575. #if defined(GIO_FOUND)
  576. struct dbus_sleep_info *dbus;
  577. struct portal_inhibit_info *portal;
  578. #endif
  579. pthread_t screensaver_thread;
  580. os_event_t *stop_event;
  581. char *reason;
  582. posix_spawnattr_t attr;
  583. bool active;
  584. };
  585. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  586. {
  587. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  588. sigset_t set;
  589. #if defined(GIO_FOUND)
  590. info->portal = portal_inhibit_info_create();
  591. if (!info->portal) {
  592. /* In a Flatpak, only the portal can be used for inhibition. */
  593. if (access("/.flatpak-info", F_OK) == 0) {
  594. bfree(info);
  595. return NULL;
  596. }
  597. info->dbus = dbus_sleep_info_create();
  598. }
  599. if (info->portal || info->dbus) {
  600. info->reason = bstrdup(reason);
  601. return info;
  602. }
  603. #endif
  604. os_event_init(&info->stop_event, OS_EVENT_TYPE_AUTO);
  605. posix_spawnattr_init(&info->attr);
  606. sigemptyset(&set);
  607. posix_spawnattr_setsigmask(&info->attr, &set);
  608. sigaddset(&set, SIGPIPE);
  609. posix_spawnattr_setsigdefault(&info->attr, &set);
  610. posix_spawnattr_setflags(&info->attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK);
  611. info->reason = bstrdup(reason);
  612. return info;
  613. }
  614. extern char **environ;
  615. static void reset_screensaver(os_inhibit_t *info)
  616. {
  617. char *argv[3] = {(char *)"xdg-screensaver", (char *)"reset", NULL};
  618. pid_t pid;
  619. int err = posix_spawnp(&pid, "xdg-screensaver", NULL, &info->attr, argv, environ);
  620. if (err == 0) {
  621. int status;
  622. while (waitpid(pid, &status, 0) == -1)
  623. ;
  624. } else {
  625. blog(LOG_WARNING, "Failed to create xdg-screensaver: %d", err);
  626. }
  627. }
  628. static void *screensaver_thread(void *param)
  629. {
  630. os_inhibit_t *info = param;
  631. while (os_event_timedwait(info->stop_event, 30000) == ETIMEDOUT)
  632. reset_screensaver(info);
  633. return NULL;
  634. }
  635. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  636. {
  637. int ret;
  638. if (!info)
  639. return false;
  640. if (info->active == active)
  641. return false;
  642. #if defined(GIO_FOUND)
  643. if (info->portal)
  644. portal_inhibit(info->portal, info->reason, active);
  645. if (info->dbus)
  646. dbus_inhibit_sleep(info->dbus, info->reason, active);
  647. if (info->portal || info->dbus) {
  648. info->active = active;
  649. return true;
  650. }
  651. #endif
  652. if (!info->stop_event)
  653. return true;
  654. if (active) {
  655. ret = pthread_create(&info->screensaver_thread, NULL, &screensaver_thread, info);
  656. if (ret < 0) {
  657. blog(LOG_ERROR, "Failed to create screensaver "
  658. "inhibitor thread");
  659. return false;
  660. }
  661. } else {
  662. os_event_signal(info->stop_event);
  663. pthread_join(info->screensaver_thread, NULL);
  664. }
  665. info->active = active;
  666. return true;
  667. }
  668. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  669. {
  670. if (info) {
  671. os_inhibit_sleep_set_active(info, false);
  672. #if defined(GIO_FOUND)
  673. if (info->portal) {
  674. portal_inhibit_info_destroy(info->portal);
  675. } else if (info->dbus) {
  676. dbus_sleep_info_destroy(info->dbus);
  677. } else {
  678. os_event_destroy(info->stop_event);
  679. posix_spawnattr_destroy(&info->attr);
  680. }
  681. #else
  682. os_event_destroy(info->stop_event);
  683. posix_spawnattr_destroy(&info->attr);
  684. #endif
  685. bfree(info->reason);
  686. bfree(info);
  687. }
  688. }
  689. #endif
  690. void os_breakpoint()
  691. {
  692. raise(SIGTRAP);
  693. }
  694. #ifndef __APPLE__
  695. static int physical_cores = 0;
  696. static int logical_cores = 0;
  697. static bool core_count_initialized = false;
  698. static void os_get_cores_internal(void)
  699. {
  700. if (core_count_initialized)
  701. return;
  702. core_count_initialized = true;
  703. logical_cores = sysconf(_SC_NPROCESSORS_ONLN);
  704. #if defined(__linux__)
  705. int physical_id = -1;
  706. int last_physical_id = -1;
  707. int core_count = 0;
  708. char *line = NULL;
  709. size_t linecap = 0;
  710. FILE *fp;
  711. struct dstr proc_phys_id;
  712. struct dstr proc_phys_ids;
  713. fp = fopen("/proc/cpuinfo", "r");
  714. if (!fp)
  715. return;
  716. dstr_init(&proc_phys_id);
  717. dstr_init(&proc_phys_ids);
  718. while (getline(&line, &linecap, fp) != -1) {
  719. if (!strncmp(line, "physical id", 11)) {
  720. char *start = strchr(line, ':');
  721. if (!start || *(++start) == '\0')
  722. continue;
  723. physical_id = atoi(start);
  724. dstr_free(&proc_phys_id);
  725. dstr_init(&proc_phys_id);
  726. dstr_catf(&proc_phys_id, "%d", physical_id);
  727. }
  728. if (!strncmp(line, "cpu cores", 9)) {
  729. char *start = strchr(line, ':');
  730. if (!start || *(++start) == '\0')
  731. continue;
  732. if (dstr_is_empty(&proc_phys_ids) ||
  733. (!dstr_is_empty(&proc_phys_ids) && !dstr_find(&proc_phys_ids, proc_phys_id.array))) {
  734. dstr_cat_dstr(&proc_phys_ids, &proc_phys_id);
  735. dstr_cat(&proc_phys_ids, " ");
  736. core_count += atoi(start);
  737. }
  738. }
  739. if (*line == '\n' && physical_id != last_physical_id) {
  740. last_physical_id = physical_id;
  741. }
  742. }
  743. if (core_count == 0)
  744. physical_cores = logical_cores;
  745. else
  746. physical_cores = core_count;
  747. fclose(fp);
  748. dstr_free(&proc_phys_ids);
  749. dstr_free(&proc_phys_id);
  750. free(line);
  751. #elif defined(__FreeBSD__)
  752. char *text = os_quick_read_utf8_file("/var/run/dmesg.boot");
  753. char *core_count = text;
  754. int packages = 0;
  755. int cores = 0;
  756. struct dstr proc_packages;
  757. struct dstr proc_cores;
  758. dstr_init(&proc_packages);
  759. dstr_init(&proc_cores);
  760. if (!text || !*text) {
  761. physical_cores = logical_cores;
  762. return;
  763. }
  764. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  765. if (!core_count)
  766. goto FreeBSD_cores_cleanup;
  767. core_count++;
  768. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  769. if (!core_count)
  770. goto FreeBSD_cores_cleanup;
  771. core_count = strstr(core_count, ": ");
  772. core_count += 2;
  773. size_t len = strcspn(core_count, " ");
  774. dstr_ncopy(&proc_packages, core_count, len);
  775. core_count = strstr(core_count, "package(s) x ");
  776. if (!core_count)
  777. goto FreeBSD_cores_cleanup;
  778. core_count += 13;
  779. len = strcspn(core_count, " ");
  780. dstr_ncopy(&proc_cores, core_count, len);
  781. FreeBSD_cores_cleanup:
  782. if (!dstr_is_empty(&proc_packages))
  783. packages = atoi(proc_packages.array);
  784. if (!dstr_is_empty(&proc_cores))
  785. cores = atoi(proc_cores.array);
  786. if (packages == 0)
  787. physical_cores = logical_cores;
  788. else if (cores == 0)
  789. physical_cores = packages;
  790. else
  791. physical_cores = packages * cores;
  792. dstr_free(&proc_cores);
  793. dstr_free(&proc_packages);
  794. bfree(text);
  795. #else
  796. physical_cores = logical_cores;
  797. #endif
  798. }
  799. int os_get_physical_cores(void)
  800. {
  801. if (!core_count_initialized)
  802. os_get_cores_internal();
  803. return physical_cores;
  804. }
  805. int os_get_logical_cores(void)
  806. {
  807. if (!core_count_initialized)
  808. os_get_cores_internal();
  809. return logical_cores;
  810. }
  811. #ifdef __FreeBSD__
  812. uint64_t os_get_sys_free_size(void)
  813. {
  814. uint64_t mem_free = 0;
  815. size_t length = sizeof(mem_free);
  816. if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &length, NULL, 0) < 0)
  817. return 0;
  818. return mem_free;
  819. }
  820. static inline bool os_get_proc_memory_usage_internal(struct kinfo_proc *kinfo)
  821. {
  822. int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
  823. size_t length = sizeof(*kinfo);
  824. if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), kinfo, &length, NULL, 0) < 0)
  825. return false;
  826. return true;
  827. }
  828. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  829. {
  830. struct kinfo_proc kinfo;
  831. if (!os_get_proc_memory_usage_internal(&kinfo))
  832. return false;
  833. usage->resident_size = (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  834. usage->virtual_size = (uint64_t)kinfo.ki_size;
  835. return true;
  836. }
  837. uint64_t os_get_proc_resident_size(void)
  838. {
  839. struct kinfo_proc kinfo;
  840. if (!os_get_proc_memory_usage_internal(&kinfo))
  841. return 0;
  842. return (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  843. }
  844. uint64_t os_get_proc_virtual_size(void)
  845. {
  846. struct kinfo_proc kinfo;
  847. if (!os_get_proc_memory_usage_internal(&kinfo))
  848. return 0;
  849. return (uint64_t)kinfo.ki_size;
  850. }
  851. #else
  852. typedef struct {
  853. unsigned long virtual_size;
  854. unsigned long resident_size;
  855. unsigned long share_pages;
  856. unsigned long text;
  857. unsigned long library;
  858. unsigned long data;
  859. unsigned long dirty_pages;
  860. } statm_t;
  861. static inline bool os_get_proc_memory_usage_internal(statm_t *statm)
  862. {
  863. const char *statm_path = "/proc/self/statm";
  864. FILE *f = fopen(statm_path, "r");
  865. if (!f)
  866. return false;
  867. if (fscanf(f, "%lu %lu %lu %lu %lu %lu %lu", &statm->virtual_size, &statm->resident_size, &statm->share_pages,
  868. &statm->text, &statm->library, &statm->data, &statm->dirty_pages) != 7) {
  869. fclose(f);
  870. return false;
  871. }
  872. fclose(f);
  873. return true;
  874. }
  875. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  876. {
  877. statm_t statm = {};
  878. if (!os_get_proc_memory_usage_internal(&statm))
  879. return false;
  880. usage->resident_size = (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE);
  881. usage->virtual_size = statm.virtual_size;
  882. return true;
  883. }
  884. uint64_t os_get_proc_resident_size(void)
  885. {
  886. statm_t statm = {};
  887. if (!os_get_proc_memory_usage_internal(&statm))
  888. return 0;
  889. return (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE);
  890. }
  891. uint64_t os_get_proc_virtual_size(void)
  892. {
  893. statm_t statm = {};
  894. if (!os_get_proc_memory_usage_internal(&statm))
  895. return 0;
  896. return (uint64_t)statm.virtual_size;
  897. }
  898. #endif
  899. static uint64_t total_memory = 0;
  900. static bool total_memory_initialized = false;
  901. static void os_get_sys_total_size_internal()
  902. {
  903. total_memory_initialized = true;
  904. #ifndef __OpenBSD__
  905. struct sysinfo info;
  906. if (sysinfo(&info) < 0)
  907. return;
  908. total_memory = (uint64_t)info.totalram * info.mem_unit;
  909. #endif
  910. }
  911. uint64_t os_get_sys_total_size(void)
  912. {
  913. if (!total_memory_initialized)
  914. os_get_sys_total_size_internal();
  915. return total_memory;
  916. }
  917. uint64_t os_get_sys_free_size(void)
  918. {
  919. uint64_t free_memory = 0;
  920. #ifndef __OpenBSD__
  921. struct sysinfo info;
  922. if (sysinfo(&info) < 0)
  923. return 0;
  924. free_memory = ((uint64_t)info.freeram + (uint64_t)info.bufferram) * info.mem_unit;
  925. #endif
  926. return free_memory;
  927. }
  928. #endif
  929. #ifndef __APPLE__
  930. uint64_t os_get_free_disk_space(const char *dir)
  931. {
  932. struct statvfs info;
  933. if (statvfs(dir, &info) != 0)
  934. return 0;
  935. return (uint64_t)info.f_frsize * (uint64_t)info.f_bavail;
  936. }
  937. #endif
  938. char *os_generate_uuid(void)
  939. {
  940. uuid_t uuid;
  941. // 36 char UUID + NULL
  942. char *out = bmalloc(37);
  943. uuid_generate(uuid);
  944. uuid_unparse_lower(uuid, out);
  945. return out;
  946. }