1
0

platform-nix.c 24 KB

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