platform-nix.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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. bool os_get_emulation_status(void)
  339. {
  340. return false;
  341. }
  342. #endif
  343. bool os_file_exists(const char *path)
  344. {
  345. return access(path, F_OK) == 0;
  346. }
  347. size_t os_get_abs_path(const char *path, char *abspath, size_t size)
  348. {
  349. size_t min_size = size < PATH_MAX ? size : PATH_MAX;
  350. char newpath[PATH_MAX];
  351. int ret;
  352. if (!abspath)
  353. return 0;
  354. if (!realpath(path, newpath))
  355. return 0;
  356. ret = snprintf(abspath, min_size, "%s", newpath);
  357. return ret >= 0 ? ret : 0;
  358. }
  359. char *os_get_abs_path_ptr(const char *path)
  360. {
  361. char *ptr = bmalloc(512);
  362. if (!os_get_abs_path(path, ptr, 512)) {
  363. bfree(ptr);
  364. ptr = NULL;
  365. }
  366. return ptr;
  367. }
  368. struct os_dir {
  369. const char *path;
  370. DIR *dir;
  371. struct dirent *cur_dirent;
  372. struct os_dirent out;
  373. };
  374. os_dir_t *os_opendir(const char *path)
  375. {
  376. struct os_dir *dir;
  377. DIR *dir_val;
  378. dir_val = opendir(path);
  379. if (!dir_val)
  380. return NULL;
  381. dir = bzalloc(sizeof(struct os_dir));
  382. dir->dir = dir_val;
  383. dir->path = path;
  384. return dir;
  385. }
  386. static inline bool is_dir(const char *path)
  387. {
  388. struct stat stat_info;
  389. if (stat(path, &stat_info) == 0)
  390. return !!S_ISDIR(stat_info.st_mode);
  391. blog(LOG_DEBUG, "is_dir: stat for %s failed, errno: %d", path, errno);
  392. return false;
  393. }
  394. struct os_dirent *os_readdir(os_dir_t *dir)
  395. {
  396. struct dstr file_path = {0};
  397. if (!dir)
  398. return NULL;
  399. dir->cur_dirent = readdir(dir->dir);
  400. if (!dir->cur_dirent)
  401. return NULL;
  402. const size_t length = strlen(dir->cur_dirent->d_name);
  403. if (sizeof(dir->out.d_name) <= length)
  404. return NULL;
  405. memcpy(dir->out.d_name, dir->cur_dirent->d_name, length + 1);
  406. dstr_copy(&file_path, dir->path);
  407. dstr_cat(&file_path, "/");
  408. dstr_cat(&file_path, dir->out.d_name);
  409. dir->out.directory = is_dir(file_path.array);
  410. dstr_free(&file_path);
  411. return &dir->out;
  412. }
  413. void os_closedir(os_dir_t *dir)
  414. {
  415. if (dir) {
  416. closedir(dir->dir);
  417. bfree(dir);
  418. }
  419. }
  420. int64_t os_get_free_space(const char *path)
  421. {
  422. struct statvfs info;
  423. int64_t ret = (int64_t)statvfs(path, &info);
  424. if (ret == 0)
  425. ret = (int64_t)info.f_bsize * (int64_t)info.f_bfree;
  426. return ret;
  427. }
  428. struct posix_glob_info {
  429. struct os_glob_info base;
  430. glob_t gl;
  431. };
  432. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  433. {
  434. struct posix_glob_info pgi;
  435. int ret = glob(pattern, 0, NULL, &pgi.gl);
  436. if (ret == 0) {
  437. DARRAY(struct os_globent) list;
  438. da_init(list);
  439. for (size_t i = 0; i < pgi.gl.gl_pathc; i++) {
  440. struct os_globent ent = {0};
  441. ent.path = pgi.gl.gl_pathv[i];
  442. ent.directory = is_dir(ent.path);
  443. da_push_back(list, &ent);
  444. }
  445. pgi.base.gl_pathc = list.num;
  446. pgi.base.gl_pathv = list.array;
  447. *pglob = bmemdup(&pgi, sizeof(pgi));
  448. } else {
  449. *pglob = NULL;
  450. }
  451. UNUSED_PARAMETER(flags);
  452. return ret;
  453. }
  454. void os_globfree(os_glob_t *pglob)
  455. {
  456. if (pglob) {
  457. struct posix_glob_info *pgi = (struct posix_glob_info *)pglob;
  458. globfree(&pgi->gl);
  459. bfree(pgi->base.gl_pathv);
  460. bfree(pgi);
  461. }
  462. }
  463. int os_unlink(const char *path)
  464. {
  465. return unlink(path);
  466. }
  467. int os_rmdir(const char *path)
  468. {
  469. return rmdir(path);
  470. }
  471. int os_mkdir(const char *path)
  472. {
  473. if (mkdir(path, 0755) == 0)
  474. return MKDIR_SUCCESS;
  475. return (errno == EEXIST) ? MKDIR_EXISTS : MKDIR_ERROR;
  476. }
  477. int os_rename(const char *old_path, const char *new_path)
  478. {
  479. return rename(old_path, new_path);
  480. }
  481. int os_safe_replace(const char *target, const char *from, const char *backup)
  482. {
  483. if (backup && os_file_exists(target) && rename(target, backup) != 0)
  484. return -1;
  485. return rename(from, target);
  486. }
  487. #if !defined(__APPLE__)
  488. os_performance_token_t *os_request_high_performance(const char *reason)
  489. {
  490. UNUSED_PARAMETER(reason);
  491. return NULL;
  492. }
  493. void os_end_high_performance(os_performance_token_t *token)
  494. {
  495. UNUSED_PARAMETER(token);
  496. }
  497. #endif
  498. int os_copyfile(const char *file_path_in, const char *file_path_out)
  499. {
  500. FILE *file_out = NULL;
  501. FILE *file_in = NULL;
  502. uint8_t data[4096];
  503. int ret = -1;
  504. size_t size;
  505. if (os_file_exists(file_path_out))
  506. return -1;
  507. file_in = fopen(file_path_in, "rb");
  508. if (!file_in)
  509. return -1;
  510. file_out = fopen(file_path_out, "ab+");
  511. if (!file_out)
  512. goto error;
  513. do {
  514. size = fread(data, 1, sizeof(data), file_in);
  515. if (size)
  516. size = fwrite(data, 1, size, file_out);
  517. } while (size == sizeof(data));
  518. ret = feof(file_in) ? 0 : -1;
  519. error:
  520. if (file_out)
  521. fclose(file_out);
  522. fclose(file_in);
  523. return ret;
  524. }
  525. char *os_getcwd(char *path, size_t size)
  526. {
  527. return getcwd(path, size);
  528. }
  529. int os_chdir(const char *path)
  530. {
  531. return chdir(path);
  532. }
  533. #if !defined(__APPLE__)
  534. #if defined(GIO_FOUND)
  535. struct dbus_sleep_info;
  536. struct portal_inhibit_info;
  537. extern struct dbus_sleep_info *dbus_sleep_info_create(void);
  538. extern void dbus_inhibit_sleep(struct dbus_sleep_info *dbus, const char *sleep,
  539. bool active);
  540. extern void dbus_sleep_info_destroy(struct dbus_sleep_info *dbus);
  541. extern struct portal_inhibit_info *portal_inhibit_info_create(void);
  542. extern void portal_inhibit(struct portal_inhibit_info *portal,
  543. const char *reason, bool active);
  544. extern void portal_inhibit_info_destroy(struct portal_inhibit_info *portal);
  545. #endif
  546. struct os_inhibit_info {
  547. #if defined(GIO_FOUND)
  548. struct dbus_sleep_info *dbus;
  549. struct portal_inhibit_info *portal;
  550. #endif
  551. pthread_t screensaver_thread;
  552. os_event_t *stop_event;
  553. char *reason;
  554. posix_spawnattr_t attr;
  555. bool active;
  556. };
  557. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  558. {
  559. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  560. sigset_t set;
  561. #if defined(GIO_FOUND)
  562. info->portal = portal_inhibit_info_create();
  563. if (!info->portal)
  564. info->dbus = dbus_sleep_info_create();
  565. #endif
  566. os_event_init(&info->stop_event, OS_EVENT_TYPE_AUTO);
  567. posix_spawnattr_init(&info->attr);
  568. sigemptyset(&set);
  569. posix_spawnattr_setsigmask(&info->attr, &set);
  570. sigaddset(&set, SIGPIPE);
  571. posix_spawnattr_setsigdefault(&info->attr, &set);
  572. posix_spawnattr_setflags(&info->attr, POSIX_SPAWN_SETSIGDEF |
  573. POSIX_SPAWN_SETSIGMASK);
  574. info->reason = bstrdup(reason);
  575. return info;
  576. }
  577. extern char **environ;
  578. static void reset_screensaver(os_inhibit_t *info)
  579. {
  580. char *argv[3] = {(char *)"xdg-screensaver", (char *)"reset", NULL};
  581. pid_t pid;
  582. int err = posix_spawnp(&pid, "xdg-screensaver", NULL, &info->attr, argv,
  583. environ);
  584. if (err == 0) {
  585. int status;
  586. while (waitpid(pid, &status, 0) == -1)
  587. ;
  588. } else {
  589. blog(LOG_WARNING, "Failed to create xdg-screensaver: %d", err);
  590. }
  591. }
  592. static void *screensaver_thread(void *param)
  593. {
  594. os_inhibit_t *info = param;
  595. while (os_event_timedwait(info->stop_event, 30000) == ETIMEDOUT)
  596. reset_screensaver(info);
  597. return NULL;
  598. }
  599. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  600. {
  601. int ret;
  602. if (!info)
  603. return false;
  604. if (info->active == active)
  605. return false;
  606. #if defined(GIO_FOUND)
  607. if (info->portal)
  608. portal_inhibit(info->portal, info->reason, active);
  609. if (info->dbus)
  610. dbus_inhibit_sleep(info->dbus, info->reason, active);
  611. #endif
  612. if (!info->stop_event)
  613. return true;
  614. if (active) {
  615. ret = pthread_create(&info->screensaver_thread, NULL,
  616. &screensaver_thread, info);
  617. if (ret < 0) {
  618. blog(LOG_ERROR, "Failed to create screensaver "
  619. "inhibitor thread");
  620. return false;
  621. }
  622. } else {
  623. os_event_signal(info->stop_event);
  624. pthread_join(info->screensaver_thread, NULL);
  625. }
  626. info->active = active;
  627. return true;
  628. }
  629. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  630. {
  631. if (info) {
  632. os_inhibit_sleep_set_active(info, false);
  633. #if defined(GIO_FOUND)
  634. portal_inhibit_info_destroy(info->portal);
  635. dbus_sleep_info_destroy(info->dbus);
  636. #endif
  637. os_event_destroy(info->stop_event);
  638. posix_spawnattr_destroy(&info->attr);
  639. bfree(info->reason);
  640. bfree(info);
  641. }
  642. }
  643. #endif
  644. void os_breakpoint()
  645. {
  646. raise(SIGTRAP);
  647. }
  648. #ifndef __APPLE__
  649. static int physical_cores = 0;
  650. static int logical_cores = 0;
  651. static bool core_count_initialized = false;
  652. static void os_get_cores_internal(void)
  653. {
  654. if (core_count_initialized)
  655. return;
  656. core_count_initialized = true;
  657. logical_cores = sysconf(_SC_NPROCESSORS_ONLN);
  658. #if defined(__linux__)
  659. int physical_id = -1;
  660. int last_physical_id = -1;
  661. int core_count = 0;
  662. char *line = NULL;
  663. size_t linecap = 0;
  664. FILE *fp;
  665. struct dstr proc_phys_id;
  666. struct dstr proc_phys_ids;
  667. fp = fopen("/proc/cpuinfo", "r");
  668. if (!fp)
  669. return;
  670. dstr_init(&proc_phys_id);
  671. dstr_init(&proc_phys_ids);
  672. while (getline(&line, &linecap, fp) != -1) {
  673. if (!strncmp(line, "physical id", 11)) {
  674. char *start = strchr(line, ':');
  675. if (!start || *(++start) == '\0')
  676. continue;
  677. physical_id = atoi(start);
  678. dstr_free(&proc_phys_id);
  679. dstr_init(&proc_phys_id);
  680. dstr_catf(&proc_phys_id, "%d", physical_id);
  681. }
  682. if (!strncmp(line, "cpu cores", 9)) {
  683. char *start = strchr(line, ':');
  684. if (!start || *(++start) == '\0')
  685. continue;
  686. if (dstr_is_empty(&proc_phys_ids) ||
  687. (!dstr_is_empty(&proc_phys_ids) &&
  688. !dstr_find(&proc_phys_ids, proc_phys_id.array))) {
  689. dstr_cat_dstr(&proc_phys_ids, &proc_phys_id);
  690. dstr_cat(&proc_phys_ids, " ");
  691. core_count += atoi(start);
  692. }
  693. }
  694. if (*line == '\n' && physical_id != last_physical_id) {
  695. last_physical_id = physical_id;
  696. }
  697. }
  698. if (core_count == 0)
  699. physical_cores = logical_cores;
  700. else
  701. physical_cores = core_count;
  702. fclose(fp);
  703. dstr_free(&proc_phys_ids);
  704. dstr_free(&proc_phys_id);
  705. free(line);
  706. #elif defined(__FreeBSD__)
  707. char *text = os_quick_read_utf8_file("/var/run/dmesg.boot");
  708. char *core_count = text;
  709. int packages = 0;
  710. int cores = 0;
  711. struct dstr proc_packages;
  712. struct dstr proc_cores;
  713. dstr_init(&proc_packages);
  714. dstr_init(&proc_cores);
  715. if (!text || !*text) {
  716. physical_cores = logical_cores;
  717. return;
  718. }
  719. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  720. if (!core_count)
  721. goto FreeBSD_cores_cleanup;
  722. core_count++;
  723. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  724. if (!core_count)
  725. goto FreeBSD_cores_cleanup;
  726. core_count = strstr(core_count, ": ");
  727. core_count += 2;
  728. size_t len = strcspn(core_count, " ");
  729. dstr_ncopy(&proc_packages, core_count, len);
  730. core_count = strstr(core_count, "package(s) x ");
  731. if (!core_count)
  732. goto FreeBSD_cores_cleanup;
  733. core_count += 13;
  734. len = strcspn(core_count, " ");
  735. dstr_ncopy(&proc_cores, core_count, len);
  736. FreeBSD_cores_cleanup:
  737. if (!dstr_is_empty(&proc_packages))
  738. packages = atoi(proc_packages.array);
  739. if (!dstr_is_empty(&proc_cores))
  740. cores = atoi(proc_cores.array);
  741. if (packages == 0)
  742. physical_cores = logical_cores;
  743. else if (cores == 0)
  744. physical_cores = packages;
  745. else
  746. physical_cores = packages * cores;
  747. dstr_free(&proc_cores);
  748. dstr_free(&proc_packages);
  749. bfree(text);
  750. #else
  751. physical_cores = logical_cores;
  752. #endif
  753. }
  754. int os_get_physical_cores(void)
  755. {
  756. if (!core_count_initialized)
  757. os_get_cores_internal();
  758. return physical_cores;
  759. }
  760. int os_get_logical_cores(void)
  761. {
  762. if (!core_count_initialized)
  763. os_get_cores_internal();
  764. return logical_cores;
  765. }
  766. #ifdef __FreeBSD__
  767. uint64_t os_get_sys_free_size(void)
  768. {
  769. uint64_t mem_free = 0;
  770. size_t length = sizeof(mem_free);
  771. if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &length, NULL,
  772. 0) < 0)
  773. return 0;
  774. return mem_free;
  775. }
  776. static inline bool os_get_proc_memory_usage_internal(struct kinfo_proc *kinfo)
  777. {
  778. int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
  779. size_t length = sizeof(*kinfo);
  780. if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), kinfo, &length, NULL, 0) <
  781. 0)
  782. return false;
  783. return true;
  784. }
  785. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  786. {
  787. struct kinfo_proc kinfo;
  788. if (!os_get_proc_memory_usage_internal(&kinfo))
  789. return false;
  790. usage->resident_size =
  791. (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  792. usage->virtual_size = (uint64_t)kinfo.ki_size;
  793. return true;
  794. }
  795. uint64_t os_get_proc_resident_size(void)
  796. {
  797. struct kinfo_proc kinfo;
  798. if (!os_get_proc_memory_usage_internal(&kinfo))
  799. return 0;
  800. return (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  801. }
  802. uint64_t os_get_proc_virtual_size(void)
  803. {
  804. struct kinfo_proc kinfo;
  805. if (!os_get_proc_memory_usage_internal(&kinfo))
  806. return 0;
  807. return (uint64_t)kinfo.ki_size;
  808. }
  809. #else
  810. uint64_t os_get_sys_free_size(void)
  811. {
  812. return 0;
  813. }
  814. typedef struct {
  815. unsigned long virtual_size;
  816. unsigned long resident_size;
  817. unsigned long share_pages;
  818. unsigned long text;
  819. unsigned long library;
  820. unsigned long data;
  821. unsigned long dirty_pages;
  822. } statm_t;
  823. static inline bool os_get_proc_memory_usage_internal(statm_t *statm)
  824. {
  825. const char *statm_path = "/proc/self/statm";
  826. FILE *f = fopen(statm_path, "r");
  827. if (!f)
  828. return false;
  829. if (fscanf(f, "%lu %lu %lu %lu %lu %lu %lu", &statm->virtual_size,
  830. &statm->resident_size, &statm->share_pages, &statm->text,
  831. &statm->library, &statm->data, &statm->dirty_pages) != 7) {
  832. fclose(f);
  833. return false;
  834. }
  835. fclose(f);
  836. return true;
  837. }
  838. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  839. {
  840. statm_t statm = {};
  841. if (!os_get_proc_memory_usage_internal(&statm))
  842. return false;
  843. usage->resident_size =
  844. (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE);
  845. usage->virtual_size = statm.virtual_size;
  846. return true;
  847. }
  848. uint64_t os_get_proc_resident_size(void)
  849. {
  850. statm_t statm = {};
  851. if (!os_get_proc_memory_usage_internal(&statm))
  852. return 0;
  853. return (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE);
  854. }
  855. uint64_t os_get_proc_virtual_size(void)
  856. {
  857. statm_t statm = {};
  858. if (!os_get_proc_memory_usage_internal(&statm))
  859. return 0;
  860. return (uint64_t)statm.virtual_size;
  861. }
  862. #endif
  863. #endif
  864. uint64_t os_get_free_disk_space(const char *dir)
  865. {
  866. struct statvfs info;
  867. if (statvfs(dir, &info) != 0)
  868. return 0;
  869. return (uint64_t)info.f_frsize * (uint64_t)info.f_bavail;
  870. }