1
0

platform-nix.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. #if defined(__FreeBSD__) || defined(__DragonFly__)
  237. int sysctlname[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
  238. size_t pathlen = PATH_MAX;
  239. ssize_t count;
  240. if (sysctl(sysctlname, nitems(sysctlname), exe, &pathlen, NULL, 0) ==
  241. -1) {
  242. blog(LOG_ERROR, "sysctl(KERN_PROC_PATHNAME) failed, errno %d",
  243. errno);
  244. return NULL;
  245. }
  246. count = pathlen;
  247. #else
  248. ssize_t count = readlink("/proc/self/exe", exe, PATH_MAX);
  249. #endif
  250. const char *path_out = NULL;
  251. struct dstr path;
  252. if (count == -1) {
  253. return NULL;
  254. }
  255. path_out = dirname(exe);
  256. if (!path_out) {
  257. return NULL;
  258. }
  259. dstr_init_copy(&path, path_out);
  260. dstr_cat(&path, "/");
  261. if (name && *name) {
  262. dstr_cat(&path, name);
  263. }
  264. return path.array;
  265. }
  266. #endif
  267. bool os_file_exists(const char *path)
  268. {
  269. return access(path, F_OK) == 0;
  270. }
  271. size_t os_get_abs_path(const char *path, char *abspath, size_t size)
  272. {
  273. size_t min_size = size < PATH_MAX ? size : PATH_MAX;
  274. char newpath[PATH_MAX];
  275. int ret;
  276. if (!abspath)
  277. return 0;
  278. if (!realpath(path, newpath))
  279. return 0;
  280. ret = snprintf(abspath, min_size, "%s", newpath);
  281. return ret >= 0 ? ret : 0;
  282. }
  283. char *os_get_abs_path_ptr(const char *path)
  284. {
  285. char *ptr = bmalloc(512);
  286. if (!os_get_abs_path(path, ptr, 512)) {
  287. bfree(ptr);
  288. ptr = NULL;
  289. }
  290. return ptr;
  291. }
  292. struct os_dir {
  293. const char *path;
  294. DIR *dir;
  295. struct dirent *cur_dirent;
  296. struct os_dirent out;
  297. };
  298. os_dir_t *os_opendir(const char *path)
  299. {
  300. struct os_dir *dir;
  301. DIR *dir_val;
  302. dir_val = opendir(path);
  303. if (!dir_val)
  304. return NULL;
  305. dir = bzalloc(sizeof(struct os_dir));
  306. dir->dir = dir_val;
  307. dir->path = path;
  308. return dir;
  309. }
  310. static inline bool is_dir(const char *path)
  311. {
  312. struct stat stat_info;
  313. if (stat(path, &stat_info) == 0)
  314. return !!S_ISDIR(stat_info.st_mode);
  315. blog(LOG_DEBUG, "is_dir: stat for %s failed, errno: %d", path, errno);
  316. return false;
  317. }
  318. struct os_dirent *os_readdir(os_dir_t *dir)
  319. {
  320. struct dstr file_path = {0};
  321. if (!dir)
  322. return NULL;
  323. dir->cur_dirent = readdir(dir->dir);
  324. if (!dir->cur_dirent)
  325. return NULL;
  326. strncpy(dir->out.d_name, dir->cur_dirent->d_name, 255);
  327. dstr_copy(&file_path, dir->path);
  328. dstr_cat(&file_path, "/");
  329. dstr_cat(&file_path, dir->out.d_name);
  330. dir->out.directory = is_dir(file_path.array);
  331. dstr_free(&file_path);
  332. return &dir->out;
  333. }
  334. void os_closedir(os_dir_t *dir)
  335. {
  336. if (dir) {
  337. closedir(dir->dir);
  338. bfree(dir);
  339. }
  340. }
  341. int64_t os_get_free_space(const char *path)
  342. {
  343. struct statvfs info;
  344. int64_t ret = (int64_t)statvfs(path, &info);
  345. if (ret == 0)
  346. ret = (int64_t)info.f_bsize * (int64_t)info.f_bfree;
  347. return ret;
  348. }
  349. struct posix_glob_info {
  350. struct os_glob_info base;
  351. glob_t gl;
  352. };
  353. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  354. {
  355. struct posix_glob_info pgi;
  356. int ret = glob(pattern, 0, NULL, &pgi.gl);
  357. if (ret == 0) {
  358. DARRAY(struct os_globent) list;
  359. da_init(list);
  360. for (size_t i = 0; i < pgi.gl.gl_pathc; i++) {
  361. struct os_globent ent = {0};
  362. ent.path = pgi.gl.gl_pathv[i];
  363. ent.directory = is_dir(ent.path);
  364. da_push_back(list, &ent);
  365. }
  366. pgi.base.gl_pathc = list.num;
  367. pgi.base.gl_pathv = list.array;
  368. *pglob = bmemdup(&pgi, sizeof(pgi));
  369. } else {
  370. *pglob = NULL;
  371. }
  372. UNUSED_PARAMETER(flags);
  373. return ret;
  374. }
  375. void os_globfree(os_glob_t *pglob)
  376. {
  377. if (pglob) {
  378. struct posix_glob_info *pgi = (struct posix_glob_info *)pglob;
  379. globfree(&pgi->gl);
  380. bfree(pgi->base.gl_pathv);
  381. bfree(pgi);
  382. }
  383. }
  384. int os_unlink(const char *path)
  385. {
  386. return unlink(path);
  387. }
  388. int os_rmdir(const char *path)
  389. {
  390. return rmdir(path);
  391. }
  392. int os_mkdir(const char *path)
  393. {
  394. if (mkdir(path, 0755) == 0)
  395. return MKDIR_SUCCESS;
  396. return (errno == EEXIST) ? MKDIR_EXISTS : MKDIR_ERROR;
  397. }
  398. int os_rename(const char *old_path, const char *new_path)
  399. {
  400. return rename(old_path, new_path);
  401. }
  402. int os_safe_replace(const char *target, const char *from, const char *backup)
  403. {
  404. if (backup && os_file_exists(target) && rename(target, backup) != 0)
  405. return -1;
  406. return rename(from, target);
  407. }
  408. #if !defined(__APPLE__)
  409. os_performance_token_t *os_request_high_performance(const char *reason)
  410. {
  411. UNUSED_PARAMETER(reason);
  412. return NULL;
  413. }
  414. void os_end_high_performance(os_performance_token_t *token)
  415. {
  416. UNUSED_PARAMETER(token);
  417. }
  418. #endif
  419. int os_copyfile(const char *file_path_in, const char *file_path_out)
  420. {
  421. FILE *file_out = NULL;
  422. FILE *file_in = NULL;
  423. uint8_t data[4096];
  424. int ret = -1;
  425. size_t size;
  426. if (os_file_exists(file_path_out))
  427. return -1;
  428. file_in = fopen(file_path_in, "rb");
  429. if (!file_in)
  430. return -1;
  431. file_out = fopen(file_path_out, "ab+");
  432. if (!file_out)
  433. goto error;
  434. do {
  435. size = fread(data, 1, sizeof(data), file_in);
  436. if (size)
  437. size = fwrite(data, 1, size, file_out);
  438. } while (size == sizeof(data));
  439. ret = feof(file_in) ? 0 : -1;
  440. error:
  441. if (file_out)
  442. fclose(file_out);
  443. fclose(file_in);
  444. return ret;
  445. }
  446. char *os_getcwd(char *path, size_t size)
  447. {
  448. return getcwd(path, size);
  449. }
  450. int os_chdir(const char *path)
  451. {
  452. return chdir(path);
  453. }
  454. #if !defined(__APPLE__)
  455. #if HAVE_DBUS
  456. struct dbus_sleep_info;
  457. extern struct dbus_sleep_info *dbus_sleep_info_create(void);
  458. extern void dbus_inhibit_sleep(struct dbus_sleep_info *dbus, const char *sleep,
  459. bool active);
  460. extern void dbus_sleep_info_destroy(struct dbus_sleep_info *dbus);
  461. #endif
  462. struct os_inhibit_info {
  463. #if HAVE_DBUS
  464. struct dbus_sleep_info *dbus;
  465. #endif
  466. pthread_t screensaver_thread;
  467. os_event_t *stop_event;
  468. char *reason;
  469. posix_spawnattr_t attr;
  470. bool active;
  471. };
  472. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  473. {
  474. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  475. sigset_t set;
  476. #if HAVE_DBUS
  477. info->dbus = dbus_sleep_info_create();
  478. #endif
  479. os_event_init(&info->stop_event, OS_EVENT_TYPE_AUTO);
  480. posix_spawnattr_init(&info->attr);
  481. sigemptyset(&set);
  482. posix_spawnattr_setsigmask(&info->attr, &set);
  483. sigaddset(&set, SIGPIPE);
  484. posix_spawnattr_setsigdefault(&info->attr, &set);
  485. posix_spawnattr_setflags(&info->attr, POSIX_SPAWN_SETSIGDEF |
  486. POSIX_SPAWN_SETSIGMASK);
  487. info->reason = bstrdup(reason);
  488. return info;
  489. }
  490. extern char **environ;
  491. static void reset_screensaver(os_inhibit_t *info)
  492. {
  493. char *argv[3] = {(char *)"xdg-screensaver", (char *)"reset", NULL};
  494. pid_t pid;
  495. int err = posix_spawnp(&pid, "xdg-screensaver", NULL, &info->attr, argv,
  496. environ);
  497. if (err == 0) {
  498. int status;
  499. while (waitpid(pid, &status, 0) == -1)
  500. ;
  501. } else {
  502. blog(LOG_WARNING, "Failed to create xdg-screensaver: %d", err);
  503. }
  504. }
  505. static void *screensaver_thread(void *param)
  506. {
  507. os_inhibit_t *info = param;
  508. while (os_event_timedwait(info->stop_event, 30000) == ETIMEDOUT)
  509. reset_screensaver(info);
  510. return NULL;
  511. }
  512. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  513. {
  514. int ret;
  515. if (!info)
  516. return false;
  517. if (info->active == active)
  518. return false;
  519. #if HAVE_DBUS
  520. if (info->dbus)
  521. dbus_inhibit_sleep(info->dbus, info->reason, active);
  522. #endif
  523. if (!info->stop_event)
  524. return true;
  525. if (active) {
  526. ret = pthread_create(&info->screensaver_thread, NULL,
  527. &screensaver_thread, info);
  528. if (ret < 0) {
  529. blog(LOG_ERROR, "Failed to create screensaver "
  530. "inhibitor thread");
  531. return false;
  532. }
  533. } else {
  534. os_event_signal(info->stop_event);
  535. pthread_join(info->screensaver_thread, NULL);
  536. }
  537. info->active = active;
  538. return true;
  539. }
  540. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  541. {
  542. if (info) {
  543. os_inhibit_sleep_set_active(info, false);
  544. #if HAVE_DBUS
  545. dbus_sleep_info_destroy(info->dbus);
  546. #endif
  547. os_event_destroy(info->stop_event);
  548. posix_spawnattr_destroy(&info->attr);
  549. bfree(info->reason);
  550. bfree(info);
  551. }
  552. }
  553. #endif
  554. void os_breakpoint()
  555. {
  556. raise(SIGTRAP);
  557. }
  558. #ifndef __APPLE__
  559. static int physical_cores = 0;
  560. static int logical_cores = 0;
  561. static bool core_count_initialized = false;
  562. static void os_get_cores_internal(void)
  563. {
  564. if (core_count_initialized)
  565. return;
  566. core_count_initialized = true;
  567. logical_cores = sysconf(_SC_NPROCESSORS_ONLN);
  568. #if defined(__linux__)
  569. int physical_id = -1;
  570. int last_physical_id = -1;
  571. int core_count = 0;
  572. char *line = NULL;
  573. size_t linecap = 0;
  574. FILE *fp;
  575. struct dstr proc_phys_id;
  576. struct dstr proc_phys_ids;
  577. fp = fopen("/proc/cpuinfo", "r");
  578. if (!fp)
  579. return;
  580. dstr_init(&proc_phys_id);
  581. dstr_init(&proc_phys_ids);
  582. while (getline(&line, &linecap, fp) != -1) {
  583. if (!strncmp(line, "physical id", 11)) {
  584. char *start = strchr(line, ':');
  585. if (!start || *(++start) == '\0')
  586. continue;
  587. physical_id = atoi(start);
  588. dstr_free(&proc_phys_id);
  589. dstr_init(&proc_phys_id);
  590. dstr_catf(&proc_phys_id, "%d", physical_id);
  591. }
  592. if (!strncmp(line, "cpu cores", 9)) {
  593. char *start = strchr(line, ':');
  594. if (!start || *(++start) == '\0')
  595. continue;
  596. if (dstr_is_empty(&proc_phys_ids) ||
  597. (!dstr_is_empty(&proc_phys_ids) &&
  598. !dstr_find(&proc_phys_ids, proc_phys_id.array))) {
  599. dstr_cat_dstr(&proc_phys_ids, &proc_phys_id);
  600. dstr_cat(&proc_phys_ids, " ");
  601. core_count += atoi(start);
  602. }
  603. }
  604. if (*line == '\n' && physical_id != last_physical_id) {
  605. last_physical_id = physical_id;
  606. }
  607. }
  608. if (core_count == 0)
  609. physical_cores = logical_cores;
  610. else
  611. physical_cores = core_count;
  612. fclose(fp);
  613. dstr_free(&proc_phys_ids);
  614. dstr_free(&proc_phys_id);
  615. free(line);
  616. #elif defined(__FreeBSD__)
  617. char *text = os_quick_read_utf8_file("/var/run/dmesg.boot");
  618. char *core_count = text;
  619. int packages = 0;
  620. int cores = 0;
  621. struct dstr proc_packages;
  622. struct dstr proc_cores;
  623. dstr_init(&proc_packages);
  624. dstr_init(&proc_cores);
  625. if (!text || !*text) {
  626. physical_cores = logical_cores;
  627. return;
  628. }
  629. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  630. if (!core_count)
  631. goto FreeBSD_cores_cleanup;
  632. core_count++;
  633. core_count = strstr(core_count, "\nFreeBSD/SMP: ");
  634. if (!core_count)
  635. goto FreeBSD_cores_cleanup;
  636. core_count = strstr(core_count, ": ");
  637. core_count += 2;
  638. size_t len = strcspn(core_count, " ");
  639. dstr_ncopy(&proc_packages, core_count, len);
  640. core_count = strstr(core_count, "package(s) x ");
  641. if (!core_count)
  642. goto FreeBSD_cores_cleanup;
  643. core_count += 13;
  644. len = strcspn(core_count, " ");
  645. dstr_ncopy(&proc_cores, core_count, len);
  646. FreeBSD_cores_cleanup:
  647. if (!dstr_is_empty(&proc_packages))
  648. packages = atoi(proc_packages.array);
  649. if (!dstr_is_empty(&proc_cores))
  650. cores = atoi(proc_cores.array);
  651. if (packages == 0)
  652. physical_cores = logical_cores;
  653. else if (cores == 0)
  654. physical_cores = packages;
  655. else
  656. physical_cores = packages * cores;
  657. dstr_free(&proc_cores);
  658. dstr_free(&proc_packages);
  659. bfree(text);
  660. #else
  661. physical_cores = logical_cores;
  662. #endif
  663. }
  664. int os_get_physical_cores(void)
  665. {
  666. if (!core_count_initialized)
  667. os_get_cores_internal();
  668. return physical_cores;
  669. }
  670. int os_get_logical_cores(void)
  671. {
  672. if (!core_count_initialized)
  673. os_get_cores_internal();
  674. return logical_cores;
  675. }
  676. #ifdef __FreeBSD__
  677. uint64_t os_get_sys_free_size(void)
  678. {
  679. uint64_t mem_free = 0;
  680. size_t length = sizeof(mem_free);
  681. if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &length, NULL,
  682. 0) < 0)
  683. return 0;
  684. return mem_free;
  685. }
  686. static inline bool os_get_proc_memory_usage_internal(struct kinfo_proc *kinfo)
  687. {
  688. int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
  689. size_t length = sizeof(*kinfo);
  690. if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), kinfo, &length, NULL, 0) <
  691. 0)
  692. return false;
  693. return true;
  694. }
  695. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  696. {
  697. struct kinfo_proc kinfo;
  698. if (!os_get_proc_memory_usage_internal(&kinfo))
  699. return false;
  700. usage->resident_size =
  701. (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  702. usage->virtual_size = (uint64_t)kinfo.ki_size;
  703. return true;
  704. }
  705. uint64_t os_get_proc_resident_size(void)
  706. {
  707. struct kinfo_proc kinfo;
  708. if (!os_get_proc_memory_usage_internal(&kinfo))
  709. return 0;
  710. return (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE);
  711. }
  712. uint64_t os_get_proc_virtual_size(void)
  713. {
  714. struct kinfo_proc kinfo;
  715. if (!os_get_proc_memory_usage_internal(&kinfo))
  716. return 0;
  717. return (uint64_t)kinfo.ki_size;
  718. }
  719. #else
  720. uint64_t os_get_sys_free_size(void)
  721. {
  722. return 0;
  723. }
  724. typedef struct {
  725. unsigned long virtual_size;
  726. unsigned long resident_size;
  727. unsigned long share_pages;
  728. unsigned long text;
  729. unsigned long library;
  730. unsigned long data;
  731. unsigned long dirty_pages;
  732. } statm_t;
  733. static inline bool os_get_proc_memory_usage_internal(statm_t *statm)
  734. {
  735. const char *statm_path = "/proc/self/statm";
  736. FILE *f = fopen(statm_path, "r");
  737. if (!f)
  738. return false;
  739. if (fscanf(f, "%lu %lu %lu %lu %lu %lu %lu", &statm->virtual_size,
  740. &statm->resident_size, &statm->share_pages, &statm->text,
  741. &statm->library, &statm->data, &statm->dirty_pages) != 7) {
  742. fclose(f);
  743. return false;
  744. }
  745. fclose(f);
  746. return true;
  747. }
  748. bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage)
  749. {
  750. statm_t statm = {};
  751. if (!os_get_proc_memory_usage_internal(&statm))
  752. return false;
  753. usage->resident_size = statm.resident_size;
  754. usage->virtual_size = statm.virtual_size;
  755. return true;
  756. }
  757. uint64_t os_get_proc_resident_size(void)
  758. {
  759. statm_t statm = {};
  760. if (!os_get_proc_memory_usage_internal(&statm))
  761. return 0;
  762. return (uint64_t)statm.resident_size;
  763. }
  764. uint64_t os_get_proc_virtual_size(void)
  765. {
  766. statm_t statm = {};
  767. if (!os_get_proc_memory_usage_internal(&statm))
  768. return 0;
  769. return (uint64_t)statm.virtual_size;
  770. }
  771. #endif
  772. #endif
  773. uint64_t os_get_free_disk_space(const char *dir)
  774. {
  775. struct statvfs info;
  776. if (statvfs(dir, &info) != 0)
  777. return 0;
  778. return (uint64_t)info.f_frsize * (uint64_t)info.f_bavail;
  779. }