1
0

platform-nix.c 23 KB

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