platform-nix.c 19 KB

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