platform-nix.c 22 KB

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