platform-nix.c 21 KB

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