platform-nix.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 <spawn.h>
  34. #endif
  35. #include "darray.h"
  36. #include "dstr.h"
  37. #include "platform.h"
  38. #include "threading.h"
  39. void *os_dlopen(const char *path)
  40. {
  41. struct dstr dylib_name;
  42. if (!path)
  43. return NULL;
  44. dstr_init_copy(&dylib_name, path);
  45. #ifdef __APPLE__
  46. if (!dstr_find(&dylib_name, ".so") && !dstr_find(&dylib_name, ".dylib"))
  47. #else
  48. if (!dstr_find(&dylib_name, ".so"))
  49. #endif
  50. dstr_cat(&dylib_name, ".so");
  51. void *res = dlopen(dylib_name.array, RTLD_LAZY);
  52. if (!res)
  53. blog(LOG_ERROR, "os_dlopen(%s->%s): %s\n",
  54. path, dylib_name.array, dlerror());
  55. dstr_free(&dylib_name);
  56. return res;
  57. }
  58. void *os_dlsym(void *module, const char *func)
  59. {
  60. return dlsym(module, func);
  61. }
  62. void os_dlclose(void *module)
  63. {
  64. if (module)
  65. dlclose(module);
  66. }
  67. #if !defined(__APPLE__)
  68. struct os_cpu_usage_info {
  69. clock_t last_cpu_time, last_sys_time, last_user_time;
  70. int core_count;
  71. };
  72. os_cpu_usage_info_t *os_cpu_usage_info_start(void)
  73. {
  74. struct os_cpu_usage_info *info = bmalloc(sizeof(*info));
  75. struct tms time_sample;
  76. info->last_cpu_time = times(&time_sample);
  77. info->last_sys_time = time_sample.tms_stime;
  78. info->last_user_time = time_sample.tms_utime;
  79. info->core_count = sysconf(_SC_NPROCESSORS_ONLN);
  80. return info;
  81. }
  82. double os_cpu_usage_info_query(os_cpu_usage_info_t *info)
  83. {
  84. struct tms time_sample;
  85. clock_t cur_cpu_time;
  86. double percent;
  87. if (!info)
  88. return 0.0;
  89. cur_cpu_time = times(&time_sample);
  90. if (cur_cpu_time <= info->last_cpu_time ||
  91. time_sample.tms_stime < info->last_sys_time ||
  92. time_sample.tms_utime < info->last_user_time)
  93. return 0.0;
  94. percent = (double)(time_sample.tms_stime - info->last_sys_time +
  95. (time_sample.tms_utime - info->last_user_time));
  96. percent /= (double)(cur_cpu_time - info->last_cpu_time);
  97. percent /= (double)info->core_count;
  98. info->last_cpu_time = cur_cpu_time;
  99. info->last_sys_time = time_sample.tms_stime;
  100. info->last_user_time = time_sample.tms_utime;
  101. return percent * 100.0;
  102. }
  103. void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info)
  104. {
  105. if (info)
  106. bfree(info);
  107. }
  108. #endif
  109. bool os_sleepto_ns(uint64_t time_target)
  110. {
  111. uint64_t current = os_gettime_ns();
  112. if (time_target < current)
  113. return false;
  114. time_target -= current;
  115. struct timespec req, remain;
  116. memset(&req, 0, sizeof(req));
  117. memset(&remain, 0, sizeof(remain));
  118. req.tv_sec = time_target/1000000000;
  119. req.tv_nsec = time_target%1000000000;
  120. while (nanosleep(&req, &remain)) {
  121. req = remain;
  122. memset(&remain, 0, sizeof(remain));
  123. }
  124. return true;
  125. }
  126. void os_sleep_ms(uint32_t duration)
  127. {
  128. usleep(duration*1000);
  129. }
  130. #if !defined(__APPLE__)
  131. uint64_t os_gettime_ns(void)
  132. {
  133. struct timespec ts;
  134. clock_gettime(CLOCK_MONOTONIC, &ts);
  135. return ((uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec);
  136. }
  137. /* should return $HOME/.[name], or when using XDG,
  138. * should return $HOME/.config/[name] as default */
  139. int os_get_config_path(char *dst, size_t size, const char *name)
  140. {
  141. #ifdef USE_XDG
  142. char *xdg_ptr = getenv("XDG_CONFIG_HOME");
  143. // If XDG_CONFIG_HOME is unset,
  144. // we use the default $HOME/.config/[name] instead
  145. if (xdg_ptr == NULL) {
  146. char *home_ptr = getenv("HOME");
  147. if (home_ptr == NULL)
  148. bcrash("Could not get $HOME\n");
  149. if (!name || !*name) {
  150. return snprintf(dst, size, "%s/.config", home_ptr);
  151. } else {
  152. return snprintf(dst, size, "%s/.config/%s", home_ptr,
  153. name);
  154. }
  155. } else {
  156. if (!name || !*name)
  157. return snprintf(dst, size, "%s", xdg_ptr);
  158. else
  159. return snprintf(dst, size, "%s/%s", xdg_ptr, name);
  160. }
  161. #else
  162. char *path_ptr = getenv("HOME");
  163. if (path_ptr == NULL)
  164. bcrash("Could not get $HOME\n");
  165. if (!name || !*name)
  166. return snprintf(dst, size, "%s", path_ptr);
  167. else
  168. return snprintf(dst, size, "%s/.%s", path_ptr, name);
  169. #endif
  170. }
  171. /* should return $HOME/.[name], or when using XDG,
  172. * should return $HOME/.config/[name] as default */
  173. char *os_get_config_path_ptr(const char *name)
  174. {
  175. #ifdef USE_XDG
  176. struct dstr path;
  177. char *xdg_ptr = getenv("XDG_CONFIG_HOME");
  178. /* If XDG_CONFIG_HOME is unset,
  179. * we use the default $HOME/.config/[name] instead */
  180. if (xdg_ptr == NULL) {
  181. char *home_ptr = getenv("HOME");
  182. if (home_ptr == NULL)
  183. bcrash("Could not get $HOME\n");
  184. dstr_init_copy(&path, home_ptr);
  185. dstr_cat(&path, "/.config/");
  186. dstr_cat(&path, name);
  187. } else {
  188. dstr_init_copy(&path, xdg_ptr);
  189. dstr_cat(&path, "/");
  190. dstr_cat(&path, name);
  191. }
  192. return path.array;
  193. #else
  194. char *path_ptr = getenv("HOME");
  195. if (path_ptr == NULL)
  196. bcrash("Could not get $HOME\n");
  197. struct dstr path;
  198. dstr_init_copy(&path, path_ptr);
  199. dstr_cat(&path, "/.");
  200. dstr_cat(&path, name);
  201. return path.array;
  202. #endif
  203. }
  204. int os_get_program_data_path(char *dst, size_t size, const char *name)
  205. {
  206. return snprintf(dst, size, "/usr/local/share/%s", !!name ? name : "");
  207. }
  208. char *os_get_program_data_path_ptr(const char *name)
  209. {
  210. size_t len = snprintf(NULL, 0, "/usr/local/share/%s", !!name ? name : "");
  211. char *str = bmalloc(len + 1);
  212. snprintf(str, len + 1, "/usr/local/share/%s", !!name ? name : "");
  213. str[len] = 0;
  214. return str;
  215. }
  216. #endif
  217. bool os_file_exists(const char *path)
  218. {
  219. return access(path, F_OK) == 0;
  220. }
  221. size_t os_get_abs_path(const char *path, char *abspath, size_t size)
  222. {
  223. size_t min_size = size < PATH_MAX ? size : PATH_MAX;
  224. char newpath[PATH_MAX];
  225. int ret;
  226. if (!abspath)
  227. return 0;
  228. if (!realpath(path, newpath))
  229. return 0;
  230. ret = snprintf(abspath, min_size, "%s", newpath);
  231. return ret >= 0 ? ret : 0;
  232. }
  233. char *os_get_abs_path_ptr(const char *path)
  234. {
  235. char *ptr = bmalloc(512);
  236. if (!os_get_abs_path(path, ptr, 512)) {
  237. bfree(ptr);
  238. ptr = NULL;
  239. }
  240. return ptr;
  241. }
  242. struct os_dir {
  243. const char *path;
  244. DIR *dir;
  245. struct dirent *cur_dirent;
  246. struct os_dirent out;
  247. };
  248. os_dir_t *os_opendir(const char *path)
  249. {
  250. struct os_dir *dir;
  251. DIR *dir_val;
  252. dir_val = opendir(path);
  253. if (!dir_val)
  254. return NULL;
  255. dir = bzalloc(sizeof(struct os_dir));
  256. dir->dir = dir_val;
  257. dir->path = path;
  258. return dir;
  259. }
  260. static inline bool is_dir(const char *path)
  261. {
  262. struct stat stat_info;
  263. if (stat(path, &stat_info) == 0)
  264. return !!S_ISDIR(stat_info.st_mode);
  265. blog(LOG_DEBUG, "is_dir: stat for %s failed, errno: %d", path, errno);
  266. return false;
  267. }
  268. struct os_dirent *os_readdir(os_dir_t *dir)
  269. {
  270. struct dstr file_path = {0};
  271. if (!dir) return NULL;
  272. dir->cur_dirent = readdir(dir->dir);
  273. if (!dir->cur_dirent)
  274. return NULL;
  275. strncpy(dir->out.d_name, dir->cur_dirent->d_name, 255);
  276. dstr_copy(&file_path, dir->path);
  277. dstr_cat(&file_path, "/");
  278. dstr_cat(&file_path, dir->out.d_name);
  279. dir->out.directory = is_dir(file_path.array);
  280. dstr_free(&file_path);
  281. return &dir->out;
  282. }
  283. void os_closedir(os_dir_t *dir)
  284. {
  285. if (dir) {
  286. closedir(dir->dir);
  287. bfree(dir);
  288. }
  289. }
  290. int64_t os_get_free_space(const char *path)
  291. {
  292. struct statvfs info;
  293. int64_t ret = (int64_t)statvfs(path, &info);
  294. if (ret == 0)
  295. ret = (int64_t)info.f_bsize * (int64_t)info.f_bfree;
  296. return ret;
  297. }
  298. struct posix_glob_info {
  299. struct os_glob_info base;
  300. glob_t gl;
  301. };
  302. int os_glob(const char *pattern, int flags, os_glob_t **pglob)
  303. {
  304. struct posix_glob_info pgi;
  305. int ret = glob(pattern, 0, NULL, &pgi.gl);
  306. if (ret == 0) {
  307. DARRAY(struct os_globent) list;
  308. da_init(list);
  309. for (size_t i = 0; i < pgi.gl.gl_pathc; i++) {
  310. struct os_globent ent = {0};
  311. ent.path = pgi.gl.gl_pathv[i];
  312. ent.directory = is_dir(ent.path);
  313. da_push_back(list, &ent);
  314. }
  315. pgi.base.gl_pathc = list.num;
  316. pgi.base.gl_pathv = list.array;
  317. *pglob = bmemdup(&pgi, sizeof(pgi));
  318. } else {
  319. *pglob = NULL;
  320. }
  321. UNUSED_PARAMETER(flags);
  322. return ret;
  323. }
  324. void os_globfree(os_glob_t *pglob)
  325. {
  326. if (pglob) {
  327. struct posix_glob_info *pgi = (struct posix_glob_info*)pglob;
  328. globfree(&pgi->gl);
  329. bfree(pgi->base.gl_pathv);
  330. bfree(pgi);
  331. }
  332. }
  333. int os_unlink(const char *path)
  334. {
  335. return unlink(path);
  336. }
  337. int os_rmdir(const char *path)
  338. {
  339. return rmdir(path);
  340. }
  341. int os_mkdir(const char *path)
  342. {
  343. if (mkdir(path, 0755) == 0)
  344. return MKDIR_SUCCESS;
  345. return (errno == EEXIST) ? MKDIR_EXISTS : MKDIR_ERROR;
  346. }
  347. int os_rename(const char *old_path, const char *new_path)
  348. {
  349. return rename(old_path, new_path);
  350. }
  351. #if !defined(__APPLE__)
  352. os_performance_token_t *os_request_high_performance(const char *reason)
  353. {
  354. UNUSED_PARAMETER(reason);
  355. return NULL;
  356. }
  357. void os_end_high_performance(os_performance_token_t *token)
  358. {
  359. UNUSED_PARAMETER(token);
  360. }
  361. #endif
  362. int os_copyfile(const char *file_path_in, const char *file_path_out)
  363. {
  364. FILE *file_out = NULL;
  365. FILE *file_in = NULL;
  366. uint8_t data[4096];
  367. int ret = -1;
  368. size_t size;
  369. if (os_file_exists(file_path_out))
  370. return -1;
  371. file_in = fopen(file_path_in, "rb");
  372. if (!file_in)
  373. return -1;
  374. file_out = fopen(file_path_out, "ab+");
  375. if (!file_out)
  376. goto error;
  377. do {
  378. size = fread(data, 1, sizeof(data), file_in);
  379. if (size)
  380. size = fwrite(data, 1, size, file_out);
  381. } while (size == sizeof(data));
  382. ret = feof(file_in) ? 0 : -1;
  383. error:
  384. if (file_out)
  385. fclose(file_out);
  386. fclose(file_in);
  387. return ret;
  388. }
  389. char *os_getcwd(char *path, size_t size)
  390. {
  391. return getcwd(path, size);
  392. }
  393. int os_chdir(const char *path)
  394. {
  395. return chdir(path);
  396. }
  397. #if !defined(__APPLE__)
  398. #if HAVE_DBUS
  399. struct dbus_sleep_info;
  400. extern struct dbus_sleep_info *dbus_sleep_info_create(void);
  401. extern void dbus_inhibit_sleep(struct dbus_sleep_info *dbus, const char *sleep,
  402. bool active);
  403. extern void dbus_sleep_info_destroy(struct dbus_sleep_info *dbus);
  404. #endif
  405. struct os_inhibit_info {
  406. #if HAVE_DBUS
  407. struct dbus_sleep_info *dbus;
  408. #endif
  409. pthread_t screensaver_thread;
  410. os_event_t *stop_event;
  411. char *reason;
  412. posix_spawnattr_t attr;
  413. bool active;
  414. };
  415. os_inhibit_t *os_inhibit_sleep_create(const char *reason)
  416. {
  417. struct os_inhibit_info *info = bzalloc(sizeof(*info));
  418. sigset_t set;
  419. #if HAVE_DBUS
  420. info->dbus = dbus_sleep_info_create();
  421. #endif
  422. os_event_init(&info->stop_event, OS_EVENT_TYPE_AUTO);
  423. posix_spawnattr_init(&info->attr);
  424. sigemptyset(&set);
  425. posix_spawnattr_setsigmask(&info->attr, &set);
  426. sigaddset(&set, SIGPIPE);
  427. posix_spawnattr_setsigdefault(&info->attr, &set);
  428. posix_spawnattr_setflags(&info->attr,
  429. POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK);
  430. info->reason = bstrdup(reason);
  431. return info;
  432. }
  433. extern char **environ;
  434. static void reset_screensaver(os_inhibit_t *info)
  435. {
  436. char *argv[3] = {(char*)"xdg-screensaver", (char*)"reset", NULL};
  437. pid_t pid;
  438. int err = posix_spawnp(&pid, "xdg-screensaver", NULL, &info->attr,
  439. argv, environ);
  440. if (err == 0) {
  441. int status;
  442. while (waitpid(pid, &status, 0) == -1);
  443. } else {
  444. blog(LOG_WARNING, "Failed to create xdg-screensaver: %d", err);
  445. }
  446. }
  447. static void *screensaver_thread(void *param)
  448. {
  449. os_inhibit_t *info = param;
  450. while (os_event_timedwait(info->stop_event, 30000) == ETIMEDOUT)
  451. reset_screensaver(info);
  452. return NULL;
  453. }
  454. bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active)
  455. {
  456. int ret;
  457. if (!info)
  458. return false;
  459. if (info->active == active)
  460. return false;
  461. #if HAVE_DBUS
  462. if (info->dbus)
  463. dbus_inhibit_sleep(info->dbus, info->reason, active);
  464. #endif
  465. if (!info->stop_event)
  466. return true;
  467. if (active) {
  468. ret = pthread_create(&info->screensaver_thread, NULL,
  469. &screensaver_thread, info);
  470. if (ret < 0) {
  471. blog(LOG_ERROR, "Failed to create screensaver "
  472. "inhibitor thread");
  473. return false;
  474. }
  475. } else {
  476. os_event_signal(info->stop_event);
  477. pthread_join(info->screensaver_thread, NULL);
  478. }
  479. info->active = active;
  480. return true;
  481. }
  482. void os_inhibit_sleep_destroy(os_inhibit_t *info)
  483. {
  484. if (info) {
  485. os_inhibit_sleep_set_active(info, false);
  486. #if HAVE_DBUS
  487. dbus_sleep_info_destroy(info->dbus);
  488. #endif
  489. os_event_destroy(info->stop_event);
  490. posix_spawnattr_destroy(&info->attr);
  491. bfree(info->reason);
  492. bfree(info);
  493. }
  494. }
  495. #endif
  496. void os_breakpoint()
  497. {
  498. raise(SIGTRAP);
  499. }