platform-nix.c 23 KB

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