platform-nix.c 24 KB

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