c_eventloop.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. /*
  2. * C eventloop example.
  3. *
  4. * Timer management is similar to eventloop.js but implemented in C.
  5. * In particular, timer insertion is an O(n) operation; in a real world
  6. * eventloop based on a heap insertion would be O(log N).
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <stdint.h>
  12. #include <sys/time.h>
  13. #include <poll.h>
  14. #include "duktape.h"
  15. #define MAX_TIMERS 4096 /* this is quite excessive for embedded use, but good for testing */
  16. #define MIN_DELAY 1.0
  17. #define MIN_WAIT 1.0
  18. #define MAX_WAIT 60000.0
  19. #define MAX_EXPIRYS 10
  20. #define MAX_FDS 256
  21. typedef struct {
  22. int64_t id; /* numeric ID (returned from e.g. setTimeout); zero if unused */
  23. double target; /* next target time */
  24. double delay; /* delay/interval */
  25. int oneshot; /* oneshot=1 (setTimeout), repeated=0 (setInterval) */
  26. int removed; /* timer has been requested for removal */
  27. /* The callback associated with the timer is held in the "global stash",
  28. * in <stash>.eventTimers[String(id)]. The references must be deleted
  29. * when a timer struct is deleted.
  30. */
  31. } ev_timer;
  32. /* Active timers. Dense list, terminates to end of list or first unused timer.
  33. * The list is sorted by 'target', with lowest 'target' (earliest expiry) last
  34. * in the list. When a timer's callback is being called, the timer is moved
  35. * to 'timer_expiring' as it needs special handling should the user callback
  36. * delete that particular timer.
  37. */
  38. static ev_timer timer_list[MAX_TIMERS];
  39. static ev_timer timer_expiring;
  40. static int timer_count; /* last timer at timer_count - 1 */
  41. static int64_t timer_next_id = 1;
  42. /* Socket poll state. */
  43. static struct pollfd poll_list[MAX_FDS];
  44. static int poll_count = 0;
  45. /* Misc */
  46. static int exit_requested = 0;
  47. /* Get Javascript compatible 'now' timestamp (millisecs since 1970). */
  48. static double get_now(void) {
  49. struct timeval tv;
  50. int rc;
  51. rc = gettimeofday(&tv, NULL);
  52. if (rc != 0) {
  53. /* Should never happen, so return whatever. */
  54. return 0.0;
  55. }
  56. return ((double) tv.tv_sec) * 1000.0 + ((double) tv.tv_usec) / 1000.0;
  57. }
  58. static ev_timer *find_nearest_timer(void) {
  59. /* Last timer expires first (list is always kept sorted). */
  60. if (timer_count <= 0) {
  61. return NULL;
  62. }
  63. return timer_list + timer_count - 1;
  64. }
  65. /* Bubble last timer on timer list backwards until it has been moved to
  66. * its proper sorted position (based on 'target' time).
  67. */
  68. static void bubble_last_timer(void) {
  69. int i;
  70. int n = timer_count;
  71. ev_timer *t;
  72. ev_timer tmp;
  73. for (i = n - 1; i > 0; i--) {
  74. /* Timer to bubble is at index i, timer to compare to is
  75. * at i-1 (both guaranteed to exist).
  76. */
  77. t = timer_list + i;
  78. if (t->target <= (t-1)->target) {
  79. /* 't' expires earlier than (or same time as) 't-1', so we're done. */
  80. break;
  81. } else {
  82. /* 't' expires later than 't-1', so swap them and repeat. */
  83. memcpy((void *) &tmp, (void *) (t - 1), sizeof(ev_timer));
  84. memcpy((void *) (t - 1), (void *) t, sizeof(ev_timer));
  85. memcpy((void *) t, (void *) &tmp, sizeof(ev_timer));
  86. }
  87. }
  88. }
  89. static void expire_timers(duk_context *ctx) {
  90. ev_timer *t;
  91. int sanity = MAX_EXPIRYS;
  92. double now;
  93. int rc;
  94. /* Because a user callback can mutate the timer list (by adding or deleting
  95. * a timer), we expire one timer and then rescan from the end again. There
  96. * is a sanity limit on how many times we do this per expiry round.
  97. */
  98. duk_push_global_stash(ctx);
  99. duk_get_prop_string(ctx, -1, "eventTimers");
  100. /* [ ... stash eventTimers ] */
  101. now = get_now();
  102. while (sanity-- > 0) {
  103. /*
  104. * If exit has been requested, exit without running further
  105. * callbacks.
  106. */
  107. if (exit_requested) {
  108. #if 0
  109. fprintf(stderr, "exit requested, exiting timer expiry loop\n");
  110. fflush(stderr);
  111. #endif
  112. break;
  113. }
  114. /*
  115. * Expired timer(s) still exist?
  116. */
  117. if (timer_count <= 0) {
  118. break;
  119. }
  120. t = timer_list + timer_count - 1;
  121. if (t->target > now) {
  122. break;
  123. }
  124. /*
  125. * Move the timer to 'expiring' for the duration of the callback.
  126. * Mark a one-shot timer deleted, compute a new target for an interval.
  127. */
  128. memcpy((void *) &timer_expiring, (void *) t, sizeof(ev_timer));
  129. memset((void *) t, 0, sizeof(ev_timer));
  130. timer_count--;
  131. t = &timer_expiring;
  132. if (t->oneshot) {
  133. t->removed = 1;
  134. } else {
  135. t->target = now + t->delay; /* XXX: or t->target + t->delay? */
  136. }
  137. /*
  138. * Call timer callback. The callback can operate on the timer list:
  139. * add new timers, remove timers. The callback can even remove the
  140. * expired timer whose callback we're calling. However, because the
  141. * timer being expired has been moved to 'timer_expiring', we don't
  142. * need to worry about the timer's offset changing on the timer list.
  143. */
  144. #if 0
  145. fprintf(stderr, "calling user callback for timer id %d\n", (int) t->id);
  146. fflush(stderr);
  147. #endif
  148. duk_push_number(ctx, (double) t->id);
  149. duk_get_prop(ctx, -2); /* -> [ ... stash eventTimers func ] */
  150. rc = duk_pcall(ctx, 0 /*nargs*/); /* -> [ ... stash eventTimers retval ] */
  151. if (rc != 0) {
  152. #if 0
  153. fprintf(stderr, "timer callback failed for timer %d: %s\n", (int) t->id, duk_to_string(ctx, -1));
  154. fflush(stderr);
  155. #endif
  156. }
  157. duk_pop(ctx); /* ignore errors for now -> [ ... stash eventTimers ] */
  158. if (t->removed) {
  159. /* One-shot timer (always removed) or removed by user callback. */
  160. #if 0
  161. fprintf(stderr, "deleting callback state for timer %d\n", (int) t->id);
  162. fflush(stderr);
  163. #endif
  164. duk_push_number(ctx, (double) t->id);
  165. duk_del_prop(ctx, -2);
  166. } else {
  167. /* Interval timer, not removed by user callback. Queue back to
  168. * timer list and bubble to its final sorted position.
  169. */
  170. #if 0
  171. fprintf(stderr, "queueing timer %d back into active list\n", (int) t->id);
  172. fflush(stderr);
  173. #endif
  174. if (timer_count >= MAX_TIMERS) {
  175. duk_error(ctx, DUK_ERR_RANGE_ERROR, "out of timer slots");
  176. }
  177. memcpy((void *) (timer_list + timer_count), (void *) t, sizeof(ev_timer));
  178. timer_count++;
  179. bubble_last_timer();
  180. }
  181. }
  182. memset((void *) &timer_expiring, 0, sizeof(ev_timer));
  183. duk_pop_2(ctx); /* -> [ ... ] */
  184. }
  185. static void compact_poll_list(void) {
  186. int i, j, n;
  187. /* i = input index
  188. * j = output index (initially same as i)
  189. */
  190. n = poll_count;
  191. for (i = 0, j = 0; i < n; i++) {
  192. struct pollfd *pfd = poll_list + i;
  193. if (pfd->fd == 0) {
  194. /* keep output index the same */
  195. #if 0
  196. fprintf(stderr, "remove pollfd (index %d): fd=%d, events=%d, revents=%d\n",
  197. i, pfd->fd, pfd->events, pfd->revents),
  198. fflush(stderr);
  199. #endif
  200. continue;
  201. }
  202. #if 0
  203. fprintf(stderr, "keep pollfd (index %d -> %d): fd=%d, events=%d, revents=%d\n",
  204. i, j, pfd->fd, pfd->events, pfd->revents),
  205. fflush(stderr);
  206. #endif
  207. if (i != j) {
  208. /* copy only if indices have diverged */
  209. memcpy((void *) (poll_list + j), (void *) (poll_list + i), sizeof(struct pollfd));
  210. }
  211. j++;
  212. }
  213. if (j < poll_count) {
  214. /* zeroize unused entries for sanity */
  215. memset((void *) (poll_list + j), 0, (poll_count - j) * sizeof(struct pollfd));
  216. }
  217. poll_count = j;
  218. }
  219. int eventloop_run(duk_context *ctx) {
  220. ev_timer *t;
  221. double now;
  222. double diff;
  223. int timeout;
  224. int rc;
  225. int i, n;
  226. int idx_eventloop;
  227. int idx_fd_handler;
  228. /* The Ecmascript poll handler is passed through EventLoop.fdPollHandler
  229. * which c_eventloop.js sets before we come here.
  230. */
  231. duk_push_global_object(ctx);
  232. duk_get_prop_string(ctx, -1, "EventLoop");
  233. duk_get_prop_string(ctx, -1, "fdPollHandler"); /* -> [ global EventLoop fdPollHandler ] */
  234. idx_fd_handler = duk_get_top_index(ctx);
  235. idx_eventloop = idx_fd_handler - 1;
  236. for (;;) {
  237. /*
  238. * Expire timers.
  239. */
  240. expire_timers(ctx);
  241. /*
  242. * If exit requested, bail out as fast as possible.
  243. */
  244. if (exit_requested) {
  245. #if 0
  246. fprintf(stderr, "exit requested, exiting event loop\n");
  247. fflush(stderr);
  248. #endif
  249. break;
  250. }
  251. /*
  252. * Compact poll list by removing pollfds with fd == 0.
  253. */
  254. compact_poll_list();
  255. /*
  256. * Determine poll() timeout (as close to poll() as possible as
  257. * the wait is relative).
  258. */
  259. now = get_now();
  260. t = find_nearest_timer();
  261. if (t) {
  262. diff = t->target - now;
  263. if (diff < MIN_WAIT) {
  264. diff = MIN_WAIT;
  265. } else if (diff > MAX_WAIT) {
  266. diff = MAX_WAIT;
  267. }
  268. timeout = (int) diff; /* clamping ensures that fits */
  269. } else {
  270. if (poll_count == 0) {
  271. #if 0
  272. fprintf(stderr, "no timers and no sockets to poll, exiting\n");
  273. fflush(stderr);
  274. #endif
  275. break;
  276. }
  277. timeout = (int) MAX_WAIT;
  278. }
  279. /*
  280. * Poll for activity or timeout.
  281. */
  282. #if 0
  283. fprintf(stderr, "going to poll, timeout %d ms, pollfd count %d\n", timeout, poll_count);
  284. fflush(stderr);
  285. #endif
  286. rc = poll(poll_list, poll_count, timeout);
  287. #if 0
  288. fprintf(stderr, "poll rc: %d\n", rc);
  289. fflush(stderr);
  290. #endif
  291. if (rc < 0) {
  292. /* error */
  293. } else if (rc == 0) {
  294. /* timeout */
  295. } else {
  296. /* 'rc' fds active */
  297. }
  298. /*
  299. * Check socket activity, handle all sockets. Handling is offloaded to
  300. * Ecmascript code (fd + revents).
  301. *
  302. * If FDs are removed from the poll list while we're processing callbacks,
  303. * the entries are simply marked unused (fd set to 0) without actually
  304. * removing them from the poll list. This ensures indices are not
  305. * disturbed. The poll list is compacted before next poll().
  306. */
  307. n = (rc == 0 ? 0 : poll_count); /* if timeout, no need to check pollfd */
  308. for (i = 0; i < n; i++) {
  309. struct pollfd *pfd = poll_list + i;
  310. if (pfd->fd == 0) {
  311. /* deleted, perhaps by previous callback */
  312. continue;
  313. }
  314. if (pfd->revents) {
  315. #if 0
  316. fprintf(stderr, "fd %d has revents: %d\n", (int) pfd->fd, (int) pfd->revents);
  317. fflush(stderr);
  318. #endif
  319. duk_dup(ctx, idx_fd_handler);
  320. duk_dup(ctx, idx_eventloop);
  321. duk_push_int(ctx, pfd->fd);
  322. duk_push_int(ctx, pfd->revents);
  323. rc = duk_pcall_method(ctx, 2 /*nargs*/);
  324. if (rc) {
  325. #if 0
  326. fprintf(stderr, "fd callback failed for fd %d: %s\n", (int) pfd->fd, duk_to_string(ctx, -1));
  327. fflush(stderr);
  328. #endif
  329. }
  330. duk_pop(ctx);
  331. pfd->revents = 0;
  332. }
  333. }
  334. }
  335. duk_pop_n(ctx, 3);
  336. return 0;
  337. }
  338. static int create_timer(duk_context *ctx) {
  339. double delay;
  340. int oneshot;
  341. int idx;
  342. int64_t timer_id;
  343. double now;
  344. ev_timer *t;
  345. now = get_now();
  346. /* indexes:
  347. * 0 = function (callback)
  348. * 1 = delay
  349. * 2 = boolean: oneshot
  350. */
  351. delay = duk_require_number(ctx, 1);
  352. if (delay < MIN_DELAY) {
  353. delay = MIN_DELAY;
  354. }
  355. oneshot = duk_require_boolean(ctx, 2);
  356. if (timer_count >= MAX_TIMERS) {
  357. duk_error(ctx, DUK_ERR_RANGE_ERROR, "out of timer slots");
  358. }
  359. idx = timer_count++;
  360. timer_id = timer_next_id++;
  361. t = timer_list + idx;
  362. memset((void *) t, 0, sizeof(ev_timer));
  363. t->id = timer_id;
  364. t->target = now + delay;
  365. t->delay = delay;
  366. t->oneshot = oneshot;
  367. t->removed = 0;
  368. /* Timer is now at the last position; use swaps to "bubble" it to its
  369. * correct sorted position.
  370. */
  371. bubble_last_timer();
  372. /* Finally, register the callback to the global stash 'eventTimers' object. */
  373. duk_push_global_stash(ctx);
  374. duk_get_prop_string(ctx, -1, "eventTimers"); /* -> [ func delay oneshot stash eventTimers ] */
  375. duk_push_number(ctx, (double) timer_id);
  376. duk_dup(ctx, 0);
  377. duk_put_prop(ctx, -3); /* eventTimers[timer_id] = callback */
  378. /* Return timer id. */
  379. duk_push_number(ctx, (double) timer_id);
  380. #if 0
  381. fprintf(stderr, "created timer id: %d\n", (int) timer_id);
  382. fflush(stderr);
  383. #endif
  384. return 1;
  385. }
  386. static int delete_timer(duk_context *ctx) {
  387. int i, n;
  388. int64_t timer_id;
  389. ev_timer *t;
  390. int found = 0;
  391. /* indexes:
  392. * 0 = timer id
  393. */
  394. timer_id = (int64_t) duk_require_number(ctx, 0);
  395. /*
  396. * Unlike insertion, deletion needs a full scan of the timer list
  397. * and an expensive remove. If no match is found, nothing is deleted.
  398. * Caller gets a boolean return code indicating match.
  399. *
  400. * When a timer is being expired and its user callback is running,
  401. * the timer has been moved to 'timer_expiring' and its deletion
  402. * needs special handling: just mark it to-be-deleted and let the
  403. * expiry code remove it.
  404. */
  405. t = &timer_expiring;
  406. if (t->id == timer_id) {
  407. t->removed = 1;
  408. duk_push_true(ctx);
  409. #if 0
  410. fprintf(stderr, "deleted expiring timer id: %d\n", (int) timer_id);
  411. fflush(stderr);
  412. #endif
  413. return 1;
  414. }
  415. n = timer_count;
  416. for (i = 0; i < n; i++) {
  417. t = timer_list + i;
  418. if (t->id == timer_id) {
  419. found = 1;
  420. /* Shift elements downwards to keep the timer list dense
  421. * (no need if last element).
  422. */
  423. if (i < timer_count - 1) {
  424. memmove((void *) t, (void *) (t + 1), (timer_count - i - 1) * sizeof(ev_timer));
  425. }
  426. /* Zero last element for clarity. */
  427. memset((void *) (timer_list + n - 1), 0, sizeof(ev_timer));
  428. /* Update timer_count. */
  429. timer_count--;
  430. /* The C state is now up-to-date, but we still need to delete
  431. * the timer callback state from the global 'stash'.
  432. */
  433. duk_push_global_stash(ctx);
  434. duk_get_prop_string(ctx, -1, "eventTimers"); /* -> [ timer_id stash eventTimers ] */
  435. duk_push_number(ctx, (double) timer_id);
  436. duk_del_prop(ctx, -2); /* delete eventTimers[timer_id] */
  437. #if 0
  438. fprintf(stderr, "deleted timer id: %d\n", (int) timer_id);
  439. fflush(stderr);
  440. #endif
  441. break;
  442. }
  443. }
  444. #if 0
  445. if (!found) {
  446. fprintf(stderr, "trying to delete timer id %d, but not found; ignoring\n", (int) timer_id);
  447. fflush(stderr);
  448. }
  449. #endif
  450. duk_push_boolean(ctx, found);
  451. return 1;
  452. }
  453. static int listen_fd(duk_context *ctx) {
  454. int fd = duk_require_int(ctx, 0);
  455. int events = duk_require_int(ctx, 1);
  456. int i, n;
  457. struct pollfd *pfd;
  458. #if 0
  459. fprintf(stderr, "listen_fd: fd=%d, events=%d\n", fd, events);
  460. fflush(stderr);
  461. #endif
  462. /* events == 0 means stop listening to the FD */
  463. n = poll_count;
  464. for (i = 0; i < n; i++) {
  465. pfd = poll_list + i;
  466. if (pfd->fd == fd) {
  467. #if 0
  468. fprintf(stderr, "listen_fd: fd found at index %d\n", i);
  469. fflush(stderr);
  470. #endif
  471. if (events == 0) {
  472. /* mark to-be-deleted, cleaned up by next poll */
  473. pfd->fd = 0;
  474. } else {
  475. pfd->events = events;
  476. }
  477. return 0;
  478. }
  479. }
  480. /* not found, append to list */
  481. #if 0
  482. fprintf(stderr, "listen_fd: fd not found on list, add new entry\n");
  483. fflush(stderr);
  484. #endif
  485. if (poll_count >= MAX_FDS) {
  486. duk_error(ctx, DUK_ERR_ERROR, "out of fd slots");
  487. }
  488. pfd = poll_list + poll_count;
  489. pfd->fd = fd;
  490. pfd->events = events;
  491. pfd->revents = 0;
  492. poll_count++;
  493. return 0;
  494. }
  495. static int request_exit(duk_context *ctx) {
  496. (void) ctx;
  497. exit_requested = 1;
  498. return 0;
  499. }
  500. static duk_function_list_entry eventloop_funcs[] = {
  501. { "createTimer", create_timer, 3 },
  502. { "deleteTimer", delete_timer, 1 },
  503. { "listenFd", listen_fd, 2 },
  504. { "requestExit", request_exit, 0 },
  505. { NULL, NULL, 0 }
  506. };
  507. void eventloop_register(duk_context *ctx) {
  508. memset((void *) timer_list, 0, MAX_TIMERS * sizeof(ev_timer));
  509. memset((void *) &timer_expiring, 0, sizeof(ev_timer));
  510. memset((void *) poll_list, 0, MAX_FDS * sizeof(struct pollfd));
  511. /* Set global 'EventLoop'. */
  512. duk_push_global_object(ctx);
  513. duk_push_object(ctx);
  514. duk_put_function_list(ctx, -1, eventloop_funcs);
  515. duk_put_prop_string(ctx, -2, "EventLoop");
  516. duk_pop(ctx);
  517. /* Initialize global stash 'eventTimers'. */
  518. duk_push_global_stash(ctx);
  519. duk_push_object(ctx);
  520. duk_put_prop_string(ctx, -2, "eventTimers");
  521. duk_pop(ctx);
  522. }