platform-nix.c 23 KB

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