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