platform-nix.c 19 KB

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