platform-nix.c 22 KB

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