platform-nix.c 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  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. #ifndef __APPLE__
  478. int64_t os_get_free_space(const char *path)
  479. {
  480. struct statvfs info;
  481. int64_t ret = (int64_t)statvfs(path, &info);
  482. if (ret == 0)
  483. ret = (int64_t)info.f_bsize * (int64_t)info.f_bfree;
  484. return ret;
  485. }
  486. #endif
  487. struct posix_glob_info {
  488. struct os_glob_info base;
  489. glob_t gl;
  490. };
  491. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  492. {
  493. struct posix_glob_info pgi;
  494. int ret = glob(pattern, 0, NULL, &pgi.gl);
  495. if (ret == 0) {
  496. DARRAY(struct os_globent) list;
  497. da_init(list);
  498. for (size_t i = 0; i < pgi.gl.gl_pathc; i++) {
  499. struct os_globent ent = {0};
  500. ent.path = pgi.gl.gl_pathv[i];
  501. ent.directory = is_dir(ent.path);
  502. da_push_back(list, &ent);
  503. }
  504. pgi.base.gl_pathc = list.num;
  505. pgi.base.gl_pathv = list.array;
  506. *pglob = bmemdup(&pgi, sizeof(pgi));
  507. } else {
  508. *pglob = NULL;
  509. }
  510. UNUSED_PARAMETER(flags);
  511. return ret;
  512. }
  513. void os_globfree(os_glob_t *pglob)
  514. {
  515. if (pglob) {
  516. struct posix_glob_info *pgi = (struct posix_glob_info *)pglob;
  517. globfree(&pgi->gl);
  518. bfree(pgi->base.gl_pathv);
  519. bfree(pgi);
  520. }
  521. }
  522. int os_unlink(const char *path)
  523. {
  524. return unlink(path);
  525. }
  526. int os_rmdir(const char *path)
  527. {
  528. return rmdir(path);
  529. }
  530. int os_mkdir(const char *path)
  531. {
  532. if (mkdir(path, 0755) == 0)
  533. return MKDIR_SUCCESS;
  534. return (errno == EEXIST) ? MKDIR_EXISTS : MKDIR_ERROR;
  535. }
  536. int os_rename(const char *old_path, const char *new_path)
  537. {
  538. return rename(old_path, new_path);
  539. }
  540. int os_safe_replace(const char *target, const char *from, const char *backup)
  541. {
  542. if (backup && os_file_exists(target) && rename(target, backup) != 0)
  543. return -1;
  544. return rename(from, target);
  545. }
  546. #if !defined(__APPLE__)
  547. os_performance_token_t *os_request_high_performance(const char *reason)
  548. {
  549. UNUSED_PARAMETER(reason);
  550. return NULL;
  551. }
  552. void os_end_high_performance(os_performance_token_t *token)
  553. {
  554. UNUSED_PARAMETER(token);
  555. }
  556. #endif
  557. int os_copyfile(const char *file_path_in, const char *file_path_out)
  558. {
  559. FILE *file_out = NULL;
  560. FILE *file_in = NULL;
  561. uint8_t data[4096];
  562. int ret = -1;
  563. size_t size;
  564. if (os_file_exists(file_path_out))
  565. return -1;
  566. file_in = fopen(file_path_in, "rb");
  567. if (!file_in)
  568. return -1;
  569. file_out = fopen(file_path_out, "ab+");
  570. if (!file_out)
  571. goto error;
  572. do {
  573. size = fread(data, 1, sizeof(data), file_in);
  574. if (size)
  575. size = fwrite(data, 1, size, file_out);
  576. } while (size == sizeof(data));
  577. ret = feof(file_in) ? 0 : -1;
  578. error:
  579. if (file_out)
  580. fclose(file_out);
  581. fclose(file_in);
  582. return ret;
  583. }
  584. char *os_getcwd(char *path, size_t size)
  585. {
  586. return getcwd(path, size);
  587. }
  588. int os_chdir(const char *path)
  589. {
  590. return chdir(path);
  591. }
  592. #if !defined(__APPLE__)
  593. #if defined(GIO_FOUND)
  594. struct dbus_sleep_info;
  595. struct portal_inhibit_info;
  596. extern struct dbus_sleep_info *dbus_sleep_info_create(void);
  597. extern void dbus_inhibit_sleep(struct dbus_sleep_info *dbus, const char *sleep,
  598. bool active);
  599. extern void dbus_sleep_info_destroy(struct dbus_sleep_info *dbus);
  600. extern struct portal_inhibit_info *portal_inhibit_info_create(void);
  601. extern void portal_inhibit(struct portal_inhibit_info *portal,
  602. const char *reason, bool active);
  603. extern void portal_inhibit_info_destroy(struct portal_inhibit_info *portal);
  604. #endif
  605. struct os_inhibit_info {
  606. #if defined(GIO_FOUND)
  607. struct dbus_sleep_info *dbus;
  608. struct portal_inhibit_info *portal;
  609. #endif
  610. pthread_t screensaver_thread;
  611. os_event_t *stop_event;
  612. char *reason;
  613. posix_spawnattr_t attr;
  614. bool active;
  615. };
  616. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  617. {
  618. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  619. sigset_t set;
  620. #if defined(GIO_FOUND)
  621. info->portal = portal_inhibit_info_create();
  622. if (!info->portal)
  623. info->dbus = dbus_sleep_info_create();
  624. #endif
  625. os_event_init(&info->stop_event, OS_EVENT_TYPE_AUTO);
  626. posix_spawnattr_init(&info->attr);
  627. sigemptyset(&set);
  628. posix_spawnattr_setsigmask(&info->attr, &set);
  629. sigaddset(&set, SIGPIPE);
  630. posix_spawnattr_setsigdefault(&info->attr, &set);
  631. posix_spawnattr_setflags(&info->attr, POSIX_SPAWN_SETSIGDEF |
  632. POSIX_SPAWN_SETSIGMASK);
  633. info->reason = bstrdup(reason);
  634. return info;
  635. }
  636. extern char **environ;
  637. static void reset_screensaver(os_inhibit_t *info)
  638. {
  639. char *argv[3] = {(char *)"xdg-screensaver", (char *)"reset", NULL};
  640. pid_t pid;
  641. int err = posix_spawnp(&pid, "xdg-screensaver", NULL, &info->attr, argv,
  642. environ);
  643. if (err == 0) {
  644. int status;
  645. while (waitpid(pid, &status, 0) == -1)
  646. ;
  647. } else {
  648. blog(LOG_WARNING, "Failed to create xdg-screensaver: %d", err);
  649. }
  650. }
  651. static void *screensaver_thread(void *param)
  652. {
  653. os_inhibit_t *info = param;
  654. while (os_event_timedwait(info->stop_event, 30000) == ETIMEDOUT)
  655. reset_screensaver(info);
  656. return NULL;
  657. }
  658. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  659. {
  660. int ret;
  661. if (!info)
  662. return false;
  663. if (info->active == active)
  664. return false;
  665. #if defined(GIO_FOUND)
  666. if (info->portal)
  667. portal_inhibit(info->portal, info->reason, active);
  668. if (info->dbus)
  669. dbus_inhibit_sleep(info->dbus, info->reason, active);
  670. #endif
  671. if (!info->stop_event)
  672. return true;
  673. if (active) {
  674. ret = pthread_create(&info->screensaver_thread, NULL,
  675. &screensaver_thread, info);
  676. if (ret < 0) {
  677. blog(LOG_ERROR, "Failed to create screensaver "
  678. "inhibitor thread");
  679. return false;
  680. }
  681. } else {
  682. os_event_signal(info->stop_event);
  683. pthread_join(info->screensaver_thread, NULL);
  684. }
  685. info->active = active;
  686. return true;
  687. }
  688. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  689. {
  690. if (info) {
  691. os_inhibit_sleep_set_active(info, false);
  692. #if defined(GIO_FOUND)
  693. portal_inhibit_info_destroy(info->portal);
  694. dbus_sleep_info_destroy(info->dbus);
  695. #endif
  696. os_event_destroy(info->stop_event);
  697. posix_spawnattr_destroy(&info->attr);
  698. bfree(info->reason);
  699. bfree(info);
  700. }
  701. }
  702. #endif
  703. void os_breakpoint()
  704. {
  705. raise(SIGTRAP);
  706. }
  707. #ifndef __APPLE__
  708. static int physical_cores = 0;
  709. static int logical_cores = 0;
  710. static bool core_count_initialized = false;
  711. static void os_get_cores_internal(void)
  712. {
  713. if (core_count_initialized)
  714. return;
  715. core_count_initialized = true;
  716. logical_cores = sysconf(_SC_NPROCESSORS_ONLN);
  717. #if defined(__linux__)
  718. int physical_id = -1;
  719. int last_physical_id = -1;
  720. int core_count = 0;
  721. char *line = NULL;
  722. size_t linecap = 0;
  723. FILE *fp;
  724. struct dstr proc_phys_id;
  725. struct dstr proc_phys_ids;
  726. fp = fopen("/proc/cpuinfo", "r");
  727. if (!fp)
  728. return;
  729. dstr_init(&proc_phys_id);
  730. dstr_init(&proc_phys_ids);
  731. while (getline(&line, &linecap, fp) != -1) {
  732. if (!strncmp(line, "physical id", 11)) {
  733. char *start = strchr(line, ':');
  734. if (!start || *(++start) == '\0')
  735. continue;
  736. physical_id = atoi(start);
  737. dstr_free(&proc_phys_id);
  738. dstr_init(&proc_phys_id);
  739. dstr_catf(&proc_phys_id, "%d", physical_id);
  740. }
  741. if (!strncmp(line, "cpu cores", 9)) {
  742. char *start = strchr(line, ':');
  743. if (!start || *(++start) == '\0')
  744. continue;
  745. if (dstr_is_empty(&proc_phys_ids) ||
  746. (!dstr_is_empty(&proc_phys_ids) &&
  747. !dstr_find(&proc_phys_ids, proc_phys_id.array))) {
  748. dstr_cat_dstr(&proc_phys_ids, &proc_phys_id);
  749. dstr_cat(&proc_phys_ids, " ");
  750. core_count += atoi(start);
  751. }
  752. }
  753. if (*line == '\n' && physical_id != last_physical_id) {
  754. last_physical_id = physical_id;
  755. }
  756. }
  757. if (core_count == 0)
  758. physical_cores = logical_cores;
  759. else
  760. physical_cores = core_count;
  761. fclose(fp);
  762. dstr_free(&proc_phys_ids);
  763. dstr_free(&proc_phys_id);
  764. free(line);
  765. #elif defined(__FreeBSD__)
  766. char *text = os_quick_read_utf8_file("/var/run/dmesg.boot");
  767. char *core_count = text;
  768. int packages = 0;
  769. int cores = 0;
  770. struct dstr proc_packages;
  771. struct dstr proc_cores;
  772. dstr_init(&proc_packages);
  773. dstr_init(&proc_cores);
  774. if (!text || !*text) {
  775. physical_cores = logical_cores;
  776. return;
  777. }
  778. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  779. if (!core_count)
  780. goto FreeBSD_cores_cleanup;
  781. core_count++;
  782. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  783. if (!core_count)
  784. goto FreeBSD_cores_cleanup;
  785. core_count = strstr(core_count, ": ");
  786. core_count += 2;
  787. size_t len = strcspn(core_count, " ");
  788. dstr_ncopy(&proc_packages, core_count, len);
  789. core_count = strstr(core_count, "package(s) x ");
  790. if (!core_count)
  791. goto FreeBSD_cores_cleanup;
  792. core_count += 13;
  793. len = strcspn(core_count, " ");
  794. dstr_ncopy(&proc_cores, core_count, len);
  795. FreeBSD_cores_cleanup:
  796. if (!dstr_is_empty(&proc_packages))
  797. packages = atoi(proc_packages.array);
  798. if (!dstr_is_empty(&proc_cores))
  799. cores = atoi(proc_cores.array);
  800. if (packages == 0)
  801. physical_cores = logical_cores;
  802. else if (cores == 0)
  803. physical_cores = packages;
  804. else
  805. physical_cores = packages * cores;
  806. dstr_free(&proc_cores);
  807. dstr_free(&proc_packages);
  808. bfree(text);
  809. #else
  810. physical_cores = logical_cores;
  811. #endif
  812. }
  813. int os_get_physical_cores(void)
  814. {
  815. if (!core_count_initialized)
  816. os_get_cores_internal();
  817. return physical_cores;
  818. }
  819. int os_get_logical_cores(void)
  820. {
  821. if (!core_count_initialized)
  822. os_get_cores_internal();
  823. return logical_cores;
  824. }
  825. #ifdef __FreeBSD__
  826. uint64_t os_get_sys_free_size(void)
  827. {
  828. uint64_t mem_free = 0;
  829. size_t length = sizeof(mem_free);
  830. if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &length, NULL,
  831. 0) < 0)
  832. return 0;
  833. return mem_free;
  834. }
  835. static inline bool os_get_proc_memory_usage_internal(struct kinfo_proc *kinfo)
  836. {
  837. int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
  838. size_t length = sizeof(*kinfo);
  839. if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), kinfo, &length, NULL, 0) <
  840. 0)
  841. return false;
  842. return true;
  843. }
  844. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  845. {
  846. struct kinfo_proc kinfo;
  847. if (!os_get_proc_memory_usage_internal(&kinfo))
  848. return false;
  849. usage->resident_size =
  850. (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  851. usage->virtual_size = (uint64_t)kinfo.ki_size;
  852. return true;
  853. }
  854. uint64_t os_get_proc_resident_size(void)
  855. {
  856. struct kinfo_proc kinfo;
  857. if (!os_get_proc_memory_usage_internal(&kinfo))
  858. return 0;
  859. return (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  860. }
  861. uint64_t os_get_proc_virtual_size(void)
  862. {
  863. struct kinfo_proc kinfo;
  864. if (!os_get_proc_memory_usage_internal(&kinfo))
  865. return 0;
  866. return (uint64_t)kinfo.ki_size;
  867. }
  868. #else
  869. uint64_t os_get_sys_free_size(void)
  870. {
  871. return 0;
  872. }
  873. typedef struct {
  874. unsigned long virtual_size;
  875. unsigned long resident_size;
  876. unsigned long share_pages;
  877. unsigned long text;
  878. unsigned long library;
  879. unsigned long data;
  880. unsigned long dirty_pages;
  881. } statm_t;
  882. static inline bool os_get_proc_memory_usage_internal(statm_t *statm)
  883. {
  884. const char *statm_path = "/proc/self/statm";
  885. FILE *f = fopen(statm_path, "r");
  886. if (!f)
  887. return false;
  888. if (fscanf(f, "%lu %lu %lu %lu %lu %lu %lu", &statm->virtual_size,
  889. &statm->resident_size, &statm->share_pages, &statm->text,
  890. &statm->library, &statm->data, &statm->dirty_pages) != 7) {
  891. fclose(f);
  892. return false;
  893. }
  894. fclose(f);
  895. return true;
  896. }
  897. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  898. {
  899. statm_t statm = {};
  900. if (!os_get_proc_memory_usage_internal(&statm))
  901. return false;
  902. usage->resident_size =
  903. (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE);
  904. usage->virtual_size = statm.virtual_size;
  905. return true;
  906. }
  907. uint64_t os_get_proc_resident_size(void)
  908. {
  909. statm_t statm = {};
  910. if (!os_get_proc_memory_usage_internal(&statm))
  911. return 0;
  912. return (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE);
  913. }
  914. uint64_t os_get_proc_virtual_size(void)
  915. {
  916. statm_t statm = {};
  917. if (!os_get_proc_memory_usage_internal(&statm))
  918. return 0;
  919. return (uint64_t)statm.virtual_size;
  920. }
  921. #endif
  922. static uint64_t total_memory = 0;
  923. static bool total_memory_initialized = false;
  924. static void os_get_sys_total_size_internal()
  925. {
  926. total_memory_initialized = true;
  927. #ifndef __OpenBSD__
  928. struct sysinfo info;
  929. if (sysinfo(&info) < 0)
  930. return;
  931. total_memory = (uint64_t)info.totalram * info.mem_unit;
  932. #endif
  933. }
  934. uint64_t os_get_sys_total_size(void)
  935. {
  936. if (!total_memory_initialized)
  937. os_get_sys_total_size_internal();
  938. return total_memory;
  939. }
  940. #endif
  941. #ifndef __APPLE__
  942. uint64_t os_get_free_disk_space(const char *dir)
  943. {
  944. struct statvfs info;
  945. if (statvfs(dir, &info) != 0)
  946. return 0;
  947. return (uint64_t)info.f_frsize * (uint64_t)info.f_bavail;
  948. }
  949. #endif
  950. char *os_generate_uuid(void)
  951. {
  952. uuid_t uuid;
  953. // 36 char UUID + NULL
  954. char *out = bmalloc(37);
  955. uuid_generate(uuid);
  956. uuid_unparse_lower(uuid, out);
  957. return out;
  958. }