You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4803 lines
116 KiB

11 years ago
  1. /*
  2. * libev event processing core, watcher management
  3. *
  4. * Copyright (c) 2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann <libev@schmorp.de>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without modifica-
  8. * tion, are permitted provided that the following conditions are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  18. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
  19. * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  20. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
  21. * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  22. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  23. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  24. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
  25. * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  26. * OF THE POSSIBILITY OF SUCH DAMAGE.
  27. *
  28. * Alternatively, the contents of this file may be used under the terms of
  29. * the GNU General Public License ("GPL") version 2 or any later version,
  30. * in which case the provisions of the GPL are applicable instead of
  31. * the above. If you wish to allow the use of your version of this file
  32. * only under the terms of the GPL and not to allow others to use your
  33. * version of this file under the BSD license, indicate your decision
  34. * by deleting the provisions above and replace them with the notice
  35. * and other provisions required by the GPL. If you do not delete the
  36. * provisions above, a recipient may use your version of this file under
  37. * either the BSD or the GPL.
  38. */
  39. /* this big block deduces configuration from config.h */
  40. #ifndef EV_STANDALONE
  41. # ifdef EV_CONFIG_H
  42. # include EV_CONFIG_H
  43. # else
  44. # include "config.h"
  45. # endif
  46. #if HAVE_FLOOR
  47. # ifndef EV_USE_FLOOR
  48. # define EV_USE_FLOOR 1
  49. # endif
  50. #endif
  51. # if HAVE_CLOCK_SYSCALL
  52. # ifndef EV_USE_CLOCK_SYSCALL
  53. # define EV_USE_CLOCK_SYSCALL 1
  54. # ifndef EV_USE_REALTIME
  55. # define EV_USE_REALTIME 0
  56. # endif
  57. # ifndef EV_USE_MONOTONIC
  58. # define EV_USE_MONOTONIC 1
  59. # endif
  60. # endif
  61. # elif !defined EV_USE_CLOCK_SYSCALL
  62. # define EV_USE_CLOCK_SYSCALL 0
  63. # endif
  64. # if HAVE_CLOCK_GETTIME
  65. # ifndef EV_USE_MONOTONIC
  66. # define EV_USE_MONOTONIC 1
  67. # endif
  68. # ifndef EV_USE_REALTIME
  69. # define EV_USE_REALTIME 0
  70. # endif
  71. # else
  72. # ifndef EV_USE_MONOTONIC
  73. # define EV_USE_MONOTONIC 0
  74. # endif
  75. # ifndef EV_USE_REALTIME
  76. # define EV_USE_REALTIME 0
  77. # endif
  78. # endif
  79. # if HAVE_NANOSLEEP
  80. # ifndef EV_USE_NANOSLEEP
  81. # define EV_USE_NANOSLEEP EV_FEATURE_OS
  82. # endif
  83. # else
  84. # undef EV_USE_NANOSLEEP
  85. # define EV_USE_NANOSLEEP 0
  86. # endif
  87. # if HAVE_SELECT && HAVE_SYS_SELECT_H
  88. # ifndef EV_USE_SELECT
  89. # define EV_USE_SELECT EV_FEATURE_BACKENDS
  90. # endif
  91. # else
  92. # undef EV_USE_SELECT
  93. # define EV_USE_SELECT 0
  94. # endif
  95. # if HAVE_POLL && HAVE_POLL_H
  96. # ifndef EV_USE_POLL
  97. # define EV_USE_POLL EV_FEATURE_BACKENDS
  98. # endif
  99. # else
  100. # undef EV_USE_POLL
  101. # define EV_USE_POLL 0
  102. # endif
  103. # if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
  104. # ifndef EV_USE_EPOLL
  105. # define EV_USE_EPOLL EV_FEATURE_BACKENDS
  106. # endif
  107. # else
  108. # undef EV_USE_EPOLL
  109. # define EV_USE_EPOLL 0
  110. # endif
  111. # if HAVE_KQUEUE && HAVE_SYS_EVENT_H
  112. # ifndef EV_USE_KQUEUE
  113. # define EV_USE_KQUEUE EV_FEATURE_BACKENDS
  114. # endif
  115. # else
  116. # undef EV_USE_KQUEUE
  117. # define EV_USE_KQUEUE 0
  118. # endif
  119. # if HAVE_PORT_H && HAVE_PORT_CREATE
  120. # ifndef EV_USE_PORT
  121. # define EV_USE_PORT EV_FEATURE_BACKENDS
  122. # endif
  123. # else
  124. # undef EV_USE_PORT
  125. # define EV_USE_PORT 0
  126. # endif
  127. # if HAVE_INOTIFY_INIT && HAVE_SYS_INOTIFY_H
  128. # ifndef EV_USE_INOTIFY
  129. # define EV_USE_INOTIFY EV_FEATURE_OS
  130. # endif
  131. # else
  132. # undef EV_USE_INOTIFY
  133. # define EV_USE_INOTIFY 0
  134. # endif
  135. # if HAVE_SIGNALFD && HAVE_SYS_SIGNALFD_H
  136. # ifndef EV_USE_SIGNALFD
  137. # define EV_USE_SIGNALFD EV_FEATURE_OS
  138. # endif
  139. # else
  140. # undef EV_USE_SIGNALFD
  141. # define EV_USE_SIGNALFD 0
  142. # endif
  143. # if HAVE_EVENTFD
  144. # ifndef EV_USE_EVENTFD
  145. # define EV_USE_EVENTFD EV_FEATURE_OS
  146. # endif
  147. # else
  148. # undef EV_USE_EVENTFD
  149. # define EV_USE_EVENTFD 0
  150. # endif
  151. #endif
  152. #include <stdlib.h>
  153. #include <string.h>
  154. #include <fcntl.h>
  155. #include <stddef.h>
  156. #include <stdio.h>
  157. #include <assert.h>
  158. #include <errno.h>
  159. #include <sys/types.h>
  160. #include <time.h>
  161. #include <limits.h>
  162. #include <signal.h>
  163. #ifdef EV_H
  164. # include EV_H
  165. #else
  166. # include "ev.h"
  167. #endif
  168. #if EV_NO_THREADS
  169. # undef EV_NO_SMP
  170. # define EV_NO_SMP 1
  171. # undef ECB_NO_THREADS
  172. # define ECB_NO_THREADS 1
  173. #endif
  174. #if EV_NO_SMP
  175. # undef EV_NO_SMP
  176. # define ECB_NO_SMP 1
  177. #endif
  178. #ifndef _WIN32
  179. # include <sys/time.h>
  180. # include <sys/wait.h>
  181. # include <unistd.h>
  182. #else
  183. # include <io.h>
  184. # define WIN32_LEAN_AND_MEAN
  185. # include <winsock2.h>
  186. # include <windows.h>
  187. # ifndef EV_SELECT_IS_WINSOCKET
  188. # define EV_SELECT_IS_WINSOCKET 1
  189. # endif
  190. # undef EV_AVOID_STDIO
  191. #endif
  192. /* OS X, in its infinite idiocy, actually HARDCODES
  193. * a limit of 1024 into their select. Where people have brains,
  194. * OS X engineers apparently have a vacuum. Or maybe they were
  195. * ordered to have a vacuum, or they do anything for money.
  196. * This might help. Or not.
  197. */
  198. #define _DARWIN_UNLIMITED_SELECT 1
  199. /* this block tries to deduce configuration from header-defined symbols and defaults */
  200. /* try to deduce the maximum number of signals on this platform */
  201. #if defined EV_NSIG
  202. /* use what's provided */
  203. #elif defined NSIG
  204. # define EV_NSIG (NSIG)
  205. #elif defined _NSIG
  206. # define EV_NSIG (_NSIG)
  207. #elif defined SIGMAX
  208. # define EV_NSIG (SIGMAX+1)
  209. #elif defined SIG_MAX
  210. # define EV_NSIG (SIG_MAX+1)
  211. #elif defined _SIG_MAX
  212. # define EV_NSIG (_SIG_MAX+1)
  213. #elif defined MAXSIG
  214. # define EV_NSIG (MAXSIG+1)
  215. #elif defined MAX_SIG
  216. # define EV_NSIG (MAX_SIG+1)
  217. #elif defined SIGARRAYSIZE
  218. # define EV_NSIG (SIGARRAYSIZE) /* Assume ary[SIGARRAYSIZE] */
  219. #elif defined _sys_nsig
  220. # define EV_NSIG (_sys_nsig) /* Solaris 2.5 */
  221. #else
  222. # error "unable to find value for NSIG, please report"
  223. /* to make it compile regardless, just remove the above line, */
  224. /* but consider reporting it, too! :) */
  225. # define EV_NSIG 65
  226. #endif
  227. #ifndef EV_USE_FLOOR
  228. # define EV_USE_FLOOR 0
  229. #endif
  230. #ifndef EV_USE_CLOCK_SYSCALL
  231. # if __linux && __GLIBC__ >= 2
  232. # define EV_USE_CLOCK_SYSCALL EV_FEATURE_OS
  233. # else
  234. # define EV_USE_CLOCK_SYSCALL 0
  235. # endif
  236. #endif
  237. #ifndef EV_USE_MONOTONIC
  238. # if defined _POSIX_MONOTONIC_CLOCK && _POSIX_MONOTONIC_CLOCK >= 0
  239. # define EV_USE_MONOTONIC EV_FEATURE_OS
  240. # else
  241. # define EV_USE_MONOTONIC 0
  242. # endif
  243. #endif
  244. #ifndef EV_USE_REALTIME
  245. # define EV_USE_REALTIME !EV_USE_CLOCK_SYSCALL
  246. #endif
  247. #ifndef EV_USE_NANOSLEEP
  248. # if _POSIX_C_SOURCE >= 199309L
  249. # define EV_USE_NANOSLEEP EV_FEATURE_OS
  250. # else
  251. # define EV_USE_NANOSLEEP 0
  252. # endif
  253. #endif
  254. #ifndef EV_USE_SELECT
  255. # define EV_USE_SELECT EV_FEATURE_BACKENDS
  256. #endif
  257. #ifndef EV_USE_POLL
  258. # ifdef _WIN32
  259. # define EV_USE_POLL 0
  260. # else
  261. # define EV_USE_POLL EV_FEATURE_BACKENDS
  262. # endif
  263. #endif
  264. #ifndef EV_USE_EPOLL
  265. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
  266. # define EV_USE_EPOLL EV_FEATURE_BACKENDS
  267. # else
  268. # define EV_USE_EPOLL 0
  269. # endif
  270. #endif
  271. #ifndef EV_USE_KQUEUE
  272. # define EV_USE_KQUEUE 0
  273. #endif
  274. #ifndef EV_USE_PORT
  275. # define EV_USE_PORT 0
  276. #endif
  277. #ifndef EV_USE_INOTIFY
  278. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
  279. # define EV_USE_INOTIFY EV_FEATURE_OS
  280. # else
  281. # define EV_USE_INOTIFY 0
  282. # endif
  283. #endif
  284. #ifndef EV_PID_HASHSIZE
  285. # define EV_PID_HASHSIZE EV_FEATURE_DATA ? 16 : 1
  286. #endif
  287. #ifndef EV_INOTIFY_HASHSIZE
  288. # define EV_INOTIFY_HASHSIZE EV_FEATURE_DATA ? 16 : 1
  289. #endif
  290. #ifndef EV_USE_EVENTFD
  291. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
  292. # define EV_USE_EVENTFD EV_FEATURE_OS
  293. # else
  294. # define EV_USE_EVENTFD 0
  295. # endif
  296. #endif
  297. #ifndef EV_USE_SIGNALFD
  298. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
  299. # define EV_USE_SIGNALFD EV_FEATURE_OS
  300. # else
  301. # define EV_USE_SIGNALFD 0
  302. # endif
  303. #endif
  304. #if 0 /* debugging */
  305. # define EV_VERIFY 3
  306. # define EV_USE_4HEAP 1
  307. # define EV_HEAP_CACHE_AT 1
  308. #endif
  309. #ifndef EV_VERIFY
  310. # define EV_VERIFY (EV_FEATURE_API ? 1 : 0)
  311. #endif
  312. #ifndef EV_USE_4HEAP
  313. # define EV_USE_4HEAP EV_FEATURE_DATA
  314. #endif
  315. #ifndef EV_HEAP_CACHE_AT
  316. # define EV_HEAP_CACHE_AT EV_FEATURE_DATA
  317. #endif
  318. #ifdef ANDROID
  319. /* supposedly, android doesn't typedef fd_mask */
  320. # undef EV_USE_SELECT
  321. # define EV_USE_SELECT 0
  322. /* supposedly, we need to include syscall.h, not sys/syscall.h, so just disable */
  323. # undef EV_USE_CLOCK_SYSCALL
  324. # define EV_USE_CLOCK_SYSCALL 0
  325. #endif
  326. /* aix's poll.h seems to cause lots of trouble */
  327. #ifdef _AIX
  328. /* AIX has a completely broken poll.h header */
  329. # undef EV_USE_POLL
  330. # define EV_USE_POLL 0
  331. #endif
  332. /* on linux, we can use a (slow) syscall to avoid a dependency on pthread, */
  333. /* which makes programs even slower. might work on other unices, too. */
  334. #if EV_USE_CLOCK_SYSCALL
  335. # include <sys/syscall.h>
  336. # ifdef SYS_clock_gettime
  337. # define clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts))
  338. # undef EV_USE_MONOTONIC
  339. # define EV_USE_MONOTONIC 1
  340. # else
  341. # undef EV_USE_CLOCK_SYSCALL
  342. # define EV_USE_CLOCK_SYSCALL 0
  343. # endif
  344. #endif
  345. /* this block fixes any misconfiguration where we know we run into trouble otherwise */
  346. #ifndef CLOCK_MONOTONIC
  347. # undef EV_USE_MONOTONIC
  348. # define EV_USE_MONOTONIC 0
  349. #endif
  350. #ifndef CLOCK_REALTIME
  351. # undef EV_USE_REALTIME
  352. # define EV_USE_REALTIME 0
  353. #endif
  354. #if !EV_STAT_ENABLE
  355. # undef EV_USE_INOTIFY
  356. # define EV_USE_INOTIFY 0
  357. #endif
  358. #if !EV_USE_NANOSLEEP
  359. /* hp-ux has it in sys/time.h, which we unconditionally include above */
  360. # if !defined _WIN32 && !defined __hpux
  361. # include <sys/select.h>
  362. # endif
  363. #endif
  364. #if EV_USE_INOTIFY
  365. # include <sys/statfs.h>
  366. # include <sys/inotify.h>
  367. /* some very old inotify.h headers don't have IN_DONT_FOLLOW */
  368. # ifndef IN_DONT_FOLLOW
  369. # undef EV_USE_INOTIFY
  370. # define EV_USE_INOTIFY 0
  371. # endif
  372. #endif
  373. #if EV_USE_EVENTFD
  374. /* our minimum requirement is glibc 2.7 which has the stub, but not the header */
  375. # include <stdint.h>
  376. # ifndef EFD_NONBLOCK
  377. # define EFD_NONBLOCK O_NONBLOCK
  378. # endif
  379. # ifndef EFD_CLOEXEC
  380. # ifdef O_CLOEXEC
  381. # define EFD_CLOEXEC O_CLOEXEC
  382. # else
  383. # define EFD_CLOEXEC 02000000
  384. # endif
  385. # endif
  386. EV_CPP(extern "C") int (eventfd) (unsigned int initval, int flags);
  387. #endif
  388. #if EV_USE_SIGNALFD
  389. /* our minimum requirement is glibc 2.7 which has the stub, but not the header */
  390. # include <stdint.h>
  391. # ifndef SFD_NONBLOCK
  392. # define SFD_NONBLOCK O_NONBLOCK
  393. # endif
  394. # ifndef SFD_CLOEXEC
  395. # ifdef O_CLOEXEC
  396. # define SFD_CLOEXEC O_CLOEXEC
  397. # else
  398. # define SFD_CLOEXEC 02000000
  399. # endif
  400. # endif
  401. EV_CPP (extern "C") int signalfd (int fd, const sigset_t *mask, int flags);
  402. struct signalfd_siginfo
  403. {
  404. uint32_t ssi_signo;
  405. char pad[128 - sizeof (uint32_t)];
  406. };
  407. #endif
  408. /**/
  409. #if EV_VERIFY >= 3
  410. # define EV_FREQUENT_CHECK ev_verify (EV_A)
  411. #else
  412. # define EV_FREQUENT_CHECK do { } while (0)
  413. #endif
  414. /*
  415. * This is used to work around floating point rounding problems.
  416. * This value is good at least till the year 4000.
  417. */
  418. #define MIN_INTERVAL 0.0001220703125 /* 1/2**13, good till 4000 */
  419. /*#define MIN_INTERVAL 0.00000095367431640625 /* 1/2**20, good till 2200 */
  420. #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
  421. #define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
  422. #define EV_TV_SET(tv,t) do { tv.tv_sec = (long)t; tv.tv_usec = (long)((t - tv.tv_sec) * 1e6); } while (0)
  423. #define EV_TS_SET(ts,t) do { ts.tv_sec = (long)t; ts.tv_nsec = (long)((t - ts.tv_sec) * 1e9); } while (0)
  424. /* the following is ecb.h embedded into libev - use update_ev_c to update from an external copy */
  425. /* ECB.H BEGIN */
  426. /*
  427. * libecb - http://software.schmorp.de/pkg/libecb
  428. *
  429. * Copyright (©) 2009-2012 Marc Alexander Lehmann <libecb@schmorp.de>
  430. * Copyright (©) 2011 Emanuele Giaquinta
  431. * All rights reserved.
  432. *
  433. * Redistribution and use in source and binary forms, with or without modifica-
  434. * tion, are permitted provided that the following conditions are met:
  435. *
  436. * 1. Redistributions of source code must retain the above copyright notice,
  437. * this list of conditions and the following disclaimer.
  438. *
  439. * 2. Redistributions in binary form must reproduce the above copyright
  440. * notice, this list of conditions and the following disclaimer in the
  441. * documentation and/or other materials provided with the distribution.
  442. *
  443. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  444. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
  445. * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  446. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
  447. * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  448. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  449. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  450. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
  451. * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  452. * OF THE POSSIBILITY OF SUCH DAMAGE.
  453. */
  454. #ifndef ECB_H
  455. #define ECB_H
  456. /* 16 bits major, 16 bits minor */
  457. #define ECB_VERSION 0x00010003
  458. #ifdef _WIN32
  459. typedef signed char int8_t;
  460. typedef unsigned char uint8_t;
  461. typedef signed short int16_t;
  462. typedef unsigned short uint16_t;
  463. typedef signed int int32_t;
  464. typedef unsigned int uint32_t;
  465. #if __GNUC__
  466. typedef signed long long int64_t;
  467. typedef unsigned long long uint64_t;
  468. #else /* _MSC_VER || __BORLANDC__ */
  469. typedef signed __int64 int64_t;
  470. typedef unsigned __int64 uint64_t;
  471. #endif
  472. #ifdef _WIN64
  473. #define ECB_PTRSIZE 8
  474. typedef uint64_t uintptr_t;
  475. typedef int64_t intptr_t;
  476. #else
  477. #define ECB_PTRSIZE 4
  478. typedef uint32_t uintptr_t;
  479. typedef int32_t intptr_t;
  480. #endif
  481. #else
  482. #include <inttypes.h>
  483. #if UINTMAX_MAX > 0xffffffffU
  484. #define ECB_PTRSIZE 8
  485. #else
  486. #define ECB_PTRSIZE 4
  487. #endif
  488. #endif
  489. /* work around x32 idiocy by defining proper macros */
  490. #if __x86_64 || _M_AMD64
  491. #if __ILP32
  492. #define ECB_AMD64_X32 1
  493. #else
  494. #define ECB_AMD64 1
  495. #endif
  496. #endif
  497. /* many compilers define _GNUC_ to some versions but then only implement
  498. * what their idiot authors think are the "more important" extensions,
  499. * causing enormous grief in return for some better fake benchmark numbers.
  500. * or so.
  501. * we try to detect these and simply assume they are not gcc - if they have
  502. * an issue with that they should have done it right in the first place.
  503. */
  504. #ifndef ECB_GCC_VERSION
  505. #if !defined __GNUC_MINOR__ || defined __INTEL_COMPILER || defined __SUNPRO_C || defined __SUNPRO_CC || defined __llvm__ || defined __clang__
  506. #define ECB_GCC_VERSION(major,minor) 0
  507. #else
  508. #define ECB_GCC_VERSION(major,minor) (__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
  509. #endif
  510. #endif
  511. #define ECB_C (__STDC__+0) /* this assumes that __STDC__ is either empty or a number */
  512. #define ECB_C99 (__STDC_VERSION__ >= 199901L)
  513. #define ECB_C11 (__STDC_VERSION__ >= 201112L)
  514. #define ECB_CPP (__cplusplus+0)
  515. #define ECB_CPP11 (__cplusplus >= 201103L)
  516. #if ECB_CPP
  517. #define ECB_EXTERN_C extern "C"
  518. #define ECB_EXTERN_C_BEG ECB_EXTERN_C {
  519. #define ECB_EXTERN_C_END }
  520. #else
  521. #define ECB_EXTERN_C extern
  522. #define ECB_EXTERN_C_BEG
  523. #define ECB_EXTERN_C_END
  524. #endif
  525. /*****************************************************************************/
  526. /* ECB_NO_THREADS - ecb is not used by multiple threads, ever */
  527. /* ECB_NO_SMP - ecb might be used in multiple threads, but only on a single cpu */
  528. #if ECB_NO_THREADS
  529. #define ECB_NO_SMP 1
  530. #endif
  531. #if ECB_NO_SMP
  532. #define ECB_MEMORY_FENCE do { } while (0)
  533. #endif
  534. #ifndef ECB_MEMORY_FENCE
  535. #if ECB_GCC_VERSION(2,5) || defined __INTEL_COMPILER || (__llvm__ && __GNUC__) || __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110
  536. #if __i386 || __i386__
  537. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("lock; orb $0, -1(%%esp)" : : : "memory")
  538. #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory")
  539. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("")
  540. #elif __amd64 || __amd64__ || __x86_64 || __x86_64__
  541. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mfence" : : : "memory")
  542. #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory")
  543. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("")
  544. #elif __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__
  545. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("sync" : : : "memory")
  546. #elif defined __ARM_ARCH_6__ || defined __ARM_ARCH_6J__ \
  547. || defined __ARM_ARCH_6K__ || defined __ARM_ARCH_6ZK__
  548. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mcr p15,0,%0,c7,c10,5" : : "r" (0) : "memory")
  549. #elif defined __ARM_ARCH_7__ || defined __ARM_ARCH_7A__ \
  550. || defined __ARM_ARCH_7M__ || defined __ARM_ARCH_7R__
  551. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb" : : : "memory")
  552. #elif __sparc || __sparc__
  553. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad | #StoreStore | #StoreLoad" : : : "memory")
  554. #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad" : : : "memory")
  555. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("membar #LoadStore | #StoreStore")
  556. #elif defined __s390__ || defined __s390x__
  557. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("bcr 15,0" : : : "memory")
  558. #elif defined __mips__
  559. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("sync" : : : "memory")
  560. #elif defined __alpha__
  561. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mb" : : : "memory")
  562. #elif defined __hppa__
  563. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory")
  564. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("")
  565. #elif defined __ia64__
  566. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mf" : : : "memory")
  567. #endif
  568. #endif
  569. #endif
  570. #ifndef ECB_MEMORY_FENCE
  571. #if ECB_GCC_VERSION(4,7)
  572. /* see comment below (stdatomic.h) about the C11 memory model. */
  573. #define ECB_MEMORY_FENCE __atomic_thread_fence (__ATOMIC_SEQ_CST)
  574. /* The __has_feature syntax from clang is so misdesigned that we cannot use it
  575. * without risking compile time errors with other compilers. We *could*
  576. * define our own ecb_clang_has_feature, but I just can't be bothered to work
  577. * around this shit time and again.
  578. * #elif defined __clang && __has_feature (cxx_atomic)
  579. * // see comment below (stdatomic.h) about the C11 memory model.
  580. * #define ECB_MEMORY_FENCE __c11_atomic_thread_fence (__ATOMIC_SEQ_CST)
  581. */
  582. #elif ECB_GCC_VERSION(4,4) || defined __INTEL_COMPILER || defined __clang__
  583. #define ECB_MEMORY_FENCE __sync_synchronize ()
  584. #elif _MSC_VER >= 1400 /* VC++ 2005 */
  585. #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier)
  586. #define ECB_MEMORY_FENCE _ReadWriteBarrier ()
  587. #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier () /* according to msdn, _ReadBarrier is not a load fence */
  588. #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier ()
  589. #elif defined _WIN32
  590. #include <WinNT.h>
  591. #define ECB_MEMORY_FENCE MemoryBarrier () /* actually just xchg on x86... scary */
  592. #elif __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110
  593. #include <mbarrier.h>
  594. #define ECB_MEMORY_FENCE __machine_rw_barrier ()
  595. #define ECB_MEMORY_FENCE_ACQUIRE __machine_r_barrier ()
  596. #define ECB_MEMORY_FENCE_RELEASE __machine_w_barrier ()
  597. #elif __xlC__
  598. #define ECB_MEMORY_FENCE __sync ()
  599. #endif
  600. #endif
  601. #ifndef ECB_MEMORY_FENCE
  602. #if ECB_C11 && !defined __STDC_NO_ATOMICS__
  603. /* we assume that these memory fences work on all variables/all memory accesses, */
  604. /* not just C11 atomics and atomic accesses */
  605. #include <stdatomic.h>
  606. /* Unfortunately, neither gcc 4.7 nor clang 3.1 generate any instructions for */
  607. /* any fence other than seq_cst, which isn't very efficient for us. */
  608. /* Why that is, we don't know - either the C11 memory model is quite useless */
  609. /* for most usages, or gcc and clang have a bug */
  610. /* I *currently* lean towards the latter, and inefficiently implement */
  611. /* all three of ecb's fences as a seq_cst fence */
  612. #define ECB_MEMORY_FENCE atomic_thread_fence (memory_order_seq_cst)
  613. #endif
  614. #endif
  615. #ifndef ECB_MEMORY_FENCE
  616. #if !ECB_AVOID_PTHREADS
  617. /*
  618. * if you get undefined symbol references to pthread_mutex_lock,
  619. * or failure to find pthread.h, then you should implement
  620. * the ECB_MEMORY_FENCE operations for your cpu/compiler
  621. * OR provide pthread.h and link against the posix thread library
  622. * of your system.
  623. */
  624. #include <pthread.h>
  625. #define ECB_NEEDS_PTHREADS 1
  626. #define ECB_MEMORY_FENCE_NEEDS_PTHREADS 1
  627. static pthread_mutex_t ecb_mf_lock = PTHREAD_MUTEX_INITIALIZER;
  628. #define ECB_MEMORY_FENCE do { pthread_mutex_lock (&ecb_mf_lock); pthread_mutex_unlock (&ecb_mf_lock); } while (0)
  629. #endif
  630. #endif
  631. #if !defined ECB_MEMORY_FENCE_ACQUIRE && defined ECB_MEMORY_FENCE
  632. #define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
  633. #endif
  634. #if !defined ECB_MEMORY_FENCE_RELEASE && defined ECB_MEMORY_FENCE
  635. #define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
  636. #endif
  637. /*****************************************************************************/
  638. #if __cplusplus
  639. #define ecb_inline static inline
  640. #elif ECB_GCC_VERSION(2,5)
  641. #define ecb_inline static __inline__
  642. #elif ECB_C99
  643. #define ecb_inline static inline
  644. #else
  645. #define ecb_inline static
  646. #endif
  647. #if ECB_GCC_VERSION(3,3)
  648. #define ecb_restrict __restrict__
  649. #elif ECB_C99
  650. #define ecb_restrict restrict
  651. #else
  652. #define ecb_restrict
  653. #endif
  654. typedef int ecb_bool;
  655. #define ECB_CONCAT_(a, b) a ## b
  656. #define ECB_CONCAT(a, b) ECB_CONCAT_(a, b)
  657. #define ECB_STRINGIFY_(a) # a
  658. #define ECB_STRINGIFY(a) ECB_STRINGIFY_(a)
  659. #define ecb_function_ ecb_inline
  660. #if ECB_GCC_VERSION(3,1)
  661. #define ecb_attribute(attrlist) __attribute__(attrlist)
  662. #define ecb_is_constant(expr) __builtin_constant_p (expr)
  663. #define ecb_expect(expr,value) __builtin_expect ((expr),(value))
  664. #define ecb_prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality)
  665. #else
  666. #define ecb_attribute(attrlist)
  667. #define ecb_is_constant(expr) 0
  668. #define ecb_expect(expr,value) (expr)
  669. #define ecb_prefetch(addr,rw,locality)
  670. #endif
  671. /* no emulation for ecb_decltype */
  672. #if ECB_GCC_VERSION(4,5)
  673. #define ecb_decltype(x) __decltype(x)
  674. #elif ECB_GCC_VERSION(3,0)
  675. #define ecb_decltype(x) __typeof(x)
  676. #endif
  677. #define ecb_noinline ecb_attribute ((__noinline__))
  678. #define ecb_unused ecb_attribute ((__unused__))
  679. #define ecb_const ecb_attribute ((__const__))
  680. #define ecb_pure ecb_attribute ((__pure__))
  681. #if ECB_C11
  682. #define ecb_noreturn _Noreturn
  683. #else
  684. #define ecb_noreturn ecb_attribute ((__noreturn__))
  685. #endif
  686. #if ECB_GCC_VERSION(4,3)
  687. #define ecb_artificial ecb_attribute ((__artificial__))
  688. #define ecb_hot ecb_attribute ((__hot__))
  689. #define ecb_cold ecb_attribute ((__cold__))
  690. #else
  691. #define ecb_artificial
  692. #define ecb_hot
  693. #define ecb_cold
  694. #endif
  695. /* put around conditional expressions if you are very sure that the */
  696. /* expression is mostly true or mostly false. note that these return */
  697. /* booleans, not the expression. */
  698. #define ecb_expect_false(expr) ecb_expect (!!(expr), 0)
  699. #define ecb_expect_true(expr) ecb_expect (!!(expr), 1)
  700. /* for compatibility to the rest of the world */
  701. #define ecb_likely(expr) ecb_expect_true (expr)
  702. #define ecb_unlikely(expr) ecb_expect_false (expr)
  703. /* count trailing zero bits and count # of one bits */
  704. #if ECB_GCC_VERSION(3,4)
  705. /* we assume int == 32 bit, long == 32 or 64 bit and long long == 64 bit */
  706. #define ecb_ld32(x) (__builtin_clz (x) ^ 31)
  707. #define ecb_ld64(x) (__builtin_clzll (x) ^ 63)
  708. #define ecb_ctz32(x) __builtin_ctz (x)
  709. #define ecb_ctz64(x) __builtin_ctzll (x)
  710. #define ecb_popcount32(x) __builtin_popcount (x)
  711. /* no popcountll */
  712. #else
  713. ecb_function_ int ecb_ctz32 (uint32_t x) ecb_const;
  714. ecb_function_ int
  715. ecb_ctz32 (uint32_t x)
  716. {
  717. int r = 0;
  718. x &= ~x + 1; /* this isolates the lowest bit */
  719. #if ECB_branchless_on_i386
  720. r += !!(x & 0xaaaaaaaa) << 0;
  721. r += !!(x & 0xcccccccc) << 1;
  722. r += !!(x & 0xf0f0f0f0) << 2;
  723. r += !!(x & 0xff00ff00) << 3;
  724. r += !!(x & 0xffff0000) << 4;
  725. #else
  726. if (x & 0xaaaaaaaa) r += 1;
  727. if (x & 0xcccccccc) r += 2;
  728. if (x & 0xf0f0f0f0) r += 4;
  729. if (x & 0xff00ff00) r += 8;
  730. if (x & 0xffff0000) r += 16;
  731. #endif
  732. return r;
  733. }
  734. ecb_function_ int ecb_ctz64 (uint64_t x) ecb_const;
  735. ecb_function_ int
  736. ecb_ctz64 (uint64_t x)
  737. {
  738. int shift = x & 0xffffffffU ? 0 : 32;
  739. return ecb_ctz32 (x >> shift) + shift;
  740. }
  741. ecb_function_ int ecb_popcount32 (uint32_t x) ecb_const;
  742. ecb_function_ int
  743. ecb_popcount32 (uint32_t x)
  744. {
  745. x -= (x >> 1) & 0x55555555;
  746. x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
  747. x = ((x >> 4) + x) & 0x0f0f0f0f;
  748. x *= 0x01010101;
  749. return x >> 24;
  750. }
  751. ecb_function_ int ecb_ld32 (uint32_t x) ecb_const;
  752. ecb_function_ int ecb_ld32 (uint32_t x)
  753. {
  754. int r = 0;
  755. if (x >> 16) { x >>= 16; r += 16; }
  756. if (x >> 8) { x >>= 8; r += 8; }
  757. if (x >> 4) { x >>= 4; r += 4; }
  758. if (x >> 2) { x >>= 2; r += 2; }
  759. if (x >> 1) { r += 1; }
  760. return r;
  761. }
  762. ecb_function_ int ecb_ld64 (uint64_t x) ecb_const;
  763. ecb_function_ int ecb_ld64 (uint64_t x)
  764. {
  765. int r = 0;
  766. if (x >> 32) { x >>= 32; r += 32; }
  767. return r + ecb_ld32 (x);
  768. }
  769. #endif
  770. ecb_function_ ecb_bool ecb_is_pot32 (uint32_t x) ecb_const;
  771. ecb_function_ ecb_bool ecb_is_pot32 (uint32_t x) { return !(x & (x - 1)); }
  772. ecb_function_ ecb_bool ecb_is_pot64 (uint64_t x) ecb_const;
  773. ecb_function_ ecb_bool ecb_is_pot64 (uint64_t x) { return !(x & (x - 1)); }
  774. ecb_function_ uint8_t ecb_bitrev8 (uint8_t x) ecb_const;
  775. ecb_function_ uint8_t ecb_bitrev8 (uint8_t x)
  776. {
  777. return ( (x * 0x0802U & 0x22110U)
  778. | (x * 0x8020U & 0x88440U)) * 0x10101U >> 16;
  779. }
  780. ecb_function_ uint16_t ecb_bitrev16 (uint16_t x) ecb_const;
  781. ecb_function_ uint16_t ecb_bitrev16 (uint16_t x)
  782. {
  783. x = ((x >> 1) & 0x5555) | ((x & 0x5555) << 1);
  784. x = ((x >> 2) & 0x3333) | ((x & 0x3333) << 2);
  785. x = ((x >> 4) & 0x0f0f) | ((x & 0x0f0f) << 4);
  786. x = ( x >> 8 ) | ( x << 8);
  787. return x;
  788. }
  789. ecb_function_ uint32_t ecb_bitrev32 (uint32_t x) ecb_const;
  790. ecb_function_ uint32_t ecb_bitrev32 (uint32_t x)
  791. {
  792. x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
  793. x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
  794. x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4);
  795. x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8);
  796. x = ( x >> 16 ) | ( x << 16);
  797. return x;
  798. }
  799. /* popcount64 is only available on 64 bit cpus as gcc builtin */
  800. /* so for this version we are lazy */
  801. ecb_function_ int ecb_popcount64 (uint64_t x) ecb_const;
  802. ecb_function_ int
  803. ecb_popcount64 (uint64_t x)
  804. {
  805. return ecb_popcount32 (x) + ecb_popcount32 (x >> 32);
  806. }
  807. ecb_inline uint8_t ecb_rotl8 (uint8_t x, unsigned int count) ecb_const;
  808. ecb_inline uint8_t ecb_rotr8 (uint8_t x, unsigned int count) ecb_const;
  809. ecb_inline uint16_t ecb_rotl16 (uint16_t x, unsigned int count) ecb_const;
  810. ecb_inline uint16_t ecb_rotr16 (uint16_t x, unsigned int count) ecb_const;
  811. ecb_inline uint32_t ecb_rotl32 (uint32_t x, unsigned int count) ecb_const;
  812. ecb_inline uint32_t ecb_rotr32 (uint32_t x, unsigned int count) ecb_const;
  813. ecb_inline uint64_t ecb_rotl64 (uint64_t x, unsigned int count) ecb_const;
  814. ecb_inline uint64_t ecb_rotr64 (uint64_t x, unsigned int count) ecb_const;
  815. ecb_inline uint8_t ecb_rotl8 (uint8_t x, unsigned int count) { return (x >> ( 8 - count)) | (x << count); }
  816. ecb_inline uint8_t ecb_rotr8 (uint8_t x, unsigned int count) { return (x << ( 8 - count)) | (x >> count); }
  817. ecb_inline uint16_t ecb_rotl16 (uint16_t x, unsigned int count) { return (x >> (16 - count)) | (x << count); }
  818. ecb_inline uint16_t ecb_rotr16 (uint16_t x, unsigned int count) { return (x << (16 - count)) | (x >> count); }
  819. ecb_inline uint32_t ecb_rotl32 (uint32_t x, unsigned int count) { return (x >> (32 - count)) | (x << count); }
  820. ecb_inline uint32_t ecb_rotr32 (uint32_t x, unsigned int count) { return (x << (32 - count)) | (x >> count); }
  821. ecb_inline uint64_t ecb_rotl64 (uint64_t x, unsigned int count) { return (x >> (64 - count)) | (x << count); }
  822. ecb_inline uint64_t ecb_rotr64 (uint64_t x, unsigned int count) { return (x << (64 - count)) | (x >> count); }
  823. #if ECB_GCC_VERSION(4,3)
  824. #define ecb_bswap16(x) (__builtin_bswap32 (x) >> 16)
  825. #define ecb_bswap32(x) __builtin_bswap32 (x)
  826. #define ecb_bswap64(x) __builtin_bswap64 (x)
  827. #else
  828. ecb_function_ uint16_t ecb_bswap16 (uint16_t x) ecb_const;
  829. ecb_function_ uint16_t
  830. ecb_bswap16 (uint16_t x)
  831. {
  832. return ecb_rotl16 (x, 8);
  833. }
  834. ecb_function_ uint32_t ecb_bswap32 (uint32_t x) ecb_const;
  835. ecb_function_ uint32_t
  836. ecb_bswap32 (uint32_t x)
  837. {
  838. return (((uint32_t)ecb_bswap16 (x)) << 16) | ecb_bswap16 (x >> 16);
  839. }
  840. ecb_function_ uint64_t ecb_bswap64 (uint64_t x) ecb_const;
  841. ecb_function_ uint64_t
  842. ecb_bswap64 (uint64_t x)
  843. {
  844. return (((uint64_t)ecb_bswap32 (x)) << 32) | ecb_bswap32 (x >> 32);
  845. }
  846. #endif
  847. #if ECB_GCC_VERSION(4,5)
  848. #define ecb_unreachable() __builtin_unreachable ()
  849. #else
  850. /* this seems to work fine, but gcc always emits a warning for it :/ */
  851. ecb_inline void ecb_unreachable (void) ecb_noreturn;
  852. ecb_inline void ecb_unreachable (void) { }
  853. #endif
  854. /* try to tell the compiler that some condition is definitely true */
  855. #define ecb_assume(cond) if (!(cond)) ecb_unreachable (); else 0
  856. ecb_inline unsigned char ecb_byteorder_helper (void) ecb_const;
  857. ecb_inline unsigned char
  858. ecb_byteorder_helper (void)
  859. {
  860. /* the union code still generates code under pressure in gcc, */
  861. /* but less than using pointers, and always seems to */
  862. /* successfully return a constant. */
  863. /* the reason why we have this horrible preprocessor mess */
  864. /* is to avoid it in all cases, at least on common architectures */
  865. /* or when using a recent enough gcc version (>= 4.6) */
  866. #if __i386 || __i386__ || _M_X86 || __amd64 || __amd64__ || _M_X64
  867. return 0x44;
  868. #elif __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  869. return 0x44;
  870. #elif __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  871. return 0x11;
  872. #else
  873. union
  874. {
  875. uint32_t i;
  876. uint8_t c;
  877. } u = { 0x11223344 };
  878. return u.c;
  879. #endif
  880. }
  881. ecb_inline ecb_bool ecb_big_endian (void) ecb_const;
  882. ecb_inline ecb_bool ecb_big_endian (void) { return ecb_byteorder_helper () == 0x11; }
  883. ecb_inline ecb_bool ecb_little_endian (void) ecb_const;
  884. ecb_inline ecb_bool ecb_little_endian (void) { return ecb_byteorder_helper () == 0x44; }
  885. #if ECB_GCC_VERSION(3,0) || ECB_C99
  886. #define ecb_mod(m,n) ((m) % (n) + ((m) % (n) < 0 ? (n) : 0))
  887. #else
  888. #define ecb_mod(m,n) ((m) < 0 ? ((n) - 1 - ((-1 - (m)) % (n))) : ((m) % (n)))
  889. #endif
  890. #if __cplusplus
  891. template<typename T>
  892. static inline T ecb_div_rd (T val, T div)
  893. {
  894. return val < 0 ? - ((-val + div - 1) / div) : (val ) / div;
  895. }
  896. template<typename T>
  897. static inline T ecb_div_ru (T val, T div)
  898. {
  899. return val < 0 ? - ((-val ) / div) : (val + div - 1) / div;
  900. }
  901. #else
  902. #define ecb_div_rd(val,div) ((val) < 0 ? - ((-(val) + (div) - 1) / (div)) : ((val) ) / (div))
  903. #define ecb_div_ru(val,div) ((val) < 0 ? - ((-(val) ) / (div)) : ((val) + (div) - 1) / (div))
  904. #endif
  905. #if ecb_cplusplus_does_not_suck
  906. /* does not work for local types (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm) */
  907. template<typename T, int N>
  908. static inline int ecb_array_length (const T (&arr)[N])
  909. {
  910. return N;
  911. }
  912. #else
  913. #define ecb_array_length(name) (sizeof (name) / sizeof (name [0]))
  914. #endif
  915. /*******************************************************************************/
  916. /* floating point stuff, can be disabled by defining ECB_NO_LIBM */
  917. /* basically, everything uses "ieee pure-endian" floating point numbers */
  918. /* the only noteworthy exception is ancient armle, which uses order 43218765 */
  919. #if 0 \
  920. || __i386 || __i386__ \
  921. || __amd64 || __amd64__ || __x86_64 || __x86_64__ \
  922. || __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__ \
  923. || defined __arm__ && defined __ARM_EABI__ \
  924. || defined __s390__ || defined __s390x__ \
  925. || defined __mips__ \
  926. || defined __alpha__ \
  927. || defined __hppa__ \
  928. || defined __ia64__ \
  929. || defined _M_IX86 || defined _M_AMD64 || defined _M_IA64
  930. #define ECB_STDFP 1
  931. #include <string.h> /* for memcpy */
  932. #else
  933. #define ECB_STDFP 0
  934. #include <math.h> /* for frexp*, ldexp* */
  935. #endif
  936. #ifndef ECB_NO_LIBM
  937. /* convert a float to ieee single/binary32 */
  938. ecb_function_ uint32_t ecb_float_to_binary32 (float x) ecb_const;
  939. ecb_function_ uint32_t
  940. ecb_float_to_binary32 (float x)
  941. {
  942. uint32_t r;
  943. #if ECB_STDFP
  944. memcpy (&r, &x, 4);
  945. #else
  946. /* slow emulation, works for anything but -0 */
  947. uint32_t m;
  948. int e;
  949. if (x == 0e0f ) return 0x00000000U;
  950. if (x > +3.40282346638528860e+38f) return 0x7f800000U;
  951. if (x < -3.40282346638528860e+38f) return 0xff800000U;
  952. if (x != x ) return 0x7fbfffffU;
  953. m = frexpf (x, &e) * 0x1000000U;
  954. r = m & 0x80000000U;
  955. if (r)
  956. m = -m;
  957. if (e <= -126)
  958. {
  959. m &= 0xffffffU;
  960. m >>= (-125 - e);
  961. e = -126;
  962. }
  963. r |= (e + 126) << 23;
  964. r |= m & 0x7fffffU;
  965. #endif
  966. return r;
  967. }
  968. /* converts an ieee single/binary32 to a float */
  969. ecb_function_ float ecb_binary32_to_float (uint32_t x) ecb_const;
  970. ecb_function_ float
  971. ecb_binary32_to_float (uint32_t x)
  972. {
  973. float r;
  974. #if ECB_STDFP
  975. memcpy (&r, &x, 4);
  976. #else
  977. /* emulation, only works for normals and subnormals and +0 */
  978. int neg = x >> 31;
  979. int e = (x >> 23) & 0xffU;
  980. x &= 0x7fffffU;
  981. if (e)
  982. x |= 0x800000U;
  983. else
  984. e = 1;
  985. /* we distrust ldexpf a bit and do the 2**-24 scaling by an extra multiply */
  986. r = ldexpf (x * (0.5f / 0x800000U), e - 126);
  987. r = neg ? -r : r;
  988. #endif
  989. return r;
  990. }
  991. /* convert a double to ieee double/binary64 */
  992. ecb_function_ uint64_t ecb_double_to_binary64 (double x) ecb_const;
  993. ecb_function_ uint64_t
  994. ecb_double_to_binary64 (double x)
  995. {
  996. uint64_t r;
  997. #if ECB_STDFP
  998. memcpy (&r, &x, 8);
  999. #else
  1000. /* slow emulation, works for anything but -0 */
  1001. uint64_t m;
  1002. int e;
  1003. if (x == 0e0 ) return 0x0000000000000000U;
  1004. if (x > +1.79769313486231470e+308) return 0x7ff0000000000000U;
  1005. if (x < -1.79769313486231470e+308) return 0xfff0000000000000U;
  1006. if (x != x ) return 0X7ff7ffffffffffffU;
  1007. m = frexp (x, &e) * 0x20000000000000U;
  1008. r = m & 0x8000000000000000;;
  1009. if (r)
  1010. m = -m;
  1011. if (e <= -1022)
  1012. {
  1013. m &= 0x1fffffffffffffU;
  1014. m >>= (-1021 - e);
  1015. e = -1022;
  1016. }
  1017. r |= ((uint64_t)(e + 1022)) << 52;
  1018. r |= m & 0xfffffffffffffU;
  1019. #endif
  1020. return r;
  1021. }
  1022. /* converts an ieee double/binary64 to a double */
  1023. ecb_function_ double ecb_binary64_to_double (uint64_t x) ecb_const;
  1024. ecb_function_ double
  1025. ecb_binary64_to_double (uint64_t x)
  1026. {
  1027. double r;
  1028. #if ECB_STDFP
  1029. memcpy (&r, &x, 8);
  1030. #else
  1031. /* emulation, only works for normals and subnormals and +0 */
  1032. int neg = x >> 63;
  1033. int e = (x >> 52) & 0x7ffU;
  1034. x &= 0xfffffffffffffU;
  1035. if (e)
  1036. x |= 0x10000000000000U;
  1037. else
  1038. e = 1;
  1039. /* we distrust ldexp a bit and do the 2**-53 scaling by an extra multiply */
  1040. r = ldexp (x * (0.5 / 0x10000000000000U), e - 1022);
  1041. r = neg ? -r : r;
  1042. #endif
  1043. return r;
  1044. }
  1045. #endif
  1046. #endif
  1047. /* ECB.H END */
  1048. #if ECB_MEMORY_FENCE_NEEDS_PTHREADS
  1049. /* if your architecture doesn't need memory fences, e.g. because it is
  1050. * single-cpu/core, or if you use libev in a project that doesn't use libev
  1051. * from multiple threads, then you can define ECB_AVOID_PTHREADS when compiling
  1052. * libev, in which cases the memory fences become nops.
  1053. * alternatively, you can remove this #error and link against libpthread,
  1054. * which will then provide the memory fences.
  1055. */
  1056. # error "memory fences not defined for your architecture, please report"
  1057. #endif
  1058. #ifndef ECB_MEMORY_FENCE
  1059. # define ECB_MEMORY_FENCE do { } while (0)
  1060. # define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
  1061. # define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
  1062. #endif
  1063. #define expect_false(cond) ecb_expect_false (cond)
  1064. #define expect_true(cond) ecb_expect_true (cond)
  1065. #define noinline ecb_noinline
  1066. #define inline_size ecb_inline
  1067. #if EV_FEATURE_CODE
  1068. # define inline_speed ecb_inline
  1069. #else
  1070. # define inline_speed static noinline
  1071. #endif
  1072. #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
  1073. #if EV_MINPRI == EV_MAXPRI
  1074. # define ABSPRI(w) (((W)w), 0)
  1075. #else
  1076. # define ABSPRI(w) (((W)w)->priority - EV_MINPRI)
  1077. #endif
  1078. #define EMPTY /* required for microsofts broken pseudo-c compiler */
  1079. #define EMPTY2(a,b) /* used to suppress some warnings */
  1080. typedef ev_watcher *W;
  1081. typedef ev_watcher_list *WL;
  1082. typedef ev_watcher_time *WT;
  1083. #define ev_active(w) ((W)(w))->active
  1084. #define ev_at(w) ((WT)(w))->at
  1085. #if EV_USE_REALTIME
  1086. /* sig_atomic_t is used to avoid per-thread variables or locking but still */
  1087. /* giving it a reasonably high chance of working on typical architectures */
  1088. static EV_ATOMIC_T have_realtime; /* did clock_gettime (CLOCK_REALTIME) work? */
  1089. #endif
  1090. #if EV_USE_MONOTONIC
  1091. static EV_ATOMIC_T have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
  1092. #endif
  1093. #ifndef EV_FD_TO_WIN32_HANDLE
  1094. # define EV_FD_TO_WIN32_HANDLE(fd) _get_osfhandle (fd)
  1095. #endif
  1096. #ifndef EV_WIN32_HANDLE_TO_FD
  1097. # define EV_WIN32_HANDLE_TO_FD(handle) _open_osfhandle (handle, 0)
  1098. #endif
  1099. #ifndef EV_WIN32_CLOSE_FD
  1100. # define EV_WIN32_CLOSE_FD(fd) close (fd)
  1101. #endif
  1102. #ifdef _WIN32
  1103. # include "ev_win32.c"
  1104. #endif
  1105. /*****************************************************************************/
  1106. /* define a suitable floor function (only used by periodics atm) */
  1107. #if EV_USE_FLOOR
  1108. # include <math.h>
  1109. # define ev_floor(v) floor (v)
  1110. #else
  1111. #include <float.h>
  1112. /* a floor() replacement function, should be independent of ev_tstamp type */
  1113. static ev_tstamp noinline
  1114. ev_floor (ev_tstamp v)
  1115. {
  1116. /* the choice of shift factor is not terribly important */
  1117. #if FLT_RADIX != 2 /* assume FLT_RADIX == 10 */
  1118. const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 10000000000000000000. : 1000000000.;
  1119. #else
  1120. const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 18446744073709551616. : 4294967296.;
  1121. #endif
  1122. /* argument too large for an unsigned long? */
  1123. if (expect_false (v >= shift))
  1124. {
  1125. ev_tstamp f;
  1126. if (v == v - 1.)
  1127. return v; /* very large number */
  1128. f = shift * ev_floor (v * (1. / shift));
  1129. return f + ev_floor (v - f);
  1130. }
  1131. /* special treatment for negative args? */
  1132. if (expect_false (v < 0.))
  1133. {
  1134. ev_tstamp f = -ev_floor (-v);
  1135. return f - (f == v ? 0 : 1);
  1136. }
  1137. /* fits into an unsigned long */
  1138. return (unsigned long)v;
  1139. }
  1140. #endif
  1141. /*****************************************************************************/
  1142. #ifdef __linux
  1143. # include <sys/utsname.h>
  1144. #endif
  1145. static unsigned int noinline ecb_cold
  1146. ev_linux_version (void)
  1147. {
  1148. #ifdef __linux
  1149. unsigned int v = 0;
  1150. struct utsname buf;
  1151. int i;
  1152. char *p = buf.release;
  1153. if (uname (&buf))
  1154. return 0;
  1155. for (i = 3+1; --i; )
  1156. {
  1157. unsigned int c = 0;
  1158. for (;;)
  1159. {
  1160. if (*p >= '0' && *p <= '9')
  1161. c = c * 10 + *p++ - '0';
  1162. else
  1163. {
  1164. p += *p == '.';
  1165. break;
  1166. }
  1167. }
  1168. v = (v << 8) | c;
  1169. }
  1170. return v;
  1171. #else
  1172. return 0;
  1173. #endif
  1174. }
  1175. /*****************************************************************************/
  1176. #if EV_AVOID_STDIO
  1177. static void noinline ecb_cold
  1178. ev_printerr (const char *msg)
  1179. {
  1180. write (STDERR_FILENO, msg, strlen (msg));
  1181. }
  1182. #endif
  1183. static void (*syserr_cb)(const char *msg) EV_THROW;
  1184. void ecb_cold
  1185. ev_set_syserr_cb (void (*cb)(const char *msg) EV_THROW) EV_THROW
  1186. {
  1187. syserr_cb = cb;
  1188. }
  1189. static void noinline ecb_cold
  1190. ev_syserr (const char *msg)
  1191. {
  1192. if (!msg)
  1193. msg = "(libev) system error";
  1194. if (syserr_cb)
  1195. syserr_cb (msg);
  1196. else
  1197. {
  1198. #if EV_AVOID_STDIO
  1199. ev_printerr (msg);
  1200. ev_printerr (": ");
  1201. ev_printerr (strerror (errno));
  1202. ev_printerr ("\n");
  1203. #else
  1204. perror (msg);
  1205. #endif
  1206. abort ();
  1207. }
  1208. }
  1209. static void *
  1210. ev_realloc_emul (void *ptr, long size) EV_THROW
  1211. {
  1212. /* some systems, notably openbsd and darwin, fail to properly
  1213. * implement realloc (x, 0) (as required by both ansi c-89 and
  1214. * the single unix specification, so work around them here.
  1215. * recently, also (at least) fedora and debian started breaking it,
  1216. * despite documenting it otherwise.
  1217. */
  1218. if (size)
  1219. return realloc (ptr, size);
  1220. free (ptr);
  1221. return 0;
  1222. }
  1223. static void *(*alloc)(void *ptr, long size) EV_THROW = ev_realloc_emul;
  1224. void ecb_cold
  1225. ev_set_allocator (void *(*cb)(void *ptr, long size) EV_THROW) EV_THROW
  1226. {
  1227. alloc = cb;
  1228. }
  1229. inline_speed void *
  1230. ev_realloc (void *ptr, long size)
  1231. {
  1232. ptr = alloc (ptr, size);
  1233. if (!ptr && size)
  1234. {
  1235. #if EV_AVOID_STDIO
  1236. ev_printerr ("(libev) memory allocation failed, aborting.\n");
  1237. #else
  1238. fprintf (stderr, "(libev) cannot allocate %ld bytes, aborting.", size);
  1239. #endif
  1240. abort ();
  1241. }
  1242. return ptr;
  1243. }
  1244. #define ev_malloc(size) ev_realloc (0, (size))
  1245. #define ev_free(ptr) ev_realloc ((ptr), 0)
  1246. /*****************************************************************************/
  1247. /* set in reify when reification needed */
  1248. #define EV_ANFD_REIFY 1
  1249. /* file descriptor info structure */
  1250. typedef struct
  1251. {
  1252. WL head;
  1253. unsigned char events; /* the events watched for */
  1254. unsigned char reify; /* flag set when this ANFD needs reification (EV_ANFD_REIFY, EV__IOFDSET) */
  1255. unsigned char emask; /* the epoll backend stores the actual kernel mask in here */
  1256. unsigned char unused;
  1257. #if EV_USE_EPOLL
  1258. unsigned int egen; /* generation counter to counter epoll bugs */
  1259. #endif
  1260. #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
  1261. SOCKET handle;
  1262. #endif
  1263. #if EV_USE_IOCP
  1264. OVERLAPPED or, ow;
  1265. #endif
  1266. } ANFD;
  1267. /* stores the pending event set for a given watcher */
  1268. typedef struct
  1269. {
  1270. W w;
  1271. int events; /* the pending event set for the given watcher */
  1272. } ANPENDING;
  1273. #if EV_USE_INOTIFY
  1274. /* hash table entry per inotify-id */
  1275. typedef struct
  1276. {
  1277. WL head;
  1278. } ANFS;
  1279. #endif
  1280. /* Heap Entry */
  1281. #if EV_HEAP_CACHE_AT
  1282. /* a heap element */
  1283. typedef struct {
  1284. ev_tstamp at;
  1285. WT w;
  1286. } ANHE;
  1287. #define ANHE_w(he) (he).w /* access watcher, read-write */
  1288. #define ANHE_at(he) (he).at /* access cached at, read-only */
  1289. #define ANHE_at_cache(he) (he).at = (he).w->at /* update at from watcher */
  1290. #else
  1291. /* a heap element */
  1292. typedef WT ANHE;
  1293. #define ANHE_w(he) (he)
  1294. #define ANHE_at(he) (he)->at
  1295. #define ANHE_at_cache(he)
  1296. #endif
  1297. #if EV_MULTIPLICITY
  1298. struct ev_loop
  1299. {
  1300. ev_tstamp ev_rt_now;
  1301. #define ev_rt_now ((loop)->ev_rt_now)
  1302. #define VAR(name,decl) decl;
  1303. #include "ev_vars.h"
  1304. #undef VAR
  1305. };
  1306. #include "ev_wrap.h"
  1307. static struct ev_loop default_loop_struct;
  1308. EV_API_DECL struct ev_loop *ev_default_loop_ptr = 0; /* needs to be initialised to make it a definition despite extern */
  1309. #else
  1310. EV_API_DECL ev_tstamp ev_rt_now = 0; /* needs to be initialised to make it a definition despite extern */
  1311. #define VAR(name,decl) static decl;
  1312. #include "ev_vars.h"
  1313. #undef VAR
  1314. static int ev_default_loop_ptr;
  1315. #endif
  1316. #if EV_FEATURE_API
  1317. # define EV_RELEASE_CB if (expect_false (release_cb)) release_cb (EV_A)
  1318. # define EV_ACQUIRE_CB if (expect_false (acquire_cb)) acquire_cb (EV_A)
  1319. # define EV_INVOKE_PENDING invoke_cb (EV_A)
  1320. #else
  1321. # define EV_RELEASE_CB (void)0
  1322. # define EV_ACQUIRE_CB (void)0
  1323. # define EV_INVOKE_PENDING ev_invoke_pending (EV_A)
  1324. #endif
  1325. #define EVBREAK_RECURSE 0x80
  1326. /*****************************************************************************/
  1327. #ifndef EV_HAVE_EV_TIME
  1328. ev_tstamp
  1329. ev_time (void) EV_THROW
  1330. {
  1331. #if EV_USE_REALTIME
  1332. if (expect_true (have_realtime))
  1333. {
  1334. struct timespec ts;
  1335. clock_gettime (CLOCK_REALTIME, &ts);
  1336. return ts.tv_sec + ts.tv_nsec * 1e-9;
  1337. }
  1338. #endif
  1339. struct timeval tv;
  1340. gettimeofday (&tv, 0);
  1341. return tv.tv_sec + tv.tv_usec * 1e-6;
  1342. }
  1343. #endif
  1344. inline_size ev_tstamp
  1345. get_clock (void)
  1346. {
  1347. #if EV_USE_MONOTONIC
  1348. if (expect_true (have_monotonic))
  1349. {
  1350. struct timespec ts;
  1351. clock_gettime (CLOCK_MONOTONIC, &ts);
  1352. return ts.tv_sec + ts.tv_nsec * 1e-9;
  1353. }
  1354. #endif
  1355. return ev_time ();
  1356. }
  1357. #if EV_MULTIPLICITY
  1358. ev_tstamp
  1359. ev_now (EV_P) EV_THROW
  1360. {
  1361. return ev_rt_now;
  1362. }
  1363. #endif
  1364. void
  1365. ev_sleep (ev_tstamp delay) EV_THROW
  1366. {
  1367. if (delay > 0.)
  1368. {
  1369. #if EV_USE_NANOSLEEP
  1370. struct timespec ts;
  1371. EV_TS_SET (ts, delay);
  1372. nanosleep (&ts, 0);
  1373. #elif defined _WIN32
  1374. Sleep ((unsigned long)(delay * 1e3));
  1375. #else
  1376. struct timeval tv;
  1377. /* here we rely on sys/time.h + sys/types.h + unistd.h providing select */
  1378. /* something not guaranteed by newer posix versions, but guaranteed */
  1379. /* by older ones */
  1380. EV_TV_SET (tv, delay);
  1381. select (0, 0, 0, 0, &tv);
  1382. #endif
  1383. }
  1384. }
  1385. /*****************************************************************************/
  1386. #define MALLOC_ROUND 4096 /* prefer to allocate in chunks of this size, must be 2**n and >> 4 longs */
  1387. /* find a suitable new size for the given array, */
  1388. /* hopefully by rounding to a nice-to-malloc size */
  1389. inline_size int
  1390. array_nextsize (int elem, int cur, int cnt)
  1391. {
  1392. int ncur = cur + 1;
  1393. do
  1394. ncur <<= 1;
  1395. while (cnt > ncur);
  1396. /* if size is large, round to MALLOC_ROUND - 4 * longs to accommodate malloc overhead */
  1397. if (elem * ncur > MALLOC_ROUND - sizeof (void *) * 4)
  1398. {
  1399. ncur *= elem;
  1400. ncur = (ncur + elem + (MALLOC_ROUND - 1) + sizeof (void *) * 4) & ~(MALLOC_ROUND - 1);
  1401. ncur = ncur - sizeof (void *) * 4;
  1402. ncur /= elem;
  1403. }
  1404. return ncur;
  1405. }
  1406. static void * noinline ecb_cold
  1407. array_realloc (int elem, void *base, int *cur, int cnt)
  1408. {
  1409. *cur = array_nextsize (elem, *cur, cnt);
  1410. return ev_realloc (base, elem * *cur);
  1411. }
  1412. #define array_init_zero(base,count) \
  1413. memset ((void *)(base), 0, sizeof (*(base)) * (count))
  1414. #define array_needsize(type,base,cur,cnt,init) \
  1415. if (expect_false ((cnt) > (cur))) \
  1416. { \
  1417. int ecb_unused ocur_ = (cur); \
  1418. (base) = (type *)array_realloc \
  1419. (sizeof (type), (base), &(cur), (cnt)); \
  1420. init ((base) + (ocur_), (cur) - ocur_); \
  1421. }
  1422. #if 0
  1423. #define array_slim(type,stem) \
  1424. if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
  1425. { \
  1426. stem ## max = array_roundsize (stem ## cnt >> 1); \
  1427. base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
  1428. fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
  1429. }
  1430. #endif
  1431. #define array_free(stem, idx) \
  1432. ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0; stem ## s idx = 0
  1433. /*****************************************************************************/
  1434. /* dummy callback for pending events */
  1435. static void noinline
  1436. pendingcb (EV_P_ ev_prepare *w, int revents)
  1437. {
  1438. }
  1439. void noinline
  1440. ev_feed_event (EV_P_ void *w, int revents) EV_THROW
  1441. {
  1442. W w_ = (W)w;
  1443. int pri = ABSPRI (w_);
  1444. if (expect_false (w_->pending))
  1445. pendings [pri][w_->pending - 1].events |= revents;
  1446. else
  1447. {
  1448. w_->pending = ++pendingcnt [pri];
  1449. array_needsize (ANPENDING, pendings [pri], pendingmax [pri], w_->pending, EMPTY2);
  1450. pendings [pri][w_->pending - 1].w = w_;
  1451. pendings [pri][w_->pending - 1].events = revents;
  1452. }
  1453. pendingpri = NUMPRI - 1;
  1454. }
  1455. inline_speed void
  1456. feed_reverse (EV_P_ W w)
  1457. {
  1458. array_needsize (W, rfeeds, rfeedmax, rfeedcnt + 1, EMPTY2);
  1459. rfeeds [rfeedcnt++] = w;
  1460. }
  1461. inline_size void
  1462. feed_reverse_done (EV_P_ int revents)
  1463. {
  1464. do
  1465. ev_feed_event (EV_A_ rfeeds [--rfeedcnt], revents);
  1466. while (rfeedcnt);
  1467. }
  1468. inline_speed void
  1469. queue_events (EV_P_ W *events, int eventcnt, int type)
  1470. {
  1471. int i;
  1472. for (i = 0; i < eventcnt; ++i)
  1473. ev_feed_event (EV_A_ events [i], type);
  1474. }
  1475. /*****************************************************************************/
  1476. inline_speed void
  1477. fd_event_nocheck (EV_P_ int fd, int revents)
  1478. {
  1479. ANFD *anfd = anfds + fd;
  1480. ev_io *w;
  1481. for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
  1482. {
  1483. int ev = w->events & revents;
  1484. if (ev)
  1485. ev_feed_event (EV_A_ (W)w, ev);
  1486. }
  1487. }
  1488. /* do not submit kernel events for fds that have reify set */
  1489. /* because that means they changed while we were polling for new events */
  1490. inline_speed void
  1491. fd_event (EV_P_ int fd, int revents)
  1492. {
  1493. ANFD *anfd = anfds + fd;
  1494. if (expect_true (!anfd->reify))
  1495. fd_event_nocheck (EV_A_ fd, revents);
  1496. }
  1497. void
  1498. ev_feed_fd_event (EV_P_ int fd, int revents) EV_THROW
  1499. {
  1500. if (fd >= 0 && fd < anfdmax)
  1501. fd_event_nocheck (EV_A_ fd, revents);
  1502. }
  1503. /* make sure the external fd watch events are in-sync */
  1504. /* with the kernel/libev internal state */
  1505. inline_size void
  1506. fd_reify (EV_P)
  1507. {
  1508. int i;
  1509. #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
  1510. for (i = 0; i < fdchangecnt; ++i)
  1511. {
  1512. int fd = fdchanges [i];
  1513. ANFD *anfd = anfds + fd;
  1514. if (anfd->reify & EV__IOFDSET && anfd->head)
  1515. {
  1516. SOCKET handle = EV_FD_TO_WIN32_HANDLE (fd);
  1517. if (handle != anfd->handle)
  1518. {
  1519. unsigned long arg;
  1520. assert (("libev: only socket fds supported in this configuration", ioctlsocket (handle, FIONREAD, &arg) == 0));
  1521. /* handle changed, but fd didn't - we need to do it in two steps */
  1522. backend_modify (EV_A_ fd, anfd->events, 0);
  1523. anfd->events = 0;
  1524. anfd->handle = handle;
  1525. }
  1526. }
  1527. }
  1528. #endif
  1529. for (i = 0; i < fdchangecnt; ++i)
  1530. {
  1531. int fd = fdchanges [i];
  1532. ANFD *anfd = anfds + fd;
  1533. ev_io *w;
  1534. unsigned char o_events = anfd->events;
  1535. unsigned char o_reify = anfd->reify;
  1536. anfd->reify = 0;
  1537. /*if (expect_true (o_reify & EV_ANFD_REIFY)) probably a deoptimisation */
  1538. {
  1539. anfd->events = 0;
  1540. for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
  1541. anfd->events |= (unsigned char)w->events;
  1542. if (o_events != anfd->events)
  1543. o_reify = EV__IOFDSET; /* actually |= */
  1544. }
  1545. if (o_reify & EV__IOFDSET)
  1546. backend_modify (EV_A_ fd, o_events, anfd->events);
  1547. }
  1548. fdchangecnt = 0;
  1549. }
  1550. /* something about the given fd changed */
  1551. inline_size void
  1552. fd_change (EV_P_ int fd, int flags)
  1553. {
  1554. unsigned char reify = anfds [fd].reify;
  1555. anfds [fd].reify |= flags;
  1556. if (expect_true (!reify))
  1557. {
  1558. ++fdchangecnt;
  1559. array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2);
  1560. fdchanges [fdchangecnt - 1] = fd;
  1561. }
  1562. }
  1563. /* the given fd is invalid/unusable, so make sure it doesn't hurt us anymore */
  1564. inline_speed void ecb_cold
  1565. fd_kill (EV_P_ int fd)
  1566. {
  1567. ev_io *w;
  1568. while ((w = (ev_io *)anfds [fd].head))
  1569. {
  1570. ev_io_stop (EV_A_ w);
  1571. ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
  1572. }
  1573. }
  1574. /* check whether the given fd is actually valid, for error recovery */
  1575. inline_size int ecb_cold
  1576. fd_valid (int fd)
  1577. {
  1578. #ifdef _WIN32
  1579. return EV_FD_TO_WIN32_HANDLE (fd) != -1;
  1580. #else
  1581. return fcntl (fd, F_GETFD) != -1;
  1582. #endif
  1583. }
  1584. /* called on EBADF to verify fds */
  1585. static void noinline ecb_cold
  1586. fd_ebadf (EV_P)
  1587. {
  1588. int fd;
  1589. for (fd = 0; fd < anfdmax; ++fd)
  1590. if (anfds [fd].events)
  1591. if (!fd_valid (fd) && errno == EBADF)
  1592. fd_kill (EV_A_ fd);
  1593. }
  1594. /* called on ENOMEM in select/poll to kill some fds and retry */
  1595. static void noinline ecb_cold
  1596. fd_enomem (EV_P)
  1597. {
  1598. int fd;
  1599. for (fd = anfdmax; fd--; )
  1600. if (anfds [fd].events)
  1601. {
  1602. fd_kill (EV_A_ fd);
  1603. break;
  1604. }
  1605. }
  1606. /* usually called after fork if backend needs to re-arm all fds from scratch */
  1607. static void noinline
  1608. fd_rearm_all (EV_P)
  1609. {
  1610. int fd;
  1611. for (fd = 0; fd < anfdmax; ++fd)
  1612. if (anfds [fd].events)
  1613. {
  1614. anfds [fd].events = 0;
  1615. anfds [fd].emask = 0;
  1616. fd_change (EV_A_ fd, EV__IOFDSET | EV_ANFD_REIFY);
  1617. }
  1618. }
  1619. /* used to prepare libev internal fd's */
  1620. /* this is not fork-safe */
  1621. inline_speed void
  1622. fd_intern (int fd)
  1623. {
  1624. #ifdef _WIN32
  1625. unsigned long arg = 1;
  1626. ioctlsocket (EV_FD_TO_WIN32_HANDLE (fd), FIONBIO, &arg);
  1627. #else
  1628. fcntl (fd, F_SETFD, FD_CLOEXEC);
  1629. fcntl (fd, F_SETFL, O_NONBLOCK);
  1630. #endif
  1631. }
  1632. /*****************************************************************************/
  1633. /*
  1634. * the heap functions want a real array index. array index 0 is guaranteed to not
  1635. * be in-use at any time. the first heap entry is at array [HEAP0]. DHEAP gives
  1636. * the branching factor of the d-tree.
  1637. */
  1638. /*
  1639. * at the moment we allow libev the luxury of two heaps,
  1640. * a small-code-size 2-heap one and a ~1.5kb larger 4-heap
  1641. * which is more cache-efficient.
  1642. * the difference is about 5% with 50000+ watchers.
  1643. */
  1644. #if EV_USE_4HEAP
  1645. #define DHEAP 4
  1646. #define HEAP0 (DHEAP - 1) /* index of first element in heap */
  1647. #define HPARENT(k) ((((k) - HEAP0 - 1) / DHEAP) + HEAP0)
  1648. #define UPHEAP_DONE(p,k) ((p) == (k))
  1649. /* away from the root */
  1650. inline_speed void
  1651. downheap (ANHE *heap, int N, int k)
  1652. {
  1653. ANHE he = heap [k];
  1654. ANHE *E = heap + N + HEAP0;
  1655. for (;;)
  1656. {
  1657. ev_tstamp minat;
  1658. ANHE *minpos;
  1659. ANHE *pos = heap + DHEAP * (k - HEAP0) + HEAP0 + 1;
  1660. /* find minimum child */
  1661. if (expect_true (pos + DHEAP - 1 < E))
  1662. {
  1663. /* fast path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
  1664. if ( ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos));
  1665. if ( ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos));
  1666. if ( ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos));
  1667. }
  1668. else if (pos < E)
  1669. {
  1670. /* slow path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
  1671. if (pos + 1 < E && ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos));
  1672. if (pos + 2 < E && ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos));
  1673. if (pos + 3 < E && ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos));
  1674. }
  1675. else
  1676. break;
  1677. if (ANHE_at (he) <= minat)
  1678. break;
  1679. heap [k] = *minpos;
  1680. ev_active (ANHE_w (*minpos)) = k;
  1681. k = minpos - heap;
  1682. }
  1683. heap [k] = he;
  1684. ev_active (ANHE_w (he)) = k;
  1685. }
  1686. #else /* 4HEAP */
  1687. #define HEAP0 1
  1688. #define HPARENT(k) ((k) >> 1)
  1689. #define UPHEAP_DONE(p,k) (!(p))
  1690. /* away from the root */
  1691. inline_speed void
  1692. downheap (ANHE *heap, int N, int k)
  1693. {
  1694. ANHE he = heap [k];
  1695. for (;;)
  1696. {
  1697. int c = k << 1;
  1698. if (c >= N + HEAP0)
  1699. break;
  1700. c += c + 1 < N + HEAP0 && ANHE_at (heap [c]) > ANHE_at (heap [c + 1])
  1701. ? 1 : 0;
  1702. if (ANHE_at (he) <= ANHE_at (heap [c]))
  1703. break;
  1704. heap [k] = heap [c];
  1705. ev_active (ANHE_w (heap [k])) = k;
  1706. k = c;
  1707. }
  1708. heap [k] = he;
  1709. ev_active (ANHE_w (he)) = k;
  1710. }
  1711. #endif
  1712. /* towards the root */
  1713. inline_speed void
  1714. upheap (ANHE *heap, int k)
  1715. {
  1716. ANHE he = heap [k];
  1717. for (;;)
  1718. {
  1719. int p = HPARENT (k);
  1720. if (UPHEAP_DONE (p, k) || ANHE_at (heap [p]) <= ANHE_at (he))
  1721. break;
  1722. heap [k] = heap [p];
  1723. ev_active (ANHE_w (heap [k])) = k;
  1724. k = p;
  1725. }
  1726. heap [k] = he;
  1727. ev_active (ANHE_w (he)) = k;
  1728. }
  1729. /* move an element suitably so it is in a correct place */
  1730. inline_size void
  1731. adjustheap (ANHE *heap, int N, int k)
  1732. {
  1733. if (k > HEAP0 && ANHE_at (heap [k]) <= ANHE_at (heap [HPARENT (k)]))
  1734. upheap (heap, k);
  1735. else
  1736. downheap (heap, N, k);
  1737. }
  1738. /* rebuild the heap: this function is used only once and executed rarely */
  1739. inline_size void
  1740. reheap (ANHE *heap, int N)
  1741. {
  1742. int i;
  1743. /* we don't use floyds algorithm, upheap is simpler and is more cache-efficient */
  1744. /* also, this is easy to implement and correct for both 2-heaps and 4-heaps */
  1745. for (i = 0; i < N; ++i)
  1746. upheap (heap, i + HEAP0);
  1747. }
  1748. /*****************************************************************************/
  1749. /* associate signal watchers to a signal signal */
  1750. typedef struct
  1751. {
  1752. EV_ATOMIC_T pending;
  1753. #if EV_MULTIPLICITY
  1754. EV_P;
  1755. #endif
  1756. WL head;
  1757. } ANSIG;
  1758. static ANSIG signals [EV_NSIG - 1];
  1759. /*****************************************************************************/
  1760. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  1761. static void noinline ecb_cold
  1762. evpipe_init (EV_P)
  1763. {
  1764. if (!ev_is_active (&pipe_w))
  1765. {
  1766. int fds [2];
  1767. # if EV_USE_EVENTFD
  1768. fds [0] = -1;
  1769. fds [1] = eventfd (0, EFD_NONBLOCK | EFD_CLOEXEC);
  1770. if (fds [1] < 0 && errno == EINVAL)
  1771. fds [1] = eventfd (0, 0);
  1772. if (fds [1] < 0)
  1773. # endif
  1774. {
  1775. while (pipe (fds))
  1776. ev_syserr ("(libev) error creating signal/async pipe");
  1777. fd_intern (fds [0]);
  1778. }
  1779. fd_intern (fds [1]);
  1780. evpipe [0] = fds [0];
  1781. if (evpipe [1] < 0)
  1782. evpipe [1] = fds [1]; /* first call, set write fd */
  1783. else
  1784. {
  1785. /* on subsequent calls, do not change evpipe [1] */
  1786. /* so that evpipe_write can always rely on its value. */
  1787. /* this branch does not do anything sensible on windows, */
  1788. /* so must not be executed on windows */
  1789. dup2 (fds [1], evpipe [1]);
  1790. close (fds [1]);
  1791. }
  1792. ev_io_set (&pipe_w, evpipe [0] < 0 ? evpipe [1] : evpipe [0], EV_READ);
  1793. ev_io_start (EV_A_ &pipe_w);
  1794. ev_unref (EV_A); /* watcher should not keep loop alive */
  1795. }
  1796. }
  1797. inline_speed void
  1798. evpipe_write (EV_P_ EV_ATOMIC_T *flag)
  1799. {
  1800. ECB_MEMORY_FENCE; /* push out the write before this function was called, acquire flag */
  1801. if (expect_true (*flag))
  1802. return;
  1803. *flag = 1;
  1804. ECB_MEMORY_FENCE_RELEASE; /* make sure flag is visible before the wakeup */
  1805. pipe_write_skipped = 1;
  1806. ECB_MEMORY_FENCE; /* make sure pipe_write_skipped is visible before we check pipe_write_wanted */
  1807. if (pipe_write_wanted)
  1808. {
  1809. int old_errno;
  1810. pipe_write_skipped = 0;
  1811. ECB_MEMORY_FENCE_RELEASE;
  1812. old_errno = errno; /* save errno because write will clobber it */
  1813. #if EV_USE_EVENTFD
  1814. if (evpipe [0] < 0)
  1815. {
  1816. uint64_t counter = 1;
  1817. write (evpipe [1], &counter, sizeof (uint64_t));
  1818. }
  1819. else
  1820. #endif
  1821. {
  1822. #ifdef _WIN32
  1823. WSABUF buf;
  1824. DWORD sent;
  1825. buf.buf = &buf;
  1826. buf.len = 1;
  1827. WSASend (EV_FD_TO_WIN32_HANDLE (evpipe [1]), &buf, 1, &sent, 0, 0, 0);
  1828. #else
  1829. write (evpipe [1], &(evpipe [1]), 1);
  1830. #endif
  1831. }
  1832. errno = old_errno;
  1833. }
  1834. }
  1835. /* called whenever the libev signal pipe */
  1836. /* got some events (signal, async) */
  1837. static void
  1838. pipecb (EV_P_ ev_io *iow, int revents)
  1839. {
  1840. int i;
  1841. if (revents & EV_READ)
  1842. {
  1843. #if EV_USE_EVENTFD
  1844. if (evpipe [0] < 0)
  1845. {
  1846. uint64_t counter;
  1847. read (evpipe [1], &counter, sizeof (uint64_t));
  1848. }
  1849. else
  1850. #endif
  1851. {
  1852. char dummy[4];
  1853. #ifdef _WIN32
  1854. WSABUF buf;
  1855. DWORD recvd;
  1856. DWORD flags = 0;
  1857. buf.buf = dummy;
  1858. buf.len = sizeof (dummy);
  1859. WSARecv (EV_FD_TO_WIN32_HANDLE (evpipe [0]), &buf, 1, &recvd, &flags, 0, 0);
  1860. #else
  1861. read (evpipe [0], &dummy, sizeof (dummy));
  1862. #endif
  1863. }
  1864. }
  1865. pipe_write_skipped = 0;
  1866. ECB_MEMORY_FENCE; /* push out skipped, acquire flags */
  1867. #if EV_SIGNAL_ENABLE
  1868. if (sig_pending)
  1869. {
  1870. sig_pending = 0;
  1871. ECB_MEMORY_FENCE;
  1872. for (i = EV_NSIG - 1; i--; )
  1873. if (expect_false (signals [i].pending))
  1874. ev_feed_signal_event (EV_A_ i + 1);
  1875. }
  1876. #endif
  1877. #if EV_ASYNC_ENABLE
  1878. if (async_pending)
  1879. {
  1880. async_pending = 0;
  1881. ECB_MEMORY_FENCE;
  1882. for (i = asynccnt; i--; )
  1883. if (asyncs [i]->sent)
  1884. {
  1885. asyncs [i]->sent = 0;
  1886. ECB_MEMORY_FENCE_RELEASE;
  1887. ev_feed_event (EV_A_ asyncs [i], EV_ASYNC);
  1888. }
  1889. }
  1890. #endif
  1891. }
  1892. /*****************************************************************************/
  1893. void
  1894. ev_feed_signal (int signum) EV_THROW
  1895. {
  1896. #if EV_MULTIPLICITY
  1897. EV_P;
  1898. ECB_MEMORY_FENCE_ACQUIRE;
  1899. EV_A = signals [signum - 1].loop;
  1900. if (!EV_A)
  1901. return;
  1902. #endif
  1903. signals [signum - 1].pending = 1;
  1904. evpipe_write (EV_A_ &sig_pending);
  1905. }
  1906. static void
  1907. ev_sighandler (int signum)
  1908. {
  1909. #ifdef _WIN32
  1910. signal (signum, ev_sighandler);
  1911. #endif
  1912. ev_feed_signal (signum);
  1913. }
  1914. void noinline
  1915. ev_feed_signal_event (EV_P_ int signum) EV_THROW
  1916. {
  1917. WL w;
  1918. if (expect_false (signum <= 0 || signum >= EV_NSIG))
  1919. return;
  1920. --signum;
  1921. #if EV_MULTIPLICITY
  1922. /* it is permissible to try to feed a signal to the wrong loop */
  1923. /* or, likely more useful, feeding a signal nobody is waiting for */
  1924. if (expect_false (signals [signum].loop != EV_A))
  1925. return;
  1926. #endif
  1927. signals [signum].pending = 0;
  1928. ECB_MEMORY_FENCE_RELEASE;
  1929. for (w = signals [signum].head; w; w = w->next)
  1930. ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
  1931. }
  1932. #if EV_USE_SIGNALFD
  1933. static void
  1934. sigfdcb (EV_P_ ev_io *iow, int revents)
  1935. {
  1936. struct signalfd_siginfo si[2], *sip; /* these structs are big */
  1937. for (;;)
  1938. {
  1939. ssize_t res = read (sigfd, si, sizeof (si));
  1940. /* not ISO-C, as res might be -1, but works with SuS */
  1941. for (sip = si; (char *)sip < (char *)si + res; ++sip)
  1942. ev_feed_signal_event (EV_A_ sip->ssi_signo);
  1943. if (res < (ssize_t)sizeof (si))
  1944. break;
  1945. }
  1946. }
  1947. #endif
  1948. #endif
  1949. /*****************************************************************************/
  1950. #if EV_CHILD_ENABLE
  1951. static WL childs [EV_PID_HASHSIZE];
  1952. static ev_signal childev;
  1953. #ifndef WIFCONTINUED
  1954. # define WIFCONTINUED(status) 0
  1955. #endif
  1956. /* handle a single child status event */
  1957. inline_speed void
  1958. child_reap (EV_P_ int chain, int pid, int status)
  1959. {
  1960. ev_child *w;
  1961. int traced = WIFSTOPPED (status) || WIFCONTINUED (status);
  1962. for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
  1963. {
  1964. if ((w->pid == pid || !w->pid)
  1965. && (!traced || (w->flags & 1)))
  1966. {
  1967. ev_set_priority (w, EV_MAXPRI); /* need to do it *now*, this *must* be the same prio as the signal watcher itself */
  1968. w->rpid = pid;
  1969. w->rstatus = status;
  1970. ev_feed_event (EV_A_ (W)w, EV_CHILD);
  1971. }
  1972. }
  1973. }
  1974. #ifndef WCONTINUED
  1975. # define WCONTINUED 0
  1976. #endif
  1977. /* called on sigchld etc., calls waitpid */
  1978. static void
  1979. childcb (EV_P_ ev_signal *sw, int revents)
  1980. {
  1981. int pid, status;
  1982. /* some systems define WCONTINUED but then fail to support it (linux 2.4) */
  1983. if (0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
  1984. if (!WCONTINUED
  1985. || errno != EINVAL
  1986. || 0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED)))
  1987. return;
  1988. /* make sure we are called again until all children have been reaped */
  1989. /* we need to do it this way so that the callback gets called before we continue */
  1990. ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
  1991. child_reap (EV_A_ pid, pid, status);
  1992. if ((EV_PID_HASHSIZE) > 1)
  1993. child_reap (EV_A_ 0, pid, status); /* this might trigger a watcher twice, but feed_event catches that */
  1994. }
  1995. #endif
  1996. /*****************************************************************************/
  1997. #if EV_USE_IOCP
  1998. # include "ev_iocp.c"
  1999. #endif
  2000. #if EV_USE_PORT
  2001. # include "ev_port.c"
  2002. #endif
  2003. #if EV_USE_KQUEUE
  2004. # include "ev_kqueue.c"
  2005. #endif
  2006. #if EV_USE_EPOLL
  2007. # include "ev_epoll.c"
  2008. #endif
  2009. #if EV_USE_POLL
  2010. # include "ev_poll.c"
  2011. #endif
  2012. #if EV_USE_SELECT
  2013. # include "ev_select.c"
  2014. #endif
  2015. int ecb_cold
  2016. ev_version_major (void) EV_THROW
  2017. {
  2018. return EV_VERSION_MAJOR;
  2019. }
  2020. int ecb_cold
  2021. ev_version_minor (void) EV_THROW
  2022. {
  2023. return EV_VERSION_MINOR;
  2024. }
  2025. /* return true if we are running with elevated privileges and should ignore env variables */
  2026. int inline_size ecb_cold
  2027. enable_secure (void)
  2028. {
  2029. #ifdef _WIN32
  2030. return 0;
  2031. #else
  2032. return getuid () != geteuid ()
  2033. || getgid () != getegid ();
  2034. #endif
  2035. }
  2036. unsigned int ecb_cold
  2037. ev_supported_backends (void) EV_THROW
  2038. {
  2039. unsigned int flags = 0;
  2040. if (EV_USE_PORT ) flags |= EVBACKEND_PORT;
  2041. if (EV_USE_KQUEUE) flags |= EVBACKEND_KQUEUE;
  2042. if (EV_USE_EPOLL ) flags |= EVBACKEND_EPOLL;
  2043. if (EV_USE_POLL ) flags |= EVBACKEND_POLL;
  2044. if (EV_USE_SELECT) flags |= EVBACKEND_SELECT;
  2045. return flags;
  2046. }
  2047. unsigned int ecb_cold
  2048. ev_recommended_backends (void) EV_THROW
  2049. {
  2050. unsigned int flags = ev_supported_backends ();
  2051. #ifndef __NetBSD__
  2052. /* kqueue is borked on everything but netbsd apparently */
  2053. /* it usually doesn't work correctly on anything but sockets and pipes */
  2054. flags &= ~EVBACKEND_KQUEUE;
  2055. #endif
  2056. #ifdef __APPLE__
  2057. /* only select works correctly on that "unix-certified" platform */
  2058. flags &= ~EVBACKEND_KQUEUE; /* horribly broken, even for sockets */
  2059. flags &= ~EVBACKEND_POLL; /* poll is based on kqueue from 10.5 onwards */
  2060. #endif
  2061. #ifdef __FreeBSD__
  2062. flags &= ~EVBACKEND_POLL; /* poll return value is unusable (http://forums.freebsd.org/archive/index.php/t-10270.html) */
  2063. #endif
  2064. return flags;
  2065. }
  2066. unsigned int ecb_cold
  2067. ev_embeddable_backends (void) EV_THROW
  2068. {
  2069. int flags = EVBACKEND_EPOLL | EVBACKEND_KQUEUE | EVBACKEND_PORT;
  2070. /* epoll embeddability broken on all linux versions up to at least 2.6.23 */
  2071. if (ev_linux_version () < 0x020620) /* disable it on linux < 2.6.32 */
  2072. flags &= ~EVBACKEND_EPOLL;
  2073. return flags;
  2074. }
  2075. unsigned int
  2076. ev_backend (EV_P) EV_THROW
  2077. {
  2078. return backend;
  2079. }
  2080. #if EV_FEATURE_API
  2081. unsigned int
  2082. ev_iteration (EV_P) EV_THROW
  2083. {
  2084. return loop_count;
  2085. }
  2086. unsigned int
  2087. ev_depth (EV_P) EV_THROW
  2088. {
  2089. return loop_depth;
  2090. }
  2091. void
  2092. ev_set_io_collect_interval (EV_P_ ev_tstamp interval) EV_THROW
  2093. {
  2094. io_blocktime = interval;
  2095. }
  2096. void
  2097. ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval) EV_THROW
  2098. {
  2099. timeout_blocktime = interval;
  2100. }
  2101. void
  2102. ev_set_userdata (EV_P_ void *data) EV_THROW
  2103. {
  2104. userdata = data;
  2105. }
  2106. void *
  2107. ev_userdata (EV_P) EV_THROW
  2108. {
  2109. return userdata;
  2110. }
  2111. void
  2112. ev_set_invoke_pending_cb (EV_P_ void (*invoke_pending_cb)(EV_P)) EV_THROW
  2113. {
  2114. invoke_cb = invoke_pending_cb;
  2115. }
  2116. void
  2117. ev_set_loop_release_cb (EV_P_ void (*release)(EV_P) EV_THROW, void (*acquire)(EV_P) EV_THROW) EV_THROW
  2118. {
  2119. release_cb = release;
  2120. acquire_cb = acquire;
  2121. }
  2122. #endif
  2123. /* initialise a loop structure, must be zero-initialised */
  2124. static void noinline ecb_cold
  2125. loop_init (EV_P_ unsigned int flags) EV_THROW
  2126. {
  2127. if (!backend)
  2128. {
  2129. origflags = flags;
  2130. #if EV_USE_REALTIME
  2131. if (!have_realtime)
  2132. {
  2133. struct timespec ts;
  2134. if (!clock_gettime (CLOCK_REALTIME, &ts))
  2135. have_realtime = 1;
  2136. }
  2137. #endif
  2138. #if EV_USE_MONOTONIC
  2139. if (!have_monotonic)
  2140. {
  2141. struct timespec ts;
  2142. if (!clock_gettime (CLOCK_MONOTONIC, &ts))
  2143. have_monotonic = 1;
  2144. }
  2145. #endif
  2146. /* pid check not overridable via env */
  2147. #ifndef _WIN32
  2148. if (flags & EVFLAG_FORKCHECK)
  2149. curpid = getpid ();
  2150. #endif
  2151. if (!(flags & EVFLAG_NOENV)
  2152. && !enable_secure ()
  2153. && getenv ("LIBEV_FLAGS"))
  2154. flags = atoi (getenv ("LIBEV_FLAGS"));
  2155. ev_rt_now = ev_time ();
  2156. mn_now = get_clock ();
  2157. now_floor = mn_now;
  2158. rtmn_diff = ev_rt_now - mn_now;
  2159. #if EV_FEATURE_API
  2160. invoke_cb = ev_invoke_pending;
  2161. #endif
  2162. io_blocktime = 0.;
  2163. timeout_blocktime = 0.;
  2164. backend = 0;
  2165. backend_fd = -1;
  2166. sig_pending = 0;
  2167. #if EV_ASYNC_ENABLE
  2168. async_pending = 0;
  2169. #endif
  2170. pipe_write_skipped = 0;
  2171. pipe_write_wanted = 0;
  2172. evpipe [0] = -1;
  2173. evpipe [1] = -1;
  2174. #if EV_USE_INOTIFY
  2175. fs_fd = flags & EVFLAG_NOINOTIFY ? -1 : -2;
  2176. #endif
  2177. #if EV_USE_SIGNALFD
  2178. sigfd = flags & EVFLAG_SIGNALFD ? -2 : -1;
  2179. #endif
  2180. if (!(flags & EVBACKEND_MASK))
  2181. flags |= ev_recommended_backends ();
  2182. #if EV_USE_IOCP
  2183. if (!backend && (flags & EVBACKEND_IOCP )) backend = iocp_init (EV_A_ flags);
  2184. #endif
  2185. #if EV_USE_PORT
  2186. if (!backend && (flags & EVBACKEND_PORT )) backend = port_init (EV_A_ flags);
  2187. #endif
  2188. #if EV_USE_KQUEUE
  2189. if (!backend && (flags & EVBACKEND_KQUEUE)) backend = kqueue_init (EV_A_ flags);
  2190. #endif
  2191. #if EV_USE_EPOLL
  2192. if (!backend && (flags & EVBACKEND_EPOLL )) backend = epoll_init (EV_A_ flags);
  2193. #endif
  2194. #if EV_USE_POLL
  2195. if (!backend && (flags & EVBACKEND_POLL )) backend = poll_init (EV_A_ flags);
  2196. #endif
  2197. #if EV_USE_SELECT
  2198. if (!backend && (flags & EVBACKEND_SELECT)) backend = select_init (EV_A_ flags);
  2199. #endif
  2200. ev_prepare_init (&pending_w, pendingcb);
  2201. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  2202. ev_init (&pipe_w, pipecb);
  2203. ev_set_priority (&pipe_w, EV_MAXPRI);
  2204. #endif
  2205. }
  2206. }
  2207. /* free up a loop structure */
  2208. void ecb_cold
  2209. ev_loop_destroy (EV_P)
  2210. {
  2211. int i;
  2212. #if EV_MULTIPLICITY
  2213. /* mimic free (0) */
  2214. if (!EV_A)
  2215. return;
  2216. #endif
  2217. #if EV_CLEANUP_ENABLE
  2218. /* queue cleanup watchers (and execute them) */
  2219. if (expect_false (cleanupcnt))
  2220. {
  2221. queue_events (EV_A_ (W *)cleanups, cleanupcnt, EV_CLEANUP);
  2222. EV_INVOKE_PENDING;
  2223. }
  2224. #endif
  2225. #if EV_CHILD_ENABLE
  2226. if (ev_is_default_loop (EV_A) && ev_is_active (&childev))
  2227. {
  2228. ev_ref (EV_A); /* child watcher */
  2229. ev_signal_stop (EV_A_ &childev);
  2230. }
  2231. #endif
  2232. if (ev_is_active (&pipe_w))
  2233. {
  2234. /*ev_ref (EV_A);*/
  2235. /*ev_io_stop (EV_A_ &pipe_w);*/
  2236. if (evpipe [0] >= 0) EV_WIN32_CLOSE_FD (evpipe [0]);
  2237. if (evpipe [1] >= 0) EV_WIN32_CLOSE_FD (evpipe [1]);
  2238. }
  2239. #if EV_USE_SIGNALFD
  2240. if (ev_is_active (&sigfd_w))
  2241. close (sigfd);
  2242. #endif
  2243. #if EV_USE_INOTIFY
  2244. if (fs_fd >= 0)
  2245. close (fs_fd);
  2246. #endif
  2247. if (backend_fd >= 0)
  2248. close (backend_fd);
  2249. #if EV_USE_IOCP
  2250. if (backend == EVBACKEND_IOCP ) iocp_destroy (EV_A);
  2251. #endif
  2252. #if EV_USE_PORT
  2253. if (backend == EVBACKEND_PORT ) port_destroy (EV_A);
  2254. #endif
  2255. #if EV_USE_KQUEUE
  2256. if (backend == EVBACKEND_KQUEUE) kqueue_destroy (EV_A);
  2257. #endif
  2258. #if EV_USE_EPOLL
  2259. if (backend == EVBACKEND_EPOLL ) epoll_destroy (EV_A);
  2260. #endif
  2261. #if EV_USE_POLL
  2262. if (backend == EVBACKEND_POLL ) poll_destroy (EV_A);
  2263. #endif
  2264. #if EV_USE_SELECT
  2265. if (backend == EVBACKEND_SELECT) select_destroy (EV_A);
  2266. #endif
  2267. for (i = NUMPRI; i--; )
  2268. {
  2269. array_free (pending, [i]);
  2270. #if EV_IDLE_ENABLE
  2271. array_free (idle, [i]);
  2272. #endif
  2273. }
  2274. ev_free (anfds); anfds = 0; anfdmax = 0;
  2275. /* have to use the microsoft-never-gets-it-right macro */
  2276. array_free (rfeed, EMPTY);
  2277. array_free (fdchange, EMPTY);
  2278. array_free (timer, EMPTY);
  2279. #if EV_PERIODIC_ENABLE
  2280. array_free (periodic, EMPTY);
  2281. #endif
  2282. #if EV_FORK_ENABLE
  2283. array_free (fork, EMPTY);
  2284. #endif
  2285. #if EV_CLEANUP_ENABLE
  2286. array_free (cleanup, EMPTY);
  2287. #endif
  2288. array_free (prepare, EMPTY);
  2289. array_free (check, EMPTY);
  2290. #if EV_ASYNC_ENABLE
  2291. array_free (async, EMPTY);
  2292. #endif
  2293. backend = 0;
  2294. #if EV_MULTIPLICITY
  2295. if (ev_is_default_loop (EV_A))
  2296. #endif
  2297. ev_default_loop_ptr = 0;
  2298. #if EV_MULTIPLICITY
  2299. else
  2300. ev_free (EV_A);
  2301. #endif
  2302. }
  2303. #if EV_USE_INOTIFY
  2304. inline_size void infy_fork (EV_P);
  2305. #endif
  2306. inline_size void
  2307. loop_fork (EV_P)
  2308. {
  2309. #if EV_USE_PORT
  2310. if (backend == EVBACKEND_PORT ) port_fork (EV_A);
  2311. #endif
  2312. #if EV_USE_KQUEUE
  2313. if (backend == EVBACKEND_KQUEUE) kqueue_fork (EV_A);
  2314. #endif
  2315. #if EV_USE_EPOLL
  2316. if (backend == EVBACKEND_EPOLL ) epoll_fork (EV_A);
  2317. #endif
  2318. #if EV_USE_INOTIFY
  2319. infy_fork (EV_A);
  2320. #endif
  2321. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  2322. if (ev_is_active (&pipe_w))
  2323. {
  2324. /* pipe_write_wanted must be false now, so modifying fd vars should be safe */
  2325. ev_ref (EV_A);
  2326. ev_io_stop (EV_A_ &pipe_w);
  2327. if (evpipe [0] >= 0)
  2328. EV_WIN32_CLOSE_FD (evpipe [0]);
  2329. evpipe_init (EV_A);
  2330. /* iterate over everything, in case we missed something before */
  2331. ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM);
  2332. }
  2333. #endif
  2334. postfork = 0;
  2335. }
  2336. #if EV_MULTIPLICITY
  2337. struct ev_loop * ecb_cold
  2338. ev_loop_new (unsigned int flags) EV_THROW
  2339. {
  2340. EV_P = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
  2341. memset (EV_A, 0, sizeof (struct ev_loop));
  2342. loop_init (EV_A_ flags);
  2343. if (ev_backend (EV_A))
  2344. return EV_A;
  2345. ev_free (EV_A);
  2346. return 0;
  2347. }
  2348. #endif /* multiplicity */
  2349. #if EV_VERIFY
  2350. static void noinline ecb_cold
  2351. verify_watcher (EV_P_ W w)
  2352. {
  2353. assert (("libev: watcher has invalid priority", ABSPRI (w) >= 0 && ABSPRI (w) < NUMPRI));
  2354. if (w->pending)
  2355. assert (("libev: pending watcher not on pending queue", pendings [ABSPRI (w)][w->pending - 1].w == w));
  2356. }
  2357. static void noinline ecb_cold
  2358. verify_heap (EV_P_ ANHE *heap, int N)
  2359. {
  2360. int i;
  2361. for (i = HEAP0; i < N + HEAP0; ++i)
  2362. {
  2363. assert (("libev: active index mismatch in heap", ev_active (ANHE_w (heap [i])) == i));
  2364. assert (("libev: heap condition violated", i == HEAP0 || ANHE_at (heap [HPARENT (i)]) <= ANHE_at (heap [i])));
  2365. assert (("libev: heap at cache mismatch", ANHE_at (heap [i]) == ev_at (ANHE_w (heap [i]))));
  2366. verify_watcher (EV_A_ (W)ANHE_w (heap [i]));
  2367. }
  2368. }
  2369. static void noinline ecb_cold
  2370. array_verify (EV_P_ W *ws, int cnt)
  2371. {
  2372. while (cnt--)
  2373. {
  2374. assert (("libev: active index mismatch", ev_active (ws [cnt]) == cnt + 1));
  2375. verify_watcher (EV_A_ ws [cnt]);
  2376. }
  2377. }
  2378. #endif
  2379. #if EV_FEATURE_API
  2380. void ecb_cold
  2381. ev_verify (EV_P) EV_THROW
  2382. {
  2383. #if EV_VERIFY
  2384. int i;
  2385. WL w, w2;
  2386. assert (activecnt >= -1);
  2387. assert (fdchangemax >= fdchangecnt);
  2388. for (i = 0; i < fdchangecnt; ++i)
  2389. assert (("libev: negative fd in fdchanges", fdchanges [i] >= 0));
  2390. assert (anfdmax >= 0);
  2391. for (i = 0; i < anfdmax; ++i)
  2392. {
  2393. int j = 0;
  2394. for (w = w2 = anfds [i].head; w; w = w->next)
  2395. {
  2396. verify_watcher (EV_A_ (W)w);
  2397. if (j++ & 1)
  2398. {
  2399. assert (("libev: io watcher list contains a loop", w != w2));
  2400. w2 = w2->next;
  2401. }
  2402. assert (("libev: inactive fd watcher on anfd list", ev_active (w) == 1));
  2403. assert (("libev: fd mismatch between watcher and anfd", ((ev_io *)w)->fd == i));
  2404. }
  2405. }
  2406. assert (timermax >= timercnt);
  2407. verify_heap (EV_A_ timers, timercnt);
  2408. #if EV_PERIODIC_ENABLE
  2409. assert (periodicmax >= periodiccnt);
  2410. verify_heap (EV_A_ periodics, periodiccnt);
  2411. #endif
  2412. for (i = NUMPRI; i--; )
  2413. {
  2414. assert (pendingmax [i] >= pendingcnt [i]);
  2415. #if EV_IDLE_ENABLE
  2416. assert (idleall >= 0);
  2417. assert (idlemax [i] >= idlecnt [i]);
  2418. array_verify (EV_A_ (W *)idles [i], idlecnt [i]);
  2419. #endif
  2420. }
  2421. #if EV_FORK_ENABLE
  2422. assert (forkmax >= forkcnt);
  2423. array_verify (EV_A_ (W *)forks, forkcnt);
  2424. #endif
  2425. #if EV_CLEANUP_ENABLE
  2426. assert (cleanupmax >= cleanupcnt);
  2427. array_verify (EV_A_ (W *)cleanups, cleanupcnt);
  2428. #endif
  2429. #if EV_ASYNC_ENABLE
  2430. assert (asyncmax >= asynccnt);
  2431. array_verify (EV_A_ (W *)asyncs, asynccnt);
  2432. #endif
  2433. #if EV_PREPARE_ENABLE
  2434. assert (preparemax >= preparecnt);
  2435. array_verify (EV_A_ (W *)prepares, preparecnt);
  2436. #endif
  2437. #if EV_CHECK_ENABLE
  2438. assert (checkmax >= checkcnt);
  2439. array_verify (EV_A_ (W *)checks, checkcnt);
  2440. #endif
  2441. # if 0
  2442. #if EV_CHILD_ENABLE
  2443. for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
  2444. for (signum = EV_NSIG; signum--; ) if (signals [signum].pending)
  2445. #endif
  2446. # endif
  2447. #endif
  2448. }
  2449. #endif
  2450. #if EV_MULTIPLICITY
  2451. struct ev_loop * ecb_cold
  2452. #else
  2453. int
  2454. #endif
  2455. ev_default_loop (unsigned int flags) EV_THROW
  2456. {
  2457. if (!ev_default_loop_ptr)
  2458. {
  2459. #if EV_MULTIPLICITY
  2460. EV_P = ev_default_loop_ptr = &default_loop_struct;
  2461. #else
  2462. ev_default_loop_ptr = 1;
  2463. #endif
  2464. loop_init (EV_A_ flags);
  2465. if (ev_backend (EV_A))
  2466. {
  2467. #if EV_CHILD_ENABLE
  2468. ev_signal_init (&childev, childcb, SIGCHLD);
  2469. ev_set_priority (&childev, EV_MAXPRI);
  2470. ev_signal_start (EV_A_ &childev);
  2471. ev_unref (EV_A); /* child watcher should not keep loop alive */
  2472. #endif
  2473. }
  2474. else
  2475. ev_default_loop_ptr = 0;
  2476. }
  2477. return ev_default_loop_ptr;
  2478. }
  2479. void
  2480. ev_loop_fork (EV_P) EV_THROW
  2481. {
  2482. postfork = 1;
  2483. }
  2484. /*****************************************************************************/
  2485. void
  2486. ev_invoke (EV_P_ void *w, int revents)
  2487. {
  2488. EV_CB_INVOKE ((W)w, revents);
  2489. }
  2490. unsigned int
  2491. ev_pending_count (EV_P) EV_THROW
  2492. {
  2493. int pri;
  2494. unsigned int count = 0;
  2495. for (pri = NUMPRI; pri--; )
  2496. count += pendingcnt [pri];
  2497. return count;
  2498. }
  2499. void noinline
  2500. ev_invoke_pending (EV_P)
  2501. {
  2502. pendingpri = NUMPRI;
  2503. while (pendingpri) /* pendingpri possibly gets modified in the inner loop */
  2504. {
  2505. --pendingpri;
  2506. while (pendingcnt [pendingpri])
  2507. {
  2508. ANPENDING *p = pendings [pendingpri] + --pendingcnt [pendingpri];
  2509. p->w->pending = 0;
  2510. EV_CB_INVOKE (p->w, p->events);
  2511. EV_FREQUENT_CHECK;
  2512. }
  2513. }
  2514. }
  2515. #if EV_IDLE_ENABLE
  2516. /* make idle watchers pending. this handles the "call-idle */
  2517. /* only when higher priorities are idle" logic */
  2518. inline_size void
  2519. idle_reify (EV_P)
  2520. {
  2521. if (expect_false (idleall))
  2522. {
  2523. int pri;
  2524. for (pri = NUMPRI; pri--; )
  2525. {
  2526. if (pendingcnt [pri])
  2527. break;
  2528. if (idlecnt [pri])
  2529. {
  2530. queue_events (EV_A_ (W *)idles [pri], idlecnt [pri], EV_IDLE);
  2531. break;
  2532. }
  2533. }
  2534. }
  2535. }
  2536. #endif
  2537. /* make timers pending */
  2538. inline_size void
  2539. timers_reify (EV_P)
  2540. {
  2541. EV_FREQUENT_CHECK;
  2542. if (timercnt && ANHE_at (timers [HEAP0]) < mn_now)
  2543. {
  2544. do
  2545. {
  2546. ev_timer *w = (ev_timer *)ANHE_w (timers [HEAP0]);
  2547. /*assert (("libev: inactive timer on timer heap detected", ev_is_active (w)));*/
  2548. /* first reschedule or stop timer */
  2549. if (w->repeat)
  2550. {
  2551. ev_at (w) += w->repeat;
  2552. if (ev_at (w) < mn_now)
  2553. ev_at (w) = mn_now;
  2554. assert (("libev: negative ev_timer repeat value found while processing timers", w->repeat > 0.));
  2555. ANHE_at_cache (timers [HEAP0]);
  2556. downheap (timers, timercnt, HEAP0);
  2557. }
  2558. else
  2559. ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
  2560. EV_FREQUENT_CHECK;
  2561. feed_reverse (EV_A_ (W)w);
  2562. }
  2563. while (timercnt && ANHE_at (timers [HEAP0]) < mn_now);
  2564. feed_reverse_done (EV_A_ EV_TIMER);
  2565. }
  2566. }
  2567. #if EV_PERIODIC_ENABLE
  2568. static void noinline
  2569. periodic_recalc (EV_P_ ev_periodic *w)
  2570. {
  2571. ev_tstamp interval = w->interval > MIN_INTERVAL ? w->interval : MIN_INTERVAL;
  2572. ev_tstamp at = w->offset + interval * ev_floor ((ev_rt_now - w->offset) / interval);
  2573. /* the above almost always errs on the low side */
  2574. while (at <= ev_rt_now)
  2575. {
  2576. ev_tstamp nat = at + w->interval;
  2577. /* when resolution fails us, we use ev_rt_now */
  2578. if (expect_false (nat == at))
  2579. {
  2580. at = ev_rt_now;
  2581. break;
  2582. }
  2583. at = nat;
  2584. }
  2585. ev_at (w) = at;
  2586. }
  2587. /* make periodics pending */
  2588. inline_size void
  2589. periodics_reify (EV_P)
  2590. {
  2591. EV_FREQUENT_CHECK;
  2592. while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now)
  2593. {
  2594. do
  2595. {
  2596. ev_periodic *w = (ev_periodic *)ANHE_w (periodics [HEAP0]);
  2597. /*assert (("libev: inactive timer on periodic heap detected", ev_is_active (w)));*/
  2598. /* first reschedule or stop timer */
  2599. if (w->reschedule_cb)
  2600. {
  2601. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  2602. assert (("libev: ev_periodic reschedule callback returned time in the past", ev_at (w) >= ev_rt_now));
  2603. ANHE_at_cache (periodics [HEAP0]);
  2604. downheap (periodics, periodiccnt, HEAP0);
  2605. }
  2606. else if (w->interval)
  2607. {
  2608. periodic_recalc (EV_A_ w);
  2609. ANHE_at_cache (periodics [HEAP0]);
  2610. downheap (periodics, periodiccnt, HEAP0);
  2611. }
  2612. else
  2613. ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
  2614. EV_FREQUENT_CHECK;
  2615. feed_reverse (EV_A_ (W)w);
  2616. }
  2617. while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now);
  2618. feed_reverse_done (EV_A_ EV_PERIODIC);
  2619. }
  2620. }
  2621. /* simply recalculate all periodics */
  2622. /* TODO: maybe ensure that at least one event happens when jumping forward? */
  2623. static void noinline ecb_cold
  2624. periodics_reschedule (EV_P)
  2625. {
  2626. int i;
  2627. /* adjust periodics after time jump */
  2628. for (i = HEAP0; i < periodiccnt + HEAP0; ++i)
  2629. {
  2630. ev_periodic *w = (ev_periodic *)ANHE_w (periodics [i]);
  2631. if (w->reschedule_cb)
  2632. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  2633. else if (w->interval)
  2634. periodic_recalc (EV_A_ w);
  2635. ANHE_at_cache (periodics [i]);
  2636. }
  2637. reheap (periodics, periodiccnt);
  2638. }
  2639. #endif
  2640. /* adjust all timers by a given offset */
  2641. static void noinline ecb_cold
  2642. timers_reschedule (EV_P_ ev_tstamp adjust)
  2643. {
  2644. int i;
  2645. for (i = 0; i < timercnt; ++i)
  2646. {
  2647. ANHE *he = timers + i + HEAP0;
  2648. ANHE_w (*he)->at += adjust;
  2649. ANHE_at_cache (*he);
  2650. }
  2651. }
  2652. /* fetch new monotonic and realtime times from the kernel */
  2653. /* also detect if there was a timejump, and act accordingly */
  2654. inline_speed void
  2655. time_update (EV_P_ ev_tstamp max_block)
  2656. {
  2657. #if EV_USE_MONOTONIC
  2658. if (expect_true (have_monotonic))
  2659. {
  2660. int i;
  2661. ev_tstamp odiff = rtmn_diff;
  2662. mn_now = get_clock ();
  2663. /* only fetch the realtime clock every 0.5*MIN_TIMEJUMP seconds */
  2664. /* interpolate in the meantime */
  2665. if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5))
  2666. {
  2667. ev_rt_now = rtmn_diff + mn_now;
  2668. return;
  2669. }
  2670. now_floor = mn_now;
  2671. ev_rt_now = ev_time ();
  2672. /* loop a few times, before making important decisions.
  2673. * on the choice of "4": one iteration isn't enough,
  2674. * in case we get preempted during the calls to
  2675. * ev_time and get_clock. a second call is almost guaranteed
  2676. * to succeed in that case, though. and looping a few more times
  2677. * doesn't hurt either as we only do this on time-jumps or
  2678. * in the unlikely event of having been preempted here.
  2679. */
  2680. for (i = 4; --i; )
  2681. {
  2682. ev_tstamp diff;
  2683. rtmn_diff = ev_rt_now - mn_now;
  2684. diff = odiff - rtmn_diff;
  2685. if (expect_true ((diff < 0. ? -diff : diff) < MIN_TIMEJUMP))
  2686. return; /* all is well */
  2687. ev_rt_now = ev_time ();
  2688. mn_now = get_clock ();
  2689. now_floor = mn_now;
  2690. }
  2691. /* no timer adjustment, as the monotonic clock doesn't jump */
  2692. /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
  2693. # if EV_PERIODIC_ENABLE
  2694. periodics_reschedule (EV_A);
  2695. # endif
  2696. }
  2697. else
  2698. #endif
  2699. {
  2700. ev_rt_now = ev_time ();
  2701. if (expect_false (mn_now > ev_rt_now || ev_rt_now > mn_now + max_block + MIN_TIMEJUMP))
  2702. {
  2703. /* adjust timers. this is easy, as the offset is the same for all of them */
  2704. timers_reschedule (EV_A_ ev_rt_now - mn_now);
  2705. #if EV_PERIODIC_ENABLE
  2706. periodics_reschedule (EV_A);
  2707. #endif
  2708. }
  2709. mn_now = ev_rt_now;
  2710. }
  2711. }
  2712. int
  2713. ev_run (EV_P_ int flags)
  2714. {
  2715. #if EV_FEATURE_API
  2716. ++loop_depth;
  2717. #endif
  2718. assert (("libev: ev_loop recursion during release detected", loop_done != EVBREAK_RECURSE));
  2719. loop_done = EVBREAK_CANCEL;
  2720. EV_INVOKE_PENDING; /* in case we recurse, ensure ordering stays nice and clean */
  2721. do
  2722. {
  2723. #if EV_VERIFY >= 2
  2724. ev_verify (EV_A);
  2725. #endif
  2726. #ifndef _WIN32
  2727. if (expect_false (curpid)) /* penalise the forking check even more */
  2728. if (expect_false (getpid () != curpid))
  2729. {
  2730. curpid = getpid ();
  2731. postfork = 1;
  2732. }
  2733. #endif
  2734. #if EV_FORK_ENABLE
  2735. /* we might have forked, so queue fork handlers */
  2736. if (expect_false (postfork))
  2737. if (forkcnt)
  2738. {
  2739. queue_events (EV_A_ (W *)forks, forkcnt, EV_FORK);
  2740. EV_INVOKE_PENDING;
  2741. }
  2742. #endif
  2743. #if EV_PREPARE_ENABLE
  2744. /* queue prepare watchers (and execute them) */
  2745. if (expect_false (preparecnt))
  2746. {
  2747. queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
  2748. EV_INVOKE_PENDING;
  2749. }
  2750. #endif
  2751. if (expect_false (loop_done))
  2752. break;
  2753. /* we might have forked, so reify kernel state if necessary */
  2754. if (expect_false (postfork))
  2755. loop_fork (EV_A);
  2756. /* update fd-related kernel structures */
  2757. fd_reify (EV_A);
  2758. /* calculate blocking time */
  2759. {
  2760. ev_tstamp waittime = 0.;
  2761. ev_tstamp sleeptime = 0.;
  2762. /* remember old timestamp for io_blocktime calculation */
  2763. ev_tstamp prev_mn_now = mn_now;
  2764. /* update time to cancel out callback processing overhead */
  2765. time_update (EV_A_ 1e100);
  2766. /* from now on, we want a pipe-wake-up */
  2767. pipe_write_wanted = 1;
  2768. ECB_MEMORY_FENCE; /* make sure pipe_write_wanted is visible before we check for potential skips */
  2769. if (expect_true (!(flags & EVRUN_NOWAIT || idleall || !activecnt || pipe_write_skipped)))
  2770. {
  2771. waittime = MAX_BLOCKTIME;
  2772. if (timercnt)
  2773. {
  2774. ev_tstamp to = ANHE_at (timers [HEAP0]) - mn_now;
  2775. if (waittime > to) waittime = to;
  2776. }
  2777. #if EV_PERIODIC_ENABLE
  2778. if (periodiccnt)
  2779. {
  2780. ev_tstamp to = ANHE_at (periodics [HEAP0]) - ev_rt_now;
  2781. if (waittime > to) waittime = to;
  2782. }
  2783. #endif
  2784. /* don't let timeouts decrease the waittime below timeout_blocktime */
  2785. if (expect_false (waittime < timeout_blocktime))
  2786. waittime = timeout_blocktime;
  2787. /* at this point, we NEED to wait, so we have to ensure */
  2788. /* to pass a minimum nonzero value to the backend */
  2789. if (expect_false (waittime < backend_mintime))
  2790. waittime = backend_mintime;
  2791. /* extra check because io_blocktime is commonly 0 */
  2792. if (expect_false (io_blocktime))
  2793. {
  2794. sleeptime = io_blocktime - (mn_now - prev_mn_now);
  2795. if (sleeptime > waittime - backend_mintime)
  2796. sleeptime = waittime - backend_mintime;
  2797. if (expect_true (sleeptime > 0.))
  2798. {
  2799. ev_sleep (sleeptime);
  2800. waittime -= sleeptime;
  2801. }
  2802. }
  2803. }
  2804. #if EV_FEATURE_API
  2805. ++loop_count;
  2806. #endif
  2807. assert ((loop_done = EVBREAK_RECURSE, 1)); /* assert for side effect */
  2808. backend_poll (EV_A_ waittime);
  2809. assert ((loop_done = EVBREAK_CANCEL, 1)); /* assert for side effect */
  2810. pipe_write_wanted = 0; /* just an optimisation, no fence needed */
  2811. ECB_MEMORY_FENCE_ACQUIRE;
  2812. if (pipe_write_skipped)
  2813. {
  2814. assert (("libev: pipe_w not active, but pipe not written", ev_is_active (&pipe_w)));
  2815. ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM);
  2816. }
  2817. /* update ev_rt_now, do magic */
  2818. time_update (EV_A_ waittime + sleeptime);
  2819. }
  2820. /* queue pending timers and reschedule them */
  2821. timers_reify (EV_A); /* relative timers called last */
  2822. #if EV_PERIODIC_ENABLE
  2823. periodics_reify (EV_A); /* absolute timers called first */
  2824. #endif
  2825. #if EV_IDLE_ENABLE
  2826. /* queue idle watchers unless other events are pending */
  2827. idle_reify (EV_A);
  2828. #endif
  2829. #if EV_CHECK_ENABLE
  2830. /* queue check watchers, to be executed first */
  2831. if (expect_false (checkcnt))
  2832. queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
  2833. #endif
  2834. EV_INVOKE_PENDING;
  2835. }
  2836. while (expect_true (
  2837. activecnt
  2838. && !loop_done
  2839. && !(flags & (EVRUN_ONCE | EVRUN_NOWAIT))
  2840. ));
  2841. if (loop_done == EVBREAK_ONE)
  2842. loop_done = EVBREAK_CANCEL;
  2843. #if EV_FEATURE_API
  2844. --loop_depth;
  2845. #endif
  2846. return activecnt;
  2847. }
  2848. void
  2849. ev_break (EV_P_ int how) EV_THROW
  2850. {
  2851. loop_done = how;
  2852. }
  2853. void
  2854. ev_ref (EV_P) EV_THROW
  2855. {
  2856. ++activecnt;
  2857. }
  2858. void
  2859. ev_unref (EV_P) EV_THROW
  2860. {
  2861. --activecnt;
  2862. }
  2863. void
  2864. ev_now_update (EV_P) EV_THROW
  2865. {
  2866. time_update (EV_A_ 1e100);
  2867. }
  2868. void
  2869. ev_suspend (EV_P) EV_THROW
  2870. {
  2871. ev_now_update (EV_A);
  2872. }
  2873. void
  2874. ev_resume (EV_P) EV_THROW
  2875. {
  2876. ev_tstamp mn_prev = mn_now;
  2877. ev_now_update (EV_A);
  2878. timers_reschedule (EV_A_ mn_now - mn_prev);
  2879. #if EV_PERIODIC_ENABLE
  2880. /* TODO: really do this? */
  2881. periodics_reschedule (EV_A);
  2882. #endif
  2883. }
  2884. /*****************************************************************************/
  2885. /* singly-linked list management, used when the expected list length is short */
  2886. inline_size void
  2887. wlist_add (WL *head, WL elem)
  2888. {
  2889. elem->next = *head;
  2890. *head = elem;
  2891. }
  2892. inline_size void
  2893. wlist_del (WL *head, WL elem)
  2894. {
  2895. while (*head)
  2896. {
  2897. if (expect_true (*head == elem))
  2898. {
  2899. *head = elem->next;
  2900. break;
  2901. }
  2902. head = &(*head)->next;
  2903. }
  2904. }
  2905. /* internal, faster, version of ev_clear_pending */
  2906. inline_speed void
  2907. clear_pending (EV_P_ W w)
  2908. {
  2909. if (w->pending)
  2910. {
  2911. pendings [ABSPRI (w)][w->pending - 1].w = (W)&pending_w;
  2912. w->pending = 0;
  2913. }
  2914. }
  2915. int
  2916. ev_clear_pending (EV_P_ void *w) EV_THROW
  2917. {
  2918. W w_ = (W)w;
  2919. int pending = w_->pending;
  2920. if (expect_true (pending))
  2921. {
  2922. ANPENDING *p = pendings [ABSPRI (w_)] + pending - 1;
  2923. p->w = (W)&pending_w;
  2924. w_->pending = 0;
  2925. return p->events;
  2926. }
  2927. else
  2928. return 0;
  2929. }
  2930. inline_size void
  2931. pri_adjust (EV_P_ W w)
  2932. {
  2933. int pri = ev_priority (w);
  2934. pri = pri < EV_MINPRI ? EV_MINPRI : pri;
  2935. pri = pri > EV_MAXPRI ? EV_MAXPRI : pri;
  2936. ev_set_priority (w, pri);
  2937. }
  2938. inline_speed void
  2939. ev_start (EV_P_ W w, int active)
  2940. {
  2941. pri_adjust (EV_A_ w);
  2942. w->active = active;
  2943. ev_ref (EV_A);
  2944. }
  2945. inline_size void
  2946. ev_stop (EV_P_ W w)
  2947. {
  2948. ev_unref (EV_A);
  2949. w->active = 0;
  2950. }
  2951. /*****************************************************************************/
  2952. void noinline
  2953. ev_io_start (EV_P_ ev_io *w) EV_THROW
  2954. {
  2955. int fd = w->fd;
  2956. if (expect_false (ev_is_active (w)))
  2957. return;
  2958. assert (("libev: ev_io_start called with negative fd", fd >= 0));
  2959. assert (("libev: ev_io_start called with illegal event mask", !(w->events & ~(EV__IOFDSET | EV_READ | EV_WRITE))));
  2960. EV_FREQUENT_CHECK;
  2961. ev_start (EV_A_ (W)w, 1);
  2962. array_needsize (ANFD, anfds, anfdmax, fd + 1, array_init_zero);
  2963. wlist_add (&anfds[fd].head, (WL)w);
  2964. /* common bug, apparently */
  2965. assert (("libev: ev_io_start called with corrupted watcher", ((WL)w)->next != (WL)w));
  2966. fd_change (EV_A_ fd, w->events & EV__IOFDSET | EV_ANFD_REIFY);
  2967. w->events &= ~EV__IOFDSET;
  2968. EV_FREQUENT_CHECK;
  2969. }
  2970. void noinline
  2971. ev_io_stop (EV_P_ ev_io *w) EV_THROW
  2972. {
  2973. clear_pending (EV_A_ (W)w);
  2974. if (expect_false (!ev_is_active (w)))
  2975. return;
  2976. assert (("libev: ev_io_stop called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax));
  2977. EV_FREQUENT_CHECK;
  2978. wlist_del (&anfds[w->fd].head, (WL)w);
  2979. ev_stop (EV_A_ (W)w);
  2980. fd_change (EV_A_ w->fd, EV_ANFD_REIFY);
  2981. EV_FREQUENT_CHECK;
  2982. }
  2983. void noinline
  2984. ev_timer_start (EV_P_ ev_timer *w) EV_THROW
  2985. {
  2986. if (expect_false (ev_is_active (w)))
  2987. return;
  2988. ev_at (w) += mn_now;
  2989. assert (("libev: ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
  2990. EV_FREQUENT_CHECK;
  2991. ++timercnt;
  2992. ev_start (EV_A_ (W)w, timercnt + HEAP0 - 1);
  2993. array_needsize (ANHE, timers, timermax, ev_active (w) + 1, EMPTY2);
  2994. ANHE_w (timers [ev_active (w)]) = (WT)w;
  2995. ANHE_at_cache (timers [ev_active (w)]);
  2996. upheap (timers, ev_active (w));
  2997. EV_FREQUENT_CHECK;
  2998. /*assert (("libev: internal timer heap corruption", timers [ev_active (w)] == (WT)w));*/
  2999. }
  3000. void noinline
  3001. ev_timer_stop (EV_P_ ev_timer *w) EV_THROW
  3002. {
  3003. clear_pending (EV_A_ (W)w);
  3004. if (expect_false (!ev_is_active (w)))
  3005. return;
  3006. EV_FREQUENT_CHECK;
  3007. {
  3008. int active = ev_active (w);
  3009. assert (("libev: internal timer heap corruption", ANHE_w (timers [active]) == (WT)w));
  3010. --timercnt;
  3011. if (expect_true (active < timercnt + HEAP0))
  3012. {
  3013. timers [active] = timers [timercnt + HEAP0];
  3014. adjustheap (timers, timercnt, active);
  3015. }
  3016. }
  3017. ev_at (w) -= mn_now;
  3018. ev_stop (EV_A_ (W)w);
  3019. EV_FREQUENT_CHECK;
  3020. }
  3021. void noinline
  3022. ev_timer_again (EV_P_ ev_timer *w) EV_THROW
  3023. {
  3024. EV_FREQUENT_CHECK;
  3025. clear_pending (EV_A_ (W)w);
  3026. if (ev_is_active (w))
  3027. {
  3028. if (w->repeat)
  3029. {
  3030. ev_at (w) = mn_now + w->repeat;
  3031. ANHE_at_cache (timers [ev_active (w)]);
  3032. adjustheap (timers, timercnt, ev_active (w));
  3033. }
  3034. else
  3035. ev_timer_stop (EV_A_ w);
  3036. }
  3037. else if (w->repeat)
  3038. {
  3039. ev_at (w) = w->repeat;
  3040. ev_timer_start (EV_A_ w);
  3041. }
  3042. EV_FREQUENT_CHECK;
  3043. }
  3044. ev_tstamp
  3045. ev_timer_remaining (EV_P_ ev_timer *w) EV_THROW
  3046. {
  3047. return ev_at (w) - (ev_is_active (w) ? mn_now : 0.);
  3048. }
  3049. #if EV_PERIODIC_ENABLE
  3050. void noinline
  3051. ev_periodic_start (EV_P_ ev_periodic *w) EV_THROW
  3052. {
  3053. if (expect_false (ev_is_active (w)))
  3054. return;
  3055. if (w->reschedule_cb)
  3056. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  3057. else if (w->interval)
  3058. {
  3059. assert (("libev: ev_periodic_start called with negative interval value", w->interval >= 0.));
  3060. periodic_recalc (EV_A_ w);
  3061. }
  3062. else
  3063. ev_at (w) = w->offset;
  3064. EV_FREQUENT_CHECK;
  3065. ++periodiccnt;
  3066. ev_start (EV_A_ (W)w, periodiccnt + HEAP0 - 1);
  3067. array_needsize (ANHE, periodics, periodicmax, ev_active (w) + 1, EMPTY2);
  3068. ANHE_w (periodics [ev_active (w)]) = (WT)w;
  3069. ANHE_at_cache (periodics [ev_active (w)]);
  3070. upheap (periodics, ev_active (w));
  3071. EV_FREQUENT_CHECK;
  3072. /*assert (("libev: internal periodic heap corruption", ANHE_w (periodics [ev_active (w)]) == (WT)w));*/
  3073. }
  3074. void noinline
  3075. ev_periodic_stop (EV_P_ ev_periodic *w) EV_THROW
  3076. {
  3077. clear_pending (EV_A_ (W)w);
  3078. if (expect_false (!ev_is_active (w)))
  3079. return;
  3080. EV_FREQUENT_CHECK;
  3081. {
  3082. int active = ev_active (w);
  3083. assert (("libev: internal periodic heap corruption", ANHE_w (periodics [active]) == (WT)w));
  3084. --periodiccnt;
  3085. if (expect_true (active < periodiccnt + HEAP0))
  3086. {
  3087. periodics [active] = periodics [periodiccnt + HEAP0];
  3088. adjustheap (periodics, periodiccnt, active);
  3089. }
  3090. }
  3091. ev_stop (EV_A_ (W)w);
  3092. EV_FREQUENT_CHECK;
  3093. }
  3094. void noinline
  3095. ev_periodic_again (EV_P_ ev_periodic *w) EV_THROW
  3096. {
  3097. /* TODO: use adjustheap and recalculation */
  3098. ev_periodic_stop (EV_A_ w);
  3099. ev_periodic_start (EV_A_ w);
  3100. }
  3101. #endif
  3102. #ifndef SA_RESTART
  3103. # define SA_RESTART 0
  3104. #endif
  3105. #if EV_SIGNAL_ENABLE
  3106. void noinline
  3107. ev_signal_start (EV_P_ ev_signal *w) EV_THROW
  3108. {
  3109. if (expect_false (ev_is_active (w)))
  3110. return;
  3111. assert (("libev: ev_signal_start called with illegal signal number", w->signum > 0 && w->signum < EV_NSIG));
  3112. #if EV_MULTIPLICITY
  3113. assert (("libev: a signal must not be attached to two different loops",
  3114. !signals [w->signum - 1].loop || signals [w->signum - 1].loop == loop));
  3115. signals [w->signum - 1].loop = EV_A;
  3116. ECB_MEMORY_FENCE_RELEASE;
  3117. #endif
  3118. EV_FREQUENT_CHECK;
  3119. #if EV_USE_SIGNALFD
  3120. if (sigfd == -2)
  3121. {
  3122. sigfd = signalfd (-1, &sigfd_set, SFD_NONBLOCK | SFD_CLOEXEC);
  3123. if (sigfd < 0 && errno == EINVAL)
  3124. sigfd = signalfd (-1, &sigfd_set, 0); /* retry without flags */
  3125. if (sigfd >= 0)
  3126. {
  3127. fd_intern (sigfd); /* doing it twice will not hurt */
  3128. sigemptyset (&sigfd_set);
  3129. ev_io_init (&sigfd_w, sigfdcb, sigfd, EV_READ);
  3130. ev_set_priority (&sigfd_w, EV_MAXPRI);
  3131. ev_io_start (EV_A_ &sigfd_w);
  3132. ev_unref (EV_A); /* signalfd watcher should not keep loop alive */
  3133. }
  3134. }
  3135. if (sigfd >= 0)
  3136. {
  3137. /* TODO: check .head */
  3138. sigaddset (&sigfd_set, w->signum);
  3139. sigprocmask (SIG_BLOCK, &sigfd_set, 0);
  3140. signalfd (sigfd, &sigfd_set, 0);
  3141. }
  3142. #endif
  3143. ev_start (EV_A_ (W)w, 1);
  3144. wlist_add (&signals [w->signum - 1].head, (WL)w);
  3145. if (!((WL)w)->next)
  3146. # if EV_USE_SIGNALFD
  3147. if (sigfd < 0) /*TODO*/
  3148. # endif
  3149. {
  3150. # ifdef _WIN32
  3151. evpipe_init (EV_A);
  3152. signal (w->signum, ev_sighandler);
  3153. # else
  3154. struct sigaction sa;
  3155. evpipe_init (EV_A);
  3156. sa.sa_handler = ev_sighandler;
  3157. sigfillset (&sa.sa_mask);
  3158. sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
  3159. sigaction (w->signum, &sa, 0);
  3160. if (origflags & EVFLAG_NOSIGMASK)
  3161. {
  3162. sigemptyset (&sa.sa_mask);
  3163. sigaddset (&sa.sa_mask, w->signum);
  3164. sigprocmask (SIG_UNBLOCK, &sa.sa_mask, 0);
  3165. }
  3166. #endif
  3167. }
  3168. EV_FREQUENT_CHECK;
  3169. }
  3170. void noinline
  3171. ev_signal_stop (EV_P_ ev_signal *w) EV_THROW
  3172. {
  3173. clear_pending (EV_A_ (W)w);
  3174. if (expect_false (!ev_is_active (w)))
  3175. return;
  3176. EV_FREQUENT_CHECK;
  3177. wlist_del (&signals [w->signum - 1].head, (WL)w);
  3178. ev_stop (EV_A_ (W)w);
  3179. if (!signals [w->signum - 1].head)
  3180. {
  3181. #if EV_MULTIPLICITY
  3182. signals [w->signum - 1].loop = 0; /* unattach from signal */
  3183. #endif
  3184. #if EV_USE_SIGNALFD
  3185. if (sigfd >= 0)
  3186. {
  3187. sigset_t ss;
  3188. sigemptyset (&ss);
  3189. sigaddset (&ss, w->signum);
  3190. sigdelset (&sigfd_set, w->signum);
  3191. signalfd (sigfd, &sigfd_set, 0);
  3192. sigprocmask (SIG_UNBLOCK, &ss, 0);
  3193. }
  3194. else
  3195. #endif
  3196. signal (w->signum, SIG_DFL);
  3197. }
  3198. EV_FREQUENT_CHECK;
  3199. }
  3200. #endif
  3201. #if EV_CHILD_ENABLE
  3202. void
  3203. ev_child_start (EV_P_ ev_child *w) EV_THROW
  3204. {
  3205. #if EV_MULTIPLICITY
  3206. assert (("libev: child watchers are only supported in the default loop", loop == ev_default_loop_ptr));
  3207. #endif
  3208. if (expect_false (ev_is_active (w)))
  3209. return;
  3210. EV_FREQUENT_CHECK;
  3211. ev_start (EV_A_ (W)w, 1);
  3212. wlist_add (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
  3213. EV_FREQUENT_CHECK;
  3214. }
  3215. void
  3216. ev_child_stop (EV_P_ ev_child *w) EV_THROW
  3217. {
  3218. clear_pending (EV_A_ (W)w);
  3219. if (expect_false (!ev_is_active (w)))
  3220. return;
  3221. EV_FREQUENT_CHECK;
  3222. wlist_del (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
  3223. ev_stop (EV_A_ (W)w);
  3224. EV_FREQUENT_CHECK;
  3225. }
  3226. #endif
  3227. #if EV_STAT_ENABLE
  3228. # ifdef _WIN32
  3229. # undef lstat
  3230. # define lstat(a,b) _stati64 (a,b)
  3231. # endif
  3232. #define DEF_STAT_INTERVAL 5.0074891
  3233. #define NFS_STAT_INTERVAL 30.1074891 /* for filesystems potentially failing inotify */
  3234. #define MIN_STAT_INTERVAL 0.1074891
  3235. static void noinline stat_timer_cb (EV_P_ ev_timer *w_, int revents);
  3236. #if EV_USE_INOTIFY
  3237. /* the * 2 is to allow for alignment padding, which for some reason is >> 8 */
  3238. # define EV_INOTIFY_BUFSIZE (sizeof (struct inotify_event) * 2 + NAME_MAX)
  3239. static void noinline
  3240. infy_add (EV_P_ ev_stat *w)
  3241. {
  3242. w->wd = inotify_add_watch (fs_fd, w->path,
  3243. IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_MODIFY
  3244. | IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO
  3245. | IN_DONT_FOLLOW | IN_MASK_ADD);
  3246. if (w->wd >= 0)
  3247. {
  3248. struct statfs sfs;
  3249. /* now local changes will be tracked by inotify, but remote changes won't */
  3250. /* unless the filesystem is known to be local, we therefore still poll */
  3251. /* also do poll on <2.6.25, but with normal frequency */
  3252. if (!fs_2625)
  3253. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  3254. else if (!statfs (w->path, &sfs)
  3255. && (sfs.f_type == 0x1373 /* devfs */
  3256. || sfs.f_type == 0x4006 /* fat */
  3257. || sfs.f_type == 0x4d44 /* msdos */
  3258. || sfs.f_type == 0xEF53 /* ext2/3 */
  3259. || sfs.f_type == 0x72b6 /* jffs2 */
  3260. || sfs.f_type == 0x858458f6 /* ramfs */
  3261. || sfs.f_type == 0x5346544e /* ntfs */
  3262. || sfs.f_type == 0x3153464a /* jfs */
  3263. || sfs.f_type == 0x9123683e /* btrfs */
  3264. || sfs.f_type == 0x52654973 /* reiser3 */
  3265. || sfs.f_type == 0x01021994 /* tmpfs */
  3266. || sfs.f_type == 0x58465342 /* xfs */))
  3267. w->timer.repeat = 0.; /* filesystem is local, kernel new enough */
  3268. else
  3269. w->timer.repeat = w->interval ? w->interval : NFS_STAT_INTERVAL; /* remote, use reduced frequency */
  3270. }
  3271. else
  3272. {
  3273. /* can't use inotify, continue to stat */
  3274. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  3275. /* if path is not there, monitor some parent directory for speedup hints */
  3276. /* note that exceeding the hardcoded path limit is not a correctness issue, */
  3277. /* but an efficiency issue only */
  3278. if ((errno == ENOENT || errno == EACCES) && strlen (w->path) < 4096)
  3279. {
  3280. char path [4096];
  3281. strcpy (path, w->path);
  3282. do
  3283. {
  3284. int mask = IN_MASK_ADD | IN_DELETE_SELF | IN_MOVE_SELF
  3285. | (errno == EACCES ? IN_ATTRIB : IN_CREATE | IN_MOVED_TO);
  3286. char *pend = strrchr (path, '/');
  3287. if (!pend || pend == path)
  3288. break;
  3289. *pend = 0;
  3290. w->wd = inotify_add_watch (fs_fd, path, mask);
  3291. }
  3292. while (w->wd < 0 && (errno == ENOENT || errno == EACCES));
  3293. }
  3294. }
  3295. if (w->wd >= 0)
  3296. wlist_add (&fs_hash [w->wd & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
  3297. /* now re-arm timer, if required */
  3298. if (ev_is_active (&w->timer)) ev_ref (EV_A);
  3299. ev_timer_again (EV_A_ &w->timer);
  3300. if (ev_is_active (&w->timer)) ev_unref (EV_A);
  3301. }
  3302. static void noinline
  3303. infy_del (EV_P_ ev_stat *w)
  3304. {
  3305. int slot;
  3306. int wd = w->wd;
  3307. if (wd < 0)
  3308. return;
  3309. w->wd = -2;
  3310. slot = wd & ((EV_INOTIFY_HASHSIZE) - 1);
  3311. wlist_del (&fs_hash [slot].head, (WL)w);
  3312. /* remove this watcher, if others are watching it, they will rearm */
  3313. inotify_rm_watch (fs_fd, wd);
  3314. }
  3315. static void noinline
  3316. infy_wd (EV_P_ int slot, int wd, struct inotify_event *ev)
  3317. {
  3318. if (slot < 0)
  3319. /* overflow, need to check for all hash slots */
  3320. for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
  3321. infy_wd (EV_A_ slot, wd, ev);
  3322. else
  3323. {
  3324. WL w_;
  3325. for (w_ = fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head; w_; )
  3326. {
  3327. ev_stat *w = (ev_stat *)w_;
  3328. w_ = w_->next; /* lets us remove this watcher and all before it */
  3329. if (w->wd == wd || wd == -1)
  3330. {
  3331. if (ev->mask & (IN_IGNORED | IN_UNMOUNT | IN_DELETE_SELF))
  3332. {
  3333. wlist_del (&fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
  3334. w->wd = -1;
  3335. infy_add (EV_A_ w); /* re-add, no matter what */
  3336. }
  3337. stat_timer_cb (EV_A_ &w->timer, 0);
  3338. }
  3339. }
  3340. }
  3341. }
  3342. static void
  3343. infy_cb (EV_P_ ev_io *w, int revents)
  3344. {
  3345. char buf [EV_INOTIFY_BUFSIZE];
  3346. int ofs;
  3347. int len = read (fs_fd, buf, sizeof (buf));
  3348. for (ofs = 0; ofs < len; )
  3349. {
  3350. struct inotify_event *ev = (struct inotify_event *)(buf + ofs);
  3351. infy_wd (EV_A_ ev->wd, ev->wd, ev);
  3352. ofs += sizeof (struct inotify_event) + ev->len;
  3353. }
  3354. }
  3355. inline_size void ecb_cold
  3356. ev_check_2625 (EV_P)
  3357. {
  3358. /* kernels < 2.6.25 are borked
  3359. * http://www.ussg.indiana.edu/hypermail/linux/kernel/0711.3/1208.html
  3360. */
  3361. if (ev_linux_version () < 0x020619)
  3362. return;
  3363. fs_2625 = 1;
  3364. }
  3365. inline_size int
  3366. infy_newfd (void)
  3367. {
  3368. #if defined IN_CLOEXEC && defined IN_NONBLOCK
  3369. int fd = inotify_init1 (IN_CLOEXEC | IN_NONBLOCK);
  3370. if (fd >= 0)
  3371. return fd;
  3372. #endif
  3373. return inotify_init ();
  3374. }
  3375. inline_size void
  3376. infy_init (EV_P)
  3377. {
  3378. if (fs_fd != -2)
  3379. return;
  3380. fs_fd = -1;
  3381. ev_check_2625 (EV_A);
  3382. fs_fd = infy_newfd ();
  3383. if (fs_fd >= 0)
  3384. {
  3385. fd_intern (fs_fd);
  3386. ev_io_init (&fs_w, infy_cb, fs_fd, EV_READ);
  3387. ev_set_priority (&fs_w, EV_MAXPRI);
  3388. ev_io_start (EV_A_ &fs_w);
  3389. ev_unref (EV_A);
  3390. }
  3391. }
  3392. inline_size void
  3393. infy_fork (EV_P)
  3394. {
  3395. int slot;
  3396. if (fs_fd < 0)
  3397. return;
  3398. ev_ref (EV_A);
  3399. ev_io_stop (EV_A_ &fs_w);
  3400. close (fs_fd);
  3401. fs_fd = infy_newfd ();
  3402. if (fs_fd >= 0)
  3403. {
  3404. fd_intern (fs_fd);
  3405. ev_io_set (&fs_w, fs_fd, EV_READ);
  3406. ev_io_start (EV_A_ &fs_w);
  3407. ev_unref (EV_A);
  3408. }
  3409. for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
  3410. {
  3411. WL w_ = fs_hash [slot].head;
  3412. fs_hash [slot].head = 0;
  3413. while (w_)
  3414. {
  3415. ev_stat *w = (ev_stat *)w_;
  3416. w_ = w_->next; /* lets us add this watcher */
  3417. w->wd = -1;
  3418. if (fs_fd >= 0)
  3419. infy_add (EV_A_ w); /* re-add, no matter what */
  3420. else
  3421. {
  3422. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  3423. if (ev_is_active (&w->timer)) ev_ref (EV_A);
  3424. ev_timer_again (EV_A_ &w->timer);
  3425. if (ev_is_active (&w->timer)) ev_unref (EV_A);
  3426. }
  3427. }
  3428. }
  3429. }
  3430. #endif
  3431. #ifdef _WIN32
  3432. # define EV_LSTAT(p,b) _stati64 (p, b)
  3433. #else
  3434. # define EV_LSTAT(p,b) lstat (p, b)
  3435. #endif
  3436. void
  3437. ev_stat_stat (EV_P_ ev_stat *w) EV_THROW
  3438. {
  3439. if (lstat (w->path, &w->attr) < 0)
  3440. w->attr.st_nlink = 0;
  3441. else if (!w->attr.st_nlink)
  3442. w->attr.st_nlink = 1;
  3443. }
  3444. static void noinline
  3445. stat_timer_cb (EV_P_ ev_timer *w_, int revents)
  3446. {
  3447. ev_stat *w = (ev_stat *)(((char *)w_) - offsetof (ev_stat, timer));
  3448. ev_statdata prev = w->attr;
  3449. ev_stat_stat (EV_A_ w);
  3450. /* memcmp doesn't work on netbsd, they.... do stuff to their struct stat */
  3451. if (
  3452. prev.st_dev != w->attr.st_dev
  3453. || prev.st_ino != w->attr.st_ino
  3454. || prev.st_mode != w->attr.st_mode
  3455. || prev.st_nlink != w->attr.st_nlink
  3456. || prev.st_uid != w->attr.st_uid
  3457. || prev.st_gid != w->attr.st_gid
  3458. || prev.st_rdev != w->attr.st_rdev
  3459. || prev.st_size != w->attr.st_size
  3460. || prev.st_atime != w->attr.st_atime
  3461. || prev.st_mtime != w->attr.st_mtime
  3462. || prev.st_ctime != w->attr.st_ctime
  3463. ) {
  3464. /* we only update w->prev on actual differences */
  3465. /* in case we test more often than invoke the callback, */
  3466. /* to ensure that prev is always different to attr */
  3467. w->prev = prev;
  3468. #if EV_USE_INOTIFY
  3469. if (fs_fd >= 0)
  3470. {
  3471. infy_del (EV_A_ w);
  3472. infy_add (EV_A_ w);
  3473. ev_stat_stat (EV_A_ w); /* avoid race... */
  3474. }
  3475. #endif
  3476. ev_feed_event (EV_A_ w, EV_STAT);
  3477. }
  3478. }
  3479. void
  3480. ev_stat_start (EV_P_ ev_stat *w) EV_THROW
  3481. {
  3482. if (expect_false (ev_is_active (w)))
  3483. return;
  3484. ev_stat_stat (EV_A_ w);
  3485. if (w->interval < MIN_STAT_INTERVAL && w->interval)
  3486. w->interval = MIN_STAT_INTERVAL;
  3487. ev_timer_init (&w->timer, stat_timer_cb, 0., w->interval ? w->interval : DEF_STAT_INTERVAL);
  3488. ev_set_priority (&w->timer, ev_priority (w));
  3489. #if EV_USE_INOTIFY
  3490. infy_init (EV_A);
  3491. if (fs_fd >= 0)
  3492. infy_add (EV_A_ w);
  3493. else
  3494. #endif
  3495. {
  3496. ev_timer_again (EV_A_ &w->timer);
  3497. ev_unref (EV_A);
  3498. }
  3499. ev_start (EV_A_ (W)w, 1);
  3500. EV_FREQUENT_CHECK;
  3501. }
  3502. void
  3503. ev_stat_stop (EV_P_ ev_stat *w) EV_THROW
  3504. {
  3505. clear_pending (EV_A_ (W)w);
  3506. if (expect_false (!ev_is_active (w)))
  3507. return;
  3508. EV_FREQUENT_CHECK;
  3509. #if EV_USE_INOTIFY
  3510. infy_del (EV_A_ w);
  3511. #endif
  3512. if (ev_is_active (&w->timer))
  3513. {
  3514. ev_ref (EV_A);
  3515. ev_timer_stop (EV_A_ &w->timer);
  3516. }
  3517. ev_stop (EV_A_ (W)w);
  3518. EV_FREQUENT_CHECK;
  3519. }
  3520. #endif
  3521. #if EV_IDLE_ENABLE
  3522. void
  3523. ev_idle_start (EV_P_ ev_idle *w) EV_THROW
  3524. {
  3525. if (expect_false (ev_is_active (w)))
  3526. return;
  3527. pri_adjust (EV_A_ (W)w);
  3528. EV_FREQUENT_CHECK;
  3529. {
  3530. int active = ++idlecnt [ABSPRI (w)];
  3531. ++idleall;
  3532. ev_start (EV_A_ (W)w, active);
  3533. array_needsize (ev_idle *, idles [ABSPRI (w)], idlemax [ABSPRI (w)], active, EMPTY2);
  3534. idles [ABSPRI (w)][active - 1] = w;
  3535. }
  3536. EV_FREQUENT_CHECK;
  3537. }
  3538. void
  3539. ev_idle_stop (EV_P_ ev_idle *w) EV_THROW
  3540. {
  3541. clear_pending (EV_A_ (W)w);
  3542. if (expect_false (!ev_is_active (w)))
  3543. return;
  3544. EV_FREQUENT_CHECK;
  3545. {
  3546. int active = ev_active (w);
  3547. idles [ABSPRI (w)][active - 1] = idles [ABSPRI (w)][--idlecnt [ABSPRI (w)]];
  3548. ev_active (idles [ABSPRI (w)][active - 1]) = active;
  3549. ev_stop (EV_A_ (W)w);
  3550. --idleall;
  3551. }
  3552. EV_FREQUENT_CHECK;
  3553. }
  3554. #endif
  3555. #if EV_PREPARE_ENABLE
  3556. void
  3557. ev_prepare_start (EV_P_ ev_prepare *w) EV_THROW
  3558. {
  3559. if (expect_false (ev_is_active (w)))
  3560. return;
  3561. EV_FREQUENT_CHECK;
  3562. ev_start (EV_A_ (W)w, ++preparecnt);
  3563. array_needsize (ev_prepare *, prepares, preparemax, preparecnt, EMPTY2);
  3564. prepares [preparecnt - 1] = w;
  3565. EV_FREQUENT_CHECK;
  3566. }
  3567. void
  3568. ev_prepare_stop (EV_P_ ev_prepare *w) EV_THROW
  3569. {
  3570. clear_pending (EV_A_ (W)w);
  3571. if (expect_false (!ev_is_active (w)))
  3572. return;
  3573. EV_FREQUENT_CHECK;
  3574. {
  3575. int active = ev_active (w);
  3576. prepares [active - 1] = prepares [--preparecnt];
  3577. ev_active (prepares [active - 1]) = active;
  3578. }
  3579. ev_stop (EV_A_ (W)w);
  3580. EV_FREQUENT_CHECK;
  3581. }
  3582. #endif
  3583. #if EV_CHECK_ENABLE
  3584. void
  3585. ev_check_start (EV_P_ ev_check *w) EV_THROW
  3586. {
  3587. if (expect_false (ev_is_active (w)))
  3588. return;
  3589. EV_FREQUENT_CHECK;
  3590. ev_start (EV_A_ (W)w, ++checkcnt);
  3591. array_needsize (ev_check *, checks, checkmax, checkcnt, EMPTY2);
  3592. checks [checkcnt - 1] = w;
  3593. EV_FREQUENT_CHECK;
  3594. }
  3595. void
  3596. ev_check_stop (EV_P_ ev_check *w) EV_THROW
  3597. {
  3598. clear_pending (EV_A_ (W)w);
  3599. if (expect_false (!ev_is_active (w)))
  3600. return;
  3601. EV_FREQUENT_CHECK;
  3602. {
  3603. int active = ev_active (w);
  3604. checks [active - 1] = checks [--checkcnt];
  3605. ev_active (checks [active - 1]) = active;
  3606. }
  3607. ev_stop (EV_A_ (W)w);
  3608. EV_FREQUENT_CHECK;
  3609. }
  3610. #endif
  3611. #if EV_EMBED_ENABLE
  3612. void noinline
  3613. ev_embed_sweep (EV_P_ ev_embed *w) EV_THROW
  3614. {
  3615. ev_run (w->other, EVRUN_NOWAIT);
  3616. }
  3617. static void
  3618. embed_io_cb (EV_P_ ev_io *io, int revents)
  3619. {
  3620. ev_embed *w = (ev_embed *)(((char *)io) - offsetof (ev_embed, io));
  3621. if (ev_cb (w))
  3622. ev_feed_event (EV_A_ (W)w, EV_EMBED);
  3623. else
  3624. ev_run (w->other, EVRUN_NOWAIT);
  3625. }
  3626. static void
  3627. embed_prepare_cb (EV_P_ ev_prepare *prepare, int revents)
  3628. {
  3629. ev_embed *w = (ev_embed *)(((char *)prepare) - offsetof (ev_embed, prepare));
  3630. {
  3631. EV_P = w->other;
  3632. while (fdchangecnt)
  3633. {
  3634. fd_reify (EV_A);
  3635. ev_run (EV_A_ EVRUN_NOWAIT);
  3636. }
  3637. }
  3638. }
  3639. static void
  3640. embed_fork_cb (EV_P_ ev_fork *fork_w, int revents)
  3641. {
  3642. ev_embed *w = (ev_embed *)(((char *)fork_w) - offsetof (ev_embed, fork));
  3643. ev_embed_stop (EV_A_ w);
  3644. {
  3645. EV_P = w->other;
  3646. ev_loop_fork (EV_A);
  3647. ev_run (EV_A_ EVRUN_NOWAIT);
  3648. }
  3649. ev_embed_start (EV_A_ w);
  3650. }
  3651. #if 0
  3652. static void
  3653. embed_idle_cb (EV_P_ ev_idle *idle, int revents)
  3654. {
  3655. ev_idle_stop (EV_A_ idle);
  3656. }
  3657. #endif
  3658. void
  3659. ev_embed_start (EV_P_ ev_embed *w) EV_THROW
  3660. {
  3661. if (expect_false (ev_is_active (w)))
  3662. return;
  3663. {
  3664. EV_P = w->other;
  3665. assert (("libev: loop to be embedded is not embeddable", backend & ev_embeddable_backends ()));
  3666. ev_io_init (&w->io, embed_io_cb, backend_fd, EV_READ);
  3667. }
  3668. EV_FREQUENT_CHECK;
  3669. ev_set_priority (&w->io, ev_priority (w));
  3670. ev_io_start (EV_A_ &w->io);
  3671. ev_prepare_init (&w->prepare, embed_prepare_cb);
  3672. ev_set_priority (&w->prepare, EV_MINPRI);
  3673. ev_prepare_start (EV_A_ &w->prepare);
  3674. ev_fork_init (&w->fork, embed_fork_cb);
  3675. ev_fork_start (EV_A_ &w->fork);
  3676. /*ev_idle_init (&w->idle, e,bed_idle_cb);*/
  3677. ev_start (EV_A_ (W)w, 1);
  3678. EV_FREQUENT_CHECK;
  3679. }
  3680. void
  3681. ev_embed_stop (EV_P_ ev_embed *w) EV_THROW
  3682. {
  3683. clear_pending (EV_A_ (W)w);
  3684. if (expect_false (!ev_is_active (w)))
  3685. return;
  3686. EV_FREQUENT_CHECK;
  3687. ev_io_stop (EV_A_ &w->io);
  3688. ev_prepare_stop (EV_A_ &w->prepare);
  3689. ev_fork_stop (EV_A_ &w->fork);
  3690. ev_stop (EV_A_ (W)w);
  3691. EV_FREQUENT_CHECK;
  3692. }
  3693. #endif
  3694. #if EV_FORK_ENABLE
  3695. void
  3696. ev_fork_start (EV_P_ ev_fork *w) EV_THROW
  3697. {
  3698. if (expect_false (ev_is_active (w)))
  3699. return;
  3700. EV_FREQUENT_CHECK;
  3701. ev_start (EV_A_ (W)w, ++forkcnt);
  3702. array_needsize (ev_fork *, forks, forkmax, forkcnt, EMPTY2);
  3703. forks [forkcnt - 1] = w;
  3704. EV_FREQUENT_CHECK;
  3705. }
  3706. void
  3707. ev_fork_stop (EV_P_ ev_fork *w) EV_THROW
  3708. {
  3709. clear_pending (EV_A_ (W)w);
  3710. if (expect_false (!ev_is_active (w)))
  3711. return;
  3712. EV_FREQUENT_CHECK;
  3713. {
  3714. int active = ev_active (w);
  3715. forks [active - 1] = forks [--forkcnt];
  3716. ev_active (forks [active - 1]) = active;
  3717. }
  3718. ev_stop (EV_A_ (W)w);
  3719. EV_FREQUENT_CHECK;
  3720. }
  3721. #endif
  3722. #if EV_CLEANUP_ENABLE
  3723. void
  3724. ev_cleanup_start (EV_P_ ev_cleanup *w) EV_THROW
  3725. {
  3726. if (expect_false (ev_is_active (w)))
  3727. return;
  3728. EV_FREQUENT_CHECK;
  3729. ev_start (EV_A_ (W)w, ++cleanupcnt);
  3730. array_needsize (ev_cleanup *, cleanups, cleanupmax, cleanupcnt, EMPTY2);
  3731. cleanups [cleanupcnt - 1] = w;
  3732. /* cleanup watchers should never keep a refcount on the loop */
  3733. ev_unref (EV_A);
  3734. EV_FREQUENT_CHECK;
  3735. }
  3736. void
  3737. ev_cleanup_stop (EV_P_ ev_cleanup *w) EV_THROW
  3738. {
  3739. clear_pending (EV_A_ (W)w);
  3740. if (expect_false (!ev_is_active (w)))
  3741. return;
  3742. EV_FREQUENT_CHECK;
  3743. ev_ref (EV_A);
  3744. {
  3745. int active = ev_active (w);
  3746. cleanups [active - 1] = cleanups [--cleanupcnt];
  3747. ev_active (cleanups [active - 1]) = active;
  3748. }
  3749. ev_stop (EV_A_ (W)w);
  3750. EV_FREQUENT_CHECK;
  3751. }
  3752. #endif
  3753. #if EV_ASYNC_ENABLE
  3754. void
  3755. ev_async_start (EV_P_ ev_async *w) EV_THROW
  3756. {
  3757. if (expect_false (ev_is_active (w)))
  3758. return;
  3759. w->sent = 0;
  3760. evpipe_init (EV_A);
  3761. EV_FREQUENT_CHECK;
  3762. ev_start (EV_A_ (W)w, ++asynccnt);
  3763. array_needsize (ev_async *, asyncs, asyncmax, asynccnt, EMPTY2);
  3764. asyncs [asynccnt - 1] = w;
  3765. EV_FREQUENT_CHECK;
  3766. }
  3767. void
  3768. ev_async_stop (EV_P_ ev_async *w) EV_THROW
  3769. {
  3770. clear_pending (EV_A_ (W)w);
  3771. if (expect_false (!ev_is_active (w)))
  3772. return;
  3773. EV_FREQUENT_CHECK;
  3774. {
  3775. int active = ev_active (w);
  3776. asyncs [active - 1] = asyncs [--asynccnt];
  3777. ev_active (asyncs [active - 1]) = active;
  3778. }
  3779. ev_stop (EV_A_ (W)w);
  3780. EV_FREQUENT_CHECK;
  3781. }
  3782. void
  3783. ev_async_send (EV_P_ ev_async *w) EV_THROW
  3784. {
  3785. w->sent = 1;
  3786. evpipe_write (EV_A_ &async_pending);
  3787. }
  3788. #endif
  3789. /*****************************************************************************/
  3790. struct ev_once
  3791. {
  3792. ev_io io;
  3793. ev_timer to;
  3794. void (*cb)(int revents, void *arg);
  3795. void *arg;
  3796. };
  3797. static void
  3798. once_cb (EV_P_ struct ev_once *once, int revents)
  3799. {
  3800. void (*cb)(int revents, void *arg) = once->cb;
  3801. void *arg = once->arg;
  3802. ev_io_stop (EV_A_ &once->io);
  3803. ev_timer_stop (EV_A_ &once->to);
  3804. ev_free (once);
  3805. cb (revents, arg);
  3806. }
  3807. static void
  3808. once_cb_io (EV_P_ ev_io *w, int revents)
  3809. {
  3810. struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io));
  3811. once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->to));
  3812. }
  3813. static void
  3814. once_cb_to (EV_P_ ev_timer *w, int revents)
  3815. {
  3816. struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to));
  3817. once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->io));
  3818. }
  3819. void
  3820. ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg) EV_THROW
  3821. {
  3822. struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once));
  3823. if (expect_false (!once))
  3824. {
  3825. cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMER, arg);
  3826. return;
  3827. }
  3828. once->cb = cb;
  3829. once->arg = arg;
  3830. ev_init (&once->io, once_cb_io);
  3831. if (fd >= 0)
  3832. {
  3833. ev_io_set (&once->io, fd, events);
  3834. ev_io_start (EV_A_ &once->io);
  3835. }
  3836. ev_init (&once->to, once_cb_to);
  3837. if (timeout >= 0.)
  3838. {
  3839. ev_timer_set (&once->to, timeout, 0.);
  3840. ev_timer_start (EV_A_ &once->to);
  3841. }
  3842. }
  3843. /*****************************************************************************/
  3844. #if EV_WALK_ENABLE
  3845. void ecb_cold
  3846. ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w)) EV_THROW
  3847. {
  3848. int i, j;
  3849. ev_watcher_list *wl, *wn;
  3850. if (types & (EV_IO | EV_EMBED))
  3851. for (i = 0; i < anfdmax; ++i)
  3852. for (wl = anfds [i].head; wl; )
  3853. {
  3854. wn = wl->next;
  3855. #if EV_EMBED_ENABLE
  3856. if (ev_cb ((ev_io *)wl) == embed_io_cb)
  3857. {
  3858. if (types & EV_EMBED)
  3859. cb (EV_A_ EV_EMBED, ((char *)wl) - offsetof (struct ev_embed, io));
  3860. }
  3861. else
  3862. #endif
  3863. #if EV_USE_INOTIFY
  3864. if (ev_cb ((ev_io *)wl) == infy_cb)
  3865. ;
  3866. else
  3867. #endif
  3868. if ((ev_io *)wl != &pipe_w)
  3869. if (types & EV_IO)
  3870. cb (EV_A_ EV_IO, wl);
  3871. wl = wn;
  3872. }
  3873. if (types & (EV_TIMER | EV_STAT))
  3874. for (i = timercnt + HEAP0; i-- > HEAP0; )
  3875. #if EV_STAT_ENABLE
  3876. /*TODO: timer is not always active*/
  3877. if (ev_cb ((ev_timer *)ANHE_w (timers [i])) == stat_timer_cb)
  3878. {
  3879. if (types & EV_STAT)
  3880. cb (EV_A_ EV_STAT, ((char *)ANHE_w (timers [i])) - offsetof (struct ev_stat, timer));
  3881. }
  3882. else
  3883. #endif
  3884. if (types & EV_TIMER)
  3885. cb (EV_A_ EV_TIMER, ANHE_w (timers [i]));
  3886. #if EV_PERIODIC_ENABLE
  3887. if (types & EV_PERIODIC)
  3888. for (i = periodiccnt + HEAP0; i-- > HEAP0; )
  3889. cb (EV_A_ EV_PERIODIC, ANHE_w (periodics [i]));
  3890. #endif
  3891. #if EV_IDLE_ENABLE
  3892. if (types & EV_IDLE)
  3893. for (j = NUMPRI; j--; )
  3894. for (i = idlecnt [j]; i--; )
  3895. cb (EV_A_ EV_IDLE, idles [j][i]);
  3896. #endif
  3897. #if EV_FORK_ENABLE
  3898. if (types & EV_FORK)
  3899. for (i = forkcnt; i--; )
  3900. if (ev_cb (forks [i]) != embed_fork_cb)
  3901. cb (EV_A_ EV_FORK, forks [i]);
  3902. #endif
  3903. #if EV_ASYNC_ENABLE
  3904. if (types & EV_ASYNC)
  3905. for (i = asynccnt; i--; )
  3906. cb (EV_A_ EV_ASYNC, asyncs [i]);
  3907. #endif
  3908. #if EV_PREPARE_ENABLE
  3909. if (types & EV_PREPARE)
  3910. for (i = preparecnt; i--; )
  3911. # if EV_EMBED_ENABLE
  3912. if (ev_cb (prepares [i]) != embed_prepare_cb)
  3913. # endif
  3914. cb (EV_A_ EV_PREPARE, prepares [i]);
  3915. #endif
  3916. #if EV_CHECK_ENABLE
  3917. if (types & EV_CHECK)
  3918. for (i = checkcnt; i--; )
  3919. cb (EV_A_ EV_CHECK, checks [i]);
  3920. #endif
  3921. #if EV_SIGNAL_ENABLE
  3922. if (types & EV_SIGNAL)
  3923. for (i = 0; i < EV_NSIG - 1; ++i)
  3924. for (wl = signals [i].head; wl; )
  3925. {
  3926. wn = wl->next;
  3927. cb (EV_A_ EV_SIGNAL, wl);
  3928. wl = wn;
  3929. }
  3930. #endif
  3931. #if EV_CHILD_ENABLE
  3932. if (types & EV_CHILD)
  3933. for (i = (EV_PID_HASHSIZE); i--; )
  3934. for (wl = childs [i]; wl; )
  3935. {
  3936. wn = wl->next;
  3937. cb (EV_A_ EV_CHILD, wl);
  3938. wl = wn;
  3939. }
  3940. #endif
  3941. /* EV_STAT 0x00001000 /* stat data changed */
  3942. /* EV_EMBED 0x00010000 /* embedded event loop needs sweep */
  3943. }
  3944. #endif
  3945. #if EV_MULTIPLICITY
  3946. #include "ev_wrap.h"
  3947. #endif