platform-nix.c 21 KB

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