backend_utils.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * backend_utils.c
  3. * Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
  4. *
  5. * Distributed under terms of the GPL3 license.
  6. */
  7. #define _GNU_SOURCE
  8. #include "backend_utils.h"
  9. #include "internal.h"
  10. #include "memfd.h"
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #include <fcntl.h>
  15. #include <errno.h>
  16. #include <time.h>
  17. #include <stdio.h>
  18. #ifdef __NetBSD__
  19. #define ppoll pollts
  20. #endif
  21. void
  22. update_fds(EventLoopData *eld) {
  23. for (nfds_t i = 0; i < eld->watches_count; i++) {
  24. Watch *w = eld->watches + i;
  25. eld->fds[i].fd = w->fd;
  26. eld->fds[i].events = w->enabled ? w->events : 0;
  27. }
  28. }
  29. static id_type watch_counter = 0;
  30. id_type
  31. addWatch(EventLoopData *eld, const char* name, int fd, int events, int enabled, watch_callback_func cb, void *cb_data) {
  32. if (eld->watches_count >= sizeof(eld->watches)/sizeof(eld->watches[0])) {
  33. _glfwInputError(GLFW_PLATFORM_ERROR, "Too many watches added");
  34. return 0;
  35. }
  36. Watch *w = eld->watches + eld->watches_count++;
  37. w->name = name;
  38. w->fd = fd; w->events = events; w->enabled = enabled;
  39. w->callback = cb;
  40. w->callback_data = cb_data;
  41. w->free = NULL;
  42. w->id = ++watch_counter;
  43. update_fds(eld);
  44. return w->id;
  45. }
  46. #define removeX(which, item_id, update_func) {\
  47. for (nfds_t i = 0; i < eld->which##_count; i++) { \
  48. if (eld->which[i].id == item_id) { \
  49. eld->which##_count--; \
  50. if (eld->which[i].callback_data && eld->which[i].free) { \
  51. eld->which[i].free(eld->which[i].id, eld->which[i].callback_data); \
  52. eld->which[i].callback_data = NULL; eld->which[i].free = NULL; \
  53. } \
  54. if (i < eld->which##_count) { \
  55. memmove(eld->which + i, eld->which + i + 1, sizeof(eld->which[0]) * (eld->which##_count - i)); \
  56. } \
  57. update_func(eld); break; \
  58. }}}
  59. void
  60. removeWatch(EventLoopData *eld, id_type watch_id) {
  61. removeX(watches, watch_id, update_fds);
  62. }
  63. void
  64. toggleWatch(EventLoopData *eld, id_type watch_id, int enabled) {
  65. for (nfds_t i = 0; i < eld->watches_count; i++) {
  66. if (eld->watches[i].id == watch_id) {
  67. if (eld->watches[i].enabled != enabled) {
  68. eld->watches[i].enabled = enabled;
  69. update_fds(eld);
  70. }
  71. break;
  72. }
  73. }
  74. }
  75. static id_type timer_counter = 0;
  76. static int
  77. compare_timers(const void *a_, const void *b_) {
  78. const Timer *a = (const Timer*)a_, *b = (const Timer*)b_;
  79. return (a->trigger_at > b->trigger_at) ? 1 : (a->trigger_at < b->trigger_at) ? -1 : 0;
  80. }
  81. static void
  82. update_timers(EventLoopData *eld) {
  83. if (eld->timers_count > 1) qsort(eld->timers, eld->timers_count, sizeof(eld->timers[0]), compare_timers);
  84. }
  85. id_type
  86. addTimer(EventLoopData *eld, const char *name, monotonic_t interval, int enabled, bool repeats, timer_callback_func cb, void *cb_data, GLFWuserdatafreefun free) {
  87. if (eld->timers_count >= sizeof(eld->timers)/sizeof(eld->timers[0])) {
  88. _glfwInputError(GLFW_PLATFORM_ERROR, "Too many timers added");
  89. return 0;
  90. }
  91. Timer *t = eld->timers + eld->timers_count++;
  92. t->interval = interval;
  93. t->name = name;
  94. t->trigger_at = enabled ? monotonic() + interval : MONOTONIC_T_MAX;
  95. t->repeats = repeats;
  96. t->callback = cb;
  97. t->callback_data = cb_data;
  98. t->free = free;
  99. t->id = ++timer_counter;
  100. update_timers(eld);
  101. return timer_counter;
  102. }
  103. void
  104. removeTimer(EventLoopData *eld, id_type timer_id) {
  105. removeX(timers, timer_id, update_timers);
  106. }
  107. void
  108. removeAllTimers(EventLoopData *eld) {
  109. for (nfds_t i = 0; i < eld->timers_count; i++) {
  110. if (eld->timers[i].free && eld->timers[i].callback_data) eld->timers[i].free(eld->timers[i].id, eld->timers[i].callback_data);
  111. }
  112. eld->timers_count = 0;
  113. }
  114. void
  115. toggleTimer(EventLoopData *eld, id_type timer_id, int enabled) {
  116. for (nfds_t i = 0; i < eld->timers_count; i++) {
  117. if (eld->timers[i].id == timer_id) {
  118. monotonic_t trigger_at = enabled ? (monotonic() + eld->timers[i].interval) : MONOTONIC_T_MAX;
  119. if (trigger_at != eld->timers[i].trigger_at) {
  120. eld->timers[i].trigger_at = trigger_at;
  121. update_timers(eld);
  122. }
  123. break;
  124. }
  125. }
  126. }
  127. void
  128. changeTimerInterval(EventLoopData *eld, id_type timer_id, monotonic_t interval) {
  129. for (nfds_t i = 0; i < eld->timers_count; i++) {
  130. if (eld->timers[i].id == timer_id) {
  131. eld->timers[i].interval = interval;
  132. break;
  133. }
  134. }
  135. }
  136. monotonic_t
  137. prepareForPoll(EventLoopData *eld, monotonic_t timeout) {
  138. for (nfds_t i = 0; i < eld->watches_count; i++) eld->fds[i].revents = 0;
  139. if (!eld->timers_count || eld->timers[0].trigger_at == MONOTONIC_T_MAX) return timeout;
  140. monotonic_t now = monotonic(), next_repeat_at = eld->timers[0].trigger_at;
  141. if (timeout < 0 || now + timeout > next_repeat_at) {
  142. timeout = next_repeat_at <= now ? 0 : next_repeat_at - now;
  143. }
  144. return timeout;
  145. }
  146. static struct timespec
  147. calc_time(monotonic_t nsec) {
  148. struct timespec result;
  149. result.tv_sec = nsec / (1000LL * 1000LL * 1000LL);
  150. result.tv_nsec = nsec % (1000LL * 1000LL * 1000LL);
  151. return result;
  152. }
  153. int
  154. pollWithTimeout(struct pollfd *fds, nfds_t nfds, monotonic_t timeout) {
  155. struct timespec tv = calc_time(timeout);
  156. return ppoll(fds, nfds, &tv, NULL);
  157. }
  158. static void
  159. dispatchEvents(EventLoopData *eld) {
  160. for (nfds_t i = 0; i < eld->watches_count; i++) {
  161. Watch *ww = eld->watches + i;
  162. struct pollfd *pfd = eld->fds + i;
  163. if (pfd->revents & ww->events) {
  164. ww->ready = 1;
  165. if (ww->callback) ww->callback(ww->fd, pfd->revents, ww->callback_data);
  166. } else ww->ready = 0;
  167. }
  168. }
  169. unsigned
  170. dispatchTimers(EventLoopData *eld) {
  171. if (!eld->timers_count || eld->timers[0].trigger_at == MONOTONIC_T_MAX) return 0;
  172. static struct { timer_callback_func func; id_type id; void* data; bool repeats; } dispatches[sizeof(eld->timers)/sizeof(eld->timers[0])];
  173. unsigned num_dispatches = 0;
  174. monotonic_t now = monotonic();
  175. for (nfds_t i = 0; i < eld->timers_count && eld->timers[i].trigger_at <= now; i++) {
  176. eld->timers[i].trigger_at = now + eld->timers[i].interval;
  177. dispatches[num_dispatches].func = eld->timers[i].callback;
  178. dispatches[num_dispatches].id = eld->timers[i].id;
  179. dispatches[num_dispatches].data = eld->timers[i].callback_data;
  180. dispatches[num_dispatches].repeats = eld->timers[i].repeats;
  181. num_dispatches++;
  182. }
  183. // we dispatch separately so that the callbacks can modify timers
  184. for (unsigned i = 0; i < num_dispatches; i++) {
  185. dispatches[i].func(dispatches[i].id, dispatches[i].data);
  186. if (!dispatches[i].repeats) {
  187. removeTimer(eld, dispatches[i].id);
  188. }
  189. }
  190. if (num_dispatches) update_timers(eld);
  191. return num_dispatches;
  192. }
  193. static void
  194. drain_wakeup_fd(int fd, EventLoopData* eld) {
  195. static char drain_buf[64];
  196. eld->wakeup_data_read = false;
  197. while(true) {
  198. ssize_t ret = read(fd, drain_buf, sizeof(drain_buf));
  199. if (ret < 0) {
  200. if (errno == EINTR) continue;
  201. break;
  202. }
  203. if (ret > 0) { eld->wakeup_data_read = true; continue; }
  204. break;
  205. }
  206. }
  207. static void
  208. mark_wakep_fd_ready(int fd UNUSED, int events UNUSED, void *data) {
  209. ((EventLoopData*)(data))->wakeup_fd_ready = true;
  210. }
  211. bool
  212. initPollData(EventLoopData *eld, int display_fd) {
  213. if (!addWatch(eld, "display", display_fd, POLLIN, 1, NULL, NULL)) return false;
  214. #ifdef HAS_EVENT_FD
  215. eld->wakeupFd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
  216. if (eld->wakeupFd == -1) return false;
  217. const int wakeup_fd = eld->wakeupFd;
  218. #else
  219. if (pipe2(eld->wakeupFds, O_CLOEXEC | O_NONBLOCK) != 0) return false;
  220. const int wakeup_fd = eld->wakeupFds[0];
  221. #endif
  222. if (!addWatch(eld, "wakeup", wakeup_fd, POLLIN, 1, mark_wakep_fd_ready, eld)) return false;
  223. return true;
  224. }
  225. void
  226. check_for_wakeup_events(EventLoopData *eld) {
  227. #ifdef HAS_EVENT_FD
  228. int fd = eld->wakeupFd;
  229. #else
  230. int fd = eld->wakeupFds[0];
  231. #endif
  232. drain_wakeup_fd(fd, eld);
  233. }
  234. void
  235. wakeupEventLoop(EventLoopData *eld) {
  236. #ifdef HAS_EVENT_FD
  237. static const uint64_t value = 1;
  238. while (write(eld->wakeupFd, &value, sizeof value) < 0 && (errno == EINTR || errno == EAGAIN));
  239. #else
  240. while (write(eld->wakeupFds[1], "w", 1) < 0 && (errno == EINTR || errno == EAGAIN));
  241. #endif
  242. }
  243. #ifndef HAS_EVENT_FD
  244. static void
  245. closeFds(int *fds, size_t count) {
  246. while(count--) {
  247. if (*fds > 0) {
  248. close(*fds);
  249. *fds = -1;
  250. }
  251. fds++;
  252. }
  253. }
  254. #endif
  255. void
  256. finalizePollData(EventLoopData *eld) {
  257. #ifdef HAS_EVENT_FD
  258. close(eld->wakeupFd); eld->wakeupFd = -1;
  259. #else
  260. closeFds(eld->wakeupFds, arraysz(eld->wakeupFds));
  261. #endif
  262. }
  263. int
  264. pollForEvents(EventLoopData *eld, monotonic_t timeout, watch_callback_func display_callback) {
  265. int read_ok = 0;
  266. timeout = prepareForPoll(eld, timeout);
  267. EVDBG("pollForEvents final timeout: %.3f", monotonic_t_to_s_double(timeout));
  268. int result;
  269. monotonic_t end_time = monotonic() + timeout;
  270. eld->wakeup_fd_ready = false;
  271. while(1) {
  272. if (timeout >= 0) {
  273. errno = 0;
  274. result = pollWithTimeout(eld->fds, eld->watches_count, timeout);
  275. int saved_errno = errno;
  276. if (display_callback) display_callback(result, eld->fds[0].revents && eld->watches[0].events, NULL);
  277. dispatchTimers(eld);
  278. if (result > 0) {
  279. dispatchEvents(eld);
  280. read_ok = eld->watches[0].ready;
  281. break;
  282. }
  283. timeout = end_time - monotonic();
  284. if (timeout <= 0) break;
  285. if (result < 0 && (saved_errno == EINTR || saved_errno == EAGAIN)) continue;
  286. break;
  287. } else {
  288. errno = 0;
  289. result = poll(eld->fds, eld->watches_count, -1);
  290. int saved_errno = errno;
  291. if (display_callback) display_callback(result, eld->fds[0].revents && eld->watches[0].events, NULL);
  292. dispatchTimers(eld);
  293. if (result > 0) {
  294. dispatchEvents(eld);
  295. read_ok = eld->watches[0].ready;
  296. }
  297. if (result < 0 && (saved_errno == EINTR || saved_errno == EAGAIN)) continue;
  298. break;
  299. }
  300. }
  301. return read_ok;
  302. }
  303. // Duplicate a UTF-8 encoded string
  304. // but cut it so that it has at most max_length bytes plus the null byte.
  305. // This does not take combining characters into account.
  306. GLFWAPI char* utf_8_strndup(const char* source, size_t max_length) {
  307. if (!source) return NULL;
  308. size_t length = strnlen(source, max_length);
  309. if (length >= max_length) {
  310. for (length = max_length; length > 0; length--) {
  311. if ((source[length] & 0xC0) != 0x80) break;
  312. }
  313. }
  314. char* result = malloc(length + 1);
  315. memcpy(result, source, length);
  316. result[length] = 0;
  317. return result;
  318. }
  319. /*
  320. * Create a new, unique, anonymous file of the given size, and
  321. * return the file descriptor for it. The file descriptor is set
  322. * CLOEXEC. The file is immediately suitable for mmap()'ing
  323. * the given size at offset zero.
  324. *
  325. * The file should not have a permanent backing store like a disk,
  326. * but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
  327. *
  328. * The file name is deleted from the file system.
  329. *
  330. * The file is suitable for buffer sharing between processes by
  331. * transmitting the file descriptor over Unix sockets using the
  332. * SCM_RIGHTS methods.
  333. *
  334. * posix_fallocate() is used to guarantee that disk space is available
  335. * for the file at the given size. If disk space is insufficient, errno
  336. * is set to ENOSPC. If posix_fallocate() is not supported, program may
  337. * receive SIGBUS on accessing mmap()'ed file contents instead.
  338. */
  339. int createAnonymousFile(off_t size) {
  340. int ret, fd = -1, shm_anon = 0;
  341. #ifdef HAS_MEMFD_CREATE
  342. fd = glfw_memfd_create("glfw-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
  343. if (fd < 0) return -1;
  344. // We can add this seal before calling posix_fallocate(), as the file
  345. // is currently zero-sized anyway.
  346. //
  347. // There is also no need to check for the return value, we couldn’t do
  348. // anything with it anyway.
  349. fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_SEAL);
  350. #elif defined(SHM_ANON)
  351. fd = shm_open(SHM_ANON, O_RDWR | O_CLOEXEC, 0600);
  352. if (fd < 0) return -1;
  353. shm_anon = 1;
  354. #else
  355. static const char template[] = "/glfw-shared-XXXXXX";
  356. const char* path;
  357. char* name;
  358. path = getenv("XDG_RUNTIME_DIR");
  359. if (!path)
  360. {
  361. errno = ENOENT;
  362. return -1;
  363. }
  364. name = calloc(strlen(path) + sizeof(template), 1);
  365. strcpy(name, path);
  366. strcat(name, template);
  367. fd = createTmpfileCloexec(name);
  368. free(name);
  369. if (fd < 0)
  370. return -1;
  371. #endif
  372. // posix_fallocate does not work on SHM descriptors
  373. ret = shm_anon ? ftruncate(fd, size) : posix_fallocate(fd, 0, size);
  374. if (ret != 0)
  375. {
  376. close(fd);
  377. errno = ret;
  378. return -1;
  379. }
  380. return fd;
  381. }