platform-nix.c 24 KB

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