platform-nix.c 22 KB

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