[DRE-commits] [ruby-nio4r] 01/03: Imported Upstream version 1.0.0
Miguel Landaeta
nomadium at moszumanska.debian.org
Sat Jul 26 21:41:15 UTC 2014
This is an automated email from the git hooks/post-receive script.
nomadium pushed a commit to branch master
in repository ruby-nio4r.
commit c43f42bd5485222643b150e5156043031282f562
Author: Miguel Landaeta <nomadium at debian.org>
Date: Fri Jul 25 23:27:58 2014 -0300
Imported Upstream version 1.0.0
---
.gitignore | 20 +
.rspec | 4 +
.travis.yml | 17 +
CHANGES.md | 81 +
Gemfile | 7 +
LICENSE.txt | 20 +
README.md | 188 ++
Rakefile | 9 +
checksums.yaml.gz | Bin 0 -> 267 bytes
examples/echo_server.rb | 47 +
ext/libev/Changes | 477 +++
ext/libev/LICENSE | 37 +
ext/libev/README | 58 +
ext/libev/README.embed | 3 +
ext/libev/ev.c | 4881 +++++++++++++++++++++++++++++++
ext/libev/ev.h | 845 ++++++
ext/libev/ev_epoll.c | 279 ++
ext/libev/ev_kqueue.c | 214 ++
ext/libev/ev_poll.c | 148 +
ext/libev/ev_port.c | 185 ++
ext/libev/ev_select.c | 314 ++
ext/libev/ev_vars.h | 203 ++
ext/libev/ev_win32.c | 163 ++
ext/libev/ev_wrap.h | 200 ++
ext/libev/test_libev_win32.c | 123 +
ext/nio4r/extconf.rb | 44 +
ext/nio4r/libev.h | 9 +
ext/nio4r/monitor.c | 217 ++
ext/nio4r/nio4r.h | 55 +
ext/nio4r/nio4r_ext.c | 16 +
ext/nio4r/org/nio4r/Nio4r.java | 433 +++
ext/nio4r/selector.c | 461 +++
lib/nio.rb | 29 +
lib/nio/monitor.rb | 43 +
lib/nio/selector.rb | 131 +
lib/nio/version.rb | 3 +
logo.png | Bin 0 -> 1529 bytes
metadata.yml | 143 +
nio4r.gemspec | 28 +
spec/nio/acceptables_spec.rb | 32 +
spec/nio/monitor_spec.rb | 61 +
spec/nio/selectables/pipe_spec.rb | 38 +
spec/nio/selectables/ssl_socket_spec.rb | 162 +
spec/nio/selectables/tcp_socket_spec.rb | 88 +
spec/nio/selectables/udp_socket_spec.rb | 31 +
spec/nio/selector_spec.rb | 170 ++
spec/spec_helper.rb | 7 +
spec/support/selectable_examples.rb | 55 +
tasks/extension.rake | 11 +
tasks/rspec.rake | 7 +
50 files changed, 10797 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a831f0a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,20 @@
+*.gem
+*.rbc
+.bundle
+.config
+.yardoc
+Gemfile.lock
+InstalledFiles
+_yardoc
+coverage
+doc/
+lib/bundler/man
+pkg
+rdoc
+spec/reports
+test/tmp
+test/version_tmp
+tmp
+lib/nio4r_ext.*
+ext/**/*.o
+ext/**/nio4r_ext.*
diff --git a/.rspec b/.rspec
new file mode 100644
index 0000000..675313d
--- /dev/null
+++ b/.rspec
@@ -0,0 +1,4 @@
+--color
+--format documentation
+--backtrace
+--default_path spec
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..4bf212b
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,17 @@
+rvm:
+ - 1.9.3
+ - 2.0.0
+ - 2.1.0
+ - ruby-head
+ - jruby
+ - jruby-head
+ - rbx
+
+matrix:
+ allow_failures:
+ - rvm: ruby-head
+ - rvm: jruby-head
+ - rvm: rbx
+
+notifications:
+ irc: "irc.freenode.org#celluloid"
diff --git a/CHANGES.md b/CHANGES.md
new file mode 100644
index 0000000..f67a195
--- /dev/null
+++ b/CHANGES.md
@@ -0,0 +1,81 @@
+1.0.0 (2014-01-14)
+------------------
+* Have Selector#register obtain the actual IO from a Monitor object
+ because Monitor#initialize might convert it.
+* Drop 1.8 support
+
+0.5.0 (2013-08-06)
+------------------
+* Fix segv when attempting to register to a closed selector
+* Fix Windows support on Ruby 2.0.0
+* Upgrade to libev 4.15
+
+0.4.6 (2013-05-27)
+------------------
+* Fix for JRuby on Windows
+
+0.4.5
+-----
+* Fix botched gem release
+
+0.4.4
+-----
+* Fix return values for Selector_synchronize and Selector_unlock
+
+0.4.3
+-----
+* REALLY have thread synchronization when closing selectors ;)
+
+0.4.2
+-----
+* Attempt to work around packaging problems with bundler-api o_O
+
+0.4.1
+-----
+* Thread synchronization when closing selectors
+
+0.4.0
+-----
+* OpenSSL::SSL::SSLSocket support
+
+0.3.3
+-----
+* NIO::Selector#select_each removed
+* Remove event buffer
+* Patch GIL unlock directly into libev
+* Re-release since 0.3.2 was botched :(
+
+0.3.1
+-----
+* Prevent CancelledKeyExceptions on JRuby
+
+0.3.0
+-----
+* NIO::Selector#select now takes a block and behaves like select_each
+* NIO::Selector#select_each is now deprecated and will be removed
+* Closing monitors detaches them from their selector
+* Java extension for JRuby
+* Upgrade to libev 4.11
+* Bugfixes for zero/negative select timeouts
+* Handle OP_CONNECT properly on JRuby
+
+0.2.2
+-----
+* Raise IOError if asked to wake up a closed selector
+
+0.2.1
+-----
+* Implement wakeup mechanism using raw pipes instead of ev_async, since
+ ev_async likes to cause segvs when used across threads (despite claims
+ in the documentation to the contrary)
+
+0.2.0
+-----
+* NIO::Monitor#readiness API to query readiness, along with #readable? and
+ #writable? helper methods
+* NIO::Selector#select_each API which avoids memory allocations if possible
+* Bugfixes for the JRuby implementation
+
+0.1.0
+-----
+* Initial release. Merry Christmas!
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..ae442d1
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,7 @@
+source "https://rubygems.org"
+
+gem 'jruby-openssl' if defined? JRUBY_VERSION
+gem 'coveralls', :require => false
+
+# Specify your gem's dependencies in nio4r.gemspec
+gemspec
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..37965ad
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,20 @@
+Copyright (c) 2011-12 Tony Arcieri
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0caac28
--- /dev/null
+++ b/README.md
@@ -0,0 +1,188 @@
+
+===============
+[](http://rubygems.org/gems/nio4r)
+[](http://travis-ci.org/celluloid/nio4r)
+[](https://codeclimate.com/github/celluloid/nio4r)
+[](https://coveralls.io/r/celluloid/nio4r)
+
+nio4r: New IO for Ruby.
+
+nio4r provides an abstract, cross-platform stateful I/O selector API for Ruby.
+I/O selectors are the heart of "reactor"-based event loops, and monitor
+multiple I/O objects for various types of readiness, e.g. ready for reading or
+writing.
+
+The most similar API provided by Ruby today is Kernel.select, however the
+select API requires you to pass in arrays of all of the I/O objects you're
+interested in every time. nio4r provides a more object-oriented API that lets
+you register I/O objects with a selector then handle them when they're selected
+for various types of events.
+
+nio4r is modeled after the Java NIO API, but simplified for ease-of-use.
+
+Its goals are:
+
+* Expose high-level interfaces for stateful IO selectors
+* Keep the API small to maximize both portability and performance across many
+ different OSes and Ruby VMs
+* Provide inherently thread-safe facilities for working with IO objects
+
+[Celluloid::IO](https://github.com/celluloid/celluloid-io) uses nio4r to
+monitor multiple IO objects from a single Celluloid actor.
+
+Supported Platforms
+-------------------
+
+nio4r is known to work on the following Ruby implementations:
+
+* MRI/YARV 1.9.3, 2.0.0, 2.1.0
+* JRuby 1.7.x
+* Rubinius 2.x
+* A pure Ruby implementation based on Kernel.select is also provided
+
+Platform notes:
+
+* MRI/YARV and Rubinius implement nio4r with a C extension based on libev,
+ which provides a high performance binding to native IO APIs
+* JRuby uses a Java extension based on the high performance Java NIO subsystem
+* A pure Ruby implementation is also provided for Ruby implementations which
+ don't implement the MRI C extension API
+
+Usage
+-----
+
+### Selectors
+
+The NIO::Selector class is the main API provided by nio4r. Use it where you
+might otherwise use Kernel.select, but want to monitor the same set of IO
+objects across multiple select calls rather than having to reregister them
+every single time:
+
+```ruby
+require 'nio'
+
+selector = NIO::Selector.new
+```
+
+To monitor IO objects, attach them to the selector with the NIO::Selector#register
+method, monitoring them for read readiness with the :r parameter, write
+readiness with the :w parameter, or both with :rw.
+
+```ruby
+>> reader, writer = IO.pipe
+ => [#<IO:0xf30>, #<IO:0xf34>]
+>> monitor = selector.register(reader, :r)
+ => #<NIO::Monitor:0xfbc>
+```
+
+After registering an IO object with the selector, you'll get a NIO::Monitor
+object which you can use for managing how a particular IO object is being
+monitored. Monitors will store an arbitrary value of your choice, which
+provides an easy way to implement callbacks:
+
+```ruby
+>> monitor = selector.register(reader, :r)
+ => #<NIO::Monitor:0xfbc>
+>> monitor.value = proc { puts "Got some data: #{monitor.io.read_nonblock(4096)}" }
+ => #<Proc:0x1000@(irb):4>
+```
+
+The main method of importance is NIO::Selector#select, which monitors all
+registered IO objects and returns an array of monitors that are ready.
+
+```ruby
+>> writer << "Hi there!"
+ => #<IO:0x103c>
+>> ready = selector.select
+ => [#<NIO::Monitor:0xfbc>]
+>> ready.each { |m| m.value.call }
+Got some data: Hi there!
+ => [#<NIO::Monitor:0xfbc>]
+```
+
+By default, NIO::Selector#select will block indefinitely until one of the IO
+objects being monitored becomes ready. However, you can also pass a timeout to
+wait in seconds to NIO::Selector#select just like you can with Kernel.select:
+
+```ruby
+ready = selector.select(15) # Wait 15 seconds
+```
+
+If a timeout occurs, ready will be nil.
+
+You can avoid allocating an array each time you call NIO::Selector#select by
+passing a block to select. The block will be called for each ready monitor
+object, with that object passed as an argument. The number of ready monitors
+is returned as a Fixnum:
+
+```ruby
+>> selector.select { |m| m.value.call }
+Got some data: Hi there!
+ => 1
+```
+
+When you're done monitoring a particular IO object, just deregister it from
+the selector:
+
+```ruby
+selector.deregister(reader)
+```
+
+### Monitors
+
+Monitors provide methods which let you introspect on why a particular IO
+object was selected. These methods are not thread safe unless you are holding
+the selector lock (i.e. if you're in a block passed to #select). Only use them
+if you aren't concerned with thread safety, or you're within a #select
+block:
+
+- ***#interests***: what this monitor is interested in (:r, :w, or :rw)
+- ***#readiness***: what the monitored IO object is ready for according to the last select operation
+- ***#readable?***: was the IO readable last time it was selected?
+- ***#writable?***: was the IO writable last time it was selected?
+
+Monitors also support a ***#value*** and ***#value=*** method for storing a
+handle to an arbitrary object of your choice (e.g. a proc)
+
+Concurrency
+-----------
+
+nio4r provides internal locking to ensure that it's safe to use from multiple
+concurrent threads. Only one thread can select on a NIO::Selector at a given
+time, and while a thread is selecting other threads are blocked from
+registering or deregistering IO objects. Once a pending select has completed,
+requests to register/unregister IO objects will be processed.
+
+NIO::Selector#wakeup allows one thread to unblock another thread that's in the
+middle of an NIO::Selector#select operation. This lets other threads that need
+to communicate immediately with the selector unblock it so it can process
+other events that it's not presently selecting on.
+
+What nio4r is not
+-----------------
+
+nio4r is not a full-featured event framework like EventMachine or Cool.io.
+Instead, nio4r is the sort of thing you might write a library like that on
+top of. nio4r provides a minimal API such that individual Ruby implementers
+may choose to produce optimized versions for their platform, without having
+to maintain a large codebase.
+
+As of the time of writing, the current implementation is (approximately):
+
+* 200 lines of Ruby code
+* 700 lines of "custom" C code (not counting libev)
+* 400 lines of Java code
+
+nio4r is also not a replacement for Kinder Gentler IO (KGIO), a set of
+advanced Ruby IO APIs. At some point in the future nio4r might provide a
+cross-platform implementation that uses KGIO on CRubies, and Java NIO on JRuby,
+however this is not the case today.
+
+License
+-------
+
+Copyright (c) 2014 Tony Arcieri. Distributed under the MIT License. See
+LICENSE.txt for further details.
+
+Includes libev 4.15. Copyright (C)2007-09 Marc Alexander Lehmann. Distributed
+under the BSD license. See ext/libev/LICENSE for details.
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..c3e52f9
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,9 @@
+#!/usr/bin/env rake
+require "bundler/gem_tasks"
+require "rake/clean"
+
+Dir[File.expand_path("../tasks/**/*.rake", __FILE__)].each { |task| load task }
+
+task :default => %w(compile spec)
+
+CLEAN.include "**/*.o", "**/*.so", "**/*.bundle", "**/*.jar", "pkg", "tmp"
diff --git a/checksums.yaml.gz b/checksums.yaml.gz
new file mode 100644
index 0000000..3f36d09
Binary files /dev/null and b/checksums.yaml.gz differ
diff --git a/examples/echo_server.rb b/examples/echo_server.rb
new file mode 100644
index 0000000..b3f16a9
--- /dev/null
+++ b/examples/echo_server.rb
@@ -0,0 +1,47 @@
+#!/usr/bin/env ruby
+
+$:.push File.expand_path('../../lib', __FILE__)
+require 'nio'
+require 'socket'
+
+class EchoServer
+ def initialize(host, port)
+ @selector = NIO::Selector.new
+
+ puts "Listening on #{host}:#{port}"
+ @server = TCPServer.new(host, port)
+
+ monitor = @selector.register(@server, :r)
+ monitor.value = proc { accept }
+ end
+
+ def run
+ while true
+ @selector.select { |monitor| monitor.value.call(monitor) }
+ end
+ end
+
+ def accept
+ socket = @server.accept
+ _, port, host = socket.peeraddr
+ puts "*** #{host}:#{port} connected"
+
+ monitor = @selector.register(socket, :r)
+ monitor.value = proc { read(socket) }
+ end
+
+ def read(socket)
+ data = socket.read_nonblock(4096)
+ socket.write_nonblock(data)
+ rescue EOFError
+ _, port, host = socket.peeraddr
+ puts "*** #{host}:#{port} disconnected"
+
+ @selector.deregister(socket)
+ socket.close
+ end
+end
+
+if $0 == __FILE__
+ EchoServer.new("localhost", 1234).run
+end
diff --git a/ext/libev/Changes b/ext/libev/Changes
new file mode 100644
index 0000000..9e8f4f2
--- /dev/null
+++ b/ext/libev/Changes
@@ -0,0 +1,477 @@
+Revision history for libev, a high-performance and full-featured event loop.
+
+TODO: ev_loop_wakeup
+TODO: EV_STANDALONE == NO_HASSEL (do not use clock_gettime in ev_standalone)
+TODO: faq, process a thing in each iteration
+TODO: dbeugging tips, ev_verify, ev_init twice
+TODO: ev_break for immediate exit (EVBREAK_NOW?)
+TODO: ev_feed_child_event
+TODO: document the special problem of signals around fork.
+TODO: store pid for each signal
+TODO: document file descriptor usage per loop
+TODO: store loop pid_t and compare isndie signal handler,store 1 for same, 2 for differign pid, clean up in loop_fork
+TODO: embed watchers need updating when fd changes
+TODO: document portbaility requirements for atomic pointer access
+
+4.15 Fri Mar 1 12:04:50 CET 2013
+ - destroying a non-default loop would stop the global waitpid
+ watcher (Denis Bilenko).
+ - queueing pending watchers of higher priority from a watcher now invokes
+ them in a timely fashion (reported by Denis Bilenko).
+ - add throw() to all libev functions that cannot throw exceptions, for
+ further code size decrease when compiling for C++.
+ - add throw () to callbacks that must not throw exceptions (allocator,
+ syserr, loop acquire/release, periodic reschedule cbs).
+ - fix event_base_loop return code, add event_get_callback, event_base_new,
+ event_base_get_method calls to improve libevent 1.x emulation and add
+ some libevent 2.x functionality (based on a patch by Jeff Davey).
+ - add more memory fences to fix a bug reported by Jeff Davey. Better
+ be overfenced than underprotected.
+ - ev_run now returns a boolean status (true meaning watchers are
+ still active).
+ - ev_once: undef EV_ERROR in ev_kqueue.c, to avoid clashing with
+ libev's EV_ERROR (reported by 191919).
+ - (ecb) add memory fence support for xlC (Darin McBride).
+ - (ecb) add memory fence support for gcc-mips (Anton Kirilov).
+ - (ecb) add memory fence support for gcc-alpha (Christian Weisgerber).
+ - work around some kernels losing file descriptors by leaking
+ the kqueue descriptor in the child.
+ - work around linux inotify not reporting IN_ATTRIB changes for directories
+ in many cases.
+ - include sys/syscall.h instead of plain syscall.h.
+ - check for io watcher loops in ev_verify, check for the most
+ common reported usage bug in ev_io_start.
+ - chose socket vs. WSASocket at compiletime using EV_USE_WSASOCKET.
+ - always use WSASend/WSARecv directly on windows, hoping that this
+ works in all cases (unlike read/write/send/recv...).
+ - try to detect signals around a fork faster (test program by
+ Denis Bilenko).
+ - work around recent glibc versions that leak memory in realloc.
+ - rename ev::embed::set to ev::embed::set_embed to avoid clashing
+ the watcher base set (loop) method.
+ - rewrite the async/signal pipe logic to always keep a valid fd, which
+ simplifies (and hopefuly correctifies :) the race checking
+ on fork, at the cost of one extra fd.
+ - add fat, msdos, jffs2, ramfs, ntfs and btrfs to the list of
+ inotify-supporting filesystems.
+ - move orig_CFLAGS assignment to after AC_INIT, as newer autoconf
+ versions ignore it before
+ (https://bugzilla.redhat.com/show_bug.cgi?id=908096).
+ - add some untested android support.
+ - enum expressions must be of type int (reported by Juan Pablo L).
+
+4.11 Sat Feb 4 19:52:39 CET 2012
+ - INCOMPATIBLE CHANGE: ev_timer_again now clears the pending status, as
+ was documented already, but not implemented in the repeating case.
+ - new compiletime symbols: EV_NO_SMP and EV_NO_THREADS.
+ - fix a race where the workaround against the epoll fork bugs
+ caused signals to not be handled anymore.
+ - correct backend_fudge for most backends, and implement a windows
+ specific workaround to avoid looping because we call both
+ select and Sleep, both with different time resolutions.
+ - document range and guarantees of ev_sleep.
+ - document reasonable ranges for periodics interval and offset.
+ - rename backend_fudge to backend_mintime to avoid future confusion :)
+ - change the default periodic reschedule function to hopefully be more
+ exact and correct even in corner cases or in the far future.
+ - do not rely on -lm anymore: use it when available but use our
+ own floor () if it is missing. This should make it easier to embed,
+ as no external libraries are required.
+ - strategically import macros from libecb and mark rarely-used functions
+ as cache-cold (saving almost 2k code size on typical amd64 setups).
+ - add Symbols.ev and Symbols.event files, that were missing.
+ - fix backend_mintime value for epoll (was 1/1024, is 1/1000 now).
+ - fix #3 "be smart about timeouts" to not "deadlock" when
+ timeout == now, also improve the section overall.
+ - avoid "AVOIDING FINISHING BEFORE RETURNING" idiom.
+ - support new EV_API_STATIC mode to make all libev symbols
+ static.
+ - supply default CFLAGS of -g -O3 with gcc when original CFLAGS
+ were empty.
+
+4.04 Wed Feb 16 09:01:51 CET 2011
+ - fix two problems in the native win32 backend, where reuse of fd's
+ with different underlying handles caused handles not to be removed
+ or added to the select set (analyzed and tested by Bert Belder).
+ - do no rely on ceil() in ev_e?poll.c.
+ - backport libev to HP-UX versions before 11 v3.
+ - configure did not detect nanosleep and clock_gettime properly when
+ they are available in the libc (as opposed to -lrt).
+
+4.03 Tue Jan 11 14:37:25 CET 2011
+ - officially support polling files with all backends.
+ - support files, /dev/zero etc. the same way as select in the epoll
+ backend, by generating events on our own.
+ - ports backend: work around solaris bug 6874410 and many related ones
+ (EINTR, maybe more), with no performance loss (note that the solaris
+ bug report is actually wrong, reality is far more bizarre and broken
+ than that).
+ - define EV_READ/EV_WRITE as macros in event.h, as some programs use
+ #ifdef to test for them.
+ - new (experimental) function: ev_feed_signal.
+ - new (to become default) EVFLAG_NOSIGMASK flag.
+ - new EVBACKEND_MASK symbol.
+ - updated COMMON IDIOMS SECTION.
+
+4.01 Fri Nov 5 21:51:29 CET 2010
+ - automake fucked it up, apparently, --add-missing -f is not quite enough
+ to make it update its files, so 4.00 didn't install ev++.h and
+ event.h on make install. grrr.
+ - ev_loop(count|depth) didn't return anything (Robin Haberkorn).
+ - change EV_UNDEF to 0xffffffff to silence some overzealous compilers.
+ - use "(libev) " prefix for all libev error messages now.
+
+4.00 Mon Oct 25 12:32:12 CEST 2010
+ - "PORTING FROM LIBEV 3.X TO 4.X" (in ev.pod) is recommended reading.
+ - ev_embed_stop did not correctly stop the watcher (very good
+ testcase by Vladimir Timofeev).
+ - ev_run will now always update the current loop time - it erroneously
+ didn't when idle watchers were active, causing timers not to fire.
+ - fix a bug where a timeout of zero caused the timer not to fire
+ in the libevent emulation (testcase by Péter Szabó).
+ - applied win32 fixes by Michael Lenaghan (also James Mansion).
+ - replace EV_MINIMAL by EV_FEATURES.
+ - prefer EPOLL_CTL_ADD over EPOLL_CTL_MOD in some more cases, as it
+ seems the former is *much* faster than the latter.
+ - linux kernel version detection (for inotify bug workarounds)
+ did not work properly.
+ - reduce the number of spurious wake-ups with the ports backend.
+ - remove dependency on sys/queue.h on freebsd (patch by Vanilla Hsu).
+ - do async init within ev_async_start, not ev_async_set, which avoids
+ an API quirk where the set function must be called in the C++ API
+ even when there is nothing to set.
+ - add (undocumented) EV_ENABLE when adding events with kqueue,
+ this might help with OS X, which seems to need it despite documenting
+ not to need it (helpfully pointed out by Tilghman Lesher).
+ - do not use poll by default on freebsd, it's broken (what isn't
+ on freebsd...).
+ - allow to embed epoll on kernels >= 2.6.32.
+ - configure now prepends -O3, not appends it, so one can still
+ override it.
+ - ev.pod: greatly expanded the portability section, added a porting
+ section, a description of watcher states and made lots of minor fixes.
+ - disable poll backend on AIX, the poll header spams the namespace
+ and it's not worth working around dead platforms (reported
+ and analyzed by Aivars Kalvans).
+ - improve header file compatibility of the standalone eventfd code
+ in an obscure case.
+ - implement EV_AVOID_STDIO option.
+ - do not use sscanf to parse linux version number (smaller, faster,
+ no sscanf dependency).
+ - new EV_CHILD_ENABLE and EV_SIGNAL_ENABLE configurable settings.
+ - update libev.m4 HAVE_CLOCK_SYSCALL test for newer glibcs.
+ - add section on accept() problems to the manpage.
+ - rename EV_TIMEOUT to EV_TIMER.
+ - rename ev_loop_count/depth/verify/loop/unloop.
+ - remove ev_default_destroy and ev_default_fork.
+ - switch to two-digit minor version.
+ - work around an apparent gentoo compiler bug.
+ - define _DARWIN_UNLIMITED_SELECT. just so.
+ - use enum instead of #define for most constants.
+ - improve compatibility to older C++ compilers.
+ - (experimental) ev_run/ev_default_loop/ev_break/ev_loop_new have now
+ default arguments when compiled as C++.
+ - enable automake dependency tracking.
+ - ev_loop_new no longer leaks memory when loop creation failed.
+ - new ev_cleanup watcher type.
+
+3.9 Thu Dec 31 07:59:59 CET 2009
+ - signalfd is no longer used by default and has to be requested
+ explicitly - this means that easy to catch bugs become hard to
+ catch race conditions, but the users have spoken.
+ - point out the unspecified signal mask in the documentation, and
+ that this is a race condition regardless of EV_SIGNALFD.
+ - backport inotify code to C89.
+ - inotify file descriptors could leak into child processes.
+ - ev_stat watchers could keep an erroneous extra ref on the loop,
+ preventing exit when unregistering all watchers (testcases
+ provided by ry at tinyclouds.org).
+ - implement EV_WIN32_HANDLE_TO_FD and EV_WIN32_CLOSE_FD configuration
+ symbols to make it easier for apps to do their own fd management.
+ - support EV_IDLE_ENABLE being disabled in ev++.h
+ (patch by Didier Spezia).
+ - take advantage of inotify_init1, if available, to set cloexec/nonblock
+ on fd creation, to avoid races.
+ - the signal handling pipe wasn't always initialised under windows
+ (analysed by lekma).
+ - changed minimum glibc requirement from glibc 2.9 to 2.7, for
+ signalfd.
+ - add missing string.h include (Denis F. Latypoff).
+ - only replace ev_stat.prev when we detect an actual difference,
+ so prev is (almost) always different to attr. this might
+ have caused the problems with 04_stat.t.
+ - add ev::timer->remaining () method to C++ API.
+
+3.8 Sun Aug 9 14:30:45 CEST 2009
+ - incompatible change: do not necessarily reset signal handler
+ to SIG_DFL when a sighandler is stopped.
+ - ev_default_destroy did not properly free or zero some members,
+ potentially causing crashes and memory corruption on repeated
+ ev_default_destroy/ev_default_loop calls.
+ - take advantage of signalfd on GNU/Linux systems.
+ - document that the signal mask might be in an unspecified
+ state when using libev's signal handling.
+ - take advantage of some GNU/Linux calls to set cloexec/nonblock
+ on fd creation, to avoid race conditions.
+
+3.7 Fri Jul 17 16:36:32 CEST 2009
+ - ev_unloop and ev_loop wrongly used a global variable to exit loops,
+ instead of using a per-loop variable (bug caught by accident...).
+ - the ev_set_io_collect_interval interpretation has changed.
+ - add new functionality: ev_set_userdata, ev_userdata,
+ ev_set_invoke_pending_cb, ev_set_loop_release_cb,
+ ev_invoke_pending, ev_pending_count, together with a long example
+ about thread locking.
+ - add ev_timer_remaining (as requested by Denis F. Latypoff).
+ - add ev_loop_depth.
+ - calling ev_unloop in fork/prepare watchers will no longer poll
+ for new events.
+ - Denis F. Latypoff corrected many typos in example code snippets.
+ - honor autoconf detection of EV_USE_CLOCK_SYSCALL, also double-
+ check that the syscall number is available before trying to
+ use it (reported by ry at tinyclouds).
+ - use GetSystemTimeAsFileTime instead of _timeb on windows, for
+ slightly higher accuracy.
+ - properly declare ev_loop_verify and ev_now_update even when
+ !EV_MULTIPLICITY.
+ - do not compile in any priority code when EV_MAXPRI == EV_MINPRI.
+ - support EV_MINIMAL==2 for a reduced API.
+ - actually 0-initialise struct sigaction when installing signals.
+ - add section on hibernate and stopped processes to ev_timer docs.
+
+3.6 Tue Apr 28 02:49:30 CEST 2009
+ - multiple timers becoming ready within an event loop iteration
+ will be invoked in the "correct" order now.
+ - do not leave the event loop early just because we have no active
+ watchers, fixing a problem when embedding a kqueue loop
+ that has active kernel events but no registered watchers
+ (reported by blacksand blacksand).
+ - correctly zero the idx values for arrays, so destroying and
+ reinitialising the default loop actually works (patch by
+ Malek Hadj-Ali).
+ - implement ev_suspend and ev_resume.
+ - new EV_CUSTOM revents flag for use by applications.
+ - add documentation section about priorities.
+ - add a glossary to the dcoumentation.
+ - extend the ev_fork description slightly.
+ - optimize a jump out of call_pending.
+
+3.53 Sun Feb 15 02:38:20 CET 2009
+ - fix a bug in event pipe creation on win32 that would cause a
+ failed assertion on event loop creation (patch by Malek Hadj-Ali).
+ - probe for CLOCK_REALTIME support at runtime as well and fall
+ back to gettimeofday if there is an error, to support older
+ operating systems with newer header files/libraries.
+ - prefer gettimeofday over clock_gettime with USE_CLOCK_SYSCALL
+ (default most everywhere), otherwise not.
+
+3.52 Wed Jan 7 21:43:02 CET 2009
+ - fix compilation of select backend in fd_set mode when NFDBITS is
+ missing (to get it to compile on QNX, reported by Rodrigo Campos).
+ - better select-nfds handling when select backend is in fd_set mode.
+ - diagnose fd_set overruns when select backend is in fd_set mode.
+ - due to a thinko, instead of disabling everything but
+ select on the borked OS X platform, everything but select was
+ allowed (reported by Emanuele Giaquinta).
+ - actually verify that local and remote port are matching in
+ libev's socketpair emulation, which makes denial-of-service
+ attacks harder (but not impossible - it's windows). Make sure
+ it even works under vista, which thinks that getpeer/sockname
+ should return fantasy port numbers.
+ - include "libev" in all assertion messages for potentially
+ clearer diagnostics.
+ - event_get_version (libevent compatibility) returned
+ a useless string instead of the expected version string
+ (patch by W.C.A. Wijngaards).
+
+3.51 Wed Dec 24 23:00:11 CET 2008
+ - fix a bug where an inotify watcher was added twice, causing
+ freezes on hash collisions (reported and analysed by Graham Leggett).
+ - new config symbol, EV_USE_CLOCK_SYSCALL, to make libev use
+ a direct syscall - slower, but no dependency on librt et al.
+ - assume negative return values != -1 signals success of port_getn
+ (http://cvs.epicsol.org/cgi/viewcvs.cgi/epic5/source/newio.c?rev=1.52)
+ (no known failure reports, but it doesn't hurt).
+ - fork detection in ev_embed now stops and restarts the watcher
+ automatically.
+ - EXPERIMENTAL: default the method to operator () in ev++.h,
+ to make it nicer to use functors (requested by Benedek László).
+ - fixed const object callbacks in ev++.h.
+ - replaced loop_ref argument of watcher.set (loop) by a direct
+ ev_loop * in ev++.h, to avoid clashes with functor patch.
+ - do not try to watch the empty string via inotify.
+ - inotify watchers could be leaked under certain circumstances.
+ - OS X 10.5 is actually even more broken than earlier versions,
+ so fall back to select on that piece of garbage.
+ - fixed some weirdness in the ev_embed documentation.
+
+3.49 Wed Nov 19 11:26:53 CET 2008
+ - ev_stat watchers will now use inotify as a mere hint on
+ kernels <2.6.25, or if the filesystem is not in the
+ "known to be good" list.
+ - better mingw32 compatibility (it's not as borked as native win32)
+ (analysed by Roger Pack).
+ - include stdio.h in the example program, as too many people are
+ confused by the weird C language otherwise. I guess the next thing
+ I get told is that the "..." ellipses in the examples don't compile
+ with their C compiler.
+
+3.48 Thu Oct 30 09:02:37 CET 2008
+ - further optimise away the EPOLL_CTL_ADD/MOD combo in the epoll
+ backend by assuming the kernel event mask hasn't changed if
+ ADD fails with EEXIST.
+ - work around spurious event notification bugs in epoll by using
+ a 32-bit generation counter. recreate kernel state if we receive
+ spurious notifications or unwanted events. this is very costly,
+ but I didn't come up with this horrible design.
+ - use memset to initialise most arrays now and do away with the
+ init functions.
+ - expand time-out strategies into a "Be smart about timeouts" section.
+ - drop the "struct" from all ev_watcher declarations in the
+ documentation and did other clarifications (yeah, it was a mistake
+ to have a struct AND a function called ev_loop).
+ - fix a bug where ev_default would not initialise the default
+ loop again after it was destroyed with ev_default_destroy.
+ - rename syserr to ev_syserr to avoid name clashes when embedding,
+ do similar changes for event.c.
+
+3.45 Tue Oct 21 21:59:26 CEST 2008
+ - disable inotify usage on linux <2.6.25, as it is broken
+ (reported by Yoann Vandoorselaere).
+ - ev_stat erroneously would try to add inotify watchers
+ even when inotify wasn't available (this should only
+ have a performance impact).
+ - ev_once now passes both timeout and io to the callback if both
+ occur concurrently, instead of giving timeouts precedence.
+ - disable EV_USE_INOTIFY when sys/inotify.h is too old.
+
+3.44 Mon Sep 29 05:18:39 CEST 2008
+ - embed watchers now automatically invoke ev_loop_fork on the
+ embedded loop when the parent loop forks.
+ - new function: ev_now_update (loop).
+ - verify_watcher was not marked static.
+ - improve the "associating..." manpage section.
+ - documentation tweaks here and there.
+
+3.43 Sun Jul 6 05:34:41 CEST 2008
+ - include more include files on windows to get struct _stati64
+ (reported by Chris Hulbert, but doesn't quite fix his issue).
+ - add missing #include <io.h> in ev.c on windows (reported by
+ Matt Tolton).
+
+3.42 Tue Jun 17 12:12:07 CEST 2008
+ - work around yet another windows bug: FD_SET actually adds fd's
+ multiple times to the fd_*SET*, despite official MSN docs claiming
+ otherwise. Reported and well-analysed by Matt Tolton.
+ - define NFDBITS to 0 when EV_SELECT_IS_WINSOCKET to make it compile
+ (reported any analysed by Chris Hulbert).
+ - fix a bug in ev_ebadf (this function is only used to catch
+ programming errors in the libev user). reported by Matt Tolton.
+ - fix a bug in fd_intern on win32 (could lead to compile errors
+ under some circumstances, but would work correctly if it compiles).
+ reported by Matt Tolton.
+ - (try to) work around missing lstat on windows.
+ - pass in the write fd set as except fd set under windows. windows
+ is so uncontrollably lame that it requires this. this means that
+ switching off oobinline is not supported (but tcp/ip doesn't
+ have oob, so that would be stupid anyways.
+ - use posix module symbol to auto-detect monotonic clock presence
+ and some other default values.
+
+3.41 Fri May 23 18:42:54 CEST 2008
+ - work around an obscure bug in winsocket select: if you
+ provide only empty fd sets then select returns WSAEINVAL. how sucky.
+ - improve timer scheduling stability and reduce use of time_epsilon.
+ - use 1-based 2-heap for EV_MINIMAL, simplifies code, reduces
+ codesize and makes for better cache-efficiency.
+ - use 3-based 4-heap for !EV_MINIMAL. this makes better use
+ of cpu cache lines and gives better growth behaviour than
+ 2-based heaps.
+ - cache timestamp within heap for !EV_MINIMAL, to avoid random
+ memory accesses.
+ - document/add EV_USE_4HEAP and EV_HEAP_CACHE_AT.
+ - fix a potential aliasing issue in ev_timer_again.
+ - add/document ev_periodic_at, retract direct access to ->at.
+ - improve ev_stat docs.
+ - add portability requirements section.
+ - fix manpage headers etc.
+ - normalise WSA error codes to lower range on windows.
+ - add consistency check code that can be called automatically
+ or on demand to check for internal structures (ev_loop_verify).
+
+3.31 Wed Apr 16 20:45:04 CEST 2008
+ - added last minute fix for ev_poll.c by Brandon Black.
+
+3.3 Wed Apr 16 19:04:10 CEST 2008
+ - event_base_loopexit should return 0 on success
+ (W.C.A. Wijngaards).
+ - added linux eventfd support.
+ - try to autodetect epoll and inotify support
+ by libc header version if not using autoconf.
+ - new symbols: EV_DEFAULT_UC and EV_DEFAULT_UC_.
+ - declare functions defined in ev.h as inline if
+ C99 or gcc are available.
+ - enable inlining with gcc versions 2 and 3.
+ - work around broken poll implementations potentially
+ not clearing revents field in ev_poll (Brandon Black)
+ (no such systems are known at this time).
+ - work around a bug in realloc on openbsd and darwin,
+ also makes the erroneous valgrind complaints
+ go away (noted by various people).
+ - fix ev_async_pending, add c++ wrapper for ev_async
+ (based on patch sent by Johannes Deisenhofer).
+ - add sensible set method to ev::embed.
+ - made integer constants type int in ev.h.
+
+3.2 Wed Apr 2 17:11:19 CEST 2008
+ - fix a 64 bit overflow issue in the select backend,
+ by using fd_mask instead of int for the mask.
+ - rename internal sighandler to avoid clash with very old perls.
+ - entering ev_loop will not clear the ONESHOT or NONBLOCKING
+ flags of any outer loops anymore.
+ - add ev_async_pending.
+
+3.1 Thu Mar 13 13:45:22 CET 2008
+ - implement ev_async watchers.
+ - only initialise signal pipe on demand.
+ - make use of sig_atomic_t configurable.
+ - improved documentation.
+
+3.0 Mon Jan 28 13:14:47 CET 2008
+ - API/ABI bump to version 3.0.
+ - ev++.h includes "ev.h" by default now, not <ev.h>.
+ - slightly improved documentation.
+ - speed up signal detection after a fork.
+ - only optionally return trace status changed in ev_child
+ watchers.
+ - experimental (and undocumented) loop wrappers for ev++.h.
+
+2.01 Tue Dec 25 08:04:41 CET 2007
+ - separate Changes file.
+ - fix ev_path_set => ev_stat_set typo.
+ - remove event_compat.h from the libev tarball.
+ - change how include files are found.
+ - doc updates.
+ - update licenses, explicitly allow for GPL relicensing.
+
+2.0 Sat Dec 22 17:47:03 CET 2007
+ - new ev_sleep, ev_set_(io|timeout)_collect_interval.
+ - removed epoll from embeddable fd set.
+ - fix embed watchers.
+ - renamed ev_embed.loop to other.
+ - added exported Symbol tables.
+ - undefine member wrapper macros at the end of ev.c.
+ - respect EV_H in ev++.h.
+
+1.86 Tue Dec 18 02:36:57 CET 2007
+ - fix memleak on loop destroy (not relevant for perl).
+
+1.85 Fri Dec 14 20:32:40 CET 2007
+ - fix some aliasing issues w.r.t. timers and periodics
+ (not relevant for perl).
+
+(for historic versions refer to EV/Changes, found in the Perl interface)
+
+0.1 Wed Oct 31 21:31:48 CET 2007
+ - original version; hacked together in <24h.
+
diff --git a/ext/libev/LICENSE b/ext/libev/LICENSE
new file mode 100644
index 0000000..777d67c
--- /dev/null
+++ b/ext/libev/LICENSE
@@ -0,0 +1,37 @@
+All files in libev are
+Copyright (c)2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Alternatively, the contents of this package may be used under the terms
+of the GNU General Public License ("GPL") version 2 or any later version,
+in which case the provisions of the GPL are applicable instead of the
+above. If you wish to allow the use of your version of this package only
+under the terms of the GPL and not to allow others to use your version of
+this file under the BSD license, indicate your decision by deleting the
+provisions above and replace them with the notice and other provisions
+required by the GPL in this and the other files of this package. If you do
+not delete the provisions above, a recipient may use your version of this
+file under either the BSD or the GPL.
diff --git a/ext/libev/README b/ext/libev/README
new file mode 100644
index 0000000..f5f3581
--- /dev/null
+++ b/ext/libev/README
@@ -0,0 +1,58 @@
+libev is a high-performance event loop/event model with lots of features.
+(see benchmark at http://libev.schmorp.de/bench.html)
+
+
+ABOUT
+
+ Homepage: http://software.schmorp.de/pkg/libev
+ Mailinglist: libev at lists.schmorp.de
+ http://lists.schmorp.de/cgi-bin/mailman/listinfo/libev
+ Library Documentation: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod
+
+ Libev is modelled (very losely) after libevent and the Event perl
+ module, but is faster, scales better and is more correct, and also more
+ featureful. And also smaller. Yay.
+
+ Some of the specialties of libev not commonly found elsewhere are:
+
+ - extensive and detailed, readable documentation (not doxygen garbage).
+ - fully supports fork, can detect fork in various ways and automatically
+ re-arms kernel mechanisms that do not support fork.
+ - highly optimised select, poll, epoll, kqueue and event ports backends.
+ - filesystem object (path) watching (with optional linux inotify support).
+ - wallclock-based times (using absolute time, cron-like).
+ - relative timers/timeouts (handle time jumps).
+ - fast intra-thread communication between multiple
+ event loops (with optional fast linux eventfd backend).
+ - extremely easy to embed (fully documented, no dependencies,
+ autoconf supported but optional).
+ - very small codebase, no bloated library, simple code.
+ - fully extensible by being able to plug into the event loop,
+ integrate other event loops, integrate other event loop users.
+ - very little memory use (small watchers, small event loop data).
+ - optional C++ interface allowing method and function callbacks
+ at no extra memory or runtime overhead.
+ - optional Perl interface with similar characteristics (capable
+ of running Glib/Gtk2 on libev).
+ - support for other languages (multiple C++ interfaces, D, Ruby,
+ Python) available from third-parties.
+
+ Examples of programs that embed libev: the EV perl module, node.js,
+ auditd, rxvt-unicode, gvpe (GNU Virtual Private Ethernet), the
+ Deliantra MMORPG server (http://www.deliantra.net/), Rubinius (a
+ next-generation Ruby VM), the Ebb web server, the Rev event toolkit.
+
+
+CONTRIBUTORS
+
+ libev was written and designed by Marc Lehmann and Emanuele Giaquinta.
+
+ The following people sent in patches or made other noteworthy
+ contributions to the design (for minor patches, see the Changes
+ file. If I forgot to include you, please shout at me, it was an
+ accident):
+
+ W.C.A. Wijngaards
+ Christopher Layne
+ Chris Brody
+
diff --git a/ext/libev/README.embed b/ext/libev/README.embed
new file mode 100644
index 0000000..0d1bd5e
--- /dev/null
+++ b/ext/libev/README.embed
@@ -0,0 +1,3 @@
+This file is now included in the main libev documentation, see
+
+ http://cvs.schmorp.de/libev/ev.html
diff --git a/ext/libev/ev.c b/ext/libev/ev.c
new file mode 100644
index 0000000..4f96d25
--- /dev/null
+++ b/ext/libev/ev.c
@@ -0,0 +1,4881 @@
+/*
+ * libev event processing core, watcher management
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+/* ########## NIO4R PATCHERY HO! ########## */
+#include "ruby.h"
+/* ######################################## */
+
+/* this big block deduces configuration from config.h */
+#ifndef EV_STANDALONE
+# ifdef EV_CONFIG_H
+# include EV_CONFIG_H
+# else
+# include "config.h"
+# endif
+
+#if HAVE_FLOOR
+# ifndef EV_USE_FLOOR
+# define EV_USE_FLOOR 1
+# endif
+#endif
+
+# if HAVE_CLOCK_SYSCALL
+# ifndef EV_USE_CLOCK_SYSCALL
+# define EV_USE_CLOCK_SYSCALL 1
+# ifndef EV_USE_REALTIME
+# define EV_USE_REALTIME 0
+# endif
+# ifndef EV_USE_MONOTONIC
+# define EV_USE_MONOTONIC 1
+# endif
+# endif
+# elif !defined EV_USE_CLOCK_SYSCALL
+# define EV_USE_CLOCK_SYSCALL 0
+# endif
+
+# if HAVE_CLOCK_GETTIME
+# ifndef EV_USE_MONOTONIC
+# define EV_USE_MONOTONIC 1
+# endif
+# ifndef EV_USE_REALTIME
+# define EV_USE_REALTIME 0
+# endif
+# else
+# ifndef EV_USE_MONOTONIC
+# define EV_USE_MONOTONIC 0
+# endif
+# ifndef EV_USE_REALTIME
+# define EV_USE_REALTIME 0
+# endif
+# endif
+
+# if HAVE_NANOSLEEP
+# ifndef EV_USE_NANOSLEEP
+# define EV_USE_NANOSLEEP EV_FEATURE_OS
+# endif
+# else
+# undef EV_USE_NANOSLEEP
+# define EV_USE_NANOSLEEP 0
+# endif
+
+# if HAVE_SELECT && HAVE_SYS_SELECT_H
+# ifndef EV_USE_SELECT
+# define EV_USE_SELECT EV_FEATURE_BACKENDS
+# endif
+# else
+# undef EV_USE_SELECT
+# define EV_USE_SELECT 0
+# endif
+
+# if HAVE_POLL && HAVE_POLL_H
+# ifndef EV_USE_POLL
+# define EV_USE_POLL EV_FEATURE_BACKENDS
+# endif
+# else
+# undef EV_USE_POLL
+# define EV_USE_POLL 0
+# endif
+
+# if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
+# ifndef EV_USE_EPOLL
+# define EV_USE_EPOLL EV_FEATURE_BACKENDS
+# endif
+# else
+# undef EV_USE_EPOLL
+# define EV_USE_EPOLL 0
+# endif
+
+# if HAVE_KQUEUE && HAVE_SYS_EVENT_H
+# ifndef EV_USE_KQUEUE
+# define EV_USE_KQUEUE EV_FEATURE_BACKENDS
+# endif
+# else
+# undef EV_USE_KQUEUE
+# define EV_USE_KQUEUE 0
+# endif
+
+# if HAVE_PORT_H && HAVE_PORT_CREATE
+# ifndef EV_USE_PORT
+# define EV_USE_PORT EV_FEATURE_BACKENDS
+# endif
+# else
+# undef EV_USE_PORT
+# define EV_USE_PORT 0
+# endif
+
+# if HAVE_INOTIFY_INIT && HAVE_SYS_INOTIFY_H
+# ifndef EV_USE_INOTIFY
+# define EV_USE_INOTIFY EV_FEATURE_OS
+# endif
+# else
+# undef EV_USE_INOTIFY
+# define EV_USE_INOTIFY 0
+# endif
+
+# if HAVE_SIGNALFD && HAVE_SYS_SIGNALFD_H
+# ifndef EV_USE_SIGNALFD
+# define EV_USE_SIGNALFD EV_FEATURE_OS
+# endif
+# else
+# undef EV_USE_SIGNALFD
+# define EV_USE_SIGNALFD 0
+# endif
+
+# if HAVE_EVENTFD
+# ifndef EV_USE_EVENTFD
+# define EV_USE_EVENTFD EV_FEATURE_OS
+# endif
+# else
+# undef EV_USE_EVENTFD
+# define EV_USE_EVENTFD 0
+# endif
+
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <stddef.h>
+
+#include <stdio.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <time.h>
+#include <limits.h>
+
+#include <signal.h>
+
+#ifdef EV_H
+# include EV_H
+#else
+# include "ev.h"
+#endif
+
+#if EV_NO_THREADS
+# undef EV_NO_SMP
+# define EV_NO_SMP 1
+# undef ECB_NO_THREADS
+# define ECB_NO_THREADS 1
+#endif
+#if EV_NO_SMP
+# undef EV_NO_SMP
+# define ECB_NO_SMP 1
+#endif
+
+#ifndef _WIN32
+# include <sys/time.h>
+# include <sys/wait.h>
+# include <unistd.h>
+#else
+# include <io.h>
+# define WIN32_LEAN_AND_MEAN
+# include <winsock2.h>
+# include <windows.h>
+# ifndef EV_SELECT_IS_WINSOCKET
+# define EV_SELECT_IS_WINSOCKET 1
+# endif
+# undef EV_AVOID_STDIO
+#endif
+
+/* OS X, in its infinite idiocy, actually HARDCODES
+ * a limit of 1024 into their select. Where people have brains,
+ * OS X engineers apparently have a vacuum. Or maybe they were
+ * ordered to have a vacuum, or they do anything for money.
+ * This might help. Or not.
+ */
+#define _DARWIN_UNLIMITED_SELECT 1
+
+/* this block tries to deduce configuration from header-defined symbols and defaults */
+
+/* try to deduce the maximum number of signals on this platform */
+#if defined EV_NSIG
+/* use what's provided */
+#elif defined NSIG
+# define EV_NSIG (NSIG)
+#elif defined _NSIG
+# define EV_NSIG (_NSIG)
+#elif defined SIGMAX
+# define EV_NSIG (SIGMAX+1)
+#elif defined SIG_MAX
+# define EV_NSIG (SIG_MAX+1)
+#elif defined _SIG_MAX
+# define EV_NSIG (_SIG_MAX+1)
+#elif defined MAXSIG
+# define EV_NSIG (MAXSIG+1)
+#elif defined MAX_SIG
+# define EV_NSIG (MAX_SIG+1)
+#elif defined SIGARRAYSIZE
+# define EV_NSIG (SIGARRAYSIZE) /* Assume ary[SIGARRAYSIZE] */
+#elif defined _sys_nsig
+# define EV_NSIG (_sys_nsig) /* Solaris 2.5 */
+#else
+# error "unable to find value for NSIG, please report"
+/* to make it compile regardless, just remove the above line, */
+/* but consider reporting it, too! :) */
+# define EV_NSIG 65
+#endif
+
+#ifndef EV_USE_FLOOR
+# define EV_USE_FLOOR 0
+#endif
+
+#ifndef EV_USE_CLOCK_SYSCALL
+# if __linux && __GLIBC__ >= 2
+# define EV_USE_CLOCK_SYSCALL EV_FEATURE_OS
+# else
+# define EV_USE_CLOCK_SYSCALL 0
+# endif
+#endif
+
+#ifndef EV_USE_MONOTONIC
+# if defined _POSIX_MONOTONIC_CLOCK && _POSIX_MONOTONIC_CLOCK >= 0
+# define EV_USE_MONOTONIC EV_FEATURE_OS
+# else
+# define EV_USE_MONOTONIC 0
+# endif
+#endif
+
+#ifndef EV_USE_REALTIME
+# define EV_USE_REALTIME !EV_USE_CLOCK_SYSCALL
+#endif
+
+#ifndef EV_USE_NANOSLEEP
+# if _POSIX_C_SOURCE >= 199309L
+# define EV_USE_NANOSLEEP EV_FEATURE_OS
+# else
+# define EV_USE_NANOSLEEP 0
+# endif
+#endif
+
+#ifndef EV_USE_SELECT
+# define EV_USE_SELECT EV_FEATURE_BACKENDS
+#endif
+
+#ifndef EV_USE_POLL
+# ifdef _WIN32
+# define EV_USE_POLL 0
+# else
+# define EV_USE_POLL EV_FEATURE_BACKENDS
+# endif
+#endif
+
+#ifndef EV_USE_EPOLL
+# if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
+# define EV_USE_EPOLL EV_FEATURE_BACKENDS
+# else
+# define EV_USE_EPOLL 0
+# endif
+#endif
+
+#ifndef EV_USE_KQUEUE
+# define EV_USE_KQUEUE 0
+#endif
+
+#ifndef EV_USE_PORT
+# define EV_USE_PORT 0
+#endif
+
+#ifndef EV_USE_INOTIFY
+# if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
+# define EV_USE_INOTIFY EV_FEATURE_OS
+# else
+# define EV_USE_INOTIFY 0
+# endif
+#endif
+
+#ifndef EV_PID_HASHSIZE
+# define EV_PID_HASHSIZE EV_FEATURE_DATA ? 16 : 1
+#endif
+
+#ifndef EV_INOTIFY_HASHSIZE
+# define EV_INOTIFY_HASHSIZE EV_FEATURE_DATA ? 16 : 1
+#endif
+
+#ifndef EV_USE_EVENTFD
+# if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
+# define EV_USE_EVENTFD EV_FEATURE_OS
+# else
+# define EV_USE_EVENTFD 0
+# endif
+#endif
+
+#ifndef EV_USE_SIGNALFD
+# if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
+# define EV_USE_SIGNALFD EV_FEATURE_OS
+# else
+# define EV_USE_SIGNALFD 0
+# endif
+#endif
+
+#if 0 /* debugging */
+# define EV_VERIFY 3
+# define EV_USE_4HEAP 1
+# define EV_HEAP_CACHE_AT 1
+#endif
+
+#ifndef EV_VERIFY
+# define EV_VERIFY (EV_FEATURE_API ? 1 : 0)
+#endif
+
+#ifndef EV_USE_4HEAP
+# define EV_USE_4HEAP EV_FEATURE_DATA
+#endif
+
+#ifndef EV_HEAP_CACHE_AT
+# define EV_HEAP_CACHE_AT EV_FEATURE_DATA
+#endif
+
+#ifdef ANDROID
+/* supposedly, android doesn't typedef fd_mask */
+# undef EV_USE_SELECT
+# define EV_USE_SELECT 0
+/* supposedly, we need to include syscall.h, not sys/syscall.h, so just disable */
+# undef EV_USE_CLOCK_SYSCALL
+# define EV_USE_CLOCK_SYSCALL 0
+#endif
+
+/* aix's poll.h seems to cause lots of trouble */
+#ifdef _AIX
+/* AIX has a completely broken poll.h header */
+# undef EV_USE_POLL
+# define EV_USE_POLL 0
+#endif
+
+/* on linux, we can use a (slow) syscall to avoid a dependency on pthread, */
+/* which makes programs even slower. might work on other unices, too. */
+#if EV_USE_CLOCK_SYSCALL
+# include <sys/syscall.h>
+# ifdef SYS_clock_gettime
+# define clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts))
+# undef EV_USE_MONOTONIC
+# define EV_USE_MONOTONIC 1
+# else
+# undef EV_USE_CLOCK_SYSCALL
+# define EV_USE_CLOCK_SYSCALL 0
+# endif
+#endif
+
+/* this block fixes any misconfiguration where we know we run into trouble otherwise */
+
+#ifndef CLOCK_MONOTONIC
+# undef EV_USE_MONOTONIC
+# define EV_USE_MONOTONIC 0
+#endif
+
+#ifndef CLOCK_REALTIME
+# undef EV_USE_REALTIME
+# define EV_USE_REALTIME 0
+#endif
+
+#if !EV_STAT_ENABLE
+# undef EV_USE_INOTIFY
+# define EV_USE_INOTIFY 0
+#endif
+
+#if !EV_USE_NANOSLEEP
+/* hp-ux has it in sys/time.h, which we unconditionally include above */
+# if !defined _WIN32 && !defined __hpux
+# include <sys/select.h>
+# endif
+#endif
+
+#if EV_USE_INOTIFY
+# include <sys/statfs.h>
+# include <sys/inotify.h>
+/* some very old inotify.h headers don't have IN_DONT_FOLLOW */
+# ifndef IN_DONT_FOLLOW
+# undef EV_USE_INOTIFY
+# define EV_USE_INOTIFY 0
+# endif
+#endif
+
+#if EV_USE_EVENTFD
+/* our minimum requirement is glibc 2.7 which has the stub, but not the header */
+# include <stdint.h>
+# ifndef EFD_NONBLOCK
+# define EFD_NONBLOCK O_NONBLOCK
+# endif
+# ifndef EFD_CLOEXEC
+# ifdef O_CLOEXEC
+# define EFD_CLOEXEC O_CLOEXEC
+# else
+# define EFD_CLOEXEC 02000000
+# endif
+# endif
+EV_CPP(extern "C") int (eventfd) (unsigned int initval, int flags);
+#endif
+
+#if EV_USE_SIGNALFD
+/* our minimum requirement is glibc 2.7 which has the stub, but not the header */
+# include <stdint.h>
+# ifndef SFD_NONBLOCK
+# define SFD_NONBLOCK O_NONBLOCK
+# endif
+# ifndef SFD_CLOEXEC
+# ifdef O_CLOEXEC
+# define SFD_CLOEXEC O_CLOEXEC
+# else
+# define SFD_CLOEXEC 02000000
+# endif
+# endif
+EV_CPP (extern "C") int signalfd (int fd, const sigset_t *mask, int flags);
+
+struct signalfd_siginfo
+{
+ uint32_t ssi_signo;
+ char pad[128 - sizeof (uint32_t)];
+};
+#endif
+
+/**/
+
+#if EV_VERIFY >= 3
+# define EV_FREQUENT_CHECK ev_verify (EV_A)
+#else
+# define EV_FREQUENT_CHECK do { } while (0)
+#endif
+
+/*
+ * This is used to work around floating point rounding problems.
+ * This value is good at least till the year 4000.
+ */
+#define MIN_INTERVAL 0.0001220703125 /* 1/2**13, good till 4000 */
+/*#define MIN_INTERVAL 0.00000095367431640625 /* 1/2**20, good till 2200 */
+
+#define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
+#define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
+
+#define EV_TV_SET(tv,t) do { tv.tv_sec = (long)t; tv.tv_usec = (long)((t - tv.tv_sec) * 1e6); } while (0)
+#define EV_TS_SET(ts,t) do { ts.tv_sec = (long)t; ts.tv_nsec = (long)((t - ts.tv_sec) * 1e9); } while (0)
+
+/* the following is ecb.h embedded into libev - use update_ev_c to update from an external copy */
+/* ECB.H BEGIN */
+/*
+ * libecb - http://software.schmorp.de/pkg/libecb
+ *
+ * Copyright (©) 2009-2012 Marc Alexander Lehmann <libecb at schmorp.de>
+ * Copyright (©) 2011 Emanuele Giaquinta
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ECB_H
+#define ECB_H
+
+/* 16 bits major, 16 bits minor */
+#define ECB_VERSION 0x00010003
+
+#ifdef _WIN32
+ typedef signed char int8_t;
+ typedef unsigned char uint8_t;
+ typedef signed short int16_t;
+ typedef unsigned short uint16_t;
+ typedef signed int int32_t;
+ typedef unsigned int uint32_t;
+ #if __GNUC__
+ typedef signed long long int64_t;
+ typedef unsigned long long uint64_t;
+ #else /* _MSC_VER || __BORLANDC__ */
+ typedef signed __int64 int64_t;
+ typedef unsigned __int64 uint64_t;
+ #endif
+ #ifdef _WIN64
+ #define ECB_PTRSIZE 8
+ typedef uint64_t uintptr_t;
+ typedef int64_t intptr_t;
+ #else
+ #define ECB_PTRSIZE 4
+ typedef uint32_t uintptr_t;
+ typedef int32_t intptr_t;
+ #endif
+#else
+ #include <inttypes.h>
+ #if UINTMAX_MAX > 0xffffffffU
+ #define ECB_PTRSIZE 8
+ #else
+ #define ECB_PTRSIZE 4
+ #endif
+#endif
+
+/* work around x32 idiocy by defining proper macros */
+#if __x86_64 || _M_AMD64
+ #if __ILP32
+ #define ECB_AMD64_X32 1
+ #else
+ #define ECB_AMD64 1
+ #endif
+#endif
+
+/* many compilers define _GNUC_ to some versions but then only implement
+ * what their idiot authors think are the "more important" extensions,
+ * causing enormous grief in return for some better fake benchmark numbers.
+ * or so.
+ * we try to detect these and simply assume they are not gcc - if they have
+ * an issue with that they should have done it right in the first place.
+ */
+#ifndef ECB_GCC_VERSION
+ #if !defined __GNUC_MINOR__ || defined __INTEL_COMPILER || defined __SUNPRO_C || defined __SUNPRO_CC || defined __llvm__ || defined __clang__
+ #define ECB_GCC_VERSION(major,minor) 0
+ #else
+ #define ECB_GCC_VERSION(major,minor) (__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
+ #endif
+#endif
+
+#define ECB_C (__STDC__+0) /* this assumes that __STDC__ is either empty or a number */
+#define ECB_C99 (__STDC_VERSION__ >= 199901L)
+#define ECB_C11 (__STDC_VERSION__ >= 201112L)
+#define ECB_CPP (__cplusplus+0)
+#define ECB_CPP11 (__cplusplus >= 201103L)
+
+#if ECB_CPP
+ #define ECB_EXTERN_C extern "C"
+ #define ECB_EXTERN_C_BEG ECB_EXTERN_C {
+ #define ECB_EXTERN_C_END }
+#else
+ #define ECB_EXTERN_C extern
+ #define ECB_EXTERN_C_BEG
+ #define ECB_EXTERN_C_END
+#endif
+
+/*****************************************************************************/
+
+/* ECB_NO_THREADS - ecb is not used by multiple threads, ever */
+/* ECB_NO_SMP - ecb might be used in multiple threads, but only on a single cpu */
+
+#if ECB_NO_THREADS
+ #define ECB_NO_SMP 1
+#endif
+
+#if ECB_NO_SMP
+ #define ECB_MEMORY_FENCE do { } while (0)
+#endif
+
+#ifndef ECB_MEMORY_FENCE
+ #if ECB_GCC_VERSION(2,5) || defined __INTEL_COMPILER || (__llvm__ && __GNUC__) || __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110
+ #if __i386 || __i386__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("lock; orb $0, -1(%%esp)" : : : "memory")
+ #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory")
+ #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("")
+ #elif __amd64 || __amd64__ || __x86_64 || __x86_64__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mfence" : : : "memory")
+ #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory")
+ #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("")
+ #elif __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("sync" : : : "memory")
+ #elif defined __ARM_ARCH_6__ || defined __ARM_ARCH_6J__ \
+ || defined __ARM_ARCH_6K__ || defined __ARM_ARCH_6ZK__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mcr p15,0,%0,c7,c10,5" : : "r" (0) : "memory")
+ #elif defined __ARM_ARCH_7__ || defined __ARM_ARCH_7A__ \
+ || defined __ARM_ARCH_7M__ || defined __ARM_ARCH_7R__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb" : : : "memory")
+ #elif __sparc || __sparc__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad | #StoreStore | #StoreLoad" : : : "memory")
+ #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad" : : : "memory")
+ #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("membar #LoadStore | #StoreStore")
+ #elif defined __s390__ || defined __s390x__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("bcr 15,0" : : : "memory")
+ #elif defined __mips__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("sync" : : : "memory")
+ #elif defined __alpha__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mb" : : : "memory")
+ #elif defined __hppa__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory")
+ #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("")
+ #elif defined __ia64__
+ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mf" : : : "memory")
+ #endif
+ #endif
+#endif
+
+#ifndef ECB_MEMORY_FENCE
+ #if ECB_GCC_VERSION(4,7)
+ /* see comment below (stdatomic.h) about the C11 memory model. */
+ #define ECB_MEMORY_FENCE __atomic_thread_fence (__ATOMIC_SEQ_CST)
+
+ /* The __has_feature syntax from clang is so misdesigned that we cannot use it
+ * without risking compile time errors with other compilers. We *could*
+ * define our own ecb_clang_has_feature, but I just can't be bothered to work
+ * around this shit time and again.
+ * #elif defined __clang && __has_feature (cxx_atomic)
+ * // see comment below (stdatomic.h) about the C11 memory model.
+ * #define ECB_MEMORY_FENCE __c11_atomic_thread_fence (__ATOMIC_SEQ_CST)
+ */
+
+ #elif ECB_GCC_VERSION(4,4) || defined __INTEL_COMPILER || defined __clang__
+ #define ECB_MEMORY_FENCE __sync_synchronize ()
+ #elif _MSC_VER >= 1400 /* VC++ 2005 */
+ #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier)
+ #define ECB_MEMORY_FENCE _ReadWriteBarrier ()
+ #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier () /* according to msdn, _ReadBarrier is not a load fence */
+ #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier ()
+ #elif defined _WIN32
+ #include <WinNT.h>
+ #define ECB_MEMORY_FENCE MemoryBarrier () /* actually just xchg on x86... scary */
+ #elif __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110
+ #include <mbarrier.h>
+ #define ECB_MEMORY_FENCE __machine_rw_barrier ()
+ #define ECB_MEMORY_FENCE_ACQUIRE __machine_r_barrier ()
+ #define ECB_MEMORY_FENCE_RELEASE __machine_w_barrier ()
+ #elif __xlC__
+ #define ECB_MEMORY_FENCE __sync ()
+ #endif
+#endif
+
+#ifndef ECB_MEMORY_FENCE
+ #if ECB_C11 && !defined __STDC_NO_ATOMICS__
+ /* we assume that these memory fences work on all variables/all memory accesses, */
+ /* not just C11 atomics and atomic accesses */
+ #include <stdatomic.h>
+ /* Unfortunately, neither gcc 4.7 nor clang 3.1 generate any instructions for */
+ /* any fence other than seq_cst, which isn't very efficient for us. */
+ /* Why that is, we don't know - either the C11 memory model is quite useless */
+ /* for most usages, or gcc and clang have a bug */
+ /* I *currently* lean towards the latter, and inefficiently implement */
+ /* all three of ecb's fences as a seq_cst fence */
+ #define ECB_MEMORY_FENCE atomic_thread_fence (memory_order_seq_cst)
+ #endif
+#endif
+
+#ifndef ECB_MEMORY_FENCE
+ #if !ECB_AVOID_PTHREADS
+ /*
+ * if you get undefined symbol references to pthread_mutex_lock,
+ * or failure to find pthread.h, then you should implement
+ * the ECB_MEMORY_FENCE operations for your cpu/compiler
+ * OR provide pthread.h and link against the posix thread library
+ * of your system.
+ */
+ #include <pthread.h>
+ #define ECB_NEEDS_PTHREADS 1
+ #define ECB_MEMORY_FENCE_NEEDS_PTHREADS 1
+
+ static pthread_mutex_t ecb_mf_lock = PTHREAD_MUTEX_INITIALIZER;
+ #define ECB_MEMORY_FENCE do { pthread_mutex_lock (&ecb_mf_lock); pthread_mutex_unlock (&ecb_mf_lock); } while (0)
+ #endif
+#endif
+
+#if !defined ECB_MEMORY_FENCE_ACQUIRE && defined ECB_MEMORY_FENCE
+ #define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
+#endif
+
+#if !defined ECB_MEMORY_FENCE_RELEASE && defined ECB_MEMORY_FENCE
+ #define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
+#endif
+
+/*****************************************************************************/
+
+#if __cplusplus
+ #define ecb_inline static inline
+#elif ECB_GCC_VERSION(2,5)
+ #define ecb_inline static __inline__
+#elif ECB_C99
+ #define ecb_inline static inline
+#else
+ #define ecb_inline static
+#endif
+
+#if ECB_GCC_VERSION(3,3)
+ #define ecb_restrict __restrict__
+#elif ECB_C99
+ #define ecb_restrict restrict
+#else
+ #define ecb_restrict
+#endif
+
+typedef int ecb_bool;
+
+#define ECB_CONCAT_(a, b) a ## b
+#define ECB_CONCAT(a, b) ECB_CONCAT_(a, b)
+#define ECB_STRINGIFY_(a) # a
+#define ECB_STRINGIFY(a) ECB_STRINGIFY_(a)
+
+#define ecb_function_ ecb_inline
+
+#if ECB_GCC_VERSION(3,1)
+ #define ecb_attribute(attrlist) __attribute__(attrlist)
+ #define ecb_is_constant(expr) __builtin_constant_p (expr)
+ #define ecb_expect(expr,value) __builtin_expect ((expr),(value))
+ #define ecb_prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality)
+#else
+ #define ecb_attribute(attrlist)
+ #define ecb_is_constant(expr) 0
+ #define ecb_expect(expr,value) (expr)
+ #define ecb_prefetch(addr,rw,locality)
+#endif
+
+/* no emulation for ecb_decltype */
+#if ECB_GCC_VERSION(4,5)
+ #define ecb_decltype(x) __decltype(x)
+#elif ECB_GCC_VERSION(3,0)
+ #define ecb_decltype(x) __typeof(x)
+#endif
+
+#define ecb_noinline ecb_attribute ((__noinline__))
+#define ecb_unused ecb_attribute ((__unused__))
+#define ecb_const ecb_attribute ((__const__))
+#define ecb_pure ecb_attribute ((__pure__))
+
+#if ECB_C11
+ #define ecb_noreturn _Noreturn
+#else
+ #define ecb_noreturn ecb_attribute ((__noreturn__))
+#endif
+
+#if ECB_GCC_VERSION(4,3)
+ #define ecb_artificial ecb_attribute ((__artificial__))
+ #define ecb_hot ecb_attribute ((__hot__))
+ #define ecb_cold ecb_attribute ((__cold__))
+#else
+ #define ecb_artificial
+ #define ecb_hot
+ #define ecb_cold
+#endif
+
+/* put around conditional expressions if you are very sure that the */
+/* expression is mostly true or mostly false. note that these return */
+/* booleans, not the expression. */
+#define ecb_expect_false(expr) ecb_expect (!!(expr), 0)
+#define ecb_expect_true(expr) ecb_expect (!!(expr), 1)
+/* for compatibility to the rest of the world */
+#define ecb_likely(expr) ecb_expect_true (expr)
+#define ecb_unlikely(expr) ecb_expect_false (expr)
+
+/* count trailing zero bits and count # of one bits */
+#if ECB_GCC_VERSION(3,4)
+ /* we assume int == 32 bit, long == 32 or 64 bit and long long == 64 bit */
+ #define ecb_ld32(x) (__builtin_clz (x) ^ 31)
+ #define ecb_ld64(x) (__builtin_clzll (x) ^ 63)
+ #define ecb_ctz32(x) __builtin_ctz (x)
+ #define ecb_ctz64(x) __builtin_ctzll (x)
+ #define ecb_popcount32(x) __builtin_popcount (x)
+ /* no popcountll */
+#else
+ ecb_function_ int ecb_ctz32 (uint32_t x) ecb_const;
+ ecb_function_ int
+ ecb_ctz32 (uint32_t x)
+ {
+ int r = 0;
+
+ x &= ~x + 1; /* this isolates the lowest bit */
+
+#if ECB_branchless_on_i386
+ r += !!(x & 0xaaaaaaaa) << 0;
+ r += !!(x & 0xcccccccc) << 1;
+ r += !!(x & 0xf0f0f0f0) << 2;
+ r += !!(x & 0xff00ff00) << 3;
+ r += !!(x & 0xffff0000) << 4;
+#else
+ if (x & 0xaaaaaaaa) r += 1;
+ if (x & 0xcccccccc) r += 2;
+ if (x & 0xf0f0f0f0) r += 4;
+ if (x & 0xff00ff00) r += 8;
+ if (x & 0xffff0000) r += 16;
+#endif
+
+ return r;
+ }
+
+ ecb_function_ int ecb_ctz64 (uint64_t x) ecb_const;
+ ecb_function_ int
+ ecb_ctz64 (uint64_t x)
+ {
+ int shift = x & 0xffffffffU ? 0 : 32;
+ return ecb_ctz32 (x >> shift) + shift;
+ }
+
+ ecb_function_ int ecb_popcount32 (uint32_t x) ecb_const;
+ ecb_function_ int
+ ecb_popcount32 (uint32_t x)
+ {
+ x -= (x >> 1) & 0x55555555;
+ x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
+ x = ((x >> 4) + x) & 0x0f0f0f0f;
+ x *= 0x01010101;
+
+ return x >> 24;
+ }
+
+ ecb_function_ int ecb_ld32 (uint32_t x) ecb_const;
+ ecb_function_ int ecb_ld32 (uint32_t x)
+ {
+ int r = 0;
+
+ if (x >> 16) { x >>= 16; r += 16; }
+ if (x >> 8) { x >>= 8; r += 8; }
+ if (x >> 4) { x >>= 4; r += 4; }
+ if (x >> 2) { x >>= 2; r += 2; }
+ if (x >> 1) { r += 1; }
+
+ return r;
+ }
+
+ ecb_function_ int ecb_ld64 (uint64_t x) ecb_const;
+ ecb_function_ int ecb_ld64 (uint64_t x)
+ {
+ int r = 0;
+
+ if (x >> 32) { x >>= 32; r += 32; }
+
+ return r + ecb_ld32 (x);
+ }
+#endif
+
+ecb_function_ ecb_bool ecb_is_pot32 (uint32_t x) ecb_const;
+ecb_function_ ecb_bool ecb_is_pot32 (uint32_t x) { return !(x & (x - 1)); }
+ecb_function_ ecb_bool ecb_is_pot64 (uint64_t x) ecb_const;
+ecb_function_ ecb_bool ecb_is_pot64 (uint64_t x) { return !(x & (x - 1)); }
+
+ecb_function_ uint8_t ecb_bitrev8 (uint8_t x) ecb_const;
+ecb_function_ uint8_t ecb_bitrev8 (uint8_t x)
+{
+ return ( (x * 0x0802U & 0x22110U)
+ | (x * 0x8020U & 0x88440U)) * 0x10101U >> 16;
+}
+
+ecb_function_ uint16_t ecb_bitrev16 (uint16_t x) ecb_const;
+ecb_function_ uint16_t ecb_bitrev16 (uint16_t x)
+{
+ x = ((x >> 1) & 0x5555) | ((x & 0x5555) << 1);
+ x = ((x >> 2) & 0x3333) | ((x & 0x3333) << 2);
+ x = ((x >> 4) & 0x0f0f) | ((x & 0x0f0f) << 4);
+ x = ( x >> 8 ) | ( x << 8);
+
+ return x;
+}
+
+ecb_function_ uint32_t ecb_bitrev32 (uint32_t x) ecb_const;
+ecb_function_ uint32_t ecb_bitrev32 (uint32_t x)
+{
+ x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
+ x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
+ x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4);
+ x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8);
+ x = ( x >> 16 ) | ( x << 16);
+
+ return x;
+}
+
+/* popcount64 is only available on 64 bit cpus as gcc builtin */
+/* so for this version we are lazy */
+ecb_function_ int ecb_popcount64 (uint64_t x) ecb_const;
+ecb_function_ int
+ecb_popcount64 (uint64_t x)
+{
+ return ecb_popcount32 (x) + ecb_popcount32 (x >> 32);
+}
+
+ecb_inline uint8_t ecb_rotl8 (uint8_t x, unsigned int count) ecb_const;
+ecb_inline uint8_t ecb_rotr8 (uint8_t x, unsigned int count) ecb_const;
+ecb_inline uint16_t ecb_rotl16 (uint16_t x, unsigned int count) ecb_const;
+ecb_inline uint16_t ecb_rotr16 (uint16_t x, unsigned int count) ecb_const;
+ecb_inline uint32_t ecb_rotl32 (uint32_t x, unsigned int count) ecb_const;
+ecb_inline uint32_t ecb_rotr32 (uint32_t x, unsigned int count) ecb_const;
+ecb_inline uint64_t ecb_rotl64 (uint64_t x, unsigned int count) ecb_const;
+ecb_inline uint64_t ecb_rotr64 (uint64_t x, unsigned int count) ecb_const;
+
+ecb_inline uint8_t ecb_rotl8 (uint8_t x, unsigned int count) { return (x >> ( 8 - count)) | (x << count); }
+ecb_inline uint8_t ecb_rotr8 (uint8_t x, unsigned int count) { return (x << ( 8 - count)) | (x >> count); }
+ecb_inline uint16_t ecb_rotl16 (uint16_t x, unsigned int count) { return (x >> (16 - count)) | (x << count); }
+ecb_inline uint16_t ecb_rotr16 (uint16_t x, unsigned int count) { return (x << (16 - count)) | (x >> count); }
+ecb_inline uint32_t ecb_rotl32 (uint32_t x, unsigned int count) { return (x >> (32 - count)) | (x << count); }
+ecb_inline uint32_t ecb_rotr32 (uint32_t x, unsigned int count) { return (x << (32 - count)) | (x >> count); }
+ecb_inline uint64_t ecb_rotl64 (uint64_t x, unsigned int count) { return (x >> (64 - count)) | (x << count); }
+ecb_inline uint64_t ecb_rotr64 (uint64_t x, unsigned int count) { return (x << (64 - count)) | (x >> count); }
+
+#if ECB_GCC_VERSION(4,3)
+ #define ecb_bswap16(x) (__builtin_bswap32 (x) >> 16)
+ #define ecb_bswap32(x) __builtin_bswap32 (x)
+ #define ecb_bswap64(x) __builtin_bswap64 (x)
+#else
+ ecb_function_ uint16_t ecb_bswap16 (uint16_t x) ecb_const;
+ ecb_function_ uint16_t
+ ecb_bswap16 (uint16_t x)
+ {
+ return ecb_rotl16 (x, 8);
+ }
+
+ ecb_function_ uint32_t ecb_bswap32 (uint32_t x) ecb_const;
+ ecb_function_ uint32_t
+ ecb_bswap32 (uint32_t x)
+ {
+ return (((uint32_t)ecb_bswap16 (x)) << 16) | ecb_bswap16 (x >> 16);
+ }
+
+ ecb_function_ uint64_t ecb_bswap64 (uint64_t x) ecb_const;
+ ecb_function_ uint64_t
+ ecb_bswap64 (uint64_t x)
+ {
+ return (((uint64_t)ecb_bswap32 (x)) << 32) | ecb_bswap32 (x >> 32);
+ }
+#endif
+
+#if ECB_GCC_VERSION(4,5)
+ #define ecb_unreachable() __builtin_unreachable ()
+#else
+ /* this seems to work fine, but gcc always emits a warning for it :/ */
+ ecb_inline void ecb_unreachable (void) ecb_noreturn;
+ ecb_inline void ecb_unreachable (void) { }
+#endif
+
+/* try to tell the compiler that some condition is definitely true */
+#define ecb_assume(cond) if (!(cond)) ecb_unreachable (); else 0
+
+ecb_inline unsigned char ecb_byteorder_helper (void) ecb_const;
+ecb_inline unsigned char
+ecb_byteorder_helper (void)
+{
+ /* the union code still generates code under pressure in gcc, */
+ /* but less than using pointers, and always seems to */
+ /* successfully return a constant. */
+ /* the reason why we have this horrible preprocessor mess */
+ /* is to avoid it in all cases, at least on common architectures */
+ /* or when using a recent enough gcc version (>= 4.6) */
+#if __i386 || __i386__ || _M_X86 || __amd64 || __amd64__ || _M_X64
+ return 0x44;
+#elif __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+ return 0x44;
+#elif __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+ return 0x11;
+#else
+ union
+ {
+ uint32_t i;
+ uint8_t c;
+ } u = { 0x11223344 };
+ return u.c;
+#endif
+}
+
+ecb_inline ecb_bool ecb_big_endian (void) ecb_const;
+ecb_inline ecb_bool ecb_big_endian (void) { return ecb_byteorder_helper () == 0x11; }
+ecb_inline ecb_bool ecb_little_endian (void) ecb_const;
+ecb_inline ecb_bool ecb_little_endian (void) { return ecb_byteorder_helper () == 0x44; }
+
+#if ECB_GCC_VERSION(3,0) || ECB_C99
+ #define ecb_mod(m,n) ((m) % (n) + ((m) % (n) < 0 ? (n) : 0))
+#else
+ #define ecb_mod(m,n) ((m) < 0 ? ((n) - 1 - ((-1 - (m)) % (n))) : ((m) % (n)))
+#endif
+
+#if __cplusplus
+ template<typename T>
+ static inline T ecb_div_rd (T val, T div)
+ {
+ return val < 0 ? - ((-val + div - 1) / div) : (val ) / div;
+ }
+ template<typename T>
+ static inline T ecb_div_ru (T val, T div)
+ {
+ return val < 0 ? - ((-val ) / div) : (val + div - 1) / div;
+ }
+#else
+ #define ecb_div_rd(val,div) ((val) < 0 ? - ((-(val) + (div) - 1) / (div)) : ((val) ) / (div))
+ #define ecb_div_ru(val,div) ((val) < 0 ? - ((-(val) ) / (div)) : ((val) + (div) - 1) / (div))
+#endif
+
+#if ecb_cplusplus_does_not_suck
+ /* does not work for local types (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm) */
+ template<typename T, int N>
+ static inline int ecb_array_length (const T (&arr)[N])
+ {
+ return N;
+ }
+#else
+ #define ecb_array_length(name) (sizeof (name) / sizeof (name [0]))
+#endif
+
+/*******************************************************************************/
+/* floating point stuff, can be disabled by defining ECB_NO_LIBM */
+
+/* basically, everything uses "ieee pure-endian" floating point numbers */
+/* the only noteworthy exception is ancient armle, which uses order 43218765 */
+#if 0 \
+ || __i386 || __i386__ \
+ || __amd64 || __amd64__ || __x86_64 || __x86_64__ \
+ || __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__ \
+ || defined __arm__ && defined __ARM_EABI__ \
+ || defined __s390__ || defined __s390x__ \
+ || defined __mips__ \
+ || defined __alpha__ \
+ || defined __hppa__ \
+ || defined __ia64__ \
+ || defined _M_IX86 || defined _M_AMD64 || defined _M_IA64
+ #define ECB_STDFP 1
+ #include <string.h> /* for memcpy */
+#else
+ #define ECB_STDFP 0
+ #include <math.h> /* for frexp*, ldexp* */
+#endif
+
+#ifndef ECB_NO_LIBM
+
+ /* convert a float to ieee single/binary32 */
+ ecb_function_ uint32_t ecb_float_to_binary32 (float x) ecb_const;
+ ecb_function_ uint32_t
+ ecb_float_to_binary32 (float x)
+ {
+ uint32_t r;
+
+ #if ECB_STDFP
+ memcpy (&r, &x, 4);
+ #else
+ /* slow emulation, works for anything but -0 */
+ uint32_t m;
+ int e;
+
+ if (x == 0e0f ) return 0x00000000U;
+ if (x > +3.40282346638528860e+38f) return 0x7f800000U;
+ if (x < -3.40282346638528860e+38f) return 0xff800000U;
+ if (x != x ) return 0x7fbfffffU;
+
+ m = frexpf (x, &e) * 0x1000000U;
+
+ r = m & 0x80000000U;
+
+ if (r)
+ m = -m;
+
+ if (e <= -126)
+ {
+ m &= 0xffffffU;
+ m >>= (-125 - e);
+ e = -126;
+ }
+
+ r |= (e + 126) << 23;
+ r |= m & 0x7fffffU;
+ #endif
+
+ return r;
+ }
+
+ /* converts an ieee single/binary32 to a float */
+ ecb_function_ float ecb_binary32_to_float (uint32_t x) ecb_const;
+ ecb_function_ float
+ ecb_binary32_to_float (uint32_t x)
+ {
+ float r;
+
+ #if ECB_STDFP
+ memcpy (&r, &x, 4);
+ #else
+ /* emulation, only works for normals and subnormals and +0 */
+ int neg = x >> 31;
+ int e = (x >> 23) & 0xffU;
+
+ x &= 0x7fffffU;
+
+ if (e)
+ x |= 0x800000U;
+ else
+ e = 1;
+
+ /* we distrust ldexpf a bit and do the 2**-24 scaling by an extra multiply */
+ r = ldexpf (x * (0.5f / 0x800000U), e - 126);
+
+ r = neg ? -r : r;
+ #endif
+
+ return r;
+ }
+
+ /* convert a double to ieee double/binary64 */
+ ecb_function_ uint64_t ecb_double_to_binary64 (double x) ecb_const;
+ ecb_function_ uint64_t
+ ecb_double_to_binary64 (double x)
+ {
+ uint64_t r;
+
+ #if ECB_STDFP
+ memcpy (&r, &x, 8);
+ #else
+ /* slow emulation, works for anything but -0 */
+ uint64_t m;
+ int e;
+
+ if (x == 0e0 ) return 0x0000000000000000U;
+ if (x > +1.79769313486231470e+308) return 0x7ff0000000000000U;
+ if (x < -1.79769313486231470e+308) return 0xfff0000000000000U;
+ if (x != x ) return 0X7ff7ffffffffffffU;
+
+ m = frexp (x, &e) * 0x20000000000000U;
+
+ r = m & 0x8000000000000000;;
+
+ if (r)
+ m = -m;
+
+ if (e <= -1022)
+ {
+ m &= 0x1fffffffffffffU;
+ m >>= (-1021 - e);
+ e = -1022;
+ }
+
+ r |= ((uint64_t)(e + 1022)) << 52;
+ r |= m & 0xfffffffffffffU;
+ #endif
+
+ return r;
+ }
+
+ /* converts an ieee double/binary64 to a double */
+ ecb_function_ double ecb_binary64_to_double (uint64_t x) ecb_const;
+ ecb_function_ double
+ ecb_binary64_to_double (uint64_t x)
+ {
+ double r;
+
+ #if ECB_STDFP
+ memcpy (&r, &x, 8);
+ #else
+ /* emulation, only works for normals and subnormals and +0 */
+ int neg = x >> 63;
+ int e = (x >> 52) & 0x7ffU;
+
+ x &= 0xfffffffffffffU;
+
+ if (e)
+ x |= 0x10000000000000U;
+ else
+ e = 1;
+
+ /* we distrust ldexp a bit and do the 2**-53 scaling by an extra multiply */
+ r = ldexp (x * (0.5 / 0x10000000000000U), e - 1022);
+
+ r = neg ? -r : r;
+ #endif
+
+ return r;
+ }
+
+#endif
+
+#endif
+
+/* ECB.H END */
+
+#if ECB_MEMORY_FENCE_NEEDS_PTHREADS
+/* if your architecture doesn't need memory fences, e.g. because it is
+ * single-cpu/core, or if you use libev in a project that doesn't use libev
+ * from multiple threads, then you can define ECB_AVOID_PTHREADS when compiling
+ * libev, in which cases the memory fences become nops.
+ * alternatively, you can remove this #error and link against libpthread,
+ * which will then provide the memory fences.
+ */
+# error "memory fences not defined for your architecture, please report"
+#endif
+
+#ifndef ECB_MEMORY_FENCE
+# define ECB_MEMORY_FENCE do { } while (0)
+# define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
+# define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
+#endif
+
+#define expect_false(cond) ecb_expect_false (cond)
+#define expect_true(cond) ecb_expect_true (cond)
+#define noinline ecb_noinline
+
+#define inline_size ecb_inline
+
+#if EV_FEATURE_CODE
+# define inline_speed ecb_inline
+#else
+# define inline_speed static noinline
+#endif
+
+#define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
+
+#if EV_MINPRI == EV_MAXPRI
+# define ABSPRI(w) (((W)w), 0)
+#else
+# define ABSPRI(w) (((W)w)->priority - EV_MINPRI)
+#endif
+
+#define EMPTY /* required for microsofts broken pseudo-c compiler */
+#define EMPTY2(a,b) /* used to suppress some warnings */
+
+typedef ev_watcher *W;
+typedef ev_watcher_list *WL;
+typedef ev_watcher_time *WT;
+
+#define ev_active(w) ((W)(w))->active
+#define ev_at(w) ((WT)(w))->at
+
+#if EV_USE_REALTIME
+/* sig_atomic_t is used to avoid per-thread variables or locking but still */
+/* giving it a reasonably high chance of working on typical architectures */
+static EV_ATOMIC_T have_realtime; /* did clock_gettime (CLOCK_REALTIME) work? */
+#endif
+
+#if EV_USE_MONOTONIC
+static EV_ATOMIC_T have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
+#endif
+
+#ifndef EV_FD_TO_WIN32_HANDLE
+# define EV_FD_TO_WIN32_HANDLE(fd) _get_osfhandle (fd)
+#endif
+#ifndef EV_WIN32_HANDLE_TO_FD
+# define EV_WIN32_HANDLE_TO_FD(handle) _open_osfhandle (handle, 0)
+#endif
+#ifndef EV_WIN32_CLOSE_FD
+# define EV_WIN32_CLOSE_FD(fd) close (fd)
+#endif
+
+#ifdef _WIN32
+# include "ev_win32.c"
+#endif
+
+/*****************************************************************************/
+
+/* define a suitable floor function (only used by periodics atm) */
+
+#if EV_USE_FLOOR
+# include <math.h>
+# define ev_floor(v) floor (v)
+#else
+
+#include <float.h>
+
+/* a floor() replacement function, should be independent of ev_tstamp type */
+static ev_tstamp noinline
+ev_floor (ev_tstamp v)
+{
+ /* the choice of shift factor is not terribly important */
+#if FLT_RADIX != 2 /* assume FLT_RADIX == 10 */
+ const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 10000000000000000000. : 1000000000.;
+#else
+ const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 18446744073709551616. : 4294967296.;
+#endif
+
+ /* argument too large for an unsigned long? */
+ if (expect_false (v >= shift))
+ {
+ ev_tstamp f;
+
+ if (v == v - 1.)
+ return v; /* very large number */
+
+ f = shift * ev_floor (v * (1. / shift));
+ return f + ev_floor (v - f);
+ }
+
+ /* special treatment for negative args? */
+ if (expect_false (v < 0.))
+ {
+ ev_tstamp f = -ev_floor (-v);
+
+ return f - (f == v ? 0 : 1);
+ }
+
+ /* fits into an unsigned long */
+ return (unsigned long)v;
+}
+
+#endif
+
+/*****************************************************************************/
+
+#ifdef __linux
+# include <sys/utsname.h>
+#endif
+
+static unsigned int noinline ecb_cold
+ev_linux_version (void)
+{
+#ifdef __linux
+ unsigned int v = 0;
+ struct utsname buf;
+ int i;
+ char *p = buf.release;
+
+ if (uname (&buf))
+ return 0;
+
+ for (i = 3+1; --i; )
+ {
+ unsigned int c = 0;
+
+ for (;;)
+ {
+ if (*p >= '0' && *p <= '9')
+ c = c * 10 + *p++ - '0';
+ else
+ {
+ p += *p == '.';
+ break;
+ }
+ }
+
+ v = (v << 8) | c;
+ }
+
+ return v;
+#else
+ return 0;
+#endif
+}
+
+/*****************************************************************************/
+
+#if EV_AVOID_STDIO
+static void noinline ecb_cold
+ev_printerr (const char *msg)
+{
+ write (STDERR_FILENO, msg, strlen (msg));
+}
+#endif
+
+static void (*syserr_cb)(const char *msg) EV_THROW;
+
+void ecb_cold
+ev_set_syserr_cb (void (*cb)(const char *msg) EV_THROW) EV_THROW
+{
+ syserr_cb = cb;
+}
+
+static void noinline ecb_cold
+ev_syserr (const char *msg)
+{
+ if (!msg)
+ msg = "(libev) system error";
+
+ if (syserr_cb)
+ syserr_cb (msg);
+ else
+ {
+#if EV_AVOID_STDIO
+ ev_printerr (msg);
+ ev_printerr (": ");
+ ev_printerr (strerror (errno));
+ ev_printerr ("\n");
+#else
+ perror (msg);
+#endif
+ abort ();
+ }
+}
+
+static void *
+ev_realloc_emul (void *ptr, long size) EV_THROW
+{
+ /* some systems, notably openbsd and darwin, fail to properly
+ * implement realloc (x, 0) (as required by both ansi c-89 and
+ * the single unix specification, so work around them here.
+ * recently, also (at least) fedora and debian started breaking it,
+ * despite documenting it otherwise.
+ */
+
+ if (size)
+ return realloc (ptr, size);
+
+ free (ptr);
+ return 0;
+}
+
+static void *(*alloc)(void *ptr, long size) EV_THROW = ev_realloc_emul;
+
+void ecb_cold
+ev_set_allocator (void *(*cb)(void *ptr, long size) EV_THROW) EV_THROW
+{
+ alloc = cb;
+}
+
+inline_speed void *
+ev_realloc (void *ptr, long size)
+{
+ ptr = alloc (ptr, size);
+
+ if (!ptr && size)
+ {
+#if EV_AVOID_STDIO
+ ev_printerr ("(libev) memory allocation failed, aborting.\n");
+#else
+ fprintf (stderr, "(libev) cannot allocate %ld bytes, aborting.", size);
+#endif
+ abort ();
+ }
+
+ return ptr;
+}
+
+#define ev_malloc(size) ev_realloc (0, (size))
+#define ev_free(ptr) ev_realloc ((ptr), 0)
+
+/*****************************************************************************/
+
+/* set in reify when reification needed */
+#define EV_ANFD_REIFY 1
+
+/* file descriptor info structure */
+typedef struct
+{
+ WL head;
+ unsigned char events; /* the events watched for */
+ unsigned char reify; /* flag set when this ANFD needs reification (EV_ANFD_REIFY, EV__IOFDSET) */
+ unsigned char emask; /* the epoll backend stores the actual kernel mask in here */
+ unsigned char unused;
+#if EV_USE_EPOLL
+ unsigned int egen; /* generation counter to counter epoll bugs */
+#endif
+#if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
+ SOCKET handle;
+#endif
+#if EV_USE_IOCP
+ OVERLAPPED or, ow;
+#endif
+} ANFD;
+
+/* stores the pending event set for a given watcher */
+typedef struct
+{
+ W w;
+ int events; /* the pending event set for the given watcher */
+} ANPENDING;
+
+#if EV_USE_INOTIFY
+/* hash table entry per inotify-id */
+typedef struct
+{
+ WL head;
+} ANFS;
+#endif
+
+/* Heap Entry */
+#if EV_HEAP_CACHE_AT
+ /* a heap element */
+ typedef struct {
+ ev_tstamp at;
+ WT w;
+ } ANHE;
+
+ #define ANHE_w(he) (he).w /* access watcher, read-write */
+ #define ANHE_at(he) (he).at /* access cached at, read-only */
+ #define ANHE_at_cache(he) (he).at = (he).w->at /* update at from watcher */
+#else
+ /* a heap element */
+ typedef WT ANHE;
+
+ #define ANHE_w(he) (he)
+ #define ANHE_at(he) (he)->at
+ #define ANHE_at_cache(he)
+#endif
+
+#if EV_MULTIPLICITY
+
+ struct ev_loop
+ {
+ ev_tstamp ev_rt_now;
+ #define ev_rt_now ((loop)->ev_rt_now)
+ #define VAR(name,decl) decl;
+ #include "ev_vars.h"
+ #undef VAR
+ };
+ #include "ev_wrap.h"
+
+ static struct ev_loop default_loop_struct;
+ EV_API_DECL struct ev_loop *ev_default_loop_ptr = 0; /* needs to be initialised to make it a definition despite extern */
+
+#else
+
+ EV_API_DECL ev_tstamp ev_rt_now = 0; /* needs to be initialised to make it a definition despite extern */
+ #define VAR(name,decl) static decl;
+ #include "ev_vars.h"
+ #undef VAR
+
+ static int ev_default_loop_ptr;
+
+#endif
+
+#if EV_FEATURE_API
+# define EV_RELEASE_CB if (expect_false (release_cb)) release_cb (EV_A)
+# define EV_ACQUIRE_CB if (expect_false (acquire_cb)) acquire_cb (EV_A)
+# define EV_INVOKE_PENDING invoke_cb (EV_A)
+#else
+# define EV_RELEASE_CB (void)0
+# define EV_ACQUIRE_CB (void)0
+# define EV_INVOKE_PENDING ev_invoke_pending (EV_A)
+#endif
+
+#define EVBREAK_RECURSE 0x80
+
+/*****************************************************************************/
+
+#ifndef EV_HAVE_EV_TIME
+ev_tstamp
+ev_time (void) EV_THROW
+{
+#if EV_USE_REALTIME
+ if (expect_true (have_realtime))
+ {
+ struct timespec ts;
+ clock_gettime (CLOCK_REALTIME, &ts);
+ return ts.tv_sec + ts.tv_nsec * 1e-9;
+ }
+#endif
+
+ struct timeval tv;
+ gettimeofday (&tv, 0);
+ return tv.tv_sec + tv.tv_usec * 1e-6;
+}
+#endif
+
+inline_size ev_tstamp
+get_clock (void)
+{
+#if EV_USE_MONOTONIC
+ if (expect_true (have_monotonic))
+ {
+ struct timespec ts;
+ clock_gettime (CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec + ts.tv_nsec * 1e-9;
+ }
+#endif
+
+ return ev_time ();
+}
+
+#if EV_MULTIPLICITY
+ev_tstamp
+ev_now (EV_P) EV_THROW
+{
+ return ev_rt_now;
+}
+#endif
+
+void
+ev_sleep (ev_tstamp delay) EV_THROW
+{
+ if (delay > 0.)
+ {
+#if EV_USE_NANOSLEEP
+ struct timespec ts;
+
+ EV_TS_SET (ts, delay);
+ nanosleep (&ts, 0);
+#elif defined _WIN32
+ Sleep ((unsigned long)(delay * 1e3));
+#else
+ struct timeval tv;
+
+ /* here we rely on sys/time.h + sys/types.h + unistd.h providing select */
+ /* something not guaranteed by newer posix versions, but guaranteed */
+ /* by older ones */
+ EV_TV_SET (tv, delay);
+ select (0, 0, 0, 0, &tv);
+#endif
+ }
+}
+
+/*****************************************************************************/
+
+#define MALLOC_ROUND 4096 /* prefer to allocate in chunks of this size, must be 2**n and >> 4 longs */
+
+/* find a suitable new size for the given array, */
+/* hopefully by rounding to a nice-to-malloc size */
+inline_size int
+array_nextsize (int elem, int cur, int cnt)
+{
+ int ncur = cur + 1;
+
+ do
+ ncur <<= 1;
+ while (cnt > ncur);
+
+ /* if size is large, round to MALLOC_ROUND - 4 * longs to accommodate malloc overhead */
+ if (elem * ncur > MALLOC_ROUND - sizeof (void *) * 4)
+ {
+ ncur *= elem;
+ ncur = (ncur + elem + (MALLOC_ROUND - 1) + sizeof (void *) * 4) & ~(MALLOC_ROUND - 1);
+ ncur = ncur - sizeof (void *) * 4;
+ ncur /= elem;
+ }
+
+ return ncur;
+}
+
+static void * noinline ecb_cold
+array_realloc (int elem, void *base, int *cur, int cnt)
+{
+ *cur = array_nextsize (elem, *cur, cnt);
+ return ev_realloc (base, elem * *cur);
+}
+
+#define array_init_zero(base,count) \
+ memset ((void *)(base), 0, sizeof (*(base)) * (count))
+
+#define array_needsize(type,base,cur,cnt,init) \
+ if (expect_false ((cnt) > (cur))) \
+ { \
+ int ecb_unused ocur_ = (cur); \
+ (base) = (type *)array_realloc \
+ (sizeof (type), (base), &(cur), (cnt)); \
+ init ((base) + (ocur_), (cur) - ocur_); \
+ }
+
+#if 0
+#define array_slim(type,stem) \
+ if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
+ { \
+ stem ## max = array_roundsize (stem ## cnt >> 1); \
+ base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
+ fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
+ }
+#endif
+
+#define array_free(stem, idx) \
+ ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0; stem ## s idx = 0
+
+/*****************************************************************************/
+
+/* dummy callback for pending events */
+static void noinline
+pendingcb (EV_P_ ev_prepare *w, int revents)
+{
+}
+
+void noinline
+ev_feed_event (EV_P_ void *w, int revents) EV_THROW
+{
+ W w_ = (W)w;
+ int pri = ABSPRI (w_);
+
+ if (expect_false (w_->pending))
+ pendings [pri][w_->pending - 1].events |= revents;
+ else
+ {
+ w_->pending = ++pendingcnt [pri];
+ array_needsize (ANPENDING, pendings [pri], pendingmax [pri], w_->pending, EMPTY2);
+ pendings [pri][w_->pending - 1].w = w_;
+ pendings [pri][w_->pending - 1].events = revents;
+ }
+
+ pendingpri = NUMPRI - 1;
+}
+
+inline_speed void
+feed_reverse (EV_P_ W w)
+{
+ array_needsize (W, rfeeds, rfeedmax, rfeedcnt + 1, EMPTY2);
+ rfeeds [rfeedcnt++] = w;
+}
+
+inline_size void
+feed_reverse_done (EV_P_ int revents)
+{
+ do
+ ev_feed_event (EV_A_ rfeeds [--rfeedcnt], revents);
+ while (rfeedcnt);
+}
+
+inline_speed void
+queue_events (EV_P_ W *events, int eventcnt, int type)
+{
+ int i;
+
+ for (i = 0; i < eventcnt; ++i)
+ ev_feed_event (EV_A_ events [i], type);
+}
+
+/*****************************************************************************/
+
+inline_speed void
+fd_event_nocheck (EV_P_ int fd, int revents)
+{
+ ANFD *anfd = anfds + fd;
+ ev_io *w;
+
+ for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
+ {
+ int ev = w->events & revents;
+
+ if (ev)
+ ev_feed_event (EV_A_ (W)w, ev);
+ }
+}
+
+/* do not submit kernel events for fds that have reify set */
+/* because that means they changed while we were polling for new events */
+inline_speed void
+fd_event (EV_P_ int fd, int revents)
+{
+ ANFD *anfd = anfds + fd;
+
+ if (expect_true (!anfd->reify))
+ fd_event_nocheck (EV_A_ fd, revents);
+}
+
+void
+ev_feed_fd_event (EV_P_ int fd, int revents) EV_THROW
+{
+ if (fd >= 0 && fd < anfdmax)
+ fd_event_nocheck (EV_A_ fd, revents);
+}
+
+/* make sure the external fd watch events are in-sync */
+/* with the kernel/libev internal state */
+inline_size void
+fd_reify (EV_P)
+{
+ int i;
+
+#if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
+ for (i = 0; i < fdchangecnt; ++i)
+ {
+ int fd = fdchanges [i];
+ ANFD *anfd = anfds + fd;
+
+ if (anfd->reify & EV__IOFDSET && anfd->head)
+ {
+ SOCKET handle = EV_FD_TO_WIN32_HANDLE (fd);
+
+ if (handle != anfd->handle)
+ {
+ unsigned long arg;
+
+ assert (("libev: only socket fds supported in this configuration", ioctlsocket (handle, FIONREAD, &arg) == 0));
+
+ /* handle changed, but fd didn't - we need to do it in two steps */
+ backend_modify (EV_A_ fd, anfd->events, 0);
+ anfd->events = 0;
+ anfd->handle = handle;
+ }
+ }
+ }
+#endif
+
+ for (i = 0; i < fdchangecnt; ++i)
+ {
+ int fd = fdchanges [i];
+ ANFD *anfd = anfds + fd;
+ ev_io *w;
+
+ unsigned char o_events = anfd->events;
+ unsigned char o_reify = anfd->reify;
+
+ anfd->reify = 0;
+
+ /*if (expect_true (o_reify & EV_ANFD_REIFY)) probably a deoptimisation */
+ {
+ anfd->events = 0;
+
+ for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
+ anfd->events |= (unsigned char)w->events;
+
+ if (o_events != anfd->events)
+ o_reify = EV__IOFDSET; /* actually |= */
+ }
+
+ if (o_reify & EV__IOFDSET)
+ backend_modify (EV_A_ fd, o_events, anfd->events);
+ }
+
+ fdchangecnt = 0;
+}
+
+/* something about the given fd changed */
+inline_size void
+fd_change (EV_P_ int fd, int flags)
+{
+ unsigned char reify = anfds [fd].reify;
+ anfds [fd].reify |= flags;
+
+ if (expect_true (!reify))
+ {
+ ++fdchangecnt;
+ array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2);
+ fdchanges [fdchangecnt - 1] = fd;
+ }
+}
+
+/* the given fd is invalid/unusable, so make sure it doesn't hurt us anymore */
+inline_speed void ecb_cold
+fd_kill (EV_P_ int fd)
+{
+ ev_io *w;
+
+ while ((w = (ev_io *)anfds [fd].head))
+ {
+ ev_io_stop (EV_A_ w);
+ ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
+ }
+}
+
+/* check whether the given fd is actually valid, for error recovery */
+inline_size int ecb_cold
+fd_valid (int fd)
+{
+#ifdef _WIN32
+ return EV_FD_TO_WIN32_HANDLE (fd) != -1;
+#else
+ return fcntl (fd, F_GETFD) != -1;
+#endif
+}
+
+/* called on EBADF to verify fds */
+static void noinline ecb_cold
+fd_ebadf (EV_P)
+{
+ int fd;
+
+ for (fd = 0; fd < anfdmax; ++fd)
+ if (anfds [fd].events)
+ if (!fd_valid (fd) && errno == EBADF)
+ fd_kill (EV_A_ fd);
+}
+
+/* called on ENOMEM in select/poll to kill some fds and retry */
+static void noinline ecb_cold
+fd_enomem (EV_P)
+{
+ int fd;
+
+ for (fd = anfdmax; fd--; )
+ if (anfds [fd].events)
+ {
+ fd_kill (EV_A_ fd);
+ break;
+ }
+}
+
+/* usually called after fork if backend needs to re-arm all fds from scratch */
+static void noinline
+fd_rearm_all (EV_P)
+{
+ int fd;
+
+ for (fd = 0; fd < anfdmax; ++fd)
+ if (anfds [fd].events)
+ {
+ anfds [fd].events = 0;
+ anfds [fd].emask = 0;
+ fd_change (EV_A_ fd, EV__IOFDSET | EV_ANFD_REIFY);
+ }
+}
+
+/* used to prepare libev internal fd's */
+/* this is not fork-safe */
+inline_speed void
+fd_intern (int fd)
+{
+#ifdef _WIN32
+ unsigned long arg = 1;
+ ioctlsocket (EV_FD_TO_WIN32_HANDLE (fd), FIONBIO, &arg);
+#else
+ fcntl (fd, F_SETFD, FD_CLOEXEC);
+ fcntl (fd, F_SETFL, O_NONBLOCK);
+#endif
+}
+
+/*****************************************************************************/
+
+/*
+ * the heap functions want a real array index. array index 0 is guaranteed to not
+ * be in-use at any time. the first heap entry is at array [HEAP0]. DHEAP gives
+ * the branching factor of the d-tree.
+ */
+
+/*
+ * at the moment we allow libev the luxury of two heaps,
+ * a small-code-size 2-heap one and a ~1.5kb larger 4-heap
+ * which is more cache-efficient.
+ * the difference is about 5% with 50000+ watchers.
+ */
+#if EV_USE_4HEAP
+
+#define DHEAP 4
+#define HEAP0 (DHEAP - 1) /* index of first element in heap */
+#define HPARENT(k) ((((k) - HEAP0 - 1) / DHEAP) + HEAP0)
+#define UPHEAP_DONE(p,k) ((p) == (k))
+
+/* away from the root */
+inline_speed void
+downheap (ANHE *heap, int N, int k)
+{
+ ANHE he = heap [k];
+ ANHE *E = heap + N + HEAP0;
+
+ for (;;)
+ {
+ ev_tstamp minat;
+ ANHE *minpos;
+ ANHE *pos = heap + DHEAP * (k - HEAP0) + HEAP0 + 1;
+
+ /* find minimum child */
+ if (expect_true (pos + DHEAP - 1 < E))
+ {
+ /* fast path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
+ if ( ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos));
+ if ( ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos));
+ if ( ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos));
+ }
+ else if (pos < E)
+ {
+ /* slow path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
+ if (pos + 1 < E && ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos));
+ if (pos + 2 < E && ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos));
+ if (pos + 3 < E && ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos));
+ }
+ else
+ break;
+
+ if (ANHE_at (he) <= minat)
+ break;
+
+ heap [k] = *minpos;
+ ev_active (ANHE_w (*minpos)) = k;
+
+ k = minpos - heap;
+ }
+
+ heap [k] = he;
+ ev_active (ANHE_w (he)) = k;
+}
+
+#else /* 4HEAP */
+
+#define HEAP0 1
+#define HPARENT(k) ((k) >> 1)
+#define UPHEAP_DONE(p,k) (!(p))
+
+/* away from the root */
+inline_speed void
+downheap (ANHE *heap, int N, int k)
+{
+ ANHE he = heap [k];
+
+ for (;;)
+ {
+ int c = k << 1;
+
+ if (c >= N + HEAP0)
+ break;
+
+ c += c + 1 < N + HEAP0 && ANHE_at (heap [c]) > ANHE_at (heap [c + 1])
+ ? 1 : 0;
+
+ if (ANHE_at (he) <= ANHE_at (heap [c]))
+ break;
+
+ heap [k] = heap [c];
+ ev_active (ANHE_w (heap [k])) = k;
+
+ k = c;
+ }
+
+ heap [k] = he;
+ ev_active (ANHE_w (he)) = k;
+}
+#endif
+
+/* towards the root */
+inline_speed void
+upheap (ANHE *heap, int k)
+{
+ ANHE he = heap [k];
+
+ for (;;)
+ {
+ int p = HPARENT (k);
+
+ if (UPHEAP_DONE (p, k) || ANHE_at (heap [p]) <= ANHE_at (he))
+ break;
+
+ heap [k] = heap [p];
+ ev_active (ANHE_w (heap [k])) = k;
+ k = p;
+ }
+
+ heap [k] = he;
+ ev_active (ANHE_w (he)) = k;
+}
+
+/* move an element suitably so it is in a correct place */
+inline_size void
+adjustheap (ANHE *heap, int N, int k)
+{
+ if (k > HEAP0 && ANHE_at (heap [k]) <= ANHE_at (heap [HPARENT (k)]))
+ upheap (heap, k);
+ else
+ downheap (heap, N, k);
+}
+
+/* rebuild the heap: this function is used only once and executed rarely */
+inline_size void
+reheap (ANHE *heap, int N)
+{
+ int i;
+
+ /* we don't use floyds algorithm, upheap is simpler and is more cache-efficient */
+ /* also, this is easy to implement and correct for both 2-heaps and 4-heaps */
+ for (i = 0; i < N; ++i)
+ upheap (heap, i + HEAP0);
+}
+
+/*****************************************************************************/
+
+/* associate signal watchers to a signal signal */
+typedef struct
+{
+ EV_ATOMIC_T pending;
+#if EV_MULTIPLICITY
+ EV_P;
+#endif
+ WL head;
+} ANSIG;
+
+static ANSIG signals [EV_NSIG - 1];
+
+/*****************************************************************************/
+
+#if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
+
+static void noinline ecb_cold
+evpipe_init (EV_P)
+{
+ if (!ev_is_active (&pipe_w))
+ {
+ int fds [2];
+
+# if EV_USE_EVENTFD
+ fds [0] = -1;
+ fds [1] = eventfd (0, EFD_NONBLOCK | EFD_CLOEXEC);
+ if (fds [1] < 0 && errno == EINVAL)
+ fds [1] = eventfd (0, 0);
+
+ if (fds [1] < 0)
+# endif
+ {
+ while (pipe (fds))
+ ev_syserr ("(libev) error creating signal/async pipe");
+
+ fd_intern (fds [0]);
+ }
+
+ fd_intern (fds [1]);
+
+ evpipe [0] = fds [0];
+
+ if (evpipe [1] < 0)
+ evpipe [1] = fds [1]; /* first call, set write fd */
+ else
+ {
+ /* on subsequent calls, do not change evpipe [1] */
+ /* so that evpipe_write can always rely on its value. */
+ /* this branch does not do anything sensible on windows, */
+ /* so must not be executed on windows */
+
+ dup2 (fds [1], evpipe [1]);
+ close (fds [1]);
+ }
+
+ ev_io_set (&pipe_w, evpipe [0] < 0 ? evpipe [1] : evpipe [0], EV_READ);
+ ev_io_start (EV_A_ &pipe_w);
+ ev_unref (EV_A); /* watcher should not keep loop alive */
+ }
+}
+
+inline_speed void
+evpipe_write (EV_P_ EV_ATOMIC_T *flag)
+{
+ ECB_MEMORY_FENCE; /* push out the write before this function was called, acquire flag */
+
+ if (expect_true (*flag))
+ return;
+
+ *flag = 1;
+ ECB_MEMORY_FENCE_RELEASE; /* make sure flag is visible before the wakeup */
+
+ pipe_write_skipped = 1;
+
+ ECB_MEMORY_FENCE; /* make sure pipe_write_skipped is visible before we check pipe_write_wanted */
+
+ if (pipe_write_wanted)
+ {
+ int old_errno;
+
+ pipe_write_skipped = 0;
+ ECB_MEMORY_FENCE_RELEASE;
+
+ old_errno = errno; /* save errno because write will clobber it */
+
+#if EV_USE_EVENTFD
+ if (evpipe [0] < 0)
+ {
+ uint64_t counter = 1;
+ write (evpipe [1], &counter, sizeof (uint64_t));
+ }
+ else
+#endif
+ {
+#ifdef _WIN32
+ WSABUF buf;
+ DWORD sent;
+ buf.buf = &buf;
+ buf.len = 1;
+ WSASend (EV_FD_TO_WIN32_HANDLE (evpipe [1]), &buf, 1, &sent, 0, 0, 0);
+#else
+ write (evpipe [1], &(evpipe [1]), 1);
+#endif
+ }
+
+ errno = old_errno;
+ }
+}
+
+/* called whenever the libev signal pipe */
+/* got some events (signal, async) */
+static void
+pipecb (EV_P_ ev_io *iow, int revents)
+{
+ int i;
+
+ if (revents & EV_READ)
+ {
+#if EV_USE_EVENTFD
+ if (evpipe [0] < 0)
+ {
+ uint64_t counter;
+ read (evpipe [1], &counter, sizeof (uint64_t));
+ }
+ else
+#endif
+ {
+ char dummy[4];
+#ifdef _WIN32
+ WSABUF buf;
+ DWORD recvd;
+ DWORD flags = 0;
+ buf.buf = dummy;
+ buf.len = sizeof (dummy);
+ WSARecv (EV_FD_TO_WIN32_HANDLE (evpipe [0]), &buf, 1, &recvd, &flags, 0, 0);
+#else
+ read (evpipe [0], &dummy, sizeof (dummy));
+#endif
+ }
+ }
+
+ pipe_write_skipped = 0;
+
+ ECB_MEMORY_FENCE; /* push out skipped, acquire flags */
+
+#if EV_SIGNAL_ENABLE
+ if (sig_pending)
+ {
+ sig_pending = 0;
+
+ ECB_MEMORY_FENCE;
+
+ for (i = EV_NSIG - 1; i--; )
+ if (expect_false (signals [i].pending))
+ ev_feed_signal_event (EV_A_ i + 1);
+ }
+#endif
+
+#if EV_ASYNC_ENABLE
+ if (async_pending)
+ {
+ async_pending = 0;
+
+ ECB_MEMORY_FENCE;
+
+ for (i = asynccnt; i--; )
+ if (asyncs [i]->sent)
+ {
+ asyncs [i]->sent = 0;
+ ECB_MEMORY_FENCE_RELEASE;
+ ev_feed_event (EV_A_ asyncs [i], EV_ASYNC);
+ }
+ }
+#endif
+}
+
+/*****************************************************************************/
+
+void
+ev_feed_signal (int signum) EV_THROW
+{
+#if EV_MULTIPLICITY
+ EV_P;
+ ECB_MEMORY_FENCE_ACQUIRE;
+ EV_A = signals [signum - 1].loop;
+
+ if (!EV_A)
+ return;
+#endif
+
+ signals [signum - 1].pending = 1;
+ evpipe_write (EV_A_ &sig_pending);
+}
+
+static void
+ev_sighandler (int signum)
+{
+#ifdef _WIN32
+ signal (signum, ev_sighandler);
+#endif
+
+ ev_feed_signal (signum);
+}
+
+void noinline
+ev_feed_signal_event (EV_P_ int signum) EV_THROW
+{
+ WL w;
+
+ if (expect_false (signum <= 0 || signum >= EV_NSIG))
+ return;
+
+ --signum;
+
+#if EV_MULTIPLICITY
+ /* it is permissible to try to feed a signal to the wrong loop */
+ /* or, likely more useful, feeding a signal nobody is waiting for */
+
+ if (expect_false (signals [signum].loop != EV_A))
+ return;
+#endif
+
+ signals [signum].pending = 0;
+ ECB_MEMORY_FENCE_RELEASE;
+
+ for (w = signals [signum].head; w; w = w->next)
+ ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
+}
+
+#if EV_USE_SIGNALFD
+static void
+sigfdcb (EV_P_ ev_io *iow, int revents)
+{
+ struct signalfd_siginfo si[2], *sip; /* these structs are big */
+
+ for (;;)
+ {
+ ssize_t res = read (sigfd, si, sizeof (si));
+
+ /* not ISO-C, as res might be -1, but works with SuS */
+ for (sip = si; (char *)sip < (char *)si + res; ++sip)
+ ev_feed_signal_event (EV_A_ sip->ssi_signo);
+
+ if (res < (ssize_t)sizeof (si))
+ break;
+ }
+}
+#endif
+
+#endif
+
+/*****************************************************************************/
+
+#if EV_CHILD_ENABLE
+static WL childs [EV_PID_HASHSIZE];
+
+static ev_signal childev;
+
+#ifndef WIFCONTINUED
+# define WIFCONTINUED(status) 0
+#endif
+
+/* handle a single child status event */
+inline_speed void
+child_reap (EV_P_ int chain, int pid, int status)
+{
+ ev_child *w;
+ int traced = WIFSTOPPED (status) || WIFCONTINUED (status);
+
+ for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
+ {
+ if ((w->pid == pid || !w->pid)
+ && (!traced || (w->flags & 1)))
+ {
+ ev_set_priority (w, EV_MAXPRI); /* need to do it *now*, this *must* be the same prio as the signal watcher itself */
+ w->rpid = pid;
+ w->rstatus = status;
+ ev_feed_event (EV_A_ (W)w, EV_CHILD);
+ }
+ }
+}
+
+#ifndef WCONTINUED
+# define WCONTINUED 0
+#endif
+
+/* called on sigchld etc., calls waitpid */
+static void
+childcb (EV_P_ ev_signal *sw, int revents)
+{
+ int pid, status;
+
+ /* some systems define WCONTINUED but then fail to support it (linux 2.4) */
+ if (0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
+ if (!WCONTINUED
+ || errno != EINVAL
+ || 0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED)))
+ return;
+
+ /* make sure we are called again until all children have been reaped */
+ /* we need to do it this way so that the callback gets called before we continue */
+ ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
+
+ child_reap (EV_A_ pid, pid, status);
+ if ((EV_PID_HASHSIZE) > 1)
+ child_reap (EV_A_ 0, pid, status); /* this might trigger a watcher twice, but feed_event catches that */
+}
+
+#endif
+
+/*****************************************************************************/
+
+#if EV_USE_IOCP
+# include "ev_iocp.c"
+#endif
+#if EV_USE_PORT
+# include "ev_port.c"
+#endif
+#if EV_USE_KQUEUE
+# include "ev_kqueue.c"
+#endif
+#if EV_USE_EPOLL
+# include "ev_epoll.c"
+#endif
+#if EV_USE_POLL
+# include "ev_poll.c"
+#endif
+#if EV_USE_SELECT
+# include "ev_select.c"
+#endif
+
+int ecb_cold
+ev_version_major (void) EV_THROW
+{
+ return EV_VERSION_MAJOR;
+}
+
+int ecb_cold
+ev_version_minor (void) EV_THROW
+{
+ return EV_VERSION_MINOR;
+}
+
+/* return true if we are running with elevated privileges and should ignore env variables */
+int inline_size ecb_cold
+enable_secure (void)
+{
+#ifdef _WIN32
+ return 0;
+#else
+ return getuid () != geteuid ()
+ || getgid () != getegid ();
+#endif
+}
+
+unsigned int ecb_cold
+ev_supported_backends (void) EV_THROW
+{
+ unsigned int flags = 0;
+
+ if (EV_USE_PORT ) flags |= EVBACKEND_PORT;
+ if (EV_USE_KQUEUE) flags |= EVBACKEND_KQUEUE;
+ if (EV_USE_EPOLL ) flags |= EVBACKEND_EPOLL;
+ if (EV_USE_POLL ) flags |= EVBACKEND_POLL;
+ if (EV_USE_SELECT) flags |= EVBACKEND_SELECT;
+
+ return flags;
+}
+
+unsigned int ecb_cold
+ev_recommended_backends (void) EV_THROW
+{
+ unsigned int flags = ev_supported_backends ();
+
+#ifndef __NetBSD__
+ /* kqueue is borked on everything but netbsd apparently */
+ /* it usually doesn't work correctly on anything but sockets and pipes */
+ flags &= ~EVBACKEND_KQUEUE;
+#endif
+#ifdef __APPLE__
+ /* only select works correctly on that "unix-certified" platform */
+ flags &= ~EVBACKEND_KQUEUE; /* horribly broken, even for sockets */
+ flags &= ~EVBACKEND_POLL; /* poll is based on kqueue from 10.5 onwards */
+#endif
+#ifdef __FreeBSD__
+ flags &= ~EVBACKEND_POLL; /* poll return value is unusable (http://forums.freebsd.org/archive/index.php/t-10270.html) */
+#endif
+
+ return flags;
+}
+
+unsigned int ecb_cold
+ev_embeddable_backends (void) EV_THROW
+{
+ int flags = EVBACKEND_EPOLL | EVBACKEND_KQUEUE | EVBACKEND_PORT;
+
+ /* epoll embeddability broken on all linux versions up to at least 2.6.23 */
+ if (ev_linux_version () < 0x020620) /* disable it on linux < 2.6.32 */
+ flags &= ~EVBACKEND_EPOLL;
+
+ return flags;
+}
+
+unsigned int
+ev_backend (EV_P) EV_THROW
+{
+ return backend;
+}
+
+#if EV_FEATURE_API
+unsigned int
+ev_iteration (EV_P) EV_THROW
+{
+ return loop_count;
+}
+
+unsigned int
+ev_depth (EV_P) EV_THROW
+{
+ return loop_depth;
+}
+
+void
+ev_set_io_collect_interval (EV_P_ ev_tstamp interval) EV_THROW
+{
+ io_blocktime = interval;
+}
+
+void
+ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval) EV_THROW
+{
+ timeout_blocktime = interval;
+}
+
+void
+ev_set_userdata (EV_P_ void *data) EV_THROW
+{
+ userdata = data;
+}
+
+void *
+ev_userdata (EV_P) EV_THROW
+{
+ return userdata;
+}
+
+void
+ev_set_invoke_pending_cb (EV_P_ void (*invoke_pending_cb)(EV_P)) EV_THROW
+{
+ invoke_cb = invoke_pending_cb;
+}
+
+void
+ev_set_loop_release_cb (EV_P_ void (*release)(EV_P) EV_THROW, void (*acquire)(EV_P) EV_THROW) EV_THROW
+{
+ release_cb = release;
+ acquire_cb = acquire;
+}
+#endif
+
+/* initialise a loop structure, must be zero-initialised */
+static void noinline ecb_cold
+loop_init (EV_P_ unsigned int flags) EV_THROW
+{
+ if (!backend)
+ {
+ origflags = flags;
+
+#if EV_USE_REALTIME
+ if (!have_realtime)
+ {
+ struct timespec ts;
+
+ if (!clock_gettime (CLOCK_REALTIME, &ts))
+ have_realtime = 1;
+ }
+#endif
+
+#if EV_USE_MONOTONIC
+ if (!have_monotonic)
+ {
+ struct timespec ts;
+
+ if (!clock_gettime (CLOCK_MONOTONIC, &ts))
+ have_monotonic = 1;
+ }
+#endif
+
+ /* pid check not overridable via env */
+#ifndef _WIN32
+ if (flags & EVFLAG_FORKCHECK)
+ curpid = getpid ();
+#endif
+
+ if (!(flags & EVFLAG_NOENV)
+ && !enable_secure ()
+ && getenv ("LIBEV_FLAGS"))
+ flags = atoi (getenv ("LIBEV_FLAGS"));
+
+ ev_rt_now = ev_time ();
+ mn_now = get_clock ();
+ now_floor = mn_now;
+ rtmn_diff = ev_rt_now - mn_now;
+#if EV_FEATURE_API
+ invoke_cb = ev_invoke_pending;
+#endif
+
+ io_blocktime = 0.;
+ timeout_blocktime = 0.;
+ backend = 0;
+ backend_fd = -1;
+ sig_pending = 0;
+#if EV_ASYNC_ENABLE
+ async_pending = 0;
+#endif
+ pipe_write_skipped = 0;
+ pipe_write_wanted = 0;
+ evpipe [0] = -1;
+ evpipe [1] = -1;
+#if EV_USE_INOTIFY
+ fs_fd = flags & EVFLAG_NOINOTIFY ? -1 : -2;
+#endif
+#if EV_USE_SIGNALFD
+ sigfd = flags & EVFLAG_SIGNALFD ? -2 : -1;
+#endif
+
+ if (!(flags & EVBACKEND_MASK))
+ flags |= ev_recommended_backends ();
+
+#if EV_USE_IOCP
+ if (!backend && (flags & EVBACKEND_IOCP )) backend = iocp_init (EV_A_ flags);
+#endif
+#if EV_USE_PORT
+ if (!backend && (flags & EVBACKEND_PORT )) backend = port_init (EV_A_ flags);
+#endif
+#if EV_USE_KQUEUE
+ if (!backend && (flags & EVBACKEND_KQUEUE)) backend = kqueue_init (EV_A_ flags);
+#endif
+#if EV_USE_EPOLL
+ if (!backend && (flags & EVBACKEND_EPOLL )) backend = epoll_init (EV_A_ flags);
+#endif
+#if EV_USE_POLL
+ if (!backend && (flags & EVBACKEND_POLL )) backend = poll_init (EV_A_ flags);
+#endif
+#if EV_USE_SELECT
+ if (!backend && (flags & EVBACKEND_SELECT)) backend = select_init (EV_A_ flags);
+#endif
+
+ ev_prepare_init (&pending_w, pendingcb);
+
+#if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
+ ev_init (&pipe_w, pipecb);
+ ev_set_priority (&pipe_w, EV_MAXPRI);
+#endif
+ }
+}
+
+/* free up a loop structure */
+void ecb_cold
+ev_loop_destroy (EV_P)
+{
+ int i;
+
+#if EV_MULTIPLICITY
+ /* mimic free (0) */
+ if (!EV_A)
+ return;
+#endif
+
+#if EV_CLEANUP_ENABLE
+ /* queue cleanup watchers (and execute them) */
+ if (expect_false (cleanupcnt))
+ {
+ queue_events (EV_A_ (W *)cleanups, cleanupcnt, EV_CLEANUP);
+ EV_INVOKE_PENDING;
+ }
+#endif
+
+#if EV_CHILD_ENABLE
+ if (ev_is_default_loop (EV_A) && ev_is_active (&childev))
+ {
+ ev_ref (EV_A); /* child watcher */
+ ev_signal_stop (EV_A_ &childev);
+ }
+#endif
+
+ if (ev_is_active (&pipe_w))
+ {
+ /*ev_ref (EV_A);*/
+ /*ev_io_stop (EV_A_ &pipe_w);*/
+
+ if (evpipe [0] >= 0) EV_WIN32_CLOSE_FD (evpipe [0]);
+ if (evpipe [1] >= 0) EV_WIN32_CLOSE_FD (evpipe [1]);
+ }
+
+#if EV_USE_SIGNALFD
+ if (ev_is_active (&sigfd_w))
+ close (sigfd);
+#endif
+
+#if EV_USE_INOTIFY
+ if (fs_fd >= 0)
+ close (fs_fd);
+#endif
+
+ if (backend_fd >= 0)
+ close (backend_fd);
+
+#if EV_USE_IOCP
+ if (backend == EVBACKEND_IOCP ) iocp_destroy (EV_A);
+#endif
+#if EV_USE_PORT
+ if (backend == EVBACKEND_PORT ) port_destroy (EV_A);
+#endif
+#if EV_USE_KQUEUE
+ if (backend == EVBACKEND_KQUEUE) kqueue_destroy (EV_A);
+#endif
+#if EV_USE_EPOLL
+ if (backend == EVBACKEND_EPOLL ) epoll_destroy (EV_A);
+#endif
+#if EV_USE_POLL
+ if (backend == EVBACKEND_POLL ) poll_destroy (EV_A);
+#endif
+#if EV_USE_SELECT
+ if (backend == EVBACKEND_SELECT) select_destroy (EV_A);
+#endif
+
+ for (i = NUMPRI; i--; )
+ {
+ array_free (pending, [i]);
+#if EV_IDLE_ENABLE
+ array_free (idle, [i]);
+#endif
+ }
+
+ ev_free (anfds); anfds = 0; anfdmax = 0;
+
+ /* have to use the microsoft-never-gets-it-right macro */
+ array_free (rfeed, EMPTY);
+ array_free (fdchange, EMPTY);
+ array_free (timer, EMPTY);
+#if EV_PERIODIC_ENABLE
+ array_free (periodic, EMPTY);
+#endif
+#if EV_FORK_ENABLE
+ array_free (fork, EMPTY);
+#endif
+#if EV_CLEANUP_ENABLE
+ array_free (cleanup, EMPTY);
+#endif
+ array_free (prepare, EMPTY);
+ array_free (check, EMPTY);
+#if EV_ASYNC_ENABLE
+ array_free (async, EMPTY);
+#endif
+
+ backend = 0;
+
+#if EV_MULTIPLICITY
+ if (ev_is_default_loop (EV_A))
+#endif
+ ev_default_loop_ptr = 0;
+#if EV_MULTIPLICITY
+ else
+ ev_free (EV_A);
+#endif
+}
+
+#if EV_USE_INOTIFY
+inline_size void infy_fork (EV_P);
+#endif
+
+inline_size void
+loop_fork (EV_P)
+{
+#if EV_USE_PORT
+ if (backend == EVBACKEND_PORT ) port_fork (EV_A);
+#endif
+#if EV_USE_KQUEUE
+ if (backend == EVBACKEND_KQUEUE) kqueue_fork (EV_A);
+#endif
+#if EV_USE_EPOLL
+ if (backend == EVBACKEND_EPOLL ) epoll_fork (EV_A);
+#endif
+#if EV_USE_INOTIFY
+ infy_fork (EV_A);
+#endif
+
+#if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
+ if (ev_is_active (&pipe_w))
+ {
+ /* pipe_write_wanted must be false now, so modifying fd vars should be safe */
+
+ ev_ref (EV_A);
+ ev_io_stop (EV_A_ &pipe_w);
+
+ if (evpipe [0] >= 0)
+ EV_WIN32_CLOSE_FD (evpipe [0]);
+
+ evpipe_init (EV_A);
+ /* iterate over everything, in case we missed something before */
+ ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM);
+ }
+#endif
+
+ postfork = 0;
+}
+
+#if EV_MULTIPLICITY
+
+struct ev_loop * ecb_cold
+ev_loop_new (unsigned int flags) EV_THROW
+{
+ EV_P = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
+
+ memset (EV_A, 0, sizeof (struct ev_loop));
+ loop_init (EV_A_ flags);
+
+ if (ev_backend (EV_A))
+ return EV_A;
+
+ ev_free (EV_A);
+ return 0;
+}
+
+#endif /* multiplicity */
+
+#if EV_VERIFY
+static void noinline ecb_cold
+verify_watcher (EV_P_ W w)
+{
+ assert (("libev: watcher has invalid priority", ABSPRI (w) >= 0 && ABSPRI (w) < NUMPRI));
+
+ if (w->pending)
+ assert (("libev: pending watcher not on pending queue", pendings [ABSPRI (w)][w->pending - 1].w == w));
+}
+
+static void noinline ecb_cold
+verify_heap (EV_P_ ANHE *heap, int N)
+{
+ int i;
+
+ for (i = HEAP0; i < N + HEAP0; ++i)
+ {
+ assert (("libev: active index mismatch in heap", ev_active (ANHE_w (heap [i])) == i));
+ assert (("libev: heap condition violated", i == HEAP0 || ANHE_at (heap [HPARENT (i)]) <= ANHE_at (heap [i])));
+ assert (("libev: heap at cache mismatch", ANHE_at (heap [i]) == ev_at (ANHE_w (heap [i]))));
+
+ verify_watcher (EV_A_ (W)ANHE_w (heap [i]));
+ }
+}
+
+static void noinline ecb_cold
+array_verify (EV_P_ W *ws, int cnt)
+{
+ while (cnt--)
+ {
+ assert (("libev: active index mismatch", ev_active (ws [cnt]) == cnt + 1));
+ verify_watcher (EV_A_ ws [cnt]);
+ }
+}
+#endif
+
+#if EV_FEATURE_API
+void ecb_cold
+ev_verify (EV_P) EV_THROW
+{
+#if EV_VERIFY
+ int i;
+ WL w, w2;
+
+ assert (activecnt >= -1);
+
+ assert (fdchangemax >= fdchangecnt);
+ for (i = 0; i < fdchangecnt; ++i)
+ assert (("libev: negative fd in fdchanges", fdchanges [i] >= 0));
+
+ assert (anfdmax >= 0);
+ for (i = 0; i < anfdmax; ++i)
+ {
+ int j = 0;
+
+ for (w = w2 = anfds [i].head; w; w = w->next)
+ {
+ verify_watcher (EV_A_ (W)w);
+
+ if (j++ & 1)
+ {
+ assert (("libev: io watcher list contains a loop", w != w2));
+ w2 = w2->next;
+ }
+
+ assert (("libev: inactive fd watcher on anfd list", ev_active (w) == 1));
+ assert (("libev: fd mismatch between watcher and anfd", ((ev_io *)w)->fd == i));
+ }
+ }
+
+ assert (timermax >= timercnt);
+ verify_heap (EV_A_ timers, timercnt);
+
+#if EV_PERIODIC_ENABLE
+ assert (periodicmax >= periodiccnt);
+ verify_heap (EV_A_ periodics, periodiccnt);
+#endif
+
+ for (i = NUMPRI; i--; )
+ {
+ assert (pendingmax [i] >= pendingcnt [i]);
+#if EV_IDLE_ENABLE
+ assert (idleall >= 0);
+ assert (idlemax [i] >= idlecnt [i]);
+ array_verify (EV_A_ (W *)idles [i], idlecnt [i]);
+#endif
+ }
+
+#if EV_FORK_ENABLE
+ assert (forkmax >= forkcnt);
+ array_verify (EV_A_ (W *)forks, forkcnt);
+#endif
+
+#if EV_CLEANUP_ENABLE
+ assert (cleanupmax >= cleanupcnt);
+ array_verify (EV_A_ (W *)cleanups, cleanupcnt);
+#endif
+
+#if EV_ASYNC_ENABLE
+ assert (asyncmax >= asynccnt);
+ array_verify (EV_A_ (W *)asyncs, asynccnt);
+#endif
+
+#if EV_PREPARE_ENABLE
+ assert (preparemax >= preparecnt);
+ array_verify (EV_A_ (W *)prepares, preparecnt);
+#endif
+
+#if EV_CHECK_ENABLE
+ assert (checkmax >= checkcnt);
+ array_verify (EV_A_ (W *)checks, checkcnt);
+#endif
+
+# if 0
+#if EV_CHILD_ENABLE
+ for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
+ for (signum = EV_NSIG; signum--; ) if (signals [signum].pending)
+#endif
+# endif
+#endif
+}
+#endif
+
+#if EV_MULTIPLICITY
+struct ev_loop * ecb_cold
+#else
+int
+#endif
+ev_default_loop (unsigned int flags) EV_THROW
+{
+ if (!ev_default_loop_ptr)
+ {
+#if EV_MULTIPLICITY
+ EV_P = ev_default_loop_ptr = &default_loop_struct;
+#else
+ ev_default_loop_ptr = 1;
+#endif
+
+ loop_init (EV_A_ flags);
+
+ if (ev_backend (EV_A))
+ {
+#if EV_CHILD_ENABLE
+ ev_signal_init (&childev, childcb, SIGCHLD);
+ ev_set_priority (&childev, EV_MAXPRI);
+ ev_signal_start (EV_A_ &childev);
+ ev_unref (EV_A); /* child watcher should not keep loop alive */
+#endif
+ }
+ else
+ ev_default_loop_ptr = 0;
+ }
+
+ return ev_default_loop_ptr;
+}
+
+void
+ev_loop_fork (EV_P) EV_THROW
+{
+ postfork = 1;
+}
+
+/*****************************************************************************/
+
+void
+ev_invoke (EV_P_ void *w, int revents)
+{
+ EV_CB_INVOKE ((W)w, revents);
+}
+
+unsigned int
+ev_pending_count (EV_P) EV_THROW
+{
+ int pri;
+ unsigned int count = 0;
+
+ for (pri = NUMPRI; pri--; )
+ count += pendingcnt [pri];
+
+ return count;
+}
+
+void noinline
+ev_invoke_pending (EV_P)
+{
+ pendingpri = NUMPRI;
+
+ while (pendingpri) /* pendingpri possibly gets modified in the inner loop */
+ {
+ --pendingpri;
+
+ while (pendingcnt [pendingpri])
+ {
+ ANPENDING *p = pendings [pendingpri] + --pendingcnt [pendingpri];
+
+ p->w->pending = 0;
+ EV_CB_INVOKE (p->w, p->events);
+ EV_FREQUENT_CHECK;
+ }
+ }
+}
+
+#if EV_IDLE_ENABLE
+/* make idle watchers pending. this handles the "call-idle */
+/* only when higher priorities are idle" logic */
+inline_size void
+idle_reify (EV_P)
+{
+ if (expect_false (idleall))
+ {
+ int pri;
+
+ for (pri = NUMPRI; pri--; )
+ {
+ if (pendingcnt [pri])
+ break;
+
+ if (idlecnt [pri])
+ {
+ queue_events (EV_A_ (W *)idles [pri], idlecnt [pri], EV_IDLE);
+ break;
+ }
+ }
+ }
+}
+#endif
+
+/* make timers pending */
+inline_size void
+timers_reify (EV_P)
+{
+ EV_FREQUENT_CHECK;
+
+ if (timercnt && ANHE_at (timers [HEAP0]) < mn_now)
+ {
+ do
+ {
+ ev_timer *w = (ev_timer *)ANHE_w (timers [HEAP0]);
+
+ /*assert (("libev: inactive timer on timer heap detected", ev_is_active (w)));*/
+
+ /* first reschedule or stop timer */
+ if (w->repeat)
+ {
+ ev_at (w) += w->repeat;
+ if (ev_at (w) < mn_now)
+ ev_at (w) = mn_now;
+
+ assert (("libev: negative ev_timer repeat value found while processing timers", w->repeat > 0.));
+
+ ANHE_at_cache (timers [HEAP0]);
+ downheap (timers, timercnt, HEAP0);
+ }
+ else
+ ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
+
+ EV_FREQUENT_CHECK;
+ feed_reverse (EV_A_ (W)w);
+ }
+ while (timercnt && ANHE_at (timers [HEAP0]) < mn_now);
+
+ feed_reverse_done (EV_A_ EV_TIMER);
+ }
+}
+
+#if EV_PERIODIC_ENABLE
+
+static void noinline
+periodic_recalc (EV_P_ ev_periodic *w)
+{
+ ev_tstamp interval = w->interval > MIN_INTERVAL ? w->interval : MIN_INTERVAL;
+ ev_tstamp at = w->offset + interval * ev_floor ((ev_rt_now - w->offset) / interval);
+
+ /* the above almost always errs on the low side */
+ while (at <= ev_rt_now)
+ {
+ ev_tstamp nat = at + w->interval;
+
+ /* when resolution fails us, we use ev_rt_now */
+ if (expect_false (nat == at))
+ {
+ at = ev_rt_now;
+ break;
+ }
+
+ at = nat;
+ }
+
+ ev_at (w) = at;
+}
+
+/* make periodics pending */
+inline_size void
+periodics_reify (EV_P)
+{
+ EV_FREQUENT_CHECK;
+
+ while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now)
+ {
+ do
+ {
+ ev_periodic *w = (ev_periodic *)ANHE_w (periodics [HEAP0]);
+
+ /*assert (("libev: inactive timer on periodic heap detected", ev_is_active (w)));*/
+
+ /* first reschedule or stop timer */
+ if (w->reschedule_cb)
+ {
+ ev_at (w) = w->reschedule_cb (w, ev_rt_now);
+
+ assert (("libev: ev_periodic reschedule callback returned time in the past", ev_at (w) >= ev_rt_now));
+
+ ANHE_at_cache (periodics [HEAP0]);
+ downheap (periodics, periodiccnt, HEAP0);
+ }
+ else if (w->interval)
+ {
+ periodic_recalc (EV_A_ w);
+ ANHE_at_cache (periodics [HEAP0]);
+ downheap (periodics, periodiccnt, HEAP0);
+ }
+ else
+ ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
+
+ EV_FREQUENT_CHECK;
+ feed_reverse (EV_A_ (W)w);
+ }
+ while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now);
+
+ feed_reverse_done (EV_A_ EV_PERIODIC);
+ }
+}
+
+/* simply recalculate all periodics */
+/* TODO: maybe ensure that at least one event happens when jumping forward? */
+static void noinline ecb_cold
+periodics_reschedule (EV_P)
+{
+ int i;
+
+ /* adjust periodics after time jump */
+ for (i = HEAP0; i < periodiccnt + HEAP0; ++i)
+ {
+ ev_periodic *w = (ev_periodic *)ANHE_w (periodics [i]);
+
+ if (w->reschedule_cb)
+ ev_at (w) = w->reschedule_cb (w, ev_rt_now);
+ else if (w->interval)
+ periodic_recalc (EV_A_ w);
+
+ ANHE_at_cache (periodics [i]);
+ }
+
+ reheap (periodics, periodiccnt);
+}
+#endif
+
+/* adjust all timers by a given offset */
+static void noinline ecb_cold
+timers_reschedule (EV_P_ ev_tstamp adjust)
+{
+ int i;
+
+ for (i = 0; i < timercnt; ++i)
+ {
+ ANHE *he = timers + i + HEAP0;
+ ANHE_w (*he)->at += adjust;
+ ANHE_at_cache (*he);
+ }
+}
+
+/* fetch new monotonic and realtime times from the kernel */
+/* also detect if there was a timejump, and act accordingly */
+inline_speed void
+time_update (EV_P_ ev_tstamp max_block)
+{
+#if EV_USE_MONOTONIC
+ if (expect_true (have_monotonic))
+ {
+ int i;
+ ev_tstamp odiff = rtmn_diff;
+
+ mn_now = get_clock ();
+
+ /* only fetch the realtime clock every 0.5*MIN_TIMEJUMP seconds */
+ /* interpolate in the meantime */
+ if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5))
+ {
+ ev_rt_now = rtmn_diff + mn_now;
+ return;
+ }
+
+ now_floor = mn_now;
+ ev_rt_now = ev_time ();
+
+ /* loop a few times, before making important decisions.
+ * on the choice of "4": one iteration isn't enough,
+ * in case we get preempted during the calls to
+ * ev_time and get_clock. a second call is almost guaranteed
+ * to succeed in that case, though. and looping a few more times
+ * doesn't hurt either as we only do this on time-jumps or
+ * in the unlikely event of having been preempted here.
+ */
+ for (i = 4; --i; )
+ {
+ ev_tstamp diff;
+ rtmn_diff = ev_rt_now - mn_now;
+
+ diff = odiff - rtmn_diff;
+
+ if (expect_true ((diff < 0. ? -diff : diff) < MIN_TIMEJUMP))
+ return; /* all is well */
+
+ ev_rt_now = ev_time ();
+ mn_now = get_clock ();
+ now_floor = mn_now;
+ }
+
+ /* no timer adjustment, as the monotonic clock doesn't jump */
+ /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
+# if EV_PERIODIC_ENABLE
+ periodics_reschedule (EV_A);
+# endif
+ }
+ else
+#endif
+ {
+ ev_rt_now = ev_time ();
+
+ if (expect_false (mn_now > ev_rt_now || ev_rt_now > mn_now + max_block + MIN_TIMEJUMP))
+ {
+ /* adjust timers. this is easy, as the offset is the same for all of them */
+ timers_reschedule (EV_A_ ev_rt_now - mn_now);
+#if EV_PERIODIC_ENABLE
+ periodics_reschedule (EV_A);
+#endif
+ }
+
+ mn_now = ev_rt_now;
+ }
+}
+
+/* ########## NIO4R PATCHERY HO! ########## */
+#if defined(HAVE_RB_THREAD_BLOCKING_REGION)
+struct ev_poll_args {
+ struct ev_loop *loop;
+ ev_tstamp waittime;
+};
+
+static
+VALUE ev_backend_poll(void *ptr)
+{
+ struct ev_poll_args *args = (struct ev_poll_args *)ptr;
+ struct ev_loop *loop = args->loop;
+ backend_poll (EV_A_ args->waittime);
+}
+#endif
+/* ######################################## */
+
+int
+ev_run (EV_P_ int flags)
+{
+/* ########## NIO4R PATCHERY HO! ########## */
+#if defined(HAVE_RB_THREAD_BLOCKING_REGION)
+ struct ev_poll_args poll_args;
+#endif
+/* ######################################## */
+
+#if EV_FEATURE_API
+ ++loop_depth;
+#endif
+
+ assert (("libev: ev_loop recursion during release detected", loop_done != EVBREAK_RECURSE));
+
+ loop_done = EVBREAK_CANCEL;
+
+ EV_INVOKE_PENDING; /* in case we recurse, ensure ordering stays nice and clean */
+
+ do
+ {
+#if EV_VERIFY >= 2
+ ev_verify (EV_A);
+#endif
+
+#ifndef _WIN32
+ if (expect_false (curpid)) /* penalise the forking check even more */
+ if (expect_false (getpid () != curpid))
+ {
+ curpid = getpid ();
+ postfork = 1;
+ }
+#endif
+
+#if EV_FORK_ENABLE
+ /* we might have forked, so queue fork handlers */
+ if (expect_false (postfork))
+ if (forkcnt)
+ {
+ queue_events (EV_A_ (W *)forks, forkcnt, EV_FORK);
+ EV_INVOKE_PENDING;
+ }
+#endif
+
+#if EV_PREPARE_ENABLE
+ /* queue prepare watchers (and execute them) */
+ if (expect_false (preparecnt))
+ {
+ queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
+ EV_INVOKE_PENDING;
+ }
+#endif
+
+ if (expect_false (loop_done))
+ break;
+
+ /* we might have forked, so reify kernel state if necessary */
+ if (expect_false (postfork))
+ loop_fork (EV_A);
+
+ /* update fd-related kernel structures */
+ fd_reify (EV_A);
+
+ /* calculate blocking time */
+ {
+ ev_tstamp waittime = 0.;
+ ev_tstamp sleeptime = 0.;
+
+ /* remember old timestamp for io_blocktime calculation */
+ ev_tstamp prev_mn_now = mn_now;
+
+ /* update time to cancel out callback processing overhead */
+ time_update (EV_A_ 1e100);
+
+ /* from now on, we want a pipe-wake-up */
+ pipe_write_wanted = 1;
+
+ ECB_MEMORY_FENCE; /* make sure pipe_write_wanted is visible before we check for potential skips */
+
+ if (expect_true (!(flags & EVRUN_NOWAIT || idleall || !activecnt || pipe_write_skipped)))
+ {
+ waittime = MAX_BLOCKTIME;
+
+ if (timercnt)
+ {
+ ev_tstamp to = ANHE_at (timers [HEAP0]) - mn_now;
+ if (waittime > to) waittime = to;
+ }
+
+#if EV_PERIODIC_ENABLE
+ if (periodiccnt)
+ {
+ ev_tstamp to = ANHE_at (periodics [HEAP0]) - ev_rt_now;
+ if (waittime > to) waittime = to;
+ }
+#endif
+
+ /* don't let timeouts decrease the waittime below timeout_blocktime */
+ if (expect_false (waittime < timeout_blocktime))
+ waittime = timeout_blocktime;
+
+ /* at this point, we NEED to wait, so we have to ensure */
+ /* to pass a minimum nonzero value to the backend */
+ if (expect_false (waittime < backend_mintime))
+ waittime = backend_mintime;
+
+ /* extra check because io_blocktime is commonly 0 */
+ if (expect_false (io_blocktime))
+ {
+ sleeptime = io_blocktime - (mn_now - prev_mn_now);
+
+ if (sleeptime > waittime - backend_mintime)
+ sleeptime = waittime - backend_mintime;
+
+ if (expect_true (sleeptime > 0.))
+ {
+ ev_sleep (sleeptime);
+ waittime -= sleeptime;
+ }
+ }
+ }
+
+#if EV_FEATURE_API
+ ++loop_count;
+#endif
+ assert ((loop_done = EVBREAK_RECURSE, 1)); /* assert for side effect */
+
+/*
+########################## NIO4R PATCHERY HO! ##########################
+
+According to the grandwizards of Ruby, locking and unlocking of the global
+interpreter lock are apparently too powerful a concept for a mere mortal to
+wield (although redefining what + and - do to numbers is totally cool).
+And so it came to pass that the only acceptable way to release the global
+interpreter lock is through a convoluted callback system that thakes a
+function pointer. While the grandwizard of libev foresaw this sort of scenario,
+he too attempted to place an API with callbacks on it, one that runs before
+the system call, and one that runs immediately after.
+
+And so it came to pass that trying to wrap everything up in callbacks created
+two incompatible APIs, Ruby's which releases the global interpreter lock and
+reacquires it when the callback returns, and libev's, which wants two
+callbacks, one which runs before the polling operation starts, and one which
+runs after it finishes.
+
+These two systems are incompatible as they both want to use callbacks to
+solve the same problem, however libev wants to use before/after callbacks,
+and Ruby wants to use an "around" callback. This presents a significant
+problem as these two patterns of callbacks are diametrical opposites of each
+other and thus cannot be composed.
+
+And thus we are left with no choice but to patch the internals of libev in
+order to release a mutex at just the precise moment.
+
+This is a great example of a situation where granular locking and unlocking
+of the GVL is practically required. The goal is to get as close to the
+system call as possible, and to keep the GVL unlocked for the shortest
+amount of time possible.
+
+Perhaps Ruby could benefit from such an API, e.g:
+
+rb_thread_unsafe_dangerous_crazy_blocking_region_begin(...);
+rb_thread_unsafe_dangerous_crazy_blocking_region_end(...);
+
+#######################################################################
+*/
+
+#if defined(HAVE_RB_THREAD_BLOCKING_REGION)
+ poll_args.loop = loop;
+ poll_args.waittime = waittime;
+ rb_thread_blocking_region(ev_backend_poll, (void *)&poll_args, RUBY_UBF_IO, 0);
+#else
+ backend_poll (EV_A_ waittime);
+#endif
+/*
+############################# END PATCHERY ############################
+*/
+
+ assert ((loop_done = EVBREAK_CANCEL, 1)); /* assert for side effect */
+
+ pipe_write_wanted = 0; /* just an optimisation, no fence needed */
+
+ ECB_MEMORY_FENCE_ACQUIRE;
+ if (pipe_write_skipped)
+ {
+ assert (("libev: pipe_w not active, but pipe not written", ev_is_active (&pipe_w)));
+ ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM);
+ }
+
+
+ /* update ev_rt_now, do magic */
+ time_update (EV_A_ waittime + sleeptime);
+ }
+
+ /* queue pending timers and reschedule them */
+ timers_reify (EV_A); /* relative timers called last */
+#if EV_PERIODIC_ENABLE
+ periodics_reify (EV_A); /* absolute timers called first */
+#endif
+
+#if EV_IDLE_ENABLE
+ /* queue idle watchers unless other events are pending */
+ idle_reify (EV_A);
+#endif
+
+#if EV_CHECK_ENABLE
+ /* queue check watchers, to be executed first */
+ if (expect_false (checkcnt))
+ queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
+#endif
+
+ EV_INVOKE_PENDING;
+ }
+ while (expect_true (
+ activecnt
+ && !loop_done
+ && !(flags & (EVRUN_ONCE | EVRUN_NOWAIT))
+ ));
+
+ if (loop_done == EVBREAK_ONE)
+ loop_done = EVBREAK_CANCEL;
+
+#if EV_FEATURE_API
+ --loop_depth;
+#endif
+
+ return activecnt;
+}
+
+void
+ev_break (EV_P_ int how) EV_THROW
+{
+ loop_done = how;
+}
+
+void
+ev_ref (EV_P) EV_THROW
+{
+ ++activecnt;
+}
+
+void
+ev_unref (EV_P) EV_THROW
+{
+ --activecnt;
+}
+
+void
+ev_now_update (EV_P) EV_THROW
+{
+ time_update (EV_A_ 1e100);
+}
+
+void
+ev_suspend (EV_P) EV_THROW
+{
+ ev_now_update (EV_A);
+}
+
+void
+ev_resume (EV_P) EV_THROW
+{
+ ev_tstamp mn_prev = mn_now;
+
+ ev_now_update (EV_A);
+ timers_reschedule (EV_A_ mn_now - mn_prev);
+#if EV_PERIODIC_ENABLE
+ /* TODO: really do this? */
+ periodics_reschedule (EV_A);
+#endif
+}
+
+/*****************************************************************************/
+/* singly-linked list management, used when the expected list length is short */
+
+inline_size void
+wlist_add (WL *head, WL elem)
+{
+ elem->next = *head;
+ *head = elem;
+}
+
+inline_size void
+wlist_del (WL *head, WL elem)
+{
+ while (*head)
+ {
+ if (expect_true (*head == elem))
+ {
+ *head = elem->next;
+ break;
+ }
+
+ head = &(*head)->next;
+ }
+}
+
+/* internal, faster, version of ev_clear_pending */
+inline_speed void
+clear_pending (EV_P_ W w)
+{
+ if (w->pending)
+ {
+ pendings [ABSPRI (w)][w->pending - 1].w = (W)&pending_w;
+ w->pending = 0;
+ }
+}
+
+int
+ev_clear_pending (EV_P_ void *w) EV_THROW
+{
+ W w_ = (W)w;
+ int pending = w_->pending;
+
+ if (expect_true (pending))
+ {
+ ANPENDING *p = pendings [ABSPRI (w_)] + pending - 1;
+ p->w = (W)&pending_w;
+ w_->pending = 0;
+ return p->events;
+ }
+ else
+ return 0;
+}
+
+inline_size void
+pri_adjust (EV_P_ W w)
+{
+ int pri = ev_priority (w);
+ pri = pri < EV_MINPRI ? EV_MINPRI : pri;
+ pri = pri > EV_MAXPRI ? EV_MAXPRI : pri;
+ ev_set_priority (w, pri);
+}
+
+inline_speed void
+ev_start (EV_P_ W w, int active)
+{
+ pri_adjust (EV_A_ w);
+ w->active = active;
+ ev_ref (EV_A);
+}
+
+inline_size void
+ev_stop (EV_P_ W w)
+{
+ ev_unref (EV_A);
+ w->active = 0;
+}
+
+/*****************************************************************************/
+
+void noinline
+ev_io_start (EV_P_ ev_io *w) EV_THROW
+{
+ int fd = w->fd;
+
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ assert (("libev: ev_io_start called with negative fd", fd >= 0));
+ assert (("libev: ev_io_start called with illegal event mask", !(w->events & ~(EV__IOFDSET | EV_READ | EV_WRITE))));
+
+ EV_FREQUENT_CHECK;
+
+ ev_start (EV_A_ (W)w, 1);
+ array_needsize (ANFD, anfds, anfdmax, fd + 1, array_init_zero);
+ wlist_add (&anfds[fd].head, (WL)w);
+
+ /* common bug, apparently */
+ assert (("libev: ev_io_start called with corrupted watcher", ((WL)w)->next != (WL)w));
+
+ fd_change (EV_A_ fd, w->events & EV__IOFDSET | EV_ANFD_REIFY);
+ w->events &= ~EV__IOFDSET;
+
+ EV_FREQUENT_CHECK;
+}
+
+void noinline
+ev_io_stop (EV_P_ ev_io *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ assert (("libev: ev_io_stop called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax));
+
+ EV_FREQUENT_CHECK;
+
+ wlist_del (&anfds[w->fd].head, (WL)w);
+ ev_stop (EV_A_ (W)w);
+
+ fd_change (EV_A_ w->fd, EV_ANFD_REIFY);
+
+ EV_FREQUENT_CHECK;
+}
+
+void noinline
+ev_timer_start (EV_P_ ev_timer *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ ev_at (w) += mn_now;
+
+ assert (("libev: ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
+
+ EV_FREQUENT_CHECK;
+
+ ++timercnt;
+ ev_start (EV_A_ (W)w, timercnt + HEAP0 - 1);
+ array_needsize (ANHE, timers, timermax, ev_active (w) + 1, EMPTY2);
+ ANHE_w (timers [ev_active (w)]) = (WT)w;
+ ANHE_at_cache (timers [ev_active (w)]);
+ upheap (timers, ev_active (w));
+
+ EV_FREQUENT_CHECK;
+
+ /*assert (("libev: internal timer heap corruption", timers [ev_active (w)] == (WT)w));*/
+}
+
+void noinline
+ev_timer_stop (EV_P_ ev_timer *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ev_active (w);
+
+ assert (("libev: internal timer heap corruption", ANHE_w (timers [active]) == (WT)w));
+
+ --timercnt;
+
+ if (expect_true (active < timercnt + HEAP0))
+ {
+ timers [active] = timers [timercnt + HEAP0];
+ adjustheap (timers, timercnt, active);
+ }
+ }
+
+ ev_at (w) -= mn_now;
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+
+void noinline
+ev_timer_again (EV_P_ ev_timer *w) EV_THROW
+{
+ EV_FREQUENT_CHECK;
+
+ clear_pending (EV_A_ (W)w);
+
+ if (ev_is_active (w))
+ {
+ if (w->repeat)
+ {
+ ev_at (w) = mn_now + w->repeat;
+ ANHE_at_cache (timers [ev_active (w)]);
+ adjustheap (timers, timercnt, ev_active (w));
+ }
+ else
+ ev_timer_stop (EV_A_ w);
+ }
+ else if (w->repeat)
+ {
+ ev_at (w) = w->repeat;
+ ev_timer_start (EV_A_ w);
+ }
+
+ EV_FREQUENT_CHECK;
+}
+
+ev_tstamp
+ev_timer_remaining (EV_P_ ev_timer *w) EV_THROW
+{
+ return ev_at (w) - (ev_is_active (w) ? mn_now : 0.);
+}
+
+#if EV_PERIODIC_ENABLE
+void noinline
+ev_periodic_start (EV_P_ ev_periodic *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ if (w->reschedule_cb)
+ ev_at (w) = w->reschedule_cb (w, ev_rt_now);
+ else if (w->interval)
+ {
+ assert (("libev: ev_periodic_start called with negative interval value", w->interval >= 0.));
+ periodic_recalc (EV_A_ w);
+ }
+ else
+ ev_at (w) = w->offset;
+
+ EV_FREQUENT_CHECK;
+
+ ++periodiccnt;
+ ev_start (EV_A_ (W)w, periodiccnt + HEAP0 - 1);
+ array_needsize (ANHE, periodics, periodicmax, ev_active (w) + 1, EMPTY2);
+ ANHE_w (periodics [ev_active (w)]) = (WT)w;
+ ANHE_at_cache (periodics [ev_active (w)]);
+ upheap (periodics, ev_active (w));
+
+ EV_FREQUENT_CHECK;
+
+ /*assert (("libev: internal periodic heap corruption", ANHE_w (periodics [ev_active (w)]) == (WT)w));*/
+}
+
+void noinline
+ev_periodic_stop (EV_P_ ev_periodic *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ev_active (w);
+
+ assert (("libev: internal periodic heap corruption", ANHE_w (periodics [active]) == (WT)w));
+
+ --periodiccnt;
+
+ if (expect_true (active < periodiccnt + HEAP0))
+ {
+ periodics [active] = periodics [periodiccnt + HEAP0];
+ adjustheap (periodics, periodiccnt, active);
+ }
+ }
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+
+void noinline
+ev_periodic_again (EV_P_ ev_periodic *w) EV_THROW
+{
+ /* TODO: use adjustheap and recalculation */
+ ev_periodic_stop (EV_A_ w);
+ ev_periodic_start (EV_A_ w);
+}
+#endif
+
+#ifndef SA_RESTART
+# define SA_RESTART 0
+#endif
+
+#if EV_SIGNAL_ENABLE
+
+void noinline
+ev_signal_start (EV_P_ ev_signal *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ assert (("libev: ev_signal_start called with illegal signal number", w->signum > 0 && w->signum < EV_NSIG));
+
+#if EV_MULTIPLICITY
+ assert (("libev: a signal must not be attached to two different loops",
+ !signals [w->signum - 1].loop || signals [w->signum - 1].loop == loop));
+
+ signals [w->signum - 1].loop = EV_A;
+ ECB_MEMORY_FENCE_RELEASE;
+#endif
+
+ EV_FREQUENT_CHECK;
+
+#if EV_USE_SIGNALFD
+ if (sigfd == -2)
+ {
+ sigfd = signalfd (-1, &sigfd_set, SFD_NONBLOCK | SFD_CLOEXEC);
+ if (sigfd < 0 && errno == EINVAL)
+ sigfd = signalfd (-1, &sigfd_set, 0); /* retry without flags */
+
+ if (sigfd >= 0)
+ {
+ fd_intern (sigfd); /* doing it twice will not hurt */
+
+ sigemptyset (&sigfd_set);
+
+ ev_io_init (&sigfd_w, sigfdcb, sigfd, EV_READ);
+ ev_set_priority (&sigfd_w, EV_MAXPRI);
+ ev_io_start (EV_A_ &sigfd_w);
+ ev_unref (EV_A); /* signalfd watcher should not keep loop alive */
+ }
+ }
+
+ if (sigfd >= 0)
+ {
+ /* TODO: check .head */
+ sigaddset (&sigfd_set, w->signum);
+ sigprocmask (SIG_BLOCK, &sigfd_set, 0);
+
+ signalfd (sigfd, &sigfd_set, 0);
+ }
+#endif
+
+ ev_start (EV_A_ (W)w, 1);
+ wlist_add (&signals [w->signum - 1].head, (WL)w);
+
+ if (!((WL)w)->next)
+# if EV_USE_SIGNALFD
+ if (sigfd < 0) /*TODO*/
+# endif
+ {
+# ifdef _WIN32
+ evpipe_init (EV_A);
+
+ signal (w->signum, ev_sighandler);
+# else
+ struct sigaction sa;
+
+ evpipe_init (EV_A);
+
+ sa.sa_handler = ev_sighandler;
+ sigfillset (&sa.sa_mask);
+ sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
+ sigaction (w->signum, &sa, 0);
+
+ if (origflags & EVFLAG_NOSIGMASK)
+ {
+ sigemptyset (&sa.sa_mask);
+ sigaddset (&sa.sa_mask, w->signum);
+ sigprocmask (SIG_UNBLOCK, &sa.sa_mask, 0);
+ }
+#endif
+ }
+
+ EV_FREQUENT_CHECK;
+}
+
+void noinline
+ev_signal_stop (EV_P_ ev_signal *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ wlist_del (&signals [w->signum - 1].head, (WL)w);
+ ev_stop (EV_A_ (W)w);
+
+ if (!signals [w->signum - 1].head)
+ {
+#if EV_MULTIPLICITY
+ signals [w->signum - 1].loop = 0; /* unattach from signal */
+#endif
+#if EV_USE_SIGNALFD
+ if (sigfd >= 0)
+ {
+ sigset_t ss;
+
+ sigemptyset (&ss);
+ sigaddset (&ss, w->signum);
+ sigdelset (&sigfd_set, w->signum);
+
+ signalfd (sigfd, &sigfd_set, 0);
+ sigprocmask (SIG_UNBLOCK, &ss, 0);
+ }
+ else
+#endif
+ signal (w->signum, SIG_DFL);
+ }
+
+ EV_FREQUENT_CHECK;
+}
+
+#endif
+
+#if EV_CHILD_ENABLE
+
+void
+ev_child_start (EV_P_ ev_child *w) EV_THROW
+{
+#if EV_MULTIPLICITY
+ assert (("libev: child watchers are only supported in the default loop", loop == ev_default_loop_ptr));
+#endif
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ ev_start (EV_A_ (W)w, 1);
+ wlist_add (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_child_stop (EV_P_ ev_child *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ wlist_del (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+
+#endif
+
+#if EV_STAT_ENABLE
+
+# ifdef _WIN32
+# undef lstat
+# define lstat(a,b) _stati64 (a,b)
+# endif
+
+#define DEF_STAT_INTERVAL 5.0074891
+#define NFS_STAT_INTERVAL 30.1074891 /* for filesystems potentially failing inotify */
+#define MIN_STAT_INTERVAL 0.1074891
+
+static void noinline stat_timer_cb (EV_P_ ev_timer *w_, int revents);
+
+#if EV_USE_INOTIFY
+
+/* the * 2 is to allow for alignment padding, which for some reason is >> 8 */
+# define EV_INOTIFY_BUFSIZE (sizeof (struct inotify_event) * 2 + NAME_MAX)
+
+static void noinline
+infy_add (EV_P_ ev_stat *w)
+{
+ w->wd = inotify_add_watch (fs_fd, w->path,
+ IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_MODIFY
+ | IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO
+ | IN_DONT_FOLLOW | IN_MASK_ADD);
+
+ if (w->wd >= 0)
+ {
+ struct statfs sfs;
+
+ /* now local changes will be tracked by inotify, but remote changes won't */
+ /* unless the filesystem is known to be local, we therefore still poll */
+ /* also do poll on <2.6.25, but with normal frequency */
+
+ if (!fs_2625)
+ w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
+ else if (!statfs (w->path, &sfs)
+ && (sfs.f_type == 0x1373 /* devfs */
+ || sfs.f_type == 0x4006 /* fat */
+ || sfs.f_type == 0x4d44 /* msdos */
+ || sfs.f_type == 0xEF53 /* ext2/3 */
+ || sfs.f_type == 0x72b6 /* jffs2 */
+ || sfs.f_type == 0x858458f6 /* ramfs */
+ || sfs.f_type == 0x5346544e /* ntfs */
+ || sfs.f_type == 0x3153464a /* jfs */
+ || sfs.f_type == 0x9123683e /* btrfs */
+ || sfs.f_type == 0x52654973 /* reiser3 */
+ || sfs.f_type == 0x01021994 /* tmpfs */
+ || sfs.f_type == 0x58465342 /* xfs */))
+ w->timer.repeat = 0.; /* filesystem is local, kernel new enough */
+ else
+ w->timer.repeat = w->interval ? w->interval : NFS_STAT_INTERVAL; /* remote, use reduced frequency */
+ }
+ else
+ {
+ /* can't use inotify, continue to stat */
+ w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
+
+ /* if path is not there, monitor some parent directory for speedup hints */
+ /* note that exceeding the hardcoded path limit is not a correctness issue, */
+ /* but an efficiency issue only */
+ if ((errno == ENOENT || errno == EACCES) && strlen (w->path) < 4096)
+ {
+ char path [4096];
+ strcpy (path, w->path);
+
+ do
+ {
+ int mask = IN_MASK_ADD | IN_DELETE_SELF | IN_MOVE_SELF
+ | (errno == EACCES ? IN_ATTRIB : IN_CREATE | IN_MOVED_TO);
+
+ char *pend = strrchr (path, '/');
+
+ if (!pend || pend == path)
+ break;
+
+ *pend = 0;
+ w->wd = inotify_add_watch (fs_fd, path, mask);
+ }
+ while (w->wd < 0 && (errno == ENOENT || errno == EACCES));
+ }
+ }
+
+ if (w->wd >= 0)
+ wlist_add (&fs_hash [w->wd & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
+
+ /* now re-arm timer, if required */
+ if (ev_is_active (&w->timer)) ev_ref (EV_A);
+ ev_timer_again (EV_A_ &w->timer);
+ if (ev_is_active (&w->timer)) ev_unref (EV_A);
+}
+
+static void noinline
+infy_del (EV_P_ ev_stat *w)
+{
+ int slot;
+ int wd = w->wd;
+
+ if (wd < 0)
+ return;
+
+ w->wd = -2;
+ slot = wd & ((EV_INOTIFY_HASHSIZE) - 1);
+ wlist_del (&fs_hash [slot].head, (WL)w);
+
+ /* remove this watcher, if others are watching it, they will rearm */
+ inotify_rm_watch (fs_fd, wd);
+}
+
+static void noinline
+infy_wd (EV_P_ int slot, int wd, struct inotify_event *ev)
+{
+ if (slot < 0)
+ /* overflow, need to check for all hash slots */
+ for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
+ infy_wd (EV_A_ slot, wd, ev);
+ else
+ {
+ WL w_;
+
+ for (w_ = fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head; w_; )
+ {
+ ev_stat *w = (ev_stat *)w_;
+ w_ = w_->next; /* lets us remove this watcher and all before it */
+
+ if (w->wd == wd || wd == -1)
+ {
+ if (ev->mask & (IN_IGNORED | IN_UNMOUNT | IN_DELETE_SELF))
+ {
+ wlist_del (&fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
+ w->wd = -1;
+ infy_add (EV_A_ w); /* re-add, no matter what */
+ }
+
+ stat_timer_cb (EV_A_ &w->timer, 0);
+ }
+ }
+ }
+}
+
+static void
+infy_cb (EV_P_ ev_io *w, int revents)
+{
+ char buf [EV_INOTIFY_BUFSIZE];
+ int ofs;
+ int len = read (fs_fd, buf, sizeof (buf));
+
+ for (ofs = 0; ofs < len; )
+ {
+ struct inotify_event *ev = (struct inotify_event *)(buf + ofs);
+ infy_wd (EV_A_ ev->wd, ev->wd, ev);
+ ofs += sizeof (struct inotify_event) + ev->len;
+ }
+}
+
+inline_size void ecb_cold
+ev_check_2625 (EV_P)
+{
+ /* kernels < 2.6.25 are borked
+ * http://www.ussg.indiana.edu/hypermail/linux/kernel/0711.3/1208.html
+ */
+ if (ev_linux_version () < 0x020619)
+ return;
+
+ fs_2625 = 1;
+}
+
+inline_size int
+infy_newfd (void)
+{
+#if defined IN_CLOEXEC && defined IN_NONBLOCK
+ int fd = inotify_init1 (IN_CLOEXEC | IN_NONBLOCK);
+ if (fd >= 0)
+ return fd;
+#endif
+ return inotify_init ();
+}
+
+inline_size void
+infy_init (EV_P)
+{
+ if (fs_fd != -2)
+ return;
+
+ fs_fd = -1;
+
+ ev_check_2625 (EV_A);
+
+ fs_fd = infy_newfd ();
+
+ if (fs_fd >= 0)
+ {
+ fd_intern (fs_fd);
+ ev_io_init (&fs_w, infy_cb, fs_fd, EV_READ);
+ ev_set_priority (&fs_w, EV_MAXPRI);
+ ev_io_start (EV_A_ &fs_w);
+ ev_unref (EV_A);
+ }
+}
+
+inline_size void
+infy_fork (EV_P)
+{
+ int slot;
+
+ if (fs_fd < 0)
+ return;
+
+ ev_ref (EV_A);
+ ev_io_stop (EV_A_ &fs_w);
+ close (fs_fd);
+ fs_fd = infy_newfd ();
+
+ if (fs_fd >= 0)
+ {
+ fd_intern (fs_fd);
+ ev_io_set (&fs_w, fs_fd, EV_READ);
+ ev_io_start (EV_A_ &fs_w);
+ ev_unref (EV_A);
+ }
+
+ for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
+ {
+ WL w_ = fs_hash [slot].head;
+ fs_hash [slot].head = 0;
+
+ while (w_)
+ {
+ ev_stat *w = (ev_stat *)w_;
+ w_ = w_->next; /* lets us add this watcher */
+
+ w->wd = -1;
+
+ if (fs_fd >= 0)
+ infy_add (EV_A_ w); /* re-add, no matter what */
+ else
+ {
+ w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
+ if (ev_is_active (&w->timer)) ev_ref (EV_A);
+ ev_timer_again (EV_A_ &w->timer);
+ if (ev_is_active (&w->timer)) ev_unref (EV_A);
+ }
+ }
+ }
+}
+
+#endif
+
+#ifdef _WIN32
+# define EV_LSTAT(p,b) _stati64 (p, b)
+#else
+# define EV_LSTAT(p,b) lstat (p, b)
+#endif
+
+void
+ev_stat_stat (EV_P_ ev_stat *w) EV_THROW
+{
+ if (lstat (w->path, &w->attr) < 0)
+ w->attr.st_nlink = 0;
+ else if (!w->attr.st_nlink)
+ w->attr.st_nlink = 1;
+}
+
+static void noinline
+stat_timer_cb (EV_P_ ev_timer *w_, int revents)
+{
+ ev_stat *w = (ev_stat *)(((char *)w_) - offsetof (ev_stat, timer));
+
+ ev_statdata prev = w->attr;
+ ev_stat_stat (EV_A_ w);
+
+ /* memcmp doesn't work on netbsd, they.... do stuff to their struct stat */
+ if (
+ prev.st_dev != w->attr.st_dev
+ || prev.st_ino != w->attr.st_ino
+ || prev.st_mode != w->attr.st_mode
+ || prev.st_nlink != w->attr.st_nlink
+ || prev.st_uid != w->attr.st_uid
+ || prev.st_gid != w->attr.st_gid
+ || prev.st_rdev != w->attr.st_rdev
+ || prev.st_size != w->attr.st_size
+ || prev.st_atime != w->attr.st_atime
+ || prev.st_mtime != w->attr.st_mtime
+ || prev.st_ctime != w->attr.st_ctime
+ ) {
+ /* we only update w->prev on actual differences */
+ /* in case we test more often than invoke the callback, */
+ /* to ensure that prev is always different to attr */
+ w->prev = prev;
+
+ #if EV_USE_INOTIFY
+ if (fs_fd >= 0)
+ {
+ infy_del (EV_A_ w);
+ infy_add (EV_A_ w);
+ ev_stat_stat (EV_A_ w); /* avoid race... */
+ }
+ #endif
+
+ ev_feed_event (EV_A_ w, EV_STAT);
+ }
+}
+
+void
+ev_stat_start (EV_P_ ev_stat *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ ev_stat_stat (EV_A_ w);
+
+ if (w->interval < MIN_STAT_INTERVAL && w->interval)
+ w->interval = MIN_STAT_INTERVAL;
+
+ ev_timer_init (&w->timer, stat_timer_cb, 0., w->interval ? w->interval : DEF_STAT_INTERVAL);
+ ev_set_priority (&w->timer, ev_priority (w));
+
+#if EV_USE_INOTIFY
+ infy_init (EV_A);
+
+ if (fs_fd >= 0)
+ infy_add (EV_A_ w);
+ else
+#endif
+ {
+ ev_timer_again (EV_A_ &w->timer);
+ ev_unref (EV_A);
+ }
+
+ ev_start (EV_A_ (W)w, 1);
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_stat_stop (EV_P_ ev_stat *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+#if EV_USE_INOTIFY
+ infy_del (EV_A_ w);
+#endif
+
+ if (ev_is_active (&w->timer))
+ {
+ ev_ref (EV_A);
+ ev_timer_stop (EV_A_ &w->timer);
+ }
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+#endif
+
+#if EV_IDLE_ENABLE
+void
+ev_idle_start (EV_P_ ev_idle *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ pri_adjust (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ++idlecnt [ABSPRI (w)];
+
+ ++idleall;
+ ev_start (EV_A_ (W)w, active);
+
+ array_needsize (ev_idle *, idles [ABSPRI (w)], idlemax [ABSPRI (w)], active, EMPTY2);
+ idles [ABSPRI (w)][active - 1] = w;
+ }
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_idle_stop (EV_P_ ev_idle *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ev_active (w);
+
+ idles [ABSPRI (w)][active - 1] = idles [ABSPRI (w)][--idlecnt [ABSPRI (w)]];
+ ev_active (idles [ABSPRI (w)][active - 1]) = active;
+
+ ev_stop (EV_A_ (W)w);
+ --idleall;
+ }
+
+ EV_FREQUENT_CHECK;
+}
+#endif
+
+#if EV_PREPARE_ENABLE
+void
+ev_prepare_start (EV_P_ ev_prepare *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ ev_start (EV_A_ (W)w, ++preparecnt);
+ array_needsize (ev_prepare *, prepares, preparemax, preparecnt, EMPTY2);
+ prepares [preparecnt - 1] = w;
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_prepare_stop (EV_P_ ev_prepare *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ev_active (w);
+
+ prepares [active - 1] = prepares [--preparecnt];
+ ev_active (prepares [active - 1]) = active;
+ }
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+#endif
+
+#if EV_CHECK_ENABLE
+void
+ev_check_start (EV_P_ ev_check *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ ev_start (EV_A_ (W)w, ++checkcnt);
+ array_needsize (ev_check *, checks, checkmax, checkcnt, EMPTY2);
+ checks [checkcnt - 1] = w;
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_check_stop (EV_P_ ev_check *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ev_active (w);
+
+ checks [active - 1] = checks [--checkcnt];
+ ev_active (checks [active - 1]) = active;
+ }
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+#endif
+
+#if EV_EMBED_ENABLE
+void noinline
+ev_embed_sweep (EV_P_ ev_embed *w) EV_THROW
+{
+ ev_run (w->other, EVRUN_NOWAIT);
+}
+
+static void
+embed_io_cb (EV_P_ ev_io *io, int revents)
+{
+ ev_embed *w = (ev_embed *)(((char *)io) - offsetof (ev_embed, io));
+
+ if (ev_cb (w))
+ ev_feed_event (EV_A_ (W)w, EV_EMBED);
+ else
+ ev_run (w->other, EVRUN_NOWAIT);
+}
+
+static void
+embed_prepare_cb (EV_P_ ev_prepare *prepare, int revents)
+{
+ ev_embed *w = (ev_embed *)(((char *)prepare) - offsetof (ev_embed, prepare));
+
+ {
+ EV_P = w->other;
+
+ while (fdchangecnt)
+ {
+ fd_reify (EV_A);
+ ev_run (EV_A_ EVRUN_NOWAIT);
+ }
+ }
+}
+
+static void
+embed_fork_cb (EV_P_ ev_fork *fork_w, int revents)
+{
+ ev_embed *w = (ev_embed *)(((char *)fork_w) - offsetof (ev_embed, fork));
+
+ ev_embed_stop (EV_A_ w);
+
+ {
+ EV_P = w->other;
+
+ ev_loop_fork (EV_A);
+ ev_run (EV_A_ EVRUN_NOWAIT);
+ }
+
+ ev_embed_start (EV_A_ w);
+}
+
+#if 0
+static void
+embed_idle_cb (EV_P_ ev_idle *idle, int revents)
+{
+ ev_idle_stop (EV_A_ idle);
+}
+#endif
+
+void
+ev_embed_start (EV_P_ ev_embed *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ {
+ EV_P = w->other;
+ assert (("libev: loop to be embedded is not embeddable", backend & ev_embeddable_backends ()));
+ ev_io_init (&w->io, embed_io_cb, backend_fd, EV_READ);
+ }
+
+ EV_FREQUENT_CHECK;
+
+ ev_set_priority (&w->io, ev_priority (w));
+ ev_io_start (EV_A_ &w->io);
+
+ ev_prepare_init (&w->prepare, embed_prepare_cb);
+ ev_set_priority (&w->prepare, EV_MINPRI);
+ ev_prepare_start (EV_A_ &w->prepare);
+
+ ev_fork_init (&w->fork, embed_fork_cb);
+ ev_fork_start (EV_A_ &w->fork);
+
+ /*ev_idle_init (&w->idle, e,bed_idle_cb);*/
+
+ ev_start (EV_A_ (W)w, 1);
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_embed_stop (EV_P_ ev_embed *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ ev_io_stop (EV_A_ &w->io);
+ ev_prepare_stop (EV_A_ &w->prepare);
+ ev_fork_stop (EV_A_ &w->fork);
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+#endif
+
+#if EV_FORK_ENABLE
+void
+ev_fork_start (EV_P_ ev_fork *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ ev_start (EV_A_ (W)w, ++forkcnt);
+ array_needsize (ev_fork *, forks, forkmax, forkcnt, EMPTY2);
+ forks [forkcnt - 1] = w;
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_fork_stop (EV_P_ ev_fork *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ev_active (w);
+
+ forks [active - 1] = forks [--forkcnt];
+ ev_active (forks [active - 1]) = active;
+ }
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+#endif
+
+#if EV_CLEANUP_ENABLE
+void
+ev_cleanup_start (EV_P_ ev_cleanup *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ ev_start (EV_A_ (W)w, ++cleanupcnt);
+ array_needsize (ev_cleanup *, cleanups, cleanupmax, cleanupcnt, EMPTY2);
+ cleanups [cleanupcnt - 1] = w;
+
+ /* cleanup watchers should never keep a refcount on the loop */
+ ev_unref (EV_A);
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_cleanup_stop (EV_P_ ev_cleanup *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+ ev_ref (EV_A);
+
+ {
+ int active = ev_active (w);
+
+ cleanups [active - 1] = cleanups [--cleanupcnt];
+ ev_active (cleanups [active - 1]) = active;
+ }
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+#endif
+
+#if EV_ASYNC_ENABLE
+void
+ev_async_start (EV_P_ ev_async *w) EV_THROW
+{
+ if (expect_false (ev_is_active (w)))
+ return;
+
+ w->sent = 0;
+
+ evpipe_init (EV_A);
+
+ EV_FREQUENT_CHECK;
+
+ ev_start (EV_A_ (W)w, ++asynccnt);
+ array_needsize (ev_async *, asyncs, asyncmax, asynccnt, EMPTY2);
+ asyncs [asynccnt - 1] = w;
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_async_stop (EV_P_ ev_async *w) EV_THROW
+{
+ clear_pending (EV_A_ (W)w);
+ if (expect_false (!ev_is_active (w)))
+ return;
+
+ EV_FREQUENT_CHECK;
+
+ {
+ int active = ev_active (w);
+
+ asyncs [active - 1] = asyncs [--asynccnt];
+ ev_active (asyncs [active - 1]) = active;
+ }
+
+ ev_stop (EV_A_ (W)w);
+
+ EV_FREQUENT_CHECK;
+}
+
+void
+ev_async_send (EV_P_ ev_async *w) EV_THROW
+{
+ w->sent = 1;
+ evpipe_write (EV_A_ &async_pending);
+}
+#endif
+
+/*****************************************************************************/
+
+struct ev_once
+{
+ ev_io io;
+ ev_timer to;
+ void (*cb)(int revents, void *arg);
+ void *arg;
+};
+
+static void
+once_cb (EV_P_ struct ev_once *once, int revents)
+{
+ void (*cb)(int revents, void *arg) = once->cb;
+ void *arg = once->arg;
+
+ ev_io_stop (EV_A_ &once->io);
+ ev_timer_stop (EV_A_ &once->to);
+ ev_free (once);
+
+ cb (revents, arg);
+}
+
+static void
+once_cb_io (EV_P_ ev_io *w, int revents)
+{
+ struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io));
+
+ once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->to));
+}
+
+static void
+once_cb_to (EV_P_ ev_timer *w, int revents)
+{
+ struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to));
+
+ once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->io));
+}
+
+void
+ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg) EV_THROW
+{
+ struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once));
+
+ if (expect_false (!once))
+ {
+ cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMER, arg);
+ return;
+ }
+
+ once->cb = cb;
+ once->arg = arg;
+
+ ev_init (&once->io, once_cb_io);
+ if (fd >= 0)
+ {
+ ev_io_set (&once->io, fd, events);
+ ev_io_start (EV_A_ &once->io);
+ }
+
+ ev_init (&once->to, once_cb_to);
+ if (timeout >= 0.)
+ {
+ ev_timer_set (&once->to, timeout, 0.);
+ ev_timer_start (EV_A_ &once->to);
+ }
+}
+
+/*****************************************************************************/
+
+#if EV_WALK_ENABLE
+void ecb_cold
+ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w)) EV_THROW
+{
+ int i, j;
+ ev_watcher_list *wl, *wn;
+
+ if (types & (EV_IO | EV_EMBED))
+ for (i = 0; i < anfdmax; ++i)
+ for (wl = anfds [i].head; wl; )
+ {
+ wn = wl->next;
+
+#if EV_EMBED_ENABLE
+ if (ev_cb ((ev_io *)wl) == embed_io_cb)
+ {
+ if (types & EV_EMBED)
+ cb (EV_A_ EV_EMBED, ((char *)wl) - offsetof (struct ev_embed, io));
+ }
+ else
+#endif
+#if EV_USE_INOTIFY
+ if (ev_cb ((ev_io *)wl) == infy_cb)
+ ;
+ else
+#endif
+ if ((ev_io *)wl != &pipe_w)
+ if (types & EV_IO)
+ cb (EV_A_ EV_IO, wl);
+
+ wl = wn;
+ }
+
+ if (types & (EV_TIMER | EV_STAT))
+ for (i = timercnt + HEAP0; i-- > HEAP0; )
+#if EV_STAT_ENABLE
+ /*TODO: timer is not always active*/
+ if (ev_cb ((ev_timer *)ANHE_w (timers [i])) == stat_timer_cb)
+ {
+ if (types & EV_STAT)
+ cb (EV_A_ EV_STAT, ((char *)ANHE_w (timers [i])) - offsetof (struct ev_stat, timer));
+ }
+ else
+#endif
+ if (types & EV_TIMER)
+ cb (EV_A_ EV_TIMER, ANHE_w (timers [i]));
+
+#if EV_PERIODIC_ENABLE
+ if (types & EV_PERIODIC)
+ for (i = periodiccnt + HEAP0; i-- > HEAP0; )
+ cb (EV_A_ EV_PERIODIC, ANHE_w (periodics [i]));
+#endif
+
+#if EV_IDLE_ENABLE
+ if (types & EV_IDLE)
+ for (j = NUMPRI; j--; )
+ for (i = idlecnt [j]; i--; )
+ cb (EV_A_ EV_IDLE, idles [j][i]);
+#endif
+
+#if EV_FORK_ENABLE
+ if (types & EV_FORK)
+ for (i = forkcnt; i--; )
+ if (ev_cb (forks [i]) != embed_fork_cb)
+ cb (EV_A_ EV_FORK, forks [i]);
+#endif
+
+#if EV_ASYNC_ENABLE
+ if (types & EV_ASYNC)
+ for (i = asynccnt; i--; )
+ cb (EV_A_ EV_ASYNC, asyncs [i]);
+#endif
+
+#if EV_PREPARE_ENABLE
+ if (types & EV_PREPARE)
+ for (i = preparecnt; i--; )
+# if EV_EMBED_ENABLE
+ if (ev_cb (prepares [i]) != embed_prepare_cb)
+# endif
+ cb (EV_A_ EV_PREPARE, prepares [i]);
+#endif
+
+#if EV_CHECK_ENABLE
+ if (types & EV_CHECK)
+ for (i = checkcnt; i--; )
+ cb (EV_A_ EV_CHECK, checks [i]);
+#endif
+
+#if EV_SIGNAL_ENABLE
+ if (types & EV_SIGNAL)
+ for (i = 0; i < EV_NSIG - 1; ++i)
+ for (wl = signals [i].head; wl; )
+ {
+ wn = wl->next;
+ cb (EV_A_ EV_SIGNAL, wl);
+ wl = wn;
+ }
+#endif
+
+#if EV_CHILD_ENABLE
+ if (types & EV_CHILD)
+ for (i = (EV_PID_HASHSIZE); i--; )
+ for (wl = childs [i]; wl; )
+ {
+ wn = wl->next;
+ cb (EV_A_ EV_CHILD, wl);
+ wl = wn;
+ }
+#endif
+/* EV_STAT 0x00001000 /* stat data changed */
+/* EV_EMBED 0x00010000 /* embedded event loop needs sweep */
+}
+#endif
+
+#if EV_MULTIPLICITY
+ #include "ev_wrap.h"
+#endif
+
diff --git a/ext/libev/ev.h b/ext/libev/ev.h
new file mode 100644
index 0000000..c5d582e
--- /dev/null
+++ b/ext/libev/ev.h
@@ -0,0 +1,845 @@
+/*
+ * libev native API header
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#ifndef EV_H_
+#define EV_H_
+
+#ifdef __cplusplus
+# define EV_CPP(x) x
+#else
+# define EV_CPP(x)
+#endif
+
+#define EV_THROW EV_CPP(throw())
+
+EV_CPP(extern "C" {)
+
+/*****************************************************************************/
+
+/* pre-4.0 compatibility */
+#ifndef EV_COMPAT3
+# define EV_COMPAT3 1
+#endif
+
+#ifndef EV_FEATURES
+# if defined __OPTIMIZE_SIZE__
+# define EV_FEATURES 0x7c
+# else
+# define EV_FEATURES 0x7f
+# endif
+#endif
+
+#define EV_FEATURE_CODE ((EV_FEATURES) & 1)
+#define EV_FEATURE_DATA ((EV_FEATURES) & 2)
+#define EV_FEATURE_CONFIG ((EV_FEATURES) & 4)
+#define EV_FEATURE_API ((EV_FEATURES) & 8)
+#define EV_FEATURE_WATCHERS ((EV_FEATURES) & 16)
+#define EV_FEATURE_BACKENDS ((EV_FEATURES) & 32)
+#define EV_FEATURE_OS ((EV_FEATURES) & 64)
+
+/* these priorities are inclusive, higher priorities will be invoked earlier */
+#ifndef EV_MINPRI
+# define EV_MINPRI (EV_FEATURE_CONFIG ? -2 : 0)
+#endif
+#ifndef EV_MAXPRI
+# define EV_MAXPRI (EV_FEATURE_CONFIG ? +2 : 0)
+#endif
+
+#ifndef EV_MULTIPLICITY
+# define EV_MULTIPLICITY EV_FEATURE_CONFIG
+#endif
+
+#ifndef EV_PERIODIC_ENABLE
+# define EV_PERIODIC_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_STAT_ENABLE
+# define EV_STAT_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_PREPARE_ENABLE
+# define EV_PREPARE_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_CHECK_ENABLE
+# define EV_CHECK_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_IDLE_ENABLE
+# define EV_IDLE_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_FORK_ENABLE
+# define EV_FORK_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_CLEANUP_ENABLE
+# define EV_CLEANUP_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_SIGNAL_ENABLE
+# define EV_SIGNAL_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_CHILD_ENABLE
+# ifdef _WIN32
+# define EV_CHILD_ENABLE 0
+# else
+# define EV_CHILD_ENABLE EV_FEATURE_WATCHERS
+#endif
+#endif
+
+#ifndef EV_ASYNC_ENABLE
+# define EV_ASYNC_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_EMBED_ENABLE
+# define EV_EMBED_ENABLE EV_FEATURE_WATCHERS
+#endif
+
+#ifndef EV_WALK_ENABLE
+# define EV_WALK_ENABLE 0 /* not yet */
+#endif
+
+/*****************************************************************************/
+
+#if EV_CHILD_ENABLE && !EV_SIGNAL_ENABLE
+# undef EV_SIGNAL_ENABLE
+# define EV_SIGNAL_ENABLE 1
+#endif
+
+/*****************************************************************************/
+
+typedef double ev_tstamp;
+
+#ifndef EV_ATOMIC_T
+# include <signal.h>
+# define EV_ATOMIC_T sig_atomic_t volatile
+#endif
+
+#if EV_STAT_ENABLE
+# ifdef _WIN32
+# include <time.h>
+# include <sys/types.h>
+# endif
+# include <sys/stat.h>
+#endif
+
+/* support multiple event loops? */
+#if EV_MULTIPLICITY
+struct ev_loop;
+# define EV_P struct ev_loop *loop /* a loop as sole parameter in a declaration */
+# define EV_P_ EV_P, /* a loop as first of multiple parameters */
+# define EV_A loop /* a loop as sole argument to a function call */
+# define EV_A_ EV_A, /* a loop as first of multiple arguments */
+# define EV_DEFAULT_UC ev_default_loop_uc_ () /* the default loop, if initialised, as sole arg */
+# define EV_DEFAULT_UC_ EV_DEFAULT_UC, /* the default loop as first of multiple arguments */
+# define EV_DEFAULT ev_default_loop (0) /* the default loop as sole arg */
+# define EV_DEFAULT_ EV_DEFAULT, /* the default loop as first of multiple arguments */
+#else
+# define EV_P void
+# define EV_P_
+# define EV_A
+# define EV_A_
+# define EV_DEFAULT
+# define EV_DEFAULT_
+# define EV_DEFAULT_UC
+# define EV_DEFAULT_UC_
+# undef EV_EMBED_ENABLE
+#endif
+
+/* EV_INLINE is used for functions in header files */
+#if __STDC_VERSION__ >= 199901L || __GNUC__ >= 3
+# define EV_INLINE static inline
+#else
+# define EV_INLINE static
+#endif
+
+#ifdef EV_API_STATIC
+# define EV_API_DECL static
+#else
+# define EV_API_DECL extern
+#endif
+
+/* EV_PROTOTYPES can be used to switch of prototype declarations */
+#ifndef EV_PROTOTYPES
+# define EV_PROTOTYPES 1
+#endif
+
+/*****************************************************************************/
+
+#define EV_VERSION_MAJOR 4
+#define EV_VERSION_MINOR 15
+
+/* eventmask, revents, events... */
+enum {
+ EV_UNDEF = (int)0xFFFFFFFF, /* guaranteed to be invalid */
+ EV_NONE = 0x00, /* no events */
+ EV_READ = 0x01, /* ev_io detected read will not block */
+ EV_WRITE = 0x02, /* ev_io detected write will not block */
+ EV__IOFDSET = 0x80, /* internal use only */
+ EV_IO = EV_READ, /* alias for type-detection */
+ EV_TIMER = 0x00000100, /* timer timed out */
+#if EV_COMPAT3
+ EV_TIMEOUT = EV_TIMER, /* pre 4.0 API compatibility */
+#endif
+ EV_PERIODIC = 0x00000200, /* periodic timer timed out */
+ EV_SIGNAL = 0x00000400, /* signal was received */
+ EV_CHILD = 0x00000800, /* child/pid had status change */
+ EV_STAT = 0x00001000, /* stat data changed */
+ EV_IDLE = 0x00002000, /* event loop is idling */
+ EV_PREPARE = 0x00004000, /* event loop about to poll */
+ EV_CHECK = 0x00008000, /* event loop finished poll */
+ EV_EMBED = 0x00010000, /* embedded event loop needs sweep */
+ EV_FORK = 0x00020000, /* event loop resumed in child */
+ EV_CLEANUP = 0x00040000, /* event loop resumed in child */
+ EV_ASYNC = 0x00080000, /* async intra-loop signal */
+ EV_CUSTOM = 0x01000000, /* for use by user code */
+ EV_ERROR = (int)0x80000000 /* sent when an error occurs */
+};
+
+/* can be used to add custom fields to all watchers, while losing binary compatibility */
+#ifndef EV_COMMON
+# define EV_COMMON void *data;
+#endif
+
+#ifndef EV_CB_DECLARE
+# define EV_CB_DECLARE(type) void (*cb)(EV_P_ struct type *w, int revents);
+#endif
+#ifndef EV_CB_INVOKE
+# define EV_CB_INVOKE(watcher,revents) (watcher)->cb (EV_A_ (watcher), (revents))
+#endif
+
+/* not official, do not use */
+#define EV_CB(type,name) void name (EV_P_ struct ev_ ## type *w, int revents)
+
+/*
+ * struct member types:
+ * private: you may look at them, but not change them,
+ * and they might not mean anything to you.
+ * ro: can be read anytime, but only changed when the watcher isn't active.
+ * rw: can be read and modified anytime, even when the watcher is active.
+ *
+ * some internal details that might be helpful for debugging:
+ *
+ * active is either 0, which means the watcher is not active,
+ * or the array index of the watcher (periodics, timers)
+ * or the array index + 1 (most other watchers)
+ * or simply 1 for watchers that aren't in some array.
+ * pending is either 0, in which case the watcher isn't,
+ * or the array index + 1 in the pendings array.
+ */
+
+#if EV_MINPRI == EV_MAXPRI
+# define EV_DECL_PRIORITY
+#elif !defined (EV_DECL_PRIORITY)
+# define EV_DECL_PRIORITY int priority;
+#endif
+
+/* shared by all watchers */
+#define EV_WATCHER(type) \
+ int active; /* private */ \
+ int pending; /* private */ \
+ EV_DECL_PRIORITY /* private */ \
+ EV_COMMON /* rw */ \
+ EV_CB_DECLARE (type) /* private */
+
+#define EV_WATCHER_LIST(type) \
+ EV_WATCHER (type) \
+ struct ev_watcher_list *next; /* private */
+
+#define EV_WATCHER_TIME(type) \
+ EV_WATCHER (type) \
+ ev_tstamp at; /* private */
+
+/* base class, nothing to see here unless you subclass */
+typedef struct ev_watcher
+{
+ EV_WATCHER (ev_watcher)
+} ev_watcher;
+
+/* base class, nothing to see here unless you subclass */
+typedef struct ev_watcher_list
+{
+ EV_WATCHER_LIST (ev_watcher_list)
+} ev_watcher_list;
+
+/* base class, nothing to see here unless you subclass */
+typedef struct ev_watcher_time
+{
+ EV_WATCHER_TIME (ev_watcher_time)
+} ev_watcher_time;
+
+/* invoked when fd is either EV_READable or EV_WRITEable */
+/* revent EV_READ, EV_WRITE */
+typedef struct ev_io
+{
+ EV_WATCHER_LIST (ev_io)
+
+ int fd; /* ro */
+ int events; /* ro */
+} ev_io;
+
+/* invoked after a specific time, repeatable (based on monotonic clock) */
+/* revent EV_TIMEOUT */
+typedef struct ev_timer
+{
+ EV_WATCHER_TIME (ev_timer)
+
+ ev_tstamp repeat; /* rw */
+} ev_timer;
+
+/* invoked at some specific time, possibly repeating at regular intervals (based on UTC) */
+/* revent EV_PERIODIC */
+typedef struct ev_periodic
+{
+ EV_WATCHER_TIME (ev_periodic)
+
+ ev_tstamp offset; /* rw */
+ ev_tstamp interval; /* rw */
+ ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now) EV_THROW; /* rw */
+} ev_periodic;
+
+/* invoked when the given signal has been received */
+/* revent EV_SIGNAL */
+typedef struct ev_signal
+{
+ EV_WATCHER_LIST (ev_signal)
+
+ int signum; /* ro */
+} ev_signal;
+
+/* invoked when sigchld is received and waitpid indicates the given pid */
+/* revent EV_CHILD */
+/* does not support priorities */
+typedef struct ev_child
+{
+ EV_WATCHER_LIST (ev_child)
+
+ int flags; /* private */
+ int pid; /* ro */
+ int rpid; /* rw, holds the received pid */
+ int rstatus; /* rw, holds the exit status, use the macros from sys/wait.h */
+} ev_child;
+
+#if EV_STAT_ENABLE
+/* st_nlink = 0 means missing file or other error */
+# ifdef _WIN32
+typedef struct _stati64 ev_statdata;
+# else
+typedef struct stat ev_statdata;
+# endif
+
+/* invoked each time the stat data changes for a given path */
+/* revent EV_STAT */
+typedef struct ev_stat
+{
+ EV_WATCHER_LIST (ev_stat)
+
+ ev_timer timer; /* private */
+ ev_tstamp interval; /* ro */
+ const char *path; /* ro */
+ ev_statdata prev; /* ro */
+ ev_statdata attr; /* ro */
+
+ int wd; /* wd for inotify, fd for kqueue */
+} ev_stat;
+#endif
+
+#if EV_IDLE_ENABLE
+/* invoked when the nothing else needs to be done, keeps the process from blocking */
+/* revent EV_IDLE */
+typedef struct ev_idle
+{
+ EV_WATCHER (ev_idle)
+} ev_idle;
+#endif
+
+/* invoked for each run of the mainloop, just before the blocking call */
+/* you can still change events in any way you like */
+/* revent EV_PREPARE */
+typedef struct ev_prepare
+{
+ EV_WATCHER (ev_prepare)
+} ev_prepare;
+
+/* invoked for each run of the mainloop, just after the blocking call */
+/* revent EV_CHECK */
+typedef struct ev_check
+{
+ EV_WATCHER (ev_check)
+} ev_check;
+
+#if EV_FORK_ENABLE
+/* the callback gets invoked before check in the child process when a fork was detected */
+/* revent EV_FORK */
+typedef struct ev_fork
+{
+ EV_WATCHER (ev_fork)
+} ev_fork;
+#endif
+
+#if EV_CLEANUP_ENABLE
+/* is invoked just before the loop gets destroyed */
+/* revent EV_CLEANUP */
+typedef struct ev_cleanup
+{
+ EV_WATCHER (ev_cleanup)
+} ev_cleanup;
+#endif
+
+#if EV_EMBED_ENABLE
+/* used to embed an event loop inside another */
+/* the callback gets invoked when the event loop has handled events, and can be 0 */
+typedef struct ev_embed
+{
+ EV_WATCHER (ev_embed)
+
+ struct ev_loop *other; /* ro */
+ ev_io io; /* private */
+ ev_prepare prepare; /* private */
+ ev_check check; /* unused */
+ ev_timer timer; /* unused */
+ ev_periodic periodic; /* unused */
+ ev_idle idle; /* unused */
+ ev_fork fork; /* private */
+#if EV_CLEANUP_ENABLE
+ ev_cleanup cleanup; /* unused */
+#endif
+} ev_embed;
+#endif
+
+#if EV_ASYNC_ENABLE
+/* invoked when somebody calls ev_async_send on the watcher */
+/* revent EV_ASYNC */
+typedef struct ev_async
+{
+ EV_WATCHER (ev_async)
+
+ EV_ATOMIC_T sent; /* private */
+} ev_async;
+
+# define ev_async_pending(w) (+(w)->sent)
+#endif
+
+/* the presence of this union forces similar struct layout */
+union ev_any_watcher
+{
+ struct ev_watcher w;
+ struct ev_watcher_list wl;
+
+ struct ev_io io;
+ struct ev_timer timer;
+ struct ev_periodic periodic;
+ struct ev_signal signal;
+ struct ev_child child;
+#if EV_STAT_ENABLE
+ struct ev_stat stat;
+#endif
+#if EV_IDLE_ENABLE
+ struct ev_idle idle;
+#endif
+ struct ev_prepare prepare;
+ struct ev_check check;
+#if EV_FORK_ENABLE
+ struct ev_fork fork;
+#endif
+#if EV_CLEANUP_ENABLE
+ struct ev_cleanup cleanup;
+#endif
+#if EV_EMBED_ENABLE
+ struct ev_embed embed;
+#endif
+#if EV_ASYNC_ENABLE
+ struct ev_async async;
+#endif
+};
+
+/* flag bits for ev_default_loop and ev_loop_new */
+enum {
+ /* the default */
+ EVFLAG_AUTO = 0x00000000U, /* not quite a mask */
+ /* flag bits */
+ EVFLAG_NOENV = 0x01000000U, /* do NOT consult environment */
+ EVFLAG_FORKCHECK = 0x02000000U, /* check for a fork in each iteration */
+ /* debugging/feature disable */
+ EVFLAG_NOINOTIFY = 0x00100000U, /* do not attempt to use inotify */
+#if EV_COMPAT3
+ EVFLAG_NOSIGFD = 0, /* compatibility to pre-3.9 */
+#endif
+ EVFLAG_SIGNALFD = 0x00200000U, /* attempt to use signalfd */
+ EVFLAG_NOSIGMASK = 0x00400000U /* avoid modifying the signal mask */
+};
+
+/* method bits to be ored together */
+enum {
+ EVBACKEND_SELECT = 0x00000001U, /* about anywhere */
+ EVBACKEND_POLL = 0x00000002U, /* !win */
+ EVBACKEND_EPOLL = 0x00000004U, /* linux */
+ EVBACKEND_KQUEUE = 0x00000008U, /* bsd */
+ EVBACKEND_DEVPOLL = 0x00000010U, /* solaris 8 */ /* NYI */
+ EVBACKEND_PORT = 0x00000020U, /* solaris 10 */
+ EVBACKEND_ALL = 0x0000003FU, /* all known backends */
+ EVBACKEND_MASK = 0x0000FFFFU /* all future backends */
+};
+
+#if EV_PROTOTYPES
+EV_API_DECL int ev_version_major (void) EV_THROW;
+EV_API_DECL int ev_version_minor (void) EV_THROW;
+
+EV_API_DECL unsigned int ev_supported_backends (void) EV_THROW;
+EV_API_DECL unsigned int ev_recommended_backends (void) EV_THROW;
+EV_API_DECL unsigned int ev_embeddable_backends (void) EV_THROW;
+
+EV_API_DECL ev_tstamp ev_time (void) EV_THROW;
+EV_API_DECL void ev_sleep (ev_tstamp delay) EV_THROW; /* sleep for a while */
+
+/* Sets the allocation function to use, works like realloc.
+ * It is used to allocate and free memory.
+ * If it returns zero when memory needs to be allocated, the library might abort
+ * or take some potentially destructive action.
+ * The default is your system realloc function.
+ */
+EV_API_DECL void ev_set_allocator (void *(*cb)(void *ptr, long size) EV_THROW) EV_THROW;
+
+/* set the callback function to call on a
+ * retryable syscall error
+ * (such as failed select, poll, epoll_wait)
+ */
+EV_API_DECL void ev_set_syserr_cb (void (*cb)(const char *msg) EV_THROW) EV_THROW;
+
+#if EV_MULTIPLICITY
+
+/* the default loop is the only one that handles signals and child watchers */
+/* you can call this as often as you like */
+EV_API_DECL struct ev_loop *ev_default_loop (unsigned int flags EV_CPP (= 0)) EV_THROW;
+
+#ifdef EV_API_STATIC
+EV_API_DECL struct ev_loop *ev_default_loop_ptr;
+#endif
+
+EV_INLINE struct ev_loop *
+ev_default_loop_uc_ (void) EV_THROW
+{
+ extern struct ev_loop *ev_default_loop_ptr;
+
+ return ev_default_loop_ptr;
+}
+
+EV_INLINE int
+ev_is_default_loop (EV_P) EV_THROW
+{
+ return EV_A == EV_DEFAULT_UC;
+}
+
+/* create and destroy alternative loops that don't handle signals */
+EV_API_DECL struct ev_loop *ev_loop_new (unsigned int flags EV_CPP (= 0)) EV_THROW;
+
+EV_API_DECL ev_tstamp ev_now (EV_P) EV_THROW; /* time w.r.t. timers and the eventloop, updated after each poll */
+
+#else
+
+EV_API_DECL int ev_default_loop (unsigned int flags EV_CPP (= 0)) EV_THROW; /* returns true when successful */
+
+EV_API_DECL ev_tstamp ev_rt_now;
+
+EV_INLINE ev_tstamp
+ev_now (void) EV_THROW
+{
+ return ev_rt_now;
+}
+
+/* looks weird, but ev_is_default_loop (EV_A) still works if this exists */
+EV_INLINE int
+ev_is_default_loop (void) EV_THROW
+{
+ return 1;
+}
+
+#endif /* multiplicity */
+
+/* destroy event loops, also works for the default loop */
+EV_API_DECL void ev_loop_destroy (EV_P);
+
+/* this needs to be called after fork, to duplicate the loop */
+/* when you want to re-use it in the child */
+/* you can call it in either the parent or the child */
+/* you can actually call it at any time, anywhere :) */
+EV_API_DECL void ev_loop_fork (EV_P) EV_THROW;
+
+EV_API_DECL unsigned int ev_backend (EV_P) EV_THROW; /* backend in use by loop */
+
+EV_API_DECL void ev_now_update (EV_P) EV_THROW; /* update event loop time */
+
+#if EV_WALK_ENABLE
+/* walk (almost) all watchers in the loop of a given type, invoking the */
+/* callback on every such watcher. The callback might stop the watcher, */
+/* but do nothing else with the loop */
+EV_API_DECL void ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w)) EV_THROW;
+#endif
+
+#endif /* prototypes */
+
+/* ev_run flags values */
+enum {
+ EVRUN_NOWAIT = 1, /* do not block/wait */
+ EVRUN_ONCE = 2 /* block *once* only */
+};
+
+/* ev_break how values */
+enum {
+ EVBREAK_CANCEL = 0, /* undo unloop */
+ EVBREAK_ONE = 1, /* unloop once */
+ EVBREAK_ALL = 2 /* unloop all loops */
+};
+
+#if EV_PROTOTYPES
+EV_API_DECL int ev_run (EV_P_ int flags EV_CPP (= 0));
+EV_API_DECL void ev_break (EV_P_ int how EV_CPP (= EVBREAK_ONE)) EV_THROW; /* break out of the loop */
+
+/*
+ * ref/unref can be used to add or remove a refcount on the mainloop. every watcher
+ * keeps one reference. if you have a long-running watcher you never unregister that
+ * should not keep ev_loop from running, unref() after starting, and ref() before stopping.
+ */
+EV_API_DECL void ev_ref (EV_P) EV_THROW;
+EV_API_DECL void ev_unref (EV_P) EV_THROW;
+
+/*
+ * convenience function, wait for a single event, without registering an event watcher
+ * if timeout is < 0, do wait indefinitely
+ */
+EV_API_DECL void ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg) EV_THROW;
+
+# if EV_FEATURE_API
+EV_API_DECL unsigned int ev_iteration (EV_P) EV_THROW; /* number of loop iterations */
+EV_API_DECL unsigned int ev_depth (EV_P) EV_THROW; /* #ev_loop enters - #ev_loop leaves */
+EV_API_DECL void ev_verify (EV_P) EV_THROW; /* abort if loop data corrupted */
+
+EV_API_DECL void ev_set_io_collect_interval (EV_P_ ev_tstamp interval) EV_THROW; /* sleep at least this time, default 0 */
+EV_API_DECL void ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval) EV_THROW; /* sleep at least this time, default 0 */
+
+/* advanced stuff for threading etc. support, see docs */
+EV_API_DECL void ev_set_userdata (EV_P_ void *data) EV_THROW;
+EV_API_DECL void *ev_userdata (EV_P) EV_THROW;
+EV_API_DECL void ev_set_invoke_pending_cb (EV_P_ void (*invoke_pending_cb)(EV_P)) EV_THROW;
+EV_API_DECL void ev_set_loop_release_cb (EV_P_ void (*release)(EV_P), void (*acquire)(EV_P) EV_THROW) EV_THROW;
+
+EV_API_DECL unsigned int ev_pending_count (EV_P) EV_THROW; /* number of pending events, if any */
+EV_API_DECL void ev_invoke_pending (EV_P); /* invoke all pending watchers */
+
+/*
+ * stop/start the timer handling.
+ */
+EV_API_DECL void ev_suspend (EV_P) EV_THROW;
+EV_API_DECL void ev_resume (EV_P) EV_THROW;
+#endif
+
+#endif
+
+/* these may evaluate ev multiple times, and the other arguments at most once */
+/* either use ev_init + ev_TYPE_set, or the ev_TYPE_init macro, below, to first initialise a watcher */
+#define ev_init(ev,cb_) do { \
+ ((ev_watcher *)(void *)(ev))->active = \
+ ((ev_watcher *)(void *)(ev))->pending = 0; \
+ ev_set_priority ((ev), 0); \
+ ev_set_cb ((ev), cb_); \
+} while (0)
+
+#define ev_io_set(ev,fd_,events_) do { (ev)->fd = (fd_); (ev)->events = (events_) | EV__IOFDSET; } while (0)
+#define ev_timer_set(ev,after_,repeat_) do { ((ev_watcher_time *)(ev))->at = (after_); (ev)->repeat = (repeat_); } while (0)
+#define ev_periodic_set(ev,ofs_,ival_,rcb_) do { (ev)->offset = (ofs_); (ev)->interval = (ival_); (ev)->reschedule_cb = (rcb_); } while (0)
+#define ev_signal_set(ev,signum_) do { (ev)->signum = (signum_); } while (0)
+#define ev_child_set(ev,pid_,trace_) do { (ev)->pid = (pid_); (ev)->flags = !!(trace_); } while (0)
+#define ev_stat_set(ev,path_,interval_) do { (ev)->path = (path_); (ev)->interval = (interval_); (ev)->wd = -2; } while (0)
+#define ev_idle_set(ev) /* nop, yes, this is a serious in-joke */
+#define ev_prepare_set(ev) /* nop, yes, this is a serious in-joke */
+#define ev_check_set(ev) /* nop, yes, this is a serious in-joke */
+#define ev_embed_set(ev,other_) do { (ev)->other = (other_); } while (0)
+#define ev_fork_set(ev) /* nop, yes, this is a serious in-joke */
+#define ev_cleanup_set(ev) /* nop, yes, this is a serious in-joke */
+#define ev_async_set(ev) /* nop, yes, this is a serious in-joke */
+
+#define ev_io_init(ev,cb,fd,events) do { ev_init ((ev), (cb)); ev_io_set ((ev),(fd),(events)); } while (0)
+#define ev_timer_init(ev,cb,after,repeat) do { ev_init ((ev), (cb)); ev_timer_set ((ev),(after),(repeat)); } while (0)
+#define ev_periodic_init(ev,cb,ofs,ival,rcb) do { ev_init ((ev), (cb)); ev_periodic_set ((ev),(ofs),(ival),(rcb)); } while (0)
+#define ev_signal_init(ev,cb,signum) do { ev_init ((ev), (cb)); ev_signal_set ((ev), (signum)); } while (0)
+#define ev_child_init(ev,cb,pid,trace) do { ev_init ((ev), (cb)); ev_child_set ((ev),(pid),(trace)); } while (0)
+#define ev_stat_init(ev,cb,path,interval) do { ev_init ((ev), (cb)); ev_stat_set ((ev),(path),(interval)); } while (0)
+#define ev_idle_init(ev,cb) do { ev_init ((ev), (cb)); ev_idle_set ((ev)); } while (0)
+#define ev_prepare_init(ev,cb) do { ev_init ((ev), (cb)); ev_prepare_set ((ev)); } while (0)
+#define ev_check_init(ev,cb) do { ev_init ((ev), (cb)); ev_check_set ((ev)); } while (0)
+#define ev_embed_init(ev,cb,other) do { ev_init ((ev), (cb)); ev_embed_set ((ev),(other)); } while (0)
+#define ev_fork_init(ev,cb) do { ev_init ((ev), (cb)); ev_fork_set ((ev)); } while (0)
+#define ev_cleanup_init(ev,cb) do { ev_init ((ev), (cb)); ev_cleanup_set ((ev)); } while (0)
+#define ev_async_init(ev,cb) do { ev_init ((ev), (cb)); ev_async_set ((ev)); } while (0)
+
+#define ev_is_pending(ev) (0 + ((ev_watcher *)(void *)(ev))->pending) /* ro, true when watcher is waiting for callback invocation */
+#define ev_is_active(ev) (0 + ((ev_watcher *)(void *)(ev))->active) /* ro, true when the watcher has been started */
+
+#define ev_cb(ev) (ev)->cb /* rw */
+
+#if EV_MINPRI == EV_MAXPRI
+# define ev_priority(ev) ((ev), EV_MINPRI)
+# define ev_set_priority(ev,pri) ((ev), (pri))
+#else
+# define ev_priority(ev) (+(((ev_watcher *)(void *)(ev))->priority))
+# define ev_set_priority(ev,pri) ( (ev_watcher *)(void *)(ev))->priority = (pri)
+#endif
+
+#define ev_periodic_at(ev) (+((ev_watcher_time *)(ev))->at)
+
+#ifndef ev_set_cb
+# define ev_set_cb(ev,cb_) ev_cb (ev) = (cb_)
+#endif
+
+/* stopping (enabling, adding) a watcher does nothing if it is already running */
+/* stopping (disabling, deleting) a watcher does nothing unless its already running */
+#if EV_PROTOTYPES
+
+/* feeds an event into a watcher as if the event actually occurred */
+/* accepts any ev_watcher type */
+EV_API_DECL void ev_feed_event (EV_P_ void *w, int revents) EV_THROW;
+EV_API_DECL void ev_feed_fd_event (EV_P_ int fd, int revents) EV_THROW;
+#if EV_SIGNAL_ENABLE
+EV_API_DECL void ev_feed_signal (int signum) EV_THROW;
+EV_API_DECL void ev_feed_signal_event (EV_P_ int signum) EV_THROW;
+#endif
+EV_API_DECL void ev_invoke (EV_P_ void *w, int revents);
+EV_API_DECL int ev_clear_pending (EV_P_ void *w) EV_THROW;
+
+EV_API_DECL void ev_io_start (EV_P_ ev_io *w) EV_THROW;
+EV_API_DECL void ev_io_stop (EV_P_ ev_io *w) EV_THROW;
+
+EV_API_DECL void ev_timer_start (EV_P_ ev_timer *w) EV_THROW;
+EV_API_DECL void ev_timer_stop (EV_P_ ev_timer *w) EV_THROW;
+/* stops if active and no repeat, restarts if active and repeating, starts if inactive and repeating */
+EV_API_DECL void ev_timer_again (EV_P_ ev_timer *w) EV_THROW;
+/* return remaining time */
+EV_API_DECL ev_tstamp ev_timer_remaining (EV_P_ ev_timer *w) EV_THROW;
+
+#if EV_PERIODIC_ENABLE
+EV_API_DECL void ev_periodic_start (EV_P_ ev_periodic *w) EV_THROW;
+EV_API_DECL void ev_periodic_stop (EV_P_ ev_periodic *w) EV_THROW;
+EV_API_DECL void ev_periodic_again (EV_P_ ev_periodic *w) EV_THROW;
+#endif
+
+/* only supported in the default loop */
+#if EV_SIGNAL_ENABLE
+EV_API_DECL void ev_signal_start (EV_P_ ev_signal *w) EV_THROW;
+EV_API_DECL void ev_signal_stop (EV_P_ ev_signal *w) EV_THROW;
+#endif
+
+/* only supported in the default loop */
+# if EV_CHILD_ENABLE
+EV_API_DECL void ev_child_start (EV_P_ ev_child *w) EV_THROW;
+EV_API_DECL void ev_child_stop (EV_P_ ev_child *w) EV_THROW;
+# endif
+
+# if EV_STAT_ENABLE
+EV_API_DECL void ev_stat_start (EV_P_ ev_stat *w) EV_THROW;
+EV_API_DECL void ev_stat_stop (EV_P_ ev_stat *w) EV_THROW;
+EV_API_DECL void ev_stat_stat (EV_P_ ev_stat *w) EV_THROW;
+# endif
+
+# if EV_IDLE_ENABLE
+EV_API_DECL void ev_idle_start (EV_P_ ev_idle *w) EV_THROW;
+EV_API_DECL void ev_idle_stop (EV_P_ ev_idle *w) EV_THROW;
+# endif
+
+#if EV_PREPARE_ENABLE
+EV_API_DECL void ev_prepare_start (EV_P_ ev_prepare *w) EV_THROW;
+EV_API_DECL void ev_prepare_stop (EV_P_ ev_prepare *w) EV_THROW;
+#endif
+
+#if EV_CHECK_ENABLE
+EV_API_DECL void ev_check_start (EV_P_ ev_check *w) EV_THROW;
+EV_API_DECL void ev_check_stop (EV_P_ ev_check *w) EV_THROW;
+#endif
+
+# if EV_FORK_ENABLE
+EV_API_DECL void ev_fork_start (EV_P_ ev_fork *w) EV_THROW;
+EV_API_DECL void ev_fork_stop (EV_P_ ev_fork *w) EV_THROW;
+# endif
+
+# if EV_CLEANUP_ENABLE
+EV_API_DECL void ev_cleanup_start (EV_P_ ev_cleanup *w) EV_THROW;
+EV_API_DECL void ev_cleanup_stop (EV_P_ ev_cleanup *w) EV_THROW;
+# endif
+
+# if EV_EMBED_ENABLE
+/* only supported when loop to be embedded is in fact embeddable */
+EV_API_DECL void ev_embed_start (EV_P_ ev_embed *w) EV_THROW;
+EV_API_DECL void ev_embed_stop (EV_P_ ev_embed *w) EV_THROW;
+EV_API_DECL void ev_embed_sweep (EV_P_ ev_embed *w) EV_THROW;
+# endif
+
+# if EV_ASYNC_ENABLE
+EV_API_DECL void ev_async_start (EV_P_ ev_async *w) EV_THROW;
+EV_API_DECL void ev_async_stop (EV_P_ ev_async *w) EV_THROW;
+EV_API_DECL void ev_async_send (EV_P_ ev_async *w) EV_THROW;
+# endif
+
+#if EV_COMPAT3
+ #define EVLOOP_NONBLOCK EVRUN_NOWAIT
+ #define EVLOOP_ONESHOT EVRUN_ONCE
+ #define EVUNLOOP_CANCEL EVBREAK_CANCEL
+ #define EVUNLOOP_ONE EVBREAK_ONE
+ #define EVUNLOOP_ALL EVBREAK_ALL
+ #if EV_PROTOTYPES
+ EV_INLINE void ev_loop (EV_P_ int flags) { ev_run (EV_A_ flags); }
+ EV_INLINE void ev_unloop (EV_P_ int how ) { ev_break (EV_A_ how ); }
+ EV_INLINE void ev_default_destroy (void) { ev_loop_destroy (EV_DEFAULT); }
+ EV_INLINE void ev_default_fork (void) { ev_loop_fork (EV_DEFAULT); }
+ #if EV_FEATURE_API
+ EV_INLINE unsigned int ev_loop_count (EV_P) { return ev_iteration (EV_A); }
+ EV_INLINE unsigned int ev_loop_depth (EV_P) { return ev_depth (EV_A); }
+ EV_INLINE void ev_loop_verify (EV_P) { ev_verify (EV_A); }
+ #endif
+ #endif
+#else
+ typedef struct ev_loop ev_loop;
+#endif
+
+#endif
+
+EV_CPP(})
+
+#endif
+
diff --git a/ext/libev/ev_epoll.c b/ext/libev/ev_epoll.c
new file mode 100644
index 0000000..f5ad618
--- /dev/null
+++ b/ext/libev/ev_epoll.c
@@ -0,0 +1,279 @@
+/*
+ * libev epoll fd activity backend
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+/*
+ * general notes about epoll:
+ *
+ * a) epoll silently removes fds from the fd set. as nothing tells us
+ * that an fd has been removed otherwise, we have to continually
+ * "rearm" fds that we suspect *might* have changed (same
+ * problem with kqueue, but much less costly there).
+ * b) the fact that ADD != MOD creates a lot of extra syscalls due to a)
+ * and seems not to have any advantage.
+ * c) the inability to handle fork or file descriptors (think dup)
+ * limits the applicability over poll, so this is not a generic
+ * poll replacement.
+ * d) epoll doesn't work the same as select with many file descriptors
+ * (such as files). while not critical, no other advanced interface
+ * seems to share this (rather non-unixy) limitation.
+ * e) epoll claims to be embeddable, but in practise you never get
+ * a ready event for the epoll fd (broken: <=2.6.26, working: >=2.6.32).
+ * f) epoll_ctl returning EPERM means the fd is always ready.
+ *
+ * lots of "weird code" and complication handling in this file is due
+ * to these design problems with epoll, as we try very hard to avoid
+ * epoll_ctl syscalls for common usage patterns and handle the breakage
+ * ensuing from receiving events for closed and otherwise long gone
+ * file descriptors.
+ */
+
+#include <sys/epoll.h>
+
+#define EV_EMASK_EPERM 0x80
+
+static void
+epoll_modify (EV_P_ int fd, int oev, int nev)
+{
+ struct epoll_event ev;
+ unsigned char oldmask;
+
+ /*
+ * we handle EPOLL_CTL_DEL by ignoring it here
+ * on the assumption that the fd is gone anyways
+ * if that is wrong, we have to handle the spurious
+ * event in epoll_poll.
+ * if the fd is added again, we try to ADD it, and, if that
+ * fails, we assume it still has the same eventmask.
+ */
+ if (!nev)
+ return;
+
+ oldmask = anfds [fd].emask;
+ anfds [fd].emask = nev;
+
+ /* store the generation counter in the upper 32 bits, the fd in the lower 32 bits */
+ ev.data.u64 = (uint64_t)(uint32_t)fd
+ | ((uint64_t)(uint32_t)++anfds [fd].egen << 32);
+ ev.events = (nev & EV_READ ? EPOLLIN : 0)
+ | (nev & EV_WRITE ? EPOLLOUT : 0);
+
+ if (expect_true (!epoll_ctl (backend_fd, oev && oldmask != nev ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, fd, &ev)))
+ return;
+
+ if (expect_true (errno == ENOENT))
+ {
+ /* if ENOENT then the fd went away, so try to do the right thing */
+ if (!nev)
+ goto dec_egen;
+
+ if (!epoll_ctl (backend_fd, EPOLL_CTL_ADD, fd, &ev))
+ return;
+ }
+ else if (expect_true (errno == EEXIST))
+ {
+ /* EEXIST means we ignored a previous DEL, but the fd is still active */
+ /* if the kernel mask is the same as the new mask, we assume it hasn't changed */
+ if (oldmask == nev)
+ goto dec_egen;
+
+ if (!epoll_ctl (backend_fd, EPOLL_CTL_MOD, fd, &ev))
+ return;
+ }
+ else if (expect_true (errno == EPERM))
+ {
+ /* EPERM means the fd is always ready, but epoll is too snobbish */
+ /* to handle it, unlike select or poll. */
+ anfds [fd].emask = EV_EMASK_EPERM;
+
+ /* add fd to epoll_eperms, if not already inside */
+ if (!(oldmask & EV_EMASK_EPERM))
+ {
+ array_needsize (int, epoll_eperms, epoll_epermmax, epoll_epermcnt + 1, EMPTY2);
+ epoll_eperms [epoll_epermcnt++] = fd;
+ }
+
+ return;
+ }
+
+ fd_kill (EV_A_ fd);
+
+dec_egen:
+ /* we didn't successfully call epoll_ctl, so decrement the generation counter again */
+ --anfds [fd].egen;
+}
+
+static void
+epoll_poll (EV_P_ ev_tstamp timeout)
+{
+ int i;
+ int eventcnt;
+
+ if (expect_false (epoll_epermcnt))
+ timeout = 0.;
+
+ /* epoll wait times cannot be larger than (LONG_MAX - 999UL) / HZ msecs, which is below */
+ /* the default libev max wait time, however. */
+ EV_RELEASE_CB;
+ eventcnt = epoll_wait (backend_fd, epoll_events, epoll_eventmax, timeout * 1e3);
+ EV_ACQUIRE_CB;
+
+ if (expect_false (eventcnt < 0))
+ {
+ if (errno != EINTR)
+ ev_syserr ("(libev) epoll_wait");
+
+ return;
+ }
+
+ for (i = 0; i < eventcnt; ++i)
+ {
+ struct epoll_event *ev = epoll_events + i;
+
+ int fd = (uint32_t)ev->data.u64; /* mask out the lower 32 bits */
+ int want = anfds [fd].events;
+ int got = (ev->events & (EPOLLOUT | EPOLLERR | EPOLLHUP) ? EV_WRITE : 0)
+ | (ev->events & (EPOLLIN | EPOLLERR | EPOLLHUP) ? EV_READ : 0);
+
+ /*
+ * check for spurious notification.
+ * this only finds spurious notifications on egen updates
+ * other spurious notifications will be found by epoll_ctl, below
+ * we assume that fd is always in range, as we never shrink the anfds array
+ */
+ if (expect_false ((uint32_t)anfds [fd].egen != (uint32_t)(ev->data.u64 >> 32)))
+ {
+ /* recreate kernel state */
+ postfork = 1;
+ continue;
+ }
+
+ if (expect_false (got & ~want))
+ {
+ anfds [fd].emask = want;
+
+ /*
+ * we received an event but are not interested in it, try mod or del
+ * this often happens because we optimistically do not unregister fds
+ * when we are no longer interested in them, but also when we get spurious
+ * notifications for fds from another process. this is partially handled
+ * above with the gencounter check (== our fd is not the event fd), and
+ * partially here, when epoll_ctl returns an error (== a child has the fd
+ * but we closed it).
+ */
+ ev->events = (want & EV_READ ? EPOLLIN : 0)
+ | (want & EV_WRITE ? EPOLLOUT : 0);
+
+ /* pre-2.6.9 kernels require a non-null pointer with EPOLL_CTL_DEL, */
+ /* which is fortunately easy to do for us. */
+ if (epoll_ctl (backend_fd, want ? EPOLL_CTL_MOD : EPOLL_CTL_DEL, fd, ev))
+ {
+ postfork = 1; /* an error occurred, recreate kernel state */
+ continue;
+ }
+ }
+
+ fd_event (EV_A_ fd, got);
+ }
+
+ /* if the receive array was full, increase its size */
+ if (expect_false (eventcnt == epoll_eventmax))
+ {
+ ev_free (epoll_events);
+ epoll_eventmax = array_nextsize (sizeof (struct epoll_event), epoll_eventmax, epoll_eventmax + 1);
+ epoll_events = (struct epoll_event *)ev_malloc (sizeof (struct epoll_event) * epoll_eventmax);
+ }
+
+ /* now synthesize events for all fds where epoll fails, while select works... */
+ for (i = epoll_epermcnt; i--; )
+ {
+ int fd = epoll_eperms [i];
+ unsigned char events = anfds [fd].events & (EV_READ | EV_WRITE);
+
+ if (anfds [fd].emask & EV_EMASK_EPERM && events)
+ fd_event (EV_A_ fd, events);
+ else
+ epoll_eperms [i] = epoll_eperms [--epoll_epermcnt];
+ }
+}
+
+int inline_size
+epoll_init (EV_P_ int flags)
+{
+#ifdef EPOLL_CLOEXEC
+ backend_fd = epoll_create1 (EPOLL_CLOEXEC);
+
+ if (backend_fd < 0 && (errno == EINVAL || errno == ENOSYS))
+#endif
+ backend_fd = epoll_create (256);
+
+ if (backend_fd < 0)
+ return 0;
+
+ fcntl (backend_fd, F_SETFD, FD_CLOEXEC);
+
+ backend_mintime = 1e-3; /* epoll does sometimes return early, this is just to avoid the worst */
+ backend_modify = epoll_modify;
+ backend_poll = epoll_poll;
+
+ epoll_eventmax = 64; /* initial number of events receivable per poll */
+ epoll_events = (struct epoll_event *)ev_malloc (sizeof (struct epoll_event) * epoll_eventmax);
+
+ return EVBACKEND_EPOLL;
+}
+
+void inline_size
+epoll_destroy (EV_P)
+{
+ ev_free (epoll_events);
+ array_free (epoll_eperm, EMPTY);
+}
+
+void inline_size
+epoll_fork (EV_P)
+{
+ close (backend_fd);
+
+ while ((backend_fd = epoll_create (256)) < 0)
+ ev_syserr ("(libev) epoll_create");
+
+ fcntl (backend_fd, F_SETFD, FD_CLOEXEC);
+
+ fd_rearm_all (EV_A);
+}
+
diff --git a/ext/libev/ev_kqueue.c b/ext/libev/ev_kqueue.c
new file mode 100644
index 0000000..9faf65a
--- /dev/null
+++ b/ext/libev/ev_kqueue.c
@@ -0,0 +1,214 @@
+/*
+ * libev kqueue backend
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/event.h>
+#include <string.h>
+#include <errno.h>
+
+void inline_speed
+kqueue_change (EV_P_ int fd, int filter, int flags, int fflags)
+{
+ ++kqueue_changecnt;
+ array_needsize (struct kevent, kqueue_changes, kqueue_changemax, kqueue_changecnt, EMPTY2);
+
+ EV_SET (&kqueue_changes [kqueue_changecnt - 1], fd, filter, flags, fflags, 0, 0);
+}
+
+/* OS X at least needs this */
+#ifndef EV_ENABLE
+# define EV_ENABLE 0
+#endif
+#ifndef NOTE_EOF
+# define NOTE_EOF 0
+#endif
+
+static void
+kqueue_modify (EV_P_ int fd, int oev, int nev)
+{
+ if (oev != nev)
+ {
+ if (oev & EV_READ)
+ kqueue_change (EV_A_ fd, EVFILT_READ , EV_DELETE, 0);
+
+ if (oev & EV_WRITE)
+ kqueue_change (EV_A_ fd, EVFILT_WRITE, EV_DELETE, 0);
+ }
+
+ /* to detect close/reopen reliably, we have to re-add */
+ /* event requests even when oev == nev */
+
+ if (nev & EV_READ)
+ kqueue_change (EV_A_ fd, EVFILT_READ , EV_ADD | EV_ENABLE, NOTE_EOF);
+
+ if (nev & EV_WRITE)
+ kqueue_change (EV_A_ fd, EVFILT_WRITE, EV_ADD | EV_ENABLE, NOTE_EOF);
+}
+
+static void
+kqueue_poll (EV_P_ ev_tstamp timeout)
+{
+ int res, i;
+ struct timespec ts;
+
+ /* need to resize so there is enough space for errors */
+ if (kqueue_changecnt > kqueue_eventmax)
+ {
+ ev_free (kqueue_events);
+ kqueue_eventmax = array_nextsize (sizeof (struct kevent), kqueue_eventmax, kqueue_changecnt);
+ kqueue_events = (struct kevent *)ev_malloc (sizeof (struct kevent) * kqueue_eventmax);
+ }
+
+ EV_RELEASE_CB;
+ EV_TS_SET (ts, timeout);
+ res = kevent (backend_fd, kqueue_changes, kqueue_changecnt, kqueue_events, kqueue_eventmax, &ts);
+ EV_ACQUIRE_CB;
+ kqueue_changecnt = 0;
+
+ if (expect_false (res < 0))
+ {
+ if (errno != EINTR)
+ ev_syserr ("(libev) kevent");
+
+ return;
+ }
+
+ for (i = 0; i < res; ++i)
+ {
+ int fd = kqueue_events [i].ident;
+
+ if (expect_false (kqueue_events [i].flags & EV_ERROR))
+ {
+ int err = kqueue_events [i].data;
+
+ /* we are only interested in errors for fds that we are interested in :) */
+ if (anfds [fd].events)
+ {
+ if (err == ENOENT) /* resubmit changes on ENOENT */
+ kqueue_modify (EV_A_ fd, 0, anfds [fd].events);
+ else if (err == EBADF) /* on EBADF, we re-check the fd */
+ {
+ if (fd_valid (fd))
+ kqueue_modify (EV_A_ fd, 0, anfds [fd].events);
+ else
+ fd_kill (EV_A_ fd);
+ }
+ else /* on all other errors, we error out on the fd */
+ fd_kill (EV_A_ fd);
+ }
+ }
+ else
+ fd_event (
+ EV_A_
+ fd,
+ kqueue_events [i].filter == EVFILT_READ ? EV_READ
+ : kqueue_events [i].filter == EVFILT_WRITE ? EV_WRITE
+ : 0
+ );
+ }
+
+ if (expect_false (res == kqueue_eventmax))
+ {
+ ev_free (kqueue_events);
+ kqueue_eventmax = array_nextsize (sizeof (struct kevent), kqueue_eventmax, kqueue_eventmax + 1);
+ kqueue_events = (struct kevent *)ev_malloc (sizeof (struct kevent) * kqueue_eventmax);
+ }
+}
+
+int inline_size
+kqueue_init (EV_P_ int flags)
+{
+ /* initialize the kernel queue */
+ kqueue_fd_pid = getpid ();
+ if ((backend_fd = kqueue ()) < 0)
+ return 0;
+
+ fcntl (backend_fd, F_SETFD, FD_CLOEXEC); /* not sure if necessary, hopefully doesn't hurt */
+
+ backend_mintime = 1e-9; /* apparently, they did the right thing in freebsd */
+ backend_modify = kqueue_modify;
+ backend_poll = kqueue_poll;
+
+ kqueue_eventmax = 64; /* initial number of events receivable per poll */
+ kqueue_events = (struct kevent *)ev_malloc (sizeof (struct kevent) * kqueue_eventmax);
+
+ kqueue_changes = 0;
+ kqueue_changemax = 0;
+ kqueue_changecnt = 0;
+
+ return EVBACKEND_KQUEUE;
+}
+
+void inline_size
+kqueue_destroy (EV_P)
+{
+ ev_free (kqueue_events);
+ ev_free (kqueue_changes);
+}
+
+void inline_size
+kqueue_fork (EV_P)
+{
+ /* some BSD kernels don't just destroy the kqueue itself,
+ * but also close the fd, which isn't documented, and
+ * impossible to support properly.
+ * we remember the pid of the kqueue call and only close
+ * the fd if the pid is still the same.
+ * this leaks fds on sane kernels, but BSD interfaces are
+ * notoriously buggy and rarely get fixed.
+ */
+ pid_t newpid = getpid ();
+
+ if (newpid == kqueue_fd_pid)
+ close (backend_fd);
+
+ kqueue_fd_pid = newpid;
+ while ((backend_fd = kqueue ()) < 0)
+ ev_syserr ("(libev) kqueue");
+
+ fcntl (backend_fd, F_SETFD, FD_CLOEXEC);
+
+ /* re-register interest in fds */
+ fd_rearm_all (EV_A);
+}
+
+/* sys/event.h defines EV_ERROR */
+#undef EV_ERROR
+
diff --git a/ext/libev/ev_poll.c b/ext/libev/ev_poll.c
new file mode 100644
index 0000000..80f8867
--- /dev/null
+++ b/ext/libev/ev_poll.c
@@ -0,0 +1,148 @@
+/*
+ * libev poll fd activity backend
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#include <poll.h>
+
+void inline_size
+pollidx_init (int *base, int count)
+{
+ /* consider using memset (.., -1, ...), which is practically guaranteed
+ * to work on all systems implementing poll */
+ while (count--)
+ *base++ = -1;
+}
+
+static void
+poll_modify (EV_P_ int fd, int oev, int nev)
+{
+ int idx;
+
+ if (oev == nev)
+ return;
+
+ array_needsize (int, pollidxs, pollidxmax, fd + 1, pollidx_init);
+
+ idx = pollidxs [fd];
+
+ if (idx < 0) /* need to allocate a new pollfd */
+ {
+ pollidxs [fd] = idx = pollcnt++;
+ array_needsize (struct pollfd, polls, pollmax, pollcnt, EMPTY2);
+ polls [idx].fd = fd;
+ }
+
+ assert (polls [idx].fd == fd);
+
+ if (nev)
+ polls [idx].events =
+ (nev & EV_READ ? POLLIN : 0)
+ | (nev & EV_WRITE ? POLLOUT : 0);
+ else /* remove pollfd */
+ {
+ pollidxs [fd] = -1;
+
+ if (expect_true (idx < --pollcnt))
+ {
+ polls [idx] = polls [pollcnt];
+ pollidxs [polls [idx].fd] = idx;
+ }
+ }
+}
+
+static void
+poll_poll (EV_P_ ev_tstamp timeout)
+{
+ struct pollfd *p;
+ int res;
+
+ EV_RELEASE_CB;
+ res = poll (polls, pollcnt, timeout * 1e3);
+ EV_ACQUIRE_CB;
+
+ if (expect_false (res < 0))
+ {
+ if (errno == EBADF)
+ fd_ebadf (EV_A);
+ else if (errno == ENOMEM && !syserr_cb)
+ fd_enomem (EV_A);
+ else if (errno != EINTR)
+ ev_syserr ("(libev) poll");
+ }
+ else
+ for (p = polls; res; ++p)
+ {
+ assert (("libev: poll() returned illegal result, broken BSD kernel?", p < polls + pollcnt));
+
+ if (expect_false (p->revents)) /* this expect is debatable */
+ {
+ --res;
+
+ if (expect_false (p->revents & POLLNVAL))
+ fd_kill (EV_A_ p->fd);
+ else
+ fd_event (
+ EV_A_
+ p->fd,
+ (p->revents & (POLLOUT | POLLERR | POLLHUP) ? EV_WRITE : 0)
+ | (p->revents & (POLLIN | POLLERR | POLLHUP) ? EV_READ : 0)
+ );
+ }
+ }
+}
+
+int inline_size
+poll_init (EV_P_ int flags)
+{
+ backend_mintime = 1e-3;
+ backend_modify = poll_modify;
+ backend_poll = poll_poll;
+
+ pollidxs = 0; pollidxmax = 0;
+ polls = 0; pollmax = 0; pollcnt = 0;
+
+ return EVBACKEND_POLL;
+}
+
+void inline_size
+poll_destroy (EV_P)
+{
+ ev_free (pollidxs);
+ ev_free (polls);
+}
+
diff --git a/ext/libev/ev_port.c b/ext/libev/ev_port.c
new file mode 100644
index 0000000..9368501
--- /dev/null
+++ b/ext/libev/ev_port.c
@@ -0,0 +1,185 @@
+/*
+ * libev solaris event port backend
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+/* useful reading:
+ *
+ * http://bugs.opensolaris.org/view_bug.do?bug_id=6268715 (random results)
+ * http://bugs.opensolaris.org/view_bug.do?bug_id=6455223 (just totally broken)
+ * http://bugs.opensolaris.org/view_bug.do?bug_id=6873782 (manpage ETIME)
+ * http://bugs.opensolaris.org/view_bug.do?bug_id=6874410 (implementation ETIME)
+ * http://www.mail-archive.com/networking-discuss@opensolaris.org/msg11898.html ETIME vs. nget
+ * http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/lib/libc/port/gen/event_port.c (libc)
+ * http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/fs/portfs/port.c#1325 (kernel)
+ */
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <poll.h>
+#include <port.h>
+#include <string.h>
+#include <errno.h>
+
+void inline_speed
+port_associate_and_check (EV_P_ int fd, int ev)
+{
+ if (0 >
+ port_associate (
+ backend_fd, PORT_SOURCE_FD, fd,
+ (ev & EV_READ ? POLLIN : 0)
+ | (ev & EV_WRITE ? POLLOUT : 0),
+ 0
+ )
+ )
+ {
+ if (errno == EBADFD)
+ fd_kill (EV_A_ fd);
+ else
+ ev_syserr ("(libev) port_associate");
+ }
+}
+
+static void
+port_modify (EV_P_ int fd, int oev, int nev)
+{
+ /* we need to reassociate no matter what, as closes are
+ * once more silently being discarded.
+ */
+ if (!nev)
+ {
+ if (oev)
+ port_dissociate (backend_fd, PORT_SOURCE_FD, fd);
+ }
+ else
+ port_associate_and_check (EV_A_ fd, nev);
+}
+
+static void
+port_poll (EV_P_ ev_tstamp timeout)
+{
+ int res, i;
+ struct timespec ts;
+ uint_t nget = 1;
+
+ /* we initialise this to something we will skip in the loop, as */
+ /* port_getn can return with nget unchanged, but no indication */
+ /* whether it was the original value or has been updated :/ */
+ port_events [0].portev_source = 0;
+
+ EV_RELEASE_CB;
+ EV_TS_SET (ts, timeout);
+ res = port_getn (backend_fd, port_events, port_eventmax, &nget, &ts);
+ EV_ACQUIRE_CB;
+
+ /* port_getn may or may not set nget on error */
+ /* so we rely on port_events [0].portev_source not being updated */
+ if (res == -1 && errno != ETIME && errno != EINTR)
+ ev_syserr ("(libev) port_getn (see http://bugs.opensolaris.org/view_bug.do?bug_id=6268715, try LIBEV_FLAGS=3 env variable)");
+
+ for (i = 0; i < nget; ++i)
+ {
+ if (port_events [i].portev_source == PORT_SOURCE_FD)
+ {
+ int fd = port_events [i].portev_object;
+
+ fd_event (
+ EV_A_
+ fd,
+ (port_events [i].portev_events & (POLLOUT | POLLERR | POLLHUP) ? EV_WRITE : 0)
+ | (port_events [i].portev_events & (POLLIN | POLLERR | POLLHUP) ? EV_READ : 0)
+ );
+
+ fd_change (EV_A_ fd, EV__IOFDSET);
+ }
+ }
+
+ if (expect_false (nget == port_eventmax))
+ {
+ ev_free (port_events);
+ port_eventmax = array_nextsize (sizeof (port_event_t), port_eventmax, port_eventmax + 1);
+ port_events = (port_event_t *)ev_malloc (sizeof (port_event_t) * port_eventmax);
+ }
+}
+
+int inline_size
+port_init (EV_P_ int flags)
+{
+ /* Initialize the kernel queue */
+ if ((backend_fd = port_create ()) < 0)
+ return 0;
+
+ assert (("libev: PORT_SOURCE_FD must not be zero", PORT_SOURCE_FD));
+
+ fcntl (backend_fd, F_SETFD, FD_CLOEXEC); /* not sure if necessary, hopefully doesn't hurt */
+
+ /* if my reading of the opensolaris kernel sources are correct, then
+ * opensolaris does something very stupid: it checks if the time has already
+ * elapsed and doesn't round up if that is the case,m otherwise it DOES round
+ * up. Since we can't know what the case is, we need to guess by using a
+ * "large enough" timeout. Normally, 1e-9 would be correct.
+ */
+ backend_mintime = 1e-3; /* needed to compensate for port_getn returning early */
+ backend_modify = port_modify;
+ backend_poll = port_poll;
+
+ port_eventmax = 64; /* initial number of events receivable per poll */
+ port_events = (port_event_t *)ev_malloc (sizeof (port_event_t) * port_eventmax);
+
+ return EVBACKEND_PORT;
+}
+
+void inline_size
+port_destroy (EV_P)
+{
+ ev_free (port_events);
+}
+
+void inline_size
+port_fork (EV_P)
+{
+ close (backend_fd);
+
+ while ((backend_fd = port_create ()) < 0)
+ ev_syserr ("(libev) port");
+
+ fcntl (backend_fd, F_SETFD, FD_CLOEXEC);
+
+ /* re-register interest in fds */
+ fd_rearm_all (EV_A);
+}
+
diff --git a/ext/libev/ev_select.c b/ext/libev/ev_select.c
new file mode 100644
index 0000000..f38d6ca
--- /dev/null
+++ b/ext/libev/ev_select.c
@@ -0,0 +1,314 @@
+/*
+ * libev select fd activity backend
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#ifndef _WIN32
+/* for unix systems */
+# include <inttypes.h>
+# ifndef __hpux
+/* for REAL unix systems */
+# include <sys/select.h>
+# endif
+#endif
+
+#ifndef EV_SELECT_USE_FD_SET
+# ifdef NFDBITS
+# define EV_SELECT_USE_FD_SET 0
+# else
+# define EV_SELECT_USE_FD_SET 1
+# endif
+#endif
+
+#if EV_SELECT_IS_WINSOCKET
+# undef EV_SELECT_USE_FD_SET
+# define EV_SELECT_USE_FD_SET 1
+# undef NFDBITS
+# define NFDBITS 0
+#endif
+
+#if !EV_SELECT_USE_FD_SET
+# define NFDBYTES (NFDBITS / 8)
+#endif
+
+#include <string.h>
+
+static void
+select_modify (EV_P_ int fd, int oev, int nev)
+{
+ if (oev == nev)
+ return;
+
+ {
+#if EV_SELECT_USE_FD_SET
+
+ #if EV_SELECT_IS_WINSOCKET
+ SOCKET handle = anfds [fd].handle;
+ #else
+ int handle = fd;
+ #endif
+
+ assert (("libev: fd >= FD_SETSIZE passed to fd_set-based select backend", fd < FD_SETSIZE));
+
+ /* FD_SET is broken on windows (it adds the fd to a set twice or more,
+ * which eventually leads to overflows). Need to call it only on changes.
+ */
+ #if EV_SELECT_IS_WINSOCKET
+ if ((oev ^ nev) & EV_READ)
+ #endif
+ if (nev & EV_READ)
+ FD_SET (handle, (fd_set *)vec_ri);
+ else
+ FD_CLR (handle, (fd_set *)vec_ri);
+
+ #if EV_SELECT_IS_WINSOCKET
+ if ((oev ^ nev) & EV_WRITE)
+ #endif
+ if (nev & EV_WRITE)
+ FD_SET (handle, (fd_set *)vec_wi);
+ else
+ FD_CLR (handle, (fd_set *)vec_wi);
+
+#else
+
+ int word = fd / NFDBITS;
+ fd_mask mask = 1UL << (fd % NFDBITS);
+
+ if (expect_false (vec_max <= word))
+ {
+ int new_max = word + 1;
+
+ vec_ri = ev_realloc (vec_ri, new_max * NFDBYTES);
+ vec_ro = ev_realloc (vec_ro, new_max * NFDBYTES); /* could free/malloc */
+ vec_wi = ev_realloc (vec_wi, new_max * NFDBYTES);
+ vec_wo = ev_realloc (vec_wo, new_max * NFDBYTES); /* could free/malloc */
+ #ifdef _WIN32
+ vec_eo = ev_realloc (vec_eo, new_max * NFDBYTES); /* could free/malloc */
+ #endif
+
+ for (; vec_max < new_max; ++vec_max)
+ ((fd_mask *)vec_ri) [vec_max] =
+ ((fd_mask *)vec_wi) [vec_max] = 0;
+ }
+
+ ((fd_mask *)vec_ri) [word] |= mask;
+ if (!(nev & EV_READ))
+ ((fd_mask *)vec_ri) [word] &= ~mask;
+
+ ((fd_mask *)vec_wi) [word] |= mask;
+ if (!(nev & EV_WRITE))
+ ((fd_mask *)vec_wi) [word] &= ~mask;
+#endif
+ }
+}
+
+static void
+select_poll (EV_P_ ev_tstamp timeout)
+{
+ struct timeval tv;
+ int res;
+ int fd_setsize;
+
+ EV_RELEASE_CB;
+ EV_TV_SET (tv, timeout);
+
+#if EV_SELECT_USE_FD_SET
+ fd_setsize = sizeof (fd_set);
+#else
+ fd_setsize = vec_max * NFDBYTES;
+#endif
+
+ memcpy (vec_ro, vec_ri, fd_setsize);
+ memcpy (vec_wo, vec_wi, fd_setsize);
+
+#ifdef _WIN32
+ /* pass in the write set as except set.
+ * the idea behind this is to work around a windows bug that causes
+ * errors to be reported as an exception and not by setting
+ * the writable bit. this is so uncontrollably lame.
+ */
+ memcpy (vec_eo, vec_wi, fd_setsize);
+ res = select (vec_max * NFDBITS, (fd_set *)vec_ro, (fd_set *)vec_wo, (fd_set *)vec_eo, &tv);
+#elif EV_SELECT_USE_FD_SET
+ fd_setsize = anfdmax < FD_SETSIZE ? anfdmax : FD_SETSIZE;
+ res = select (fd_setsize, (fd_set *)vec_ro, (fd_set *)vec_wo, 0, &tv);
+#else
+ res = select (vec_max * NFDBITS, (fd_set *)vec_ro, (fd_set *)vec_wo, 0, &tv);
+#endif
+ EV_ACQUIRE_CB;
+
+ if (expect_false (res < 0))
+ {
+ #if EV_SELECT_IS_WINSOCKET
+ errno = WSAGetLastError ();
+ #endif
+ #ifdef WSABASEERR
+ /* on windows, select returns incompatible error codes, fix this */
+ if (errno >= WSABASEERR && errno < WSABASEERR + 1000)
+ if (errno == WSAENOTSOCK)
+ errno = EBADF;
+ else
+ errno -= WSABASEERR;
+ #endif
+
+ #ifdef _WIN32
+ /* select on windows erroneously returns EINVAL when no fd sets have been
+ * provided (this is documented). what microsoft doesn't tell you that this bug
+ * exists even when the fd sets _are_ provided, so we have to check for this bug
+ * here and emulate by sleeping manually.
+ * we also get EINVAL when the timeout is invalid, but we ignore this case here
+ * and assume that EINVAL always means: you have to wait manually.
+ */
+ if (errno == EINVAL)
+ {
+ if (timeout)
+ {
+ unsigned long ms = timeout * 1e3;
+ Sleep (ms ? ms : 1);
+ }
+
+ return;
+ }
+ #endif
+
+ if (errno == EBADF)
+ fd_ebadf (EV_A);
+ else if (errno == ENOMEM && !syserr_cb)
+ fd_enomem (EV_A);
+ else if (errno != EINTR)
+ ev_syserr ("(libev) select");
+
+ return;
+ }
+
+#if EV_SELECT_USE_FD_SET
+
+ {
+ int fd;
+
+ for (fd = 0; fd < anfdmax; ++fd)
+ if (anfds [fd].events)
+ {
+ int events = 0;
+ #if EV_SELECT_IS_WINSOCKET
+ SOCKET handle = anfds [fd].handle;
+ #else
+ int handle = fd;
+ #endif
+
+ if (FD_ISSET (handle, (fd_set *)vec_ro)) events |= EV_READ;
+ if (FD_ISSET (handle, (fd_set *)vec_wo)) events |= EV_WRITE;
+ #ifdef _WIN32
+ if (FD_ISSET (handle, (fd_set *)vec_eo)) events |= EV_WRITE;
+ #endif
+
+ if (expect_true (events))
+ fd_event (EV_A_ fd, events);
+ }
+ }
+
+#else
+
+ {
+ int word, bit;
+ for (word = vec_max; word--; )
+ {
+ fd_mask word_r = ((fd_mask *)vec_ro) [word];
+ fd_mask word_w = ((fd_mask *)vec_wo) [word];
+ #ifdef _WIN32
+ word_w |= ((fd_mask *)vec_eo) [word];
+ #endif
+
+ if (word_r || word_w)
+ for (bit = NFDBITS; bit--; )
+ {
+ fd_mask mask = 1UL << bit;
+ int events = 0;
+
+ events |= word_r & mask ? EV_READ : 0;
+ events |= word_w & mask ? EV_WRITE : 0;
+
+ if (expect_true (events))
+ fd_event (EV_A_ word * NFDBITS + bit, events);
+ }
+ }
+ }
+
+#endif
+}
+
+int inline_size
+select_init (EV_P_ int flags)
+{
+ backend_mintime = 1e-6;
+ backend_modify = select_modify;
+ backend_poll = select_poll;
+
+#if EV_SELECT_USE_FD_SET
+ vec_ri = ev_malloc (sizeof (fd_set)); FD_ZERO ((fd_set *)vec_ri);
+ vec_ro = ev_malloc (sizeof (fd_set));
+ vec_wi = ev_malloc (sizeof (fd_set)); FD_ZERO ((fd_set *)vec_wi);
+ vec_wo = ev_malloc (sizeof (fd_set));
+ #ifdef _WIN32
+ vec_eo = ev_malloc (sizeof (fd_set));
+ #endif
+#else
+ vec_max = 0;
+ vec_ri = 0;
+ vec_ro = 0;
+ vec_wi = 0;
+ vec_wo = 0;
+ #ifdef _WIN32
+ vec_eo = 0;
+ #endif
+#endif
+
+ return EVBACKEND_SELECT;
+}
+
+void inline_size
+select_destroy (EV_P)
+{
+ ev_free (vec_ri);
+ ev_free (vec_ro);
+ ev_free (vec_wi);
+ ev_free (vec_wo);
+ #ifdef _WIN32
+ ev_free (vec_eo);
+ #endif
+}
+
diff --git a/ext/libev/ev_vars.h b/ext/libev/ev_vars.h
new file mode 100644
index 0000000..5fd9c7a
--- /dev/null
+++ b/ext/libev/ev_vars.h
@@ -0,0 +1,203 @@
+/*
+ * loop member variable declarations
+ *
+ * Copyright (c) 2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#define VARx(type,name) VAR(name, type name)
+
+VARx(ev_tstamp, now_floor) /* last time we refreshed rt_time */
+VARx(ev_tstamp, mn_now) /* monotonic clock "now" */
+VARx(ev_tstamp, rtmn_diff) /* difference realtime - monotonic time */
+
+/* for reverse feeding of events */
+VARx(W *, rfeeds)
+VARx(int, rfeedmax)
+VARx(int, rfeedcnt)
+
+VAR (pendings, ANPENDING *pendings [NUMPRI])
+VAR (pendingmax, int pendingmax [NUMPRI])
+VAR (pendingcnt, int pendingcnt [NUMPRI])
+VARx(int, pendingpri) /* highest priority currently pending */
+VARx(ev_prepare, pending_w) /* dummy pending watcher */
+
+VARx(ev_tstamp, io_blocktime)
+VARx(ev_tstamp, timeout_blocktime)
+
+VARx(int, backend)
+VARx(int, activecnt) /* total number of active events ("refcount") */
+VARx(EV_ATOMIC_T, loop_done) /* signal by ev_break */
+
+VARx(int, backend_fd)
+VARx(ev_tstamp, backend_mintime) /* assumed typical timer resolution */
+VAR (backend_modify, void (*backend_modify)(EV_P_ int fd, int oev, int nev))
+VAR (backend_poll , void (*backend_poll)(EV_P_ ev_tstamp timeout))
+
+VARx(ANFD *, anfds)
+VARx(int, anfdmax)
+
+VAR (evpipe, int evpipe [2])
+VARx(ev_io, pipe_w)
+VARx(EV_ATOMIC_T, pipe_write_wanted)
+VARx(EV_ATOMIC_T, pipe_write_skipped)
+
+#if !defined(_WIN32) || EV_GENWRAP
+VARx(pid_t, curpid)
+#endif
+
+VARx(char, postfork) /* true if we need to recreate kernel state after fork */
+
+#if EV_USE_SELECT || EV_GENWRAP
+VARx(void *, vec_ri)
+VARx(void *, vec_ro)
+VARx(void *, vec_wi)
+VARx(void *, vec_wo)
+#if defined(_WIN32) || EV_GENWRAP
+VARx(void *, vec_eo)
+#endif
+VARx(int, vec_max)
+#endif
+
+#if EV_USE_POLL || EV_GENWRAP
+VARx(struct pollfd *, polls)
+VARx(int, pollmax)
+VARx(int, pollcnt)
+VARx(int *, pollidxs) /* maps fds into structure indices */
+VARx(int, pollidxmax)
+#endif
+
+#if EV_USE_EPOLL || EV_GENWRAP
+VARx(struct epoll_event *, epoll_events)
+VARx(int, epoll_eventmax)
+VARx(int *, epoll_eperms)
+VARx(int, epoll_epermcnt)
+VARx(int, epoll_epermmax)
+#endif
+
+#if EV_USE_KQUEUE || EV_GENWRAP
+VARx(pid_t, kqueue_fd_pid)
+VARx(struct kevent *, kqueue_changes)
+VARx(int, kqueue_changemax)
+VARx(int, kqueue_changecnt)
+VARx(struct kevent *, kqueue_events)
+VARx(int, kqueue_eventmax)
+#endif
+
+#if EV_USE_PORT || EV_GENWRAP
+VARx(struct port_event *, port_events)
+VARx(int, port_eventmax)
+#endif
+
+#if EV_USE_IOCP || EV_GENWRAP
+VARx(HANDLE, iocp)
+#endif
+
+VARx(int *, fdchanges)
+VARx(int, fdchangemax)
+VARx(int, fdchangecnt)
+
+VARx(ANHE *, timers)
+VARx(int, timermax)
+VARx(int, timercnt)
+
+#if EV_PERIODIC_ENABLE || EV_GENWRAP
+VARx(ANHE *, periodics)
+VARx(int, periodicmax)
+VARx(int, periodiccnt)
+#endif
+
+#if EV_IDLE_ENABLE || EV_GENWRAP
+VAR (idles, ev_idle **idles [NUMPRI])
+VAR (idlemax, int idlemax [NUMPRI])
+VAR (idlecnt, int idlecnt [NUMPRI])
+#endif
+VARx(int, idleall) /* total number */
+
+VARx(struct ev_prepare **, prepares)
+VARx(int, preparemax)
+VARx(int, preparecnt)
+
+VARx(struct ev_check **, checks)
+VARx(int, checkmax)
+VARx(int, checkcnt)
+
+#if EV_FORK_ENABLE || EV_GENWRAP
+VARx(struct ev_fork **, forks)
+VARx(int, forkmax)
+VARx(int, forkcnt)
+#endif
+
+#if EV_CLEANUP_ENABLE || EV_GENWRAP
+VARx(struct ev_cleanup **, cleanups)
+VARx(int, cleanupmax)
+VARx(int, cleanupcnt)
+#endif
+
+#if EV_ASYNC_ENABLE || EV_GENWRAP
+VARx(EV_ATOMIC_T, async_pending)
+VARx(struct ev_async **, asyncs)
+VARx(int, asyncmax)
+VARx(int, asynccnt)
+#endif
+
+#if EV_USE_INOTIFY || EV_GENWRAP
+VARx(int, fs_fd)
+VARx(ev_io, fs_w)
+VARx(char, fs_2625) /* whether we are running in linux 2.6.25 or newer */
+VAR (fs_hash, ANFS fs_hash [EV_INOTIFY_HASHSIZE])
+#endif
+
+VARx(EV_ATOMIC_T, sig_pending)
+#if EV_USE_SIGNALFD || EV_GENWRAP
+VARx(int, sigfd)
+VARx(ev_io, sigfd_w)
+VARx(sigset_t, sigfd_set)
+#endif
+
+VARx(unsigned int, origflags) /* original loop flags */
+
+#if EV_FEATURE_API || EV_GENWRAP
+VARx(unsigned int, loop_count) /* total number of loop iterations/blocks */
+VARx(unsigned int, loop_depth) /* #ev_run enters - #ev_run leaves */
+
+VARx(void *, userdata)
+VAR (release_cb, void (*release_cb)(EV_P) EV_THROW)
+VAR (acquire_cb, void (*acquire_cb)(EV_P) EV_THROW)
+VAR (invoke_cb , void (*invoke_cb) (EV_P))
+#endif
+
+#undef VARx
+
diff --git a/ext/libev/ev_win32.c b/ext/libev/ev_win32.c
new file mode 100644
index 0000000..d65634c
--- /dev/null
+++ b/ext/libev/ev_win32.c
@@ -0,0 +1,163 @@
+/*
+ * libev win32 compatibility cruft (_not_ a backend)
+ *
+ * Copyright (c) 2007,2008,2009 Marc Alexander Lehmann <libev at schmorp.de>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#ifdef _WIN32
+
+/* timeb.h is actually xsi legacy functionality */
+#include <sys/timeb.h>
+
+/* note: the comment below could not be substantiated, but what would I care */
+/* MSDN says this is required to handle SIGFPE */
+/* my wild guess would be that using something floating-pointy is required */
+/* for the crt to do something about it */
+volatile double SIGFPE_REQ = 0.0f;
+
+static SOCKET
+ev_tcp_socket (void)
+{
+#if EV_USE_WSASOCKET
+ return WSASocket (AF_INET, SOCK_STREAM, 0, 0, 0, 0);
+#else
+ return socket (AF_INET, SOCK_STREAM, 0);
+#endif
+}
+
+/* oh, the humanity! */
+static int
+ev_pipe (int filedes [2])
+{
+ struct sockaddr_in addr = { 0 };
+ int addr_size = sizeof (addr);
+ struct sockaddr_in adr2;
+ int adr2_size = sizeof (adr2);
+ SOCKET listener;
+ SOCKET sock [2] = { -1, -1 };
+
+ if ((listener = ev_tcp_socket ()) == INVALID_SOCKET)
+ return -1;
+
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
+ addr.sin_port = 0;
+
+ if (bind (listener, (struct sockaddr *)&addr, addr_size))
+ goto fail;
+
+ if (getsockname (listener, (struct sockaddr *)&addr, &addr_size))
+ goto fail;
+
+ if (listen (listener, 1))
+ goto fail;
+
+ if ((sock [0] = ev_tcp_socket ()) == INVALID_SOCKET)
+ goto fail;
+
+ if (connect (sock [0], (struct sockaddr *)&addr, addr_size))
+ goto fail;
+
+ if ((sock [1] = accept (listener, 0, 0)) < 0)
+ goto fail;
+
+ /* windows vista returns fantasy port numbers for sockets:
+ * example for two interconnected tcp sockets:
+ *
+ * (Socket::unpack_sockaddr_in getsockname $sock0)[0] == 53364
+ * (Socket::unpack_sockaddr_in getpeername $sock0)[0] == 53363
+ * (Socket::unpack_sockaddr_in getsockname $sock1)[0] == 53363
+ * (Socket::unpack_sockaddr_in getpeername $sock1)[0] == 53365
+ *
+ * wow! tridirectional sockets!
+ *
+ * this way of checking ports seems to work:
+ */
+ if (getpeername (sock [0], (struct sockaddr *)&addr, &addr_size))
+ goto fail;
+
+ if (getsockname (sock [1], (struct sockaddr *)&adr2, &adr2_size))
+ goto fail;
+
+ errno = WSAEINVAL;
+ if (addr_size != adr2_size
+ || addr.sin_addr.s_addr != adr2.sin_addr.s_addr /* just to be sure, I mean, it's windows */
+ || addr.sin_port != adr2.sin_port)
+ goto fail;
+
+ closesocket (listener);
+
+#if EV_SELECT_IS_WINSOCKET
+ filedes [0] = EV_WIN32_HANDLE_TO_FD (sock [0]);
+ filedes [1] = EV_WIN32_HANDLE_TO_FD (sock [1]);
+#else
+ /* when select isn't winsocket, we also expect socket, connect, accept etc.
+ * to work on fds */
+ filedes [0] = sock [0];
+ filedes [1] = sock [1];
+#endif
+
+ return 0;
+
+fail:
+ closesocket (listener);
+
+ if (sock [0] != INVALID_SOCKET) closesocket (sock [0]);
+ if (sock [1] != INVALID_SOCKET) closesocket (sock [1]);
+
+ return -1;
+}
+
+#undef pipe
+#define pipe(filedes) ev_pipe (filedes)
+
+#define EV_HAVE_EV_TIME 1
+ev_tstamp
+ev_time (void)
+{
+ FILETIME ft;
+ ULARGE_INTEGER ui;
+
+ GetSystemTimeAsFileTime (&ft);
+ ui.u.LowPart = ft.dwLowDateTime;
+ ui.u.HighPart = ft.dwHighDateTime;
+
+ /* msvc cannot convert ulonglong to double... yes, it is that sucky */
+ return (LONGLONG)(ui.QuadPart - 116444736000000000) * 1e-7;
+}
+
+#endif
+
diff --git a/ext/libev/ev_wrap.h b/ext/libev/ev_wrap.h
new file mode 100644
index 0000000..ad989ea
--- /dev/null
+++ b/ext/libev/ev_wrap.h
@@ -0,0 +1,200 @@
+/* DO NOT EDIT, automatically generated by update_ev_wrap */
+#ifndef EV_WRAP_H
+#define EV_WRAP_H
+#define acquire_cb ((loop)->acquire_cb)
+#define activecnt ((loop)->activecnt)
+#define anfdmax ((loop)->anfdmax)
+#define anfds ((loop)->anfds)
+#define async_pending ((loop)->async_pending)
+#define asynccnt ((loop)->asynccnt)
+#define asyncmax ((loop)->asyncmax)
+#define asyncs ((loop)->asyncs)
+#define backend ((loop)->backend)
+#define backend_fd ((loop)->backend_fd)
+#define backend_mintime ((loop)->backend_mintime)
+#define backend_modify ((loop)->backend_modify)
+#define backend_poll ((loop)->backend_poll)
+#define checkcnt ((loop)->checkcnt)
+#define checkmax ((loop)->checkmax)
+#define checks ((loop)->checks)
+#define cleanupcnt ((loop)->cleanupcnt)
+#define cleanupmax ((loop)->cleanupmax)
+#define cleanups ((loop)->cleanups)
+#define curpid ((loop)->curpid)
+#define epoll_epermcnt ((loop)->epoll_epermcnt)
+#define epoll_epermmax ((loop)->epoll_epermmax)
+#define epoll_eperms ((loop)->epoll_eperms)
+#define epoll_eventmax ((loop)->epoll_eventmax)
+#define epoll_events ((loop)->epoll_events)
+#define evpipe ((loop)->evpipe)
+#define fdchangecnt ((loop)->fdchangecnt)
+#define fdchangemax ((loop)->fdchangemax)
+#define fdchanges ((loop)->fdchanges)
+#define forkcnt ((loop)->forkcnt)
+#define forkmax ((loop)->forkmax)
+#define forks ((loop)->forks)
+#define fs_2625 ((loop)->fs_2625)
+#define fs_fd ((loop)->fs_fd)
+#define fs_hash ((loop)->fs_hash)
+#define fs_w ((loop)->fs_w)
+#define idleall ((loop)->idleall)
+#define idlecnt ((loop)->idlecnt)
+#define idlemax ((loop)->idlemax)
+#define idles ((loop)->idles)
+#define invoke_cb ((loop)->invoke_cb)
+#define io_blocktime ((loop)->io_blocktime)
+#define iocp ((loop)->iocp)
+#define kqueue_changecnt ((loop)->kqueue_changecnt)
+#define kqueue_changemax ((loop)->kqueue_changemax)
+#define kqueue_changes ((loop)->kqueue_changes)
+#define kqueue_eventmax ((loop)->kqueue_eventmax)
+#define kqueue_events ((loop)->kqueue_events)
+#define kqueue_fd_pid ((loop)->kqueue_fd_pid)
+#define loop_count ((loop)->loop_count)
+#define loop_depth ((loop)->loop_depth)
+#define loop_done ((loop)->loop_done)
+#define mn_now ((loop)->mn_now)
+#define now_floor ((loop)->now_floor)
+#define origflags ((loop)->origflags)
+#define pending_w ((loop)->pending_w)
+#define pendingcnt ((loop)->pendingcnt)
+#define pendingmax ((loop)->pendingmax)
+#define pendingpri ((loop)->pendingpri)
+#define pendings ((loop)->pendings)
+#define periodiccnt ((loop)->periodiccnt)
+#define periodicmax ((loop)->periodicmax)
+#define periodics ((loop)->periodics)
+#define pipe_w ((loop)->pipe_w)
+#define pipe_write_skipped ((loop)->pipe_write_skipped)
+#define pipe_write_wanted ((loop)->pipe_write_wanted)
+#define pollcnt ((loop)->pollcnt)
+#define pollidxmax ((loop)->pollidxmax)
+#define pollidxs ((loop)->pollidxs)
+#define pollmax ((loop)->pollmax)
+#define polls ((loop)->polls)
+#define port_eventmax ((loop)->port_eventmax)
+#define port_events ((loop)->port_events)
+#define postfork ((loop)->postfork)
+#define preparecnt ((loop)->preparecnt)
+#define preparemax ((loop)->preparemax)
+#define prepares ((loop)->prepares)
+#define release_cb ((loop)->release_cb)
+#define rfeedcnt ((loop)->rfeedcnt)
+#define rfeedmax ((loop)->rfeedmax)
+#define rfeeds ((loop)->rfeeds)
+#define rtmn_diff ((loop)->rtmn_diff)
+#define sig_pending ((loop)->sig_pending)
+#define sigfd ((loop)->sigfd)
+#define sigfd_set ((loop)->sigfd_set)
+#define sigfd_w ((loop)->sigfd_w)
+#define timeout_blocktime ((loop)->timeout_blocktime)
+#define timercnt ((loop)->timercnt)
+#define timermax ((loop)->timermax)
+#define timers ((loop)->timers)
+#define userdata ((loop)->userdata)
+#define vec_eo ((loop)->vec_eo)
+#define vec_max ((loop)->vec_max)
+#define vec_ri ((loop)->vec_ri)
+#define vec_ro ((loop)->vec_ro)
+#define vec_wi ((loop)->vec_wi)
+#define vec_wo ((loop)->vec_wo)
+#else
+#undef EV_WRAP_H
+#undef acquire_cb
+#undef activecnt
+#undef anfdmax
+#undef anfds
+#undef async_pending
+#undef asynccnt
+#undef asyncmax
+#undef asyncs
+#undef backend
+#undef backend_fd
+#undef backend_mintime
+#undef backend_modify
+#undef backend_poll
+#undef checkcnt
+#undef checkmax
+#undef checks
+#undef cleanupcnt
+#undef cleanupmax
+#undef cleanups
+#undef curpid
+#undef epoll_epermcnt
+#undef epoll_epermmax
+#undef epoll_eperms
+#undef epoll_eventmax
+#undef epoll_events
+#undef evpipe
+#undef fdchangecnt
+#undef fdchangemax
+#undef fdchanges
+#undef forkcnt
+#undef forkmax
+#undef forks
+#undef fs_2625
+#undef fs_fd
+#undef fs_hash
+#undef fs_w
+#undef idleall
+#undef idlecnt
+#undef idlemax
+#undef idles
+#undef invoke_cb
+#undef io_blocktime
+#undef iocp
+#undef kqueue_changecnt
+#undef kqueue_changemax
+#undef kqueue_changes
+#undef kqueue_eventmax
+#undef kqueue_events
+#undef kqueue_fd_pid
+#undef loop_count
+#undef loop_depth
+#undef loop_done
+#undef mn_now
+#undef now_floor
+#undef origflags
+#undef pending_w
+#undef pendingcnt
+#undef pendingmax
+#undef pendingpri
+#undef pendings
+#undef periodiccnt
+#undef periodicmax
+#undef periodics
+#undef pipe_w
+#undef pipe_write_skipped
+#undef pipe_write_wanted
+#undef pollcnt
+#undef pollidxmax
+#undef pollidxs
+#undef pollmax
+#undef polls
+#undef port_eventmax
+#undef port_events
+#undef postfork
+#undef preparecnt
+#undef preparemax
+#undef prepares
+#undef release_cb
+#undef rfeedcnt
+#undef rfeedmax
+#undef rfeeds
+#undef rtmn_diff
+#undef sig_pending
+#undef sigfd
+#undef sigfd_set
+#undef sigfd_w
+#undef timeout_blocktime
+#undef timercnt
+#undef timermax
+#undef timers
+#undef userdata
+#undef vec_eo
+#undef vec_max
+#undef vec_ri
+#undef vec_ro
+#undef vec_wi
+#undef vec_wo
+#endif
diff --git a/ext/libev/test_libev_win32.c b/ext/libev/test_libev_win32.c
new file mode 100644
index 0000000..143ec68
--- /dev/null
+++ b/ext/libev/test_libev_win32.c
@@ -0,0 +1,123 @@
+ // a single header file is required
+ #include <ev.h>
+ #include <stdio.h>
+ #include <io.h>
+
+ // every watcher type has its own typedef'd struct
+ // with the name ev_TYPE
+ ev_io stdin_watcher;
+ ev_timer timeout_watcher;
+
+ // all watcher callbacks have a similar signature
+ // this callback is called when data is readable on stdin
+ static void
+ stdin_cb (EV_P_ ev_io *w, int revents)
+ {
+ puts ("stdin ready or done or something");
+ // for one-shot events, one must manually stop the watcher
+ // with its corresponding stop function.
+ //ev_io_stop (EV_A_ w);
+
+ // this causes all nested ev_loop's to stop iterating
+ //ev_unloop (EV_A_ EVUNLOOP_ALL);
+ }
+
+ // another callback, this time for a time-out
+ static void
+ timeout_cb (EV_P_ ev_timer *w, int revents)
+ {
+ puts ("timeout");
+ // this causes the innermost ev_loop to stop iterating
+ ev_unloop (EV_A_ EVUNLOOP_ONE);
+ }
+
+
+
+ #include <winsock.h>
+
+#include <stdlib.h>
+#include <iostream>
+ int get_server_fd()
+ {
+
+ //----------------------
+ // Initialize Winsock.
+ WSADATA wsaData;
+ int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
+ if (iResult != NO_ERROR) {
+ printf("Error at WSAStartup()\n");
+ return 1;
+ }
+
+ //----------------------
+ // Create a SOCKET for listening for
+ // incoming connection requests.
+ SOCKET ListenSocket;
+ ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (ListenSocket == INVALID_SOCKET) {
+ printf("Error at socket(): %ld\n", WSAGetLastError());
+ WSACleanup();
+ return 1;
+ }
+ printf("socket returned %d\n", ListenSocket);
+
+ //----------------------
+ // The sockaddr_in structure specifies the address family,
+ // IP address, and port for the socket that is being bound.
+ sockaddr_in service;
+ service.sin_family = AF_INET;
+ service.sin_addr.s_addr = inet_addr("127.0.0.1");
+ service.sin_port = htons(4444);
+
+ if (bind( ListenSocket,
+ (SOCKADDR*) &service,
+ sizeof(service)) == SOCKET_ERROR) {
+ printf("bind() failed.\n");
+ closesocket(ListenSocket);
+ WSACleanup();
+ return 1;
+ }
+
+ //----------------------
+ // Listen for incoming connection requests.
+ // on the created socket
+ if (listen( ListenSocket, 1 ) == SOCKET_ERROR) {
+ printf("Error listening on socket.\n");
+ closesocket(ListenSocket);
+ WSACleanup();
+ return 1;
+ }
+
+
+ printf("sock and osf handle are %d %d, error is \n", ListenSocket, _get_osfhandle (ListenSocket)); // -1 is invalid file handle: http://msdn.microsoft.com/en-us/library/ks2530z6.aspx
+ printf("err was %d\n", WSAGetLastError());
+ //----------------------
+ return ListenSocket;
+ }
+
+
+ int
+ main (void)
+ {
+ struct ev_loop *loopy = ev_default_loop(0);
+ int fd = get_server_fd();
+ int fd_real = _open_osfhandle(fd, NULL);
+ int conv = _get_osfhandle(fd_real);
+ printf("got server fd %d, loop %d, fd_real %d, that converted %d\n", fd, loopy, fd_real, conv);
+ // accept(fd, NULL, NULL);
+ // initialise an io watcher, then start it
+ // this one will watch for stdin to become readable
+ ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ conv, EV_READ);
+ ev_io_start (loopy, &stdin_watcher);
+
+ // initialise a timer watcher, then start it
+ // simple non-repeating 5.5 second timeout
+ //ev_timer_init (&timeout_watcher, timeout_cb, 15.5, 0.);
+ //ev_timer_start (loopy, &timeout_watcher);
+ printf("starting loop\n");
+ // now wait for events to arrive
+ ev_loop (loopy, 0);
+
+ // unloop was called, so exit
+ return 0;
+ }
diff --git a/ext/nio4r/extconf.rb b/ext/nio4r/extconf.rb
new file mode 100644
index 0000000..8c6cbd2
--- /dev/null
+++ b/ext/nio4r/extconf.rb
@@ -0,0 +1,44 @@
+require 'mkmf'
+
+if have_func('rb_thread_blocking_region')
+ $defs << '-DHAVE_RB_THREAD_BLOCKING_REGION'
+end
+
+if have_header('sys/select.h')
+ $defs << '-DEV_USE_SELECT'
+end
+
+if have_header('poll.h')
+ $defs << '-DEV_USE_POLL'
+end
+
+if have_header('sys/epoll.h')
+ $defs << '-DEV_USE_EPOLL'
+end
+
+if have_header('sys/event.h') and have_header('sys/queue.h')
+ $defs << '-DEV_USE_KQUEUE'
+end
+
+if have_header('port.h')
+ $defs << '-DEV_USE_PORT'
+end
+
+if have_header('sys/resource.h')
+ $defs << '-DHAVE_SYS_RESOURCE_H'
+end
+
+dir_config 'nio4r_ext'
+create_makefile 'nio4r_ext'
+
+# win32 needs to link in "just the right order" for some reason or ioctlsocket will be mapped to an [inverted] ruby specific version.
+# See libev mailing list for (not so helpful discussion--true cause I'm not sure, but this overcomes the symptom)
+if RUBY_PLATFORM =~ /mingw|win32/
+ makefile_contents = File.read 'Makefile'
+
+ # "Init_cool could not be found" when loading cool.io.so.
+ makefile_contents.gsub! 'DLDFLAGS = ', 'DLDFLAGS = -export-all '
+
+ makefile_contents.gsub! 'LIBS = $(LIBRUBYARG_SHARED)', 'LIBS = -lws2_32 $(LIBRUBYARG_SHARED)'
+ File.open('Makefile', 'w') { |f| f.write makefile_contents }
+end
\ No newline at end of file
diff --git a/ext/nio4r/libev.h b/ext/nio4r/libev.h
new file mode 100644
index 0000000..d4531dd
--- /dev/null
+++ b/ext/nio4r/libev.h
@@ -0,0 +1,9 @@
+#define EV_STANDALONE /* keeps ev from requiring config.h */
+
+#ifdef _WIN32
+#define EV_SELECT_IS_WINSOCKET 1
+#define EV_USE_MONOTONIC 0
+#define EV_USE_REALTIME 0
+#endif
+
+#include "../libev/ev.h"
\ No newline at end of file
diff --git a/ext/nio4r/monitor.c b/ext/nio4r/monitor.c
new file mode 100644
index 0000000..38ec4ee
--- /dev/null
+++ b/ext/nio4r/monitor.c
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2011 Tony Arcieri. Distributed under the MIT License. See
+ * LICENSE.txt for further details.
+ */
+
+#include "nio4r.h"
+
+static VALUE mNIO = Qnil;
+static VALUE cNIO_Monitor = Qnil;
+
+/* Allocator/deallocator */
+static VALUE NIO_Monitor_allocate(VALUE klass);
+static void NIO_Monitor_mark(struct NIO_Monitor *monitor);
+static void NIO_Monitor_free(struct NIO_Monitor *monitor);
+
+/* Methods */
+static VALUE NIO_Monitor_initialize(VALUE self, VALUE selector, VALUE io, VALUE interests);
+static VALUE NIO_Monitor_close(int argc, VALUE *argv, VALUE self);
+static VALUE NIO_Monitor_is_closed(VALUE self);
+static VALUE NIO_Monitor_io(VALUE self);
+static VALUE NIO_Monitor_interests(VALUE self);
+static VALUE NIO_Monitor_selector(VALUE self);
+static VALUE NIO_Monitor_is_readable(VALUE self);
+static VALUE NIO_Monitor_is_writable(VALUE self);
+static VALUE NIO_Monitor_value(VALUE self);
+static VALUE NIO_Monitor_set_value(VALUE self, VALUE obj);
+static VALUE NIO_Monitor_readiness(VALUE self);
+
+/* Internal functions */
+static void NIO_Monitor_callback(struct ev_loop *ev_loop, struct ev_io *io, int revents);
+
+#if HAVE_RB_IO_T
+ rb_io_t *fptr;
+#else
+ OpenFile *fptr;
+#endif
+
+/* Monitor control how a channel is being waited for by a monitor */
+void Init_NIO_Monitor()
+{
+ mNIO = rb_define_module("NIO");
+ cNIO_Monitor = rb_define_class_under(mNIO, "Monitor", rb_cObject);
+ rb_define_alloc_func(cNIO_Monitor, NIO_Monitor_allocate);
+
+ rb_define_method(cNIO_Monitor, "initialize", NIO_Monitor_initialize, 3);
+ rb_define_method(cNIO_Monitor, "close", NIO_Monitor_close, -1);
+ rb_define_method(cNIO_Monitor, "closed?", NIO_Monitor_is_closed, 0);
+ rb_define_method(cNIO_Monitor, "io", NIO_Monitor_io, 0);
+ rb_define_method(cNIO_Monitor, "interests", NIO_Monitor_interests, 0);
+ rb_define_method(cNIO_Monitor, "selector", NIO_Monitor_selector, 0);
+ rb_define_method(cNIO_Monitor, "value", NIO_Monitor_value, 0);
+ rb_define_method(cNIO_Monitor, "value=", NIO_Monitor_set_value, 1);
+ rb_define_method(cNIO_Monitor, "readiness", NIO_Monitor_readiness, 0);
+ rb_define_method(cNIO_Monitor, "readable?", NIO_Monitor_is_readable, 0);
+ rb_define_method(cNIO_Monitor, "writable?", NIO_Monitor_is_writable, 0);
+ rb_define_method(cNIO_Monitor, "writeable?", NIO_Monitor_is_writable, 0);
+}
+
+static VALUE NIO_Monitor_allocate(VALUE klass)
+{
+ struct NIO_Monitor *monitor = (struct NIO_Monitor *)xmalloc(sizeof(struct NIO_Monitor));
+
+ return Data_Wrap_Struct(klass, NIO_Monitor_mark, NIO_Monitor_free, monitor);
+}
+
+static void NIO_Monitor_mark(struct NIO_Monitor *monitor)
+{
+}
+
+static void NIO_Monitor_free(struct NIO_Monitor *monitor)
+{
+ xfree(monitor);
+}
+
+static VALUE NIO_Monitor_initialize(VALUE self, VALUE io, VALUE interests, VALUE selector_obj)
+{
+ struct NIO_Monitor *monitor;
+ struct NIO_Selector *selector;
+ ID interests_id;
+
+ #if HAVE_RB_IO_T
+ rb_io_t *fptr;
+ #else
+ OpenFile *fptr;
+ #endif
+
+ interests_id = SYM2ID(interests);
+
+ Data_Get_Struct(self, struct NIO_Monitor, monitor);
+
+ if(interests_id == rb_intern("r")) {
+ monitor->interests = EV_READ;
+ } else if(interests_id == rb_intern("w")) {
+ monitor->interests = EV_WRITE;
+ } else if(interests_id == rb_intern("rw")) {
+ monitor->interests = EV_READ | EV_WRITE;
+ } else {
+ rb_raise(rb_eArgError, "invalid event type %s (must be :r, :w, or :rw)",
+ RSTRING_PTR(rb_funcall(interests, rb_intern("inspect"), 0, 0)));
+ }
+
+ GetOpenFile(rb_convert_type(io, T_FILE, "IO", "to_io"), fptr);
+ ev_io_init(&monitor->ev_io, NIO_Selector_monitor_callback, FPTR_TO_FD(fptr), monitor->interests);
+
+ rb_ivar_set(self, rb_intern("io"), io);
+ rb_ivar_set(self, rb_intern("interests"), interests);
+ rb_ivar_set(self, rb_intern("selector"), selector_obj);
+
+ Data_Get_Struct(selector_obj, struct NIO_Selector, selector);
+
+ monitor->self = self;
+ monitor->ev_io.data = (void *)monitor;
+
+ /* We can safely hang onto this as we also hang onto a reference to the
+ object where it originally came from */
+ monitor->selector = selector;
+
+ ev_io_start(selector->ev_loop, &monitor->ev_io);
+
+ return Qnil;
+}
+
+static VALUE NIO_Monitor_close(int argc, VALUE *argv, VALUE self)
+{
+ VALUE deregister, selector;
+ struct NIO_Monitor *monitor;
+ Data_Get_Struct(self, struct NIO_Monitor, monitor);
+
+ rb_scan_args(argc, argv, "01", &deregister);
+ selector = rb_ivar_get(self, rb_intern("selector"));
+
+ if(selector != Qnil) {
+ ev_io_stop(monitor->selector->ev_loop, &monitor->ev_io);
+ monitor->selector = 0;
+ rb_ivar_set(self, rb_intern("selector"), Qnil);
+
+ /* Default value is true */
+ if(deregister == Qtrue || deregister == Qnil) {
+ rb_funcall(selector, rb_intern("deregister"), 1, rb_ivar_get(self, rb_intern("io")));
+ }
+ }
+
+ return Qnil;
+}
+
+static VALUE NIO_Monitor_is_closed(VALUE self)
+{
+ struct NIO_Monitor *monitor;
+ Data_Get_Struct(self, struct NIO_Monitor, monitor);
+
+ return !monitor->selector;
+}
+
+static VALUE NIO_Monitor_io(VALUE self)
+{
+ return rb_ivar_get(self, rb_intern("io"));
+}
+
+static VALUE NIO_Monitor_interests(VALUE self)
+{
+ return rb_ivar_get(self, rb_intern("interests"));
+}
+
+static VALUE NIO_Monitor_selector(VALUE self)
+{
+ return rb_ivar_get(self, rb_intern("selector"));
+}
+
+static VALUE NIO_Monitor_value(VALUE self)
+{
+ return rb_ivar_get(self, rb_intern("value"));
+}
+
+static VALUE NIO_Monitor_set_value(VALUE self, VALUE obj)
+{
+ return rb_ivar_set(self, rb_intern("value"), obj);
+}
+
+static VALUE NIO_Monitor_readiness(VALUE self)
+{
+ struct NIO_Monitor *monitor;
+ Data_Get_Struct(self, struct NIO_Monitor, monitor);
+
+ if((monitor->revents & (EV_READ | EV_WRITE)) == (EV_READ | EV_WRITE)) {
+ return ID2SYM(rb_intern("rw"));
+ } else if(monitor->revents & EV_READ) {
+ return ID2SYM(rb_intern("r"));
+ } else if(monitor->revents & EV_WRITE) {
+ return ID2SYM(rb_intern("w"));
+ } else {
+ return Qnil;
+ }
+}
+
+static VALUE NIO_Monitor_is_readable(VALUE self)
+{
+ struct NIO_Monitor *monitor;
+ Data_Get_Struct(self, struct NIO_Monitor, monitor);
+
+ if(monitor->revents & EV_READ) {
+ return Qtrue;
+ } else {
+ return Qfalse;
+ }
+}
+
+static VALUE NIO_Monitor_is_writable(VALUE self)
+{
+ struct NIO_Monitor *monitor;
+ Data_Get_Struct(self, struct NIO_Monitor, monitor);
+
+ if(monitor->revents & EV_WRITE) {
+ return Qtrue;
+ } else {
+ return Qfalse;
+ }
+}
\ No newline at end of file
diff --git a/ext/nio4r/nio4r.h b/ext/nio4r/nio4r.h
new file mode 100644
index 0000000..603d0a5
--- /dev/null
+++ b/ext/nio4r/nio4r.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2011 Tony Arcieri. Distributed under the MIT License. See
+ * LICENSE.txt for further details.
+ */
+
+#ifndef NIO4R_H
+#define NIO4R_H
+
+#include "ruby.h"
+#include "rubyio.h"
+#include "libev.h"
+
+struct NIO_Selector
+{
+ struct ev_loop *ev_loop;
+ struct ev_timer timer; /* for timeouts */
+ struct ev_io wakeup;
+
+ int wakeup_reader, wakeup_writer;
+ int closed, selecting;
+ int ready_count;
+
+ VALUE ready_array;
+};
+
+struct NIO_callback_data
+{
+ VALUE *monitor;
+ struct NIO_Selector *selector;
+};
+
+struct NIO_Monitor
+{
+ VALUE self;
+ int interests, revents;
+ struct ev_io ev_io;
+ struct NIO_Selector *selector;
+};
+
+#ifdef GetReadFile
+# define FPTR_TO_FD(fptr) (fileno(GetReadFile(fptr)))
+#else
+
+#if !HAVE_RB_IO_T || (RUBY_VERSION_MAJOR == 1 && RUBY_VERSION_MINOR == 8)
+# define FPTR_TO_FD(fptr) fileno(fptr->f)
+#else
+# define FPTR_TO_FD(fptr) fptr->fd
+#endif /* !HAVE_RB_IO_T */
+
+#endif /* GetReadFile */
+
+/* Thunk between libev callbacks in NIO::Monitors and NIO::Selectors */
+void NIO_Selector_monitor_callback(struct ev_loop *ev_loop, struct ev_io *io, int revents);
+
+#endif /* NIO4R_H */
diff --git a/ext/nio4r/nio4r_ext.c b/ext/nio4r/nio4r_ext.c
new file mode 100644
index 0000000..9e87209
--- /dev/null
+++ b/ext/nio4r/nio4r_ext.c
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2011 Tony Arcieri. Distributed under the MIT License. See
+ * LICENSE.txt for further details.
+ */
+
+#include "nio4r.h"
+#include "../libev/ev.c"
+
+void Init_NIO_Selector();
+void Init_NIO_Monitor();
+
+void Init_nio4r_ext()
+{
+ Init_NIO_Selector();
+ Init_NIO_Monitor();
+}
diff --git a/ext/nio4r/org/nio4r/Nio4r.java b/ext/nio4r/org/nio4r/Nio4r.java
new file mode 100644
index 0000000..a5da013
--- /dev/null
+++ b/ext/nio4r/org/nio4r/Nio4r.java
@@ -0,0 +1,433 @@
+package org.nio4r;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.HashMap;
+import java.io.IOException;
+import java.nio.channels.Channel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
+import org.jruby.Ruby;
+import org.jruby.RubyModule;
+import org.jruby.RubyClass;
+import org.jruby.RubyObject;
+import org.jruby.RubyIO;
+import org.jruby.RubyNumeric;
+import org.jruby.RubyArray;
+import org.jruby.anno.JRubyMethod;
+import org.jruby.runtime.ObjectAllocator;
+import org.jruby.runtime.ThreadContext;
+import org.jruby.runtime.load.Library;
+import org.jruby.runtime.builtin.IRubyObject;
+import org.jruby.runtime.Block;
+
+public class Nio4r implements Library {
+ private Ruby ruby;
+
+ public void load(final Ruby ruby, boolean bln) {
+ this.ruby = ruby;
+
+ RubyModule nio = ruby.defineModule("NIO");
+
+ RubyClass selector = ruby.defineClassUnder("Selector", ruby.getObject(), new ObjectAllocator() {
+ public IRubyObject allocate(Ruby ruby, RubyClass rc) {
+ return new Selector(ruby, rc);
+ }
+ }, nio);
+
+ selector.defineAnnotatedMethods(Selector.class);
+
+ RubyClass monitor = ruby.defineClassUnder("Monitor", ruby.getObject(), new ObjectAllocator() {
+ public IRubyObject allocate(Ruby ruby, RubyClass rc) {
+ return new Monitor(ruby, rc);
+ }
+ }, nio);
+
+ monitor.defineAnnotatedMethods(Monitor.class);
+ }
+
+ public static int symbolToInterestOps(Ruby ruby, SelectableChannel channel, IRubyObject interest) {
+ if(interest == ruby.newSymbol("r")) {
+ if((channel.validOps() & SelectionKey.OP_ACCEPT) != 0) {
+ return SelectionKey.OP_ACCEPT;
+ } else {
+ return SelectionKey.OP_READ;
+ }
+ } else if(interest == ruby.newSymbol("w")) {
+ if(channel instanceof SocketChannel && !((SocketChannel)channel).isConnected()) {
+ return SelectionKey.OP_CONNECT;
+ } else {
+ return SelectionKey.OP_WRITE;
+ }
+ } else if(interest == ruby.newSymbol("rw")) {
+ int interestOps = 0;
+
+ /* nio4r emulates the POSIX behavior, which is sloppy about allowed modes */
+ if((channel.validOps() & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) {
+ interestOps |= symbolToInterestOps(ruby, channel, ruby.newSymbol("r"));
+ }
+
+ if((channel.validOps() & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) {
+ interestOps |= symbolToInterestOps(ruby, channel, ruby.newSymbol("w"));
+ }
+
+ return interestOps;
+ } else {
+ throw ruby.newArgumentError("invalid interest type: " + interest);
+ }
+ }
+
+ public static IRubyObject interestOpsToSymbol(Ruby ruby, int interestOps) {
+ switch(interestOps) {
+ case SelectionKey.OP_READ:
+ case SelectionKey.OP_ACCEPT:
+ return ruby.newSymbol("r");
+ case SelectionKey.OP_WRITE:
+ case SelectionKey.OP_CONNECT:
+ return ruby.newSymbol("w");
+ case SelectionKey.OP_READ | SelectionKey.OP_CONNECT:
+ case SelectionKey.OP_READ | SelectionKey.OP_WRITE:
+ return ruby.newSymbol("rw");
+ default:
+ throw ruby.newArgumentError("unknown interest op combination");
+ }
+ }
+
+ public class Selector extends RubyObject {
+ private java.nio.channels.Selector selector;
+ private HashMap<SelectableChannel,SelectionKey> cancelledKeys;
+
+ public Selector(final Ruby ruby, RubyClass rubyClass) {
+ super(ruby, rubyClass);
+ }
+
+ @JRubyMethod
+ public IRubyObject initialize(ThreadContext context) {
+ this.cancelledKeys = new HashMap<SelectableChannel,SelectionKey>();
+ try {
+ this.selector = java.nio.channels.Selector.open();
+ } catch(IOException ie) {
+ throw context.runtime.newIOError(ie.getLocalizedMessage());
+ }
+
+ return context.nil;
+ }
+
+ @JRubyMethod
+ public IRubyObject close(ThreadContext context) {
+ try {
+ this.selector.close();
+ } catch(IOException ie) {
+ throw context.runtime.newIOError(ie.getLocalizedMessage());
+ }
+
+ return context.nil;
+ }
+
+ @JRubyMethod(name = "closed?")
+ public IRubyObject isClosed(ThreadContext context) {
+ Ruby runtime = context.getRuntime();
+ return this.selector.isOpen() ? runtime.getFalse() : runtime.getTrue();
+ }
+
+ @JRubyMethod(name = "empty?")
+ public IRubyObject isEmpty(ThreadContext context) {
+ Ruby runtime = context.getRuntime();
+ return this.selector.keys().isEmpty() ? runtime.getTrue() : runtime.getFalse();
+ }
+
+ @JRubyMethod
+ public IRubyObject register(ThreadContext context, IRubyObject io, IRubyObject interests) {
+ Ruby runtime = context.getRuntime();
+ Channel rawChannel = RubyIO.convertToIO(context, io).getChannel();
+
+ if(!this.selector.isOpen()) {
+ throw context.getRuntime().newIOError("selector is closed");
+ }
+
+ if(!(rawChannel instanceof SelectableChannel)) {
+ throw runtime.newArgumentError("not a selectable IO object");
+ }
+
+ SelectableChannel channel = (SelectableChannel)rawChannel;
+
+ try {
+ channel.configureBlocking(false);
+ } catch(IOException ie) {
+ throw runtime.newIOError(ie.getLocalizedMessage());
+ }
+
+ int interestOps = Nio4r.symbolToInterestOps(runtime, channel, interests);
+ SelectionKey key;
+
+ key = this.cancelledKeys.remove(channel);
+
+ if(key != null) {
+ key.interestOps(interestOps);
+ } else {
+ try {
+ key = channel.register(this.selector, interestOps);
+ } catch(java.lang.IllegalArgumentException ia) {
+ throw runtime.newArgumentError("mode not supported for this object: " + interests);
+ } catch(java.nio.channels.ClosedChannelException cce) {
+ throw context.runtime.newIOError(cce.getLocalizedMessage());
+ }
+ }
+
+ RubyClass monitorClass = runtime.getModule("NIO").getClass("Monitor");
+ Monitor monitor = (Monitor)monitorClass.newInstance(context, io, interests, this, null);
+ monitor.setSelectionKey(key);
+
+ return monitor;
+ }
+
+ @JRubyMethod
+ public IRubyObject deregister(ThreadContext context, IRubyObject io) {
+ Ruby runtime = context.getRuntime();
+ Channel rawChannel = RubyIO.convertToIO(context, io).getChannel();
+
+ if(!(rawChannel instanceof SelectableChannel)) {
+ throw runtime.newArgumentError("not a selectable IO object");
+ }
+
+ SelectableChannel channel = (SelectableChannel)rawChannel;
+ SelectionKey key = channel.keyFor(this.selector);
+
+ if(key == null)
+ return context.nil;
+
+ Monitor monitor = (Monitor)key.attachment();
+ monitor.close(context, runtime.getFalse());
+ cancelledKeys.put(channel, key);
+
+ return monitor;
+ }
+
+ @JRubyMethod(name = "registered?")
+ public IRubyObject isRegistered(ThreadContext context, IRubyObject io) {
+ Ruby runtime = context.getRuntime();
+ Channel rawChannel = RubyIO.convertToIO(context, io).getChannel();
+
+ if(!(rawChannel instanceof SelectableChannel)) {
+ throw runtime.newArgumentError("not a selectable IO object");
+ }
+
+ SelectableChannel channel = (SelectableChannel)rawChannel;
+ SelectionKey key = channel.keyFor(this.selector);
+
+ if(key == null)
+ return context.nil;
+
+
+ if(((Monitor)key.attachment()).isClosed(context) == runtime.getTrue()) {
+ return runtime.getFalse();
+ } else {
+ return runtime.getTrue();
+ }
+ }
+
+ @JRubyMethod
+ public synchronized IRubyObject select(ThreadContext context, Block block) {
+ return select(context, context.nil, block);
+ }
+
+ @JRubyMethod
+ public synchronized IRubyObject select(ThreadContext context, IRubyObject timeout, Block block) {
+ Ruby runtime = context.getRuntime();
+ int ready = doSelect(runtime, context, timeout);
+
+ /* Timeout or wakeup */
+ if(ready <= 0)
+ return context.nil;
+
+ RubyArray array = null;
+ if(!block.isGiven()) {
+ array = runtime.newArray(this.selector.selectedKeys().size());
+ }
+
+ Iterator selectedKeys = this.selector.selectedKeys().iterator();
+ while(selectedKeys.hasNext()) {
+ SelectionKey key = (SelectionKey)selectedKeys.next();
+ processKey(key);
+ selectedKeys.remove();
+
+ if(block.isGiven()) {
+ block.call(context, (IRubyObject)key.attachment());
+ } else {
+ array.add(key.attachment());
+ }
+ }
+
+ if(block.isGiven()) {
+ return RubyNumeric.int2fix(runtime, ready);
+ } else {
+ return array;
+ }
+ }
+
+ /* Run the selector */
+ private int doSelect(Ruby runtime, ThreadContext context, IRubyObject timeout) {
+ int result;
+
+ cancelKeys();
+ try {
+ context.getThread().beforeBlockingCall();
+ if(timeout.isNil()) {
+ result = this.selector.select();
+ } else {
+ double t = RubyNumeric.num2dbl(timeout);
+ if(t == 0) {
+ result = this.selector.selectNow();
+ } else if(t < 0) {
+ throw runtime.newArgumentError("time interval must be positive");
+ } else {
+ result = this.selector.select((long)(t * 1000));
+ }
+ }
+ context.getThread().afterBlockingCall();
+ return result;
+ } catch(IOException ie) {
+ throw runtime.newIOError(ie.getLocalizedMessage());
+ }
+ }
+
+ /* Flush our internal buffer of cancelled keys */
+ private void cancelKeys() {
+ Iterator cancelledKeys = this.cancelledKeys.entrySet().iterator();
+ while(cancelledKeys.hasNext()) {
+ Map.Entry entry = (Map.Entry)cancelledKeys.next();
+ SelectionKey key = (SelectionKey)entry.getValue();
+ key.cancel();
+ cancelledKeys.remove();
+ }
+ }
+
+ // Remove connect interest from connected sockets
+ // See: http://stackoverflow.com/questions/204186/java-nio-select-returns-without-selected-keys-why
+ private void processKey(SelectionKey key) {
+ if((key.readyOps() & SelectionKey.OP_CONNECT) != 0) {
+ int interestOps = key.interestOps();
+
+ interestOps &= ~SelectionKey.OP_CONNECT;
+ interestOps |= SelectionKey.OP_WRITE;
+
+ key.interestOps(interestOps);
+ }
+ }
+
+ @JRubyMethod
+ public IRubyObject wakeup(ThreadContext context) {
+ if(!this.selector.isOpen()) {
+ throw context.getRuntime().newIOError("selector is closed");
+ }
+
+ this.selector.wakeup();
+ return context.nil;
+ }
+ }
+
+ public class Monitor extends RubyObject {
+ private SelectionKey key;
+ private RubyIO io;
+ private IRubyObject interests, selector, value, closed;
+
+ public Monitor(final Ruby ruby, RubyClass rubyClass) {
+ super(ruby, rubyClass);
+ }
+
+ @JRubyMethod
+ public IRubyObject initialize(ThreadContext context, IRubyObject selectable, IRubyObject interests, IRubyObject selector) {
+ this.io = RubyIO.convertToIO(context, selectable);
+ this.interests = interests;
+ this.selector = selector;
+
+ this.value = context.nil;
+ this.closed = context.getRuntime().getFalse();
+
+ return context.nil;
+ }
+
+ public void setSelectionKey(SelectionKey key) {
+ this.key = key;
+ key.attach(this);
+ }
+
+ @JRubyMethod
+ public IRubyObject io(ThreadContext context) {
+ return io;
+ }
+
+ @JRubyMethod
+ public IRubyObject selector(ThreadContext context) {
+ return selector;
+ }
+
+ @JRubyMethod
+ public IRubyObject interests(ThreadContext context) {
+ return interests;
+ }
+
+ @JRubyMethod
+ public IRubyObject readiness(ThreadContext context) {
+ return Nio4r.interestOpsToSymbol(context.getRuntime(), key.readyOps());
+ }
+
+ @JRubyMethod(name = "readable?")
+ public IRubyObject isReadable(ThreadContext context) {
+ Ruby runtime = context.getRuntime();
+ int readyOps = this.key.readyOps();
+
+ if((readyOps & SelectionKey.OP_READ) != 0 || (readyOps & SelectionKey.OP_ACCEPT) != 0) {
+ return runtime.getTrue();
+ } else {
+ return runtime.getFalse();
+ }
+ }
+
+ @JRubyMethod(name = {"writable?", "writeable?"})
+ public IRubyObject writable(ThreadContext context) {
+ Ruby runtime = context.getRuntime();
+ int readyOps = this.key.readyOps();
+
+ if((readyOps & SelectionKey.OP_WRITE) != 0 || (readyOps & SelectionKey.OP_CONNECT) != 0) {
+ return runtime.getTrue();
+ } else {
+ return runtime.getFalse();
+ }
+ }
+
+ @JRubyMethod(name = "value")
+ public IRubyObject getValue(ThreadContext context) {
+ return this.value;
+ }
+
+ @JRubyMethod(name = "value=")
+ public IRubyObject setValue(ThreadContext context, IRubyObject obj) {
+ this.value = obj;
+ return context.nil;
+ }
+
+ @JRubyMethod
+ public IRubyObject close(ThreadContext context) {
+ return close(context, context.getRuntime().getTrue());
+ }
+
+ @JRubyMethod
+ public IRubyObject close(ThreadContext context, IRubyObject deregister) {
+ Ruby runtime = context.getRuntime();
+ this.closed = runtime.getTrue();
+
+ if(deregister == runtime.getTrue()) {
+ selector.callMethod(context, "deregister", io);
+ }
+
+ return context.nil;
+ }
+
+ @JRubyMethod(name = "closed?")
+ public IRubyObject isClosed(ThreadContext context) {
+ return this.closed;
+ }
+ }
+}
diff --git a/ext/nio4r/selector.c b/ext/nio4r/selector.c
new file mode 100644
index 0000000..af9b61b
--- /dev/null
+++ b/ext/nio4r/selector.c
@@ -0,0 +1,461 @@
+/*
+ * Copyright (c) 2011 Tony Arcieri. Distributed under the MIT License. See
+ * LICENSE.txt for further details.
+ */
+
+#include "nio4r.h"
+#include "rubysig.h"
+#include <unistd.h>
+#include <fcntl.h>
+#include <assert.h>
+
+static VALUE mNIO = Qnil;
+static VALUE cNIO_Monitor = Qnil;
+static VALUE cNIO_Selector = Qnil;
+
+/* Allocator/deallocator */
+static VALUE NIO_Selector_allocate(VALUE klass);
+static void NIO_Selector_mark(struct NIO_Selector *loop);
+static void NIO_Selector_shutdown(struct NIO_Selector *selector);
+static void NIO_Selector_free(struct NIO_Selector *loop);
+
+/* Methods */
+static VALUE NIO_Selector_initialize(VALUE self);
+static VALUE NIO_Selector_register(VALUE self, VALUE selectable, VALUE interest);
+static VALUE NIO_Selector_deregister(VALUE self, VALUE io);
+static VALUE NIO_Selector_is_registered(VALUE self, VALUE io);
+static VALUE NIO_Selector_select(int argc, VALUE *argv, VALUE self);
+static VALUE NIO_Selector_wakeup(VALUE self);
+static VALUE NIO_Selector_close(VALUE self);
+static VALUE NIO_Selector_closed(VALUE self);
+static VALUE NIO_Selector_is_empty(VALUE self);
+
+/* Internal functions */
+static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args);
+static VALUE NIO_Selector_unlock(VALUE lock);
+static VALUE NIO_Selector_register_synchronized(VALUE *args);
+static VALUE NIO_Selector_deregister_synchronized(VALUE *args);
+static VALUE NIO_Selector_select_synchronized(VALUE *args);
+static VALUE NIO_Selector_close_synchronized(VALUE self);
+static VALUE NIO_Selector_closed_synchronized(VALUE self);
+
+static int NIO_Selector_run(struct NIO_Selector *selector, VALUE timeout);
+static void NIO_Selector_timeout_callback(struct ev_loop *ev_loop, struct ev_timer *timer, int revents);
+static void NIO_Selector_wakeup_callback(struct ev_loop *ev_loop, struct ev_io *io, int revents);
+
+/* Default number of slots in the buffer for selected monitors */
+#define INITIAL_READY_BUFFER 32
+
+/* Ruby 1.8 needs us to busy wait and run the green threads scheduler every 10ms */
+#define BUSYWAIT_INTERVAL 0.01
+
+/* Selectors wait for events */
+void Init_NIO_Selector()
+{
+ mNIO = rb_define_module("NIO");
+ cNIO_Selector = rb_define_class_under(mNIO, "Selector", rb_cObject);
+ rb_define_alloc_func(cNIO_Selector, NIO_Selector_allocate);
+
+ rb_define_method(cNIO_Selector, "initialize", NIO_Selector_initialize, 0);
+ rb_define_method(cNIO_Selector, "register", NIO_Selector_register, 2);
+ rb_define_method(cNIO_Selector, "deregister", NIO_Selector_deregister, 1);
+ rb_define_method(cNIO_Selector, "registered?", NIO_Selector_is_registered, 1);
+ rb_define_method(cNIO_Selector, "select", NIO_Selector_select, -1);
+ rb_define_method(cNIO_Selector, "wakeup", NIO_Selector_wakeup, 0);
+ rb_define_method(cNIO_Selector, "close", NIO_Selector_close, 0);
+ rb_define_method(cNIO_Selector, "closed?", NIO_Selector_closed, 0);
+ rb_define_method(cNIO_Selector, "empty?", NIO_Selector_is_empty, 0);
+
+ cNIO_Monitor = rb_define_class_under(mNIO, "Monitor", rb_cObject);
+}
+
+/* Create the libev event loop and incoming event buffer */
+static VALUE NIO_Selector_allocate(VALUE klass)
+{
+ struct NIO_Selector *selector;
+ int fds[2];
+
+ /* Use a pipe to implement the wakeup mechanism. I know libev provides
+ async watchers that implement this same behavior, but I'm getting
+ segvs trying to use that between threads, despite claims of thread
+ safety. Pipes are nice and safe to use between threads.
+
+ Note that Java NIO uses this same mechanism */
+ if(pipe(fds) < 0) {
+ rb_sys_fail("pipe");
+ }
+
+ if(fcntl(fds[0], F_SETFL, O_NONBLOCK) < 0) {
+ rb_sys_fail("fcntl");
+ }
+
+ selector = (struct NIO_Selector *)xmalloc(sizeof(struct NIO_Selector));
+ selector->ev_loop = ev_loop_new(0);
+ ev_init(&selector->timer, NIO_Selector_timeout_callback);
+
+ selector->wakeup_reader = fds[0];
+ selector->wakeup_writer = fds[1];
+
+ ev_io_init(&selector->wakeup, NIO_Selector_wakeup_callback, selector->wakeup_reader, EV_READ);
+ selector->wakeup.data = (void *)selector;
+ ev_io_start(selector->ev_loop, &selector->wakeup);
+
+ selector->closed = selector->selecting = selector->ready_count = 0;
+ selector->ready_array = Qnil;
+
+ return Data_Wrap_Struct(klass, NIO_Selector_mark, NIO_Selector_free, selector);
+}
+
+/* NIO selectors store all Ruby objects in instance variables so mark is a stub */
+static void NIO_Selector_mark(struct NIO_Selector *selector)
+{
+ if(selector->ready_array != Qnil) {
+ rb_gc_mark(selector->ready_array);
+ }
+}
+
+/* Free a Selector's system resources.
+ Called by both NIO::Selector#close and the finalizer below */
+static void NIO_Selector_shutdown(struct NIO_Selector *selector)
+{
+ if(selector->closed) {
+ return;
+ }
+
+ close(selector->wakeup_reader);
+ close(selector->wakeup_writer);
+
+ if(selector->ev_loop) {
+ ev_loop_destroy(selector->ev_loop);
+ selector->ev_loop = 0;
+ }
+ selector->closed = 1;
+}
+
+/* Ruby finalizer for selector objects */
+static void NIO_Selector_free(struct NIO_Selector *selector)
+{
+ NIO_Selector_shutdown(selector);
+ xfree(selector);
+}
+
+/* Create a new selector. This is more or less the pure Ruby version
+ translated into an MRI cext */
+static VALUE NIO_Selector_initialize(VALUE self)
+{
+ VALUE lock;
+
+ rb_ivar_set(self, rb_intern("selectables"), rb_hash_new());
+
+ lock = rb_class_new_instance(0, 0, rb_const_get(rb_cObject, rb_intern("Mutex")));
+ rb_ivar_set(self, rb_intern("lock"), lock);
+
+ return Qnil;
+}
+
+/* Synchronize around a reentrant selector lock */
+static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args)
+{
+ VALUE current_thread, lock_holder, lock;
+
+ current_thread = rb_thread_current();
+ lock_holder = rb_ivar_get(self, rb_intern("lock_holder"));
+
+ if(lock_holder != rb_thread_current()) {
+ lock = rb_ivar_get(self, rb_intern("lock"));
+ rb_funcall(lock, rb_intern("lock"), 0, 0);
+ rb_ivar_set(self, rb_intern("lock_holder"), rb_thread_current());
+
+ /* We've acquired the lock, so ensure we unlock it */
+ return rb_ensure(func, (VALUE)args, NIO_Selector_unlock, self);
+ } else {
+ /* We already hold the selector lock, so no need to unlock it */
+ return func(args);
+ }
+}
+
+/* Unlock the selector mutex */
+static VALUE NIO_Selector_unlock(VALUE self)
+{
+ VALUE lock;
+
+ rb_ivar_set(self, rb_intern("lock_holder"), Qnil);
+
+ lock = rb_ivar_get(self, rb_intern("lock"));
+ rb_funcall(lock, rb_intern("unlock"), 0, 0);
+
+ return Qnil;
+}
+
+/* Register an IO object with the selector for the given interests */
+static VALUE NIO_Selector_register(VALUE self, VALUE io, VALUE interests)
+{
+ VALUE args[3] = {self, io, interests};
+ return NIO_Selector_synchronize(self, NIO_Selector_register_synchronized, args);
+}
+
+/* Internal implementation of register after acquiring mutex */
+static VALUE NIO_Selector_register_synchronized(VALUE *args)
+{
+ VALUE self, io, interests, selectables, monitor;
+ VALUE monitor_args[3];
+ struct NIO_Selector *selector;
+
+ self = args[0];
+ io = args[1];
+ interests = args[2];
+
+ Data_Get_Struct(self, struct NIO_Selector, selector);
+ if(selector->closed) {
+ rb_raise(rb_eIOError, "selector is closed");
+ }
+
+ selectables = rb_ivar_get(self, rb_intern("selectables"));
+ monitor = rb_hash_lookup(selectables, io);
+
+ if(monitor != Qnil)
+ rb_raise(rb_eArgError, "this IO is already registered with selector");
+
+ /* Create a new NIO::Monitor */
+ monitor_args[0] = io;
+ monitor_args[1] = interests;
+ monitor_args[2] = self;
+
+ monitor = rb_class_new_instance(3, monitor_args, cNIO_Monitor);
+ rb_hash_aset(selectables, rb_funcall(monitor, rb_intern("io"), 0), monitor);
+
+ return monitor;
+}
+
+/* Deregister an IO object from the selector */
+static VALUE NIO_Selector_deregister(VALUE self, VALUE io)
+{
+ VALUE args[2] = {self, io};
+ return NIO_Selector_synchronize(self, NIO_Selector_deregister_synchronized, args);
+}
+
+/* Internal implementation of register after acquiring mutex */
+static VALUE NIO_Selector_deregister_synchronized(VALUE *args)
+{
+ VALUE self, io, interests, selectables, monitor;
+ VALUE monitor_args[3];
+
+ self = args[0];
+ io = args[1];
+
+ selectables = rb_ivar_get(self, rb_intern("selectables"));
+ monitor = rb_hash_delete(selectables, io);
+
+ if(monitor != Qnil) {
+ rb_funcall(monitor, rb_intern("close"), 1, Qfalse);
+ }
+
+ return monitor;
+}
+
+/* Is the given IO object registered with the selector */
+static VALUE NIO_Selector_is_registered(VALUE self, VALUE io)
+{
+ VALUE selectables = rb_ivar_get(self, rb_intern("selectables"));
+
+ /* Perhaps this should be holding the mutex? */
+ return rb_funcall(selectables, rb_intern("has_key?"), 1, io);
+}
+
+/* Select from all registered IO objects */
+static VALUE NIO_Selector_select(int argc, VALUE *argv, VALUE self)
+{
+ VALUE timeout, array;
+ VALUE args[2];
+
+ rb_scan_args(argc, argv, "01", &timeout);
+
+ if(timeout != Qnil && NUM2DBL(timeout) < 0) {
+ rb_raise(rb_eArgError, "time interval must be positive");
+ }
+
+ args[0] = self;
+ args[1] = timeout;
+
+ return NIO_Selector_synchronize(self, NIO_Selector_select_synchronized, args);
+}
+
+/* Internal implementation of select with the selector lock held */
+static VALUE NIO_Selector_select_synchronized(VALUE *args)
+{
+ int i, ready;
+ VALUE ready_array;
+ struct NIO_Selector *selector;
+
+ Data_Get_Struct(args[0], struct NIO_Selector, selector);
+ if(!rb_block_given_p()) {
+ selector->ready_array = rb_ary_new();
+ }
+
+ ready = NIO_Selector_run(selector, args[1]);
+ if(ready > 0) {
+ if(rb_block_given_p()) {
+ return INT2NUM(ready);
+ } else {
+ ready_array = selector->ready_array;
+ selector->ready_array = Qnil;
+ return ready_array;
+ }
+ } else {
+ selector->ready_array = Qnil;
+ return Qnil;
+ }
+}
+
+static int NIO_Selector_run(struct NIO_Selector *selector, VALUE timeout)
+{
+ int result;
+ selector->selecting = 1;
+
+#if defined(HAVE_RB_THREAD_BLOCKING_REGION) || defined(HAVE_RB_THREAD_ALONE)
+ /* Implement the optional timeout (if any) as a ev_timer */
+ if(timeout != Qnil) {
+ /* It seems libev is not a fan of timers being zero, so fudge a little */
+ selector->timer.repeat = NUM2DBL(timeout) + 0.0001;
+ ev_timer_again(selector->ev_loop, &selector->timer);
+ } else {
+ ev_timer_stop(selector->ev_loop, &selector->timer);
+ }
+#else
+ /* Store when we started the loop so we can calculate the timeout */
+ ev_tstamp started_at = ev_now(selector->ev_loop);
+#endif
+
+#if defined(HAVE_RB_THREAD_BLOCKING_REGION)
+ /* libev is patched to release the GIL when it makes its system call */
+ ev_loop(selector->ev_loop, EVLOOP_ONESHOT);
+#elif defined(HAVE_RB_THREAD_ALONE)
+ /* If we're the only thread we can make a blocking system call */
+ if(rb_thread_alone()) {
+#else
+ /* If we don't have rb_thread_alone() we can't block */
+ if(0) {
+#endif /* defined(HAVE_RB_THREAD_BLOCKING_REGION) */
+
+#if !defined(HAVE_RB_THREAD_BLOCKING_REGION)
+ TRAP_BEG;
+ ev_loop(selector->ev_loop, EVLOOP_ONESHOT);
+ TRAP_END;
+ } else {
+ /* We need to busy wait as not to stall the green thread scheduler
+ Ruby 1.8: just say no! :( */
+ ev_timer_init(&selector->timer, NIO_Selector_timeout_callback, BUSYWAIT_INTERVAL, BUSYWAIT_INTERVAL);
+ ev_timer_start(selector->ev_loop, &selector->timer);
+
+ /* Loop until we receive events */
+ while(selector->selecting && !selector->ready_count) {
+ TRAP_BEG;
+ ev_loop(selector->ev_loop, EVLOOP_ONESHOT);
+ TRAP_END;
+
+ /* Run the next green thread */
+ rb_thread_schedule();
+
+ /* Break if the timeout has elapsed */
+ if(timeout != Qnil && ev_now(selector->ev_loop) - started_at >= NUM2DBL(timeout))
+ break;
+ }
+
+ ev_timer_stop(selector->ev_loop, &selector->timer);
+ }
+#endif /* defined(HAVE_RB_THREAD_BLOCKING_REGION) */
+
+ result = selector->ready_count;
+ selector->selecting = selector->ready_count = 0;
+
+ return result;
+}
+
+/* Wake the selector up from another thread */
+static VALUE NIO_Selector_wakeup(VALUE self)
+{
+ struct NIO_Selector *selector;
+ Data_Get_Struct(self, struct NIO_Selector, selector);
+
+ if(selector->closed) {
+ rb_raise(rb_eIOError, "selector is closed");
+ }
+
+ write(selector->wakeup_writer, "\0", 1);
+ return Qnil;
+}
+
+/* Close the selector and free system resources */
+static VALUE NIO_Selector_close(VALUE self)
+{
+ return NIO_Selector_synchronize(self, NIO_Selector_close_synchronized, self);
+}
+
+static VALUE NIO_Selector_close_synchronized(VALUE self)
+{
+ struct NIO_Selector *selector;
+ Data_Get_Struct(self, struct NIO_Selector, selector);
+
+ NIO_Selector_shutdown(selector);
+
+ return Qnil;
+}
+
+/* Is the selector closed? */
+static VALUE NIO_Selector_closed(VALUE self)
+{
+ return NIO_Selector_synchronize(self, NIO_Selector_closed_synchronized, self);
+}
+
+static VALUE NIO_Selector_closed_synchronized(VALUE self)
+{ struct NIO_Selector *selector;
+ Data_Get_Struct(self, struct NIO_Selector, selector);
+
+ return selector->closed ? Qtrue : Qfalse;
+}
+
+/* True if there are monitors on the loop */
+static VALUE NIO_Selector_is_empty(VALUE self)
+{
+ VALUE selectables = rb_ivar_get(self, rb_intern("selectables"));
+
+ return rb_funcall(selectables, rb_intern("empty?"), 0) == Qtrue ? Qtrue : Qfalse;
+}
+
+
+/* Called whenever a timeout fires on the event loop */
+static void NIO_Selector_timeout_callback(struct ev_loop *ev_loop, struct ev_timer *timer, int revents)
+{
+ /* We don't actually need to do anything here, the mere firing of the
+ timer is sufficient to interrupt the selector. However, libev still wants a callback */
+}
+
+/* Called whenever a wakeup request is sent to a selector */
+static void NIO_Selector_wakeup_callback(struct ev_loop *ev_loop, struct ev_io *io, int revents)
+{
+ char buffer[128];
+ struct NIO_Selector *selector = (struct NIO_Selector *)io->data;
+ selector->selecting = 0;
+
+ /* Drain the wakeup pipe, giving us level-triggered behavior */
+ while(read(selector->wakeup_reader, buffer, 128) > 0);
+}
+
+/* libev callback fired whenever a monitor gets an event */
+void NIO_Selector_monitor_callback(struct ev_loop *ev_loop, struct ev_io *io, int revents)
+{
+ struct NIO_Monitor *monitor_data = (struct NIO_Monitor *)io->data;
+ struct NIO_Selector *selector = monitor_data->selector;
+ VALUE monitor = monitor_data->self;
+
+ assert(selector != 0);
+ selector->ready_count++;
+ monitor_data->revents = revents;
+
+ if(rb_block_given_p()) {
+ rb_yield(monitor);
+ } else {
+ assert(selector->ready_array != Qnil);
+ rb_ary_push(selector->ready_array, monitor);
+ }
+}
diff --git a/lib/nio.rb b/lib/nio.rb
new file mode 100644
index 0000000..405e0e8
--- /dev/null
+++ b/lib/nio.rb
@@ -0,0 +1,29 @@
+require 'thread'
+require 'socket'
+require 'nio/version'
+
+# New I/O for Ruby
+module NIO
+ # NIO implementation, one of the following (as a string):
+ # * select: in pure Ruby using Kernel.select
+ # * libev: as a C extension using libev
+ # * java: using Java NIO
+ def self.engine; ENGINE end
+end
+
+if ENV["NIO4R_PURE"] || (ENV["OS"] =~ /Windows/i && !defined?(JRUBY_VERSION))
+ require 'nio/monitor'
+ require 'nio/selector'
+ NIO::ENGINE = 'select'
+else
+ require 'nio4r_ext'
+
+ if defined?(JRUBY_VERSION)
+ require 'java'
+ require 'jruby'
+ org.nio4r.Nio4r.new.load(JRuby.runtime, false)
+ NIO::ENGINE = 'java'
+ else
+ NIO::ENGINE = 'libev'
+ end
+end
diff --git a/lib/nio/monitor.rb b/lib/nio/monitor.rb
new file mode 100644
index 0000000..0c3b14f
--- /dev/null
+++ b/lib/nio/monitor.rb
@@ -0,0 +1,43 @@
+module NIO
+ # Monitors watch IO objects for specific events
+ class Monitor
+ attr_reader :io, :interests, :selector
+ attr_accessor :value, :readiness
+
+ # :nodoc
+ def initialize(io, interests, selector)
+ unless io.is_a?(IO)
+ if IO.respond_to? :try_convert
+ io = IO.try_convert(io)
+ elsif io.respond_to? :to_io
+ io = io.to_io
+ end
+
+ raise TypeError, "can't convert #{io.class} into IO" unless io.is_a? IO
+ end
+
+ @io, @interests, @selector = io, interests, selector
+ @closed = false
+ end
+
+ # Is the IO object readable?
+ def readable?
+ readiness == :r || readiness == :rw
+ end
+
+ # Is the IO object writable?
+ def writable?
+ readiness == :w || readiness == :rw
+ end
+ alias_method :writeable?, :writable?
+
+ # Is this monitor closed?
+ def closed?; @closed; end
+
+ # Deactivate this monitor
+ def close(deregister = true)
+ @closed = true
+ @selector.deregister(io) if deregister
+ end
+ end
+end
diff --git a/lib/nio/selector.rb b/lib/nio/selector.rb
new file mode 100644
index 0000000..0a0ccab
--- /dev/null
+++ b/lib/nio/selector.rb
@@ -0,0 +1,131 @@
+module NIO
+ # Selectors monitor IO objects for events of interest
+ class Selector
+ # Create a new NIO::Selector
+ def initialize
+ @selectables = {}
+ @lock = Mutex.new
+
+ # Other threads can wake up a selector
+ @wakeup, @waker = IO.pipe
+ @closed = false
+ end
+
+ # Register interest in an IO object with the selector for the given types
+ # of events. Valid event types for interest are:
+ # * :r - is the IO readable?
+ # * :w - is the IO writeable?
+ # * :rw - is the IO either readable or writeable?
+ def register(io, interest)
+ @lock.synchronize do
+ if closed?
+ raise IOError, "selector is closed"
+ end
+
+ if monitor = @selectables[io]
+ raise ArgumentError, "this IO is already registered with the selector as #{monitor.interests.inspect}"
+ end
+
+ monitor = Monitor.new(io, interest, self)
+ @selectables[monitor.io] = monitor
+
+ monitor
+ end
+ end
+
+ # Deregister the given IO object from the selector
+ def deregister(io)
+ @lock.synchronize do
+ monitor = @selectables.delete io
+ monitor.close(false) if monitor and not monitor.closed?
+ monitor
+ end
+ end
+
+ # Is the given IO object registered with the selector?
+ def registered?(io)
+ @lock.synchronize { @selectables.has_key? io }
+ end
+
+ # Select which monitors are ready
+ def select(timeout = nil)
+ @lock.synchronize do
+ readers, writers = [@wakeup], []
+
+ @selectables.each do |io, monitor|
+ readers << io if monitor.interests == :r || monitor.interests == :rw
+ writers << io if monitor.interests == :w || monitor.interests == :rw
+ monitor.readiness = nil
+ end
+
+ ready_readers, ready_writers = Kernel.select readers, writers, [], timeout
+ return unless ready_readers # timeout or wakeup
+
+ selected_monitors = Set.new
+
+ ready_readers.each do |io|
+ if io == @wakeup
+ # Clear all wakeup signals we've received by reading them
+ # Wakeups should have level triggered behavior
+ @wakeup.read(@wakeup.stat.size)
+ return
+ else
+ monitor = @selectables[io]
+ monitor.readiness = :r
+ selected_monitors << monitor
+ end
+ end
+
+ ready_writers.each do |io|
+ monitor = @selectables[io]
+ monitor.readiness = case monitor.readiness
+ when :r
+ :rw
+ else
+ :w
+ end
+ selected_monitors << monitor
+ end
+
+ if block_given?
+ selected_monitors.each do |m|
+ yield m
+ end
+ selected_monitors.size
+ else
+ selected_monitors
+ end
+ end
+ end
+
+ # Wake up a thread that's in the middle of selecting on this selector, if
+ # any such thread exists.
+ #
+ # Invoking this method more than once between two successive select calls
+ # has the same effect as invoking it just once. In other words, it provides
+ # level-triggered behavior.
+ def wakeup
+ # Send the selector a signal in the form of writing data to a pipe
+ @waker.write "\0"
+ nil
+ end
+
+ # Close this selector and free its resources
+ def close
+ @lock.synchronize do
+ return if @closed
+
+ @wakeup.close rescue nil
+ @waker.close rescue nil
+ @closed = true
+ end
+ end
+
+ # Is this selector closed?
+ def closed?; @closed end
+
+ def empty?
+ @selectables.empty?
+ end
+ end
+end
diff --git a/lib/nio/version.rb b/lib/nio/version.rb
new file mode 100644
index 0000000..8f0ccd8
--- /dev/null
+++ b/lib/nio/version.rb
@@ -0,0 +1,3 @@
+module NIO
+ VERSION = "1.0.0"
+end
diff --git a/logo.png b/logo.png
new file mode 100644
index 0000000..2c8d771
Binary files /dev/null and b/logo.png differ
diff --git a/metadata.yml b/metadata.yml
new file mode 100644
index 0000000..aed9893
--- /dev/null
+++ b/metadata.yml
@@ -0,0 +1,143 @@
+--- !ruby/object:Gem::Specification
+name: nio4r
+version: !ruby/object:Gem::Version
+ version: 1.0.0
+platform: ruby
+authors:
+- Tony Arcieri
+autorequire:
+bindir: bin
+cert_chain: []
+date: 2014-01-15 00:00:00.000000000 Z
+dependencies:
+- !ruby/object:Gem::Dependency
+ name: rake-compiler
+ requirement: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+ type: :development
+ prerelease: false
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+- !ruby/object:Gem::Dependency
+ name: rake
+ requirement: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+ type: :development
+ prerelease: false
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+- !ruby/object:Gem::Dependency
+ name: rspec
+ requirement: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+ type: :development
+ prerelease: false
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+description: New IO for Ruby
+email:
+- tony.arcieri at gmail.com
+executables: []
+extensions:
+- ext/nio4r/extconf.rb
+extra_rdoc_files: []
+files:
+- ".gitignore"
+- ".rspec"
+- ".travis.yml"
+- CHANGES.md
+- Gemfile
+- LICENSE.txt
+- README.md
+- Rakefile
+- examples/echo_server.rb
+- ext/libev/Changes
+- ext/libev/LICENSE
+- ext/libev/README
+- ext/libev/README.embed
+- ext/libev/ev.c
+- ext/libev/ev.h
+- ext/libev/ev_epoll.c
+- ext/libev/ev_kqueue.c
+- ext/libev/ev_poll.c
+- ext/libev/ev_port.c
+- ext/libev/ev_select.c
+- ext/libev/ev_vars.h
+- ext/libev/ev_win32.c
+- ext/libev/ev_wrap.h
+- ext/libev/test_libev_win32.c
+- ext/nio4r/extconf.rb
+- ext/nio4r/libev.h
+- ext/nio4r/monitor.c
+- ext/nio4r/nio4r.h
+- ext/nio4r/nio4r_ext.c
+- ext/nio4r/org/nio4r/Nio4r.java
+- ext/nio4r/selector.c
+- lib/nio.rb
+- lib/nio/monitor.rb
+- lib/nio/selector.rb
+- lib/nio/version.rb
+- logo.png
+- nio4r.gemspec
+- spec/nio/acceptables_spec.rb
+- spec/nio/monitor_spec.rb
+- spec/nio/selectables/pipe_spec.rb
+- spec/nio/selectables/ssl_socket_spec.rb
+- spec/nio/selectables/tcp_socket_spec.rb
+- spec/nio/selectables/udp_socket_spec.rb
+- spec/nio/selector_spec.rb
+- spec/spec_helper.rb
+- spec/support/selectable_examples.rb
+- tasks/extension.rake
+- tasks/rspec.rake
+homepage: https://github.com/celluloid/nio4r
+licenses: []
+metadata: {}
+post_install_message:
+rdoc_options: []
+require_paths:
+- lib
+required_ruby_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+required_rubygems_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+requirements: []
+rubyforge_project:
+rubygems_version: 2.2.0
+signing_key:
+specification_version: 4
+summary: NIO provides a high performance selector API for monitoring IO objects
+test_files:
+- spec/nio/acceptables_spec.rb
+- spec/nio/monitor_spec.rb
+- spec/nio/selectables/pipe_spec.rb
+- spec/nio/selectables/ssl_socket_spec.rb
+- spec/nio/selectables/tcp_socket_spec.rb
+- spec/nio/selectables/udp_socket_spec.rb
+- spec/nio/selector_spec.rb
+- spec/spec_helper.rb
+- spec/support/selectable_examples.rb
diff --git a/nio4r.gemspec b/nio4r.gemspec
new file mode 100644
index 0000000..06ea9da
--- /dev/null
+++ b/nio4r.gemspec
@@ -0,0 +1,28 @@
+# -*- encoding: utf-8 -*-
+require File.expand_path('../lib/nio/version', __FILE__)
+
+Gem::Specification.new do |gem|
+ gem.authors = ["Tony Arcieri"]
+ gem.email = ["tony.arcieri at gmail.com"]
+ gem.description = "New IO for Ruby"
+ gem.summary = "NIO provides a high performance selector API for monitoring IO objects"
+ gem.homepage = "https://github.com/celluloid/nio4r"
+
+ gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
+ gem.files = `git ls-files`.split("\n")
+ gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
+ gem.name = "nio4r"
+ gem.require_paths = ["lib"]
+ gem.version = NIO::VERSION
+
+ if defined? JRUBY_VERSION
+ gem.files << "lib/nio4r_ext.jar"
+ gem.platform = "java"
+ else
+ gem.extensions = ["ext/nio4r/extconf.rb"]
+ end
+
+ gem.add_development_dependency "rake-compiler"
+ gem.add_development_dependency "rake"
+ gem.add_development_dependency "rspec"
+end
diff --git a/spec/nio/acceptables_spec.rb b/spec/nio/acceptables_spec.rb
new file mode 100644
index 0000000..4283aad
--- /dev/null
+++ b/spec/nio/acceptables_spec.rb
@@ -0,0 +1,32 @@
+require 'spec_helper'
+
+describe "NIO acceptables" do
+ shared_context "an NIO acceptable" do
+ let(:selector) { NIO::Selector.new }
+
+ it "selects for read readiness" do
+ waiting_monitor = selector.register(unacceptable_subject, :r)
+ ready_monitor = selector.register(acceptable_subject, :r)
+
+ ready_monitors = selector.select
+ ready_monitors.should include ready_monitor
+ ready_monitors.should_not include waiting_monitor
+ end
+ end
+
+ describe TCPServer do
+ let(:tcp_port) { 23456 }
+
+ let :acceptable_subject do
+ server = TCPServer.new("localhost", tcp_port)
+ TCPSocket.open("localhost", tcp_port)
+ server
+ end
+
+ let :unacceptable_subject do
+ TCPServer.new("localhost", tcp_port + 1)
+ end
+
+ it_behaves_like "an NIO acceptable"
+ end
+end
diff --git a/spec/nio/monitor_spec.rb b/spec/nio/monitor_spec.rb
new file mode 100644
index 0000000..89e8777
--- /dev/null
+++ b/spec/nio/monitor_spec.rb
@@ -0,0 +1,61 @@
+require 'spec_helper'
+
+describe NIO::Monitor do
+ let(:pipes) { IO.pipe }
+ let(:reader) { pipes.first }
+ let(:writer) { pipes.last }
+ let(:selector) { NIO::Selector.new }
+
+ subject { selector.register(reader, :r) }
+ let(:peer) { selector.register(writer, :rw) }
+ after { selector.close }
+
+ it "knows its interests" do
+ subject.interests.should == :r
+ peer.interests.should == :rw
+ end
+
+ it "knows its IO object" do
+ subject.io.should == reader
+ end
+
+ it "knows its selector" do
+ subject.selector.should == selector
+ end
+
+ it "stores arbitrary values" do
+ subject.value = 42
+ subject.value.should == 42
+ end
+
+ it "knows what operations IO objects are ready for" do
+ # For whatever odd reason this breaks unless we eagerly evaluate subject
+ reader_monitor, writer_monitor = subject, peer
+
+ selected = selector.select(0)
+ selected.should_not include(reader_monitor)
+ selected.should include(writer_monitor)
+
+ writer_monitor.readiness.should == :w
+ writer_monitor.should_not be_readable
+ writer_monitor.should be_writable
+
+ writer << "loldata"
+
+ selected = selector.select(0)
+ selected.should include(reader_monitor)
+
+ reader_monitor.readiness.should == :r
+ reader_monitor.should be_readable
+ reader_monitor.should_not be_writable
+ end
+
+ it "closes" do
+ subject.should_not be_closed
+ selector.registered?(reader).should be_true
+
+ subject.close
+ subject.should be_closed
+ selector.registered?(reader).should be_false
+ end
+end
diff --git a/spec/nio/selectables/pipe_spec.rb b/spec/nio/selectables/pipe_spec.rb
new file mode 100644
index 0000000..9bfd8e1
--- /dev/null
+++ b/spec/nio/selectables/pipe_spec.rb
@@ -0,0 +1,38 @@
+require 'spec_helper'
+
+describe "IO.pipe" do
+ let(:pair) { IO.pipe }
+
+ let :unreadable_subject do
+ pair.first
+ end
+ let :readable_subject do
+ pipe, peer = pair
+ peer << "data"
+ pipe
+ end
+
+ let :writable_subject do
+ pair.last
+ end
+ let :unwritable_subject do
+ reader, pipe = IO.pipe
+
+ #HACK: On OS X 10.8, this str must be larger than PIPE_BUF. Otherwise,
+ # the write is atomic and select() will return writable but write()
+ # will throw EAGAIN if there is too little space to write the string
+ # TODO: Use FFI to lookup the platform-specific size of PIPE_BUF
+ str = "JUNK IN THE TUBES" * 10000
+ begin
+ pipe.write_nonblock str
+ _, writers = select [], [pipe], [], 0
+ rescue Errno::EPIPE
+ break
+ end while writers and writers.include? pipe
+
+ pipe
+ end
+
+ it_behaves_like "an NIO selectable"
+ it_behaves_like "an NIO selectable stream"
+end
diff --git a/spec/nio/selectables/ssl_socket_spec.rb b/spec/nio/selectables/ssl_socket_spec.rb
new file mode 100644
index 0000000..246238d
--- /dev/null
+++ b/spec/nio/selectables/ssl_socket_spec.rb
@@ -0,0 +1,162 @@
+require 'spec_helper'
+require 'openssl'
+
+describe OpenSSL::SSL::SSLSocket, :if => RUBY_VERSION >= "1.9.0" do
+ let(:tcp_port) { 34567 }
+
+ let(:ssl_key) { OpenSSL::PKey::RSA.new(1024) }
+
+ let(:ssl_cert) do
+ name = OpenSSL::X509::Name.new([%w[CN localhost]])
+ OpenSSL::X509::Certificate.new.tap do |cert|
+ cert.version = 2
+ cert.serial = 1
+ cert.issuer = name
+ cert.subject = name
+ cert.not_before = Time.now
+ cert.not_after = Time.now + (365 * 24 *60 *60)
+ cert.public_key = ssl_key.public_key
+
+ cert.sign(ssl_key, OpenSSL::Digest::SHA1.new)
+ end
+ end
+
+ let(:ssl_server_context) do
+ OpenSSL::SSL::SSLContext.new.tap do |ctx|
+ ctx.cert = ssl_cert
+ ctx.key = ssl_key
+ end
+ end
+
+ let :readable_subject do
+ server = TCPServer.new("localhost", tcp_port)
+ client = TCPSocket.open("localhost", tcp_port)
+ peer = server.accept
+
+ ssl_peer = OpenSSL::SSL::SSLSocket.new(peer, ssl_server_context)
+ ssl_peer.sync_close = true
+
+ ssl_client = OpenSSL::SSL::SSLSocket.new(client)
+ ssl_client.sync_close = true
+
+ # SSLSocket#connect and #accept are blocking calls.
+ thread = Thread.new { ssl_client.connect }
+
+ ssl_peer.accept
+ ssl_peer << "data"
+
+ thread.join
+ pending "Failed to produce a readable SSL socket" unless select([ssl_client], [], [], 0)
+
+ ssl_client
+ end
+
+ let :unreadable_subject do
+ server = TCPServer.new("localhost", tcp_port + 1)
+ client = TCPSocket.new("localhost", tcp_port + 1)
+ peer = server.accept
+
+ ssl_peer = OpenSSL::SSL::SSLSocket.new(peer, ssl_server_context)
+ ssl_peer.sync_close = true
+
+ ssl_client = OpenSSL::SSL::SSLSocket.new(client)
+ ssl_client.sync_close = true
+
+ # SSLSocket#connect and #accept are blocking calls.
+ thread = Thread.new { ssl_client.connect }
+ ssl_peer.accept
+ thread.join
+
+ pending "Failed to produce an unreadable socket" if select([ssl_client], [], [], 0)
+ ssl_client
+ end
+
+ let :writable_subject do
+ server = TCPServer.new("localhost", tcp_port + 2)
+ client = TCPSocket.new("localhost", tcp_port + 2)
+ peer = server.accept
+
+ ssl_peer = OpenSSL::SSL::SSLSocket.new(peer, ssl_server_context)
+ ssl_peer.sync_close = true
+
+ ssl_client = OpenSSL::SSL::SSLSocket.new(client)
+ ssl_client.sync_close = true
+
+ # SSLSocket#connect and #accept are blocking calls.
+ thread = Thread.new { ssl_client.connect }
+
+ ssl_peer.accept
+ thread.join
+
+ ssl_client
+ end
+
+ let :unwritable_subject do
+ server = TCPServer.new("localhost", tcp_port + 3)
+ client = TCPSocket.open("localhost", tcp_port + 3)
+ peer = server.accept
+
+ ssl_peer = OpenSSL::SSL::SSLSocket.new(peer, ssl_server_context)
+ ssl_peer.sync_close = true
+
+ ssl_client = OpenSSL::SSL::SSLSocket.new(client)
+ ssl_client.sync_close = true
+
+ # SSLSocket#connect and #accept are blocking calls.
+ thread = Thread.new { ssl_client.connect }
+
+ ssl_peer.accept
+ thread.join
+
+ begin
+ _, writers = select [], [ssl_client], [], 0
+ count = ssl_client.write_nonblock "X" * 1024
+ count.should_not == 0
+ rescue IO::WaitReadable, IO::WaitWritable
+ pending "SSL will report writable but not accept writes"
+ raise if(writers.include? ssl_client)
+ end while writers and writers.include? ssl_client
+
+ # I think the kernel might manage to drain its buffer a bit even after
+ # the socket first goes unwritable. Attempt to sleep past this and then
+ # attempt to write again
+ sleep 0.1
+
+ # Once more for good measure!
+ begin
+# ssl_client.write_nonblock "X" * 1024
+ loop { ssl_client.write_nonblock "X" * 1024 }
+ rescue OpenSSL::SSL::SSLError
+ end
+
+ # Sanity check to make sure we actually produced an unwritable socket
+# if select([], [ssl_client], [], 0)
+# pending "Failed to produce an unwritable socket"
+# end
+
+ ssl_client
+ end
+
+ let :pair do
+ pending "figure out why newly created sockets are selecting readable immediately"
+
+ server = TCPServer.new("localhost", tcp_port + 4)
+ client = TCPSocket.open("localhost", tcp_port + 4)
+ peer = server.accept
+
+ ssl_peer = OpenSSL::SSL::SSLSocket.new(peer, ssl_server_context)
+ ssl_peer.sync_close = true
+
+ ssl_client = OpenSSL::SSL::SSLSocket.new(client)
+ ssl_client.sync_close = true
+
+ # SSLSocket#connect and #accept are blocking calls.
+ thread = Thread.new { ssl_client.connect }
+ ssl_peer.accept
+
+ [thread.value, ssl_peer]
+ end
+
+ it_behaves_like "an NIO selectable"
+ it_behaves_like "an NIO selectable stream"
+end
diff --git a/spec/nio/selectables/tcp_socket_spec.rb b/spec/nio/selectables/tcp_socket_spec.rb
new file mode 100644
index 0000000..7896dd1
--- /dev/null
+++ b/spec/nio/selectables/tcp_socket_spec.rb
@@ -0,0 +1,88 @@
+require 'spec_helper'
+
+describe TCPSocket do
+ port_offset = 0
+ let(:tcp_port) { 12345 + (port_offset += 1) }
+
+ let :readable_subject do
+ server = TCPServer.new("localhost", tcp_port)
+ sock = TCPSocket.open("localhost", tcp_port)
+ peer = server.accept
+ peer << "data"
+ sock
+ end
+
+ let :unreadable_subject do
+ TCPServer.new("localhost", tcp_port)
+ sock = TCPSocket.new("localhost", tcp_port)
+
+ # Sanity check to make sure we actually produced an unreadable socket
+ if select([sock], [], [], 0)
+ pending "Failed to produce an unreadable socket"
+ end
+
+ sock
+ end
+
+ let :writable_subject do
+ TCPServer.new("localhost", tcp_port)
+ TCPSocket.new("localhost", tcp_port)
+ end
+
+ let :unwritable_subject do
+ server = TCPServer.new("localhost", tcp_port)
+ sock = TCPSocket.open("localhost", tcp_port)
+ peer = server.accept
+
+ begin
+ sock.write_nonblock "X" * 1024
+ _, writers = select [], [sock], [], 0
+ end while writers and writers.include? sock
+
+ # I think the kernel might manage to drain its buffer a bit even after
+ # the socket first goes unwritable. Attempt to sleep past this and then
+ # attempt to write again
+ sleep 0.1
+
+ # Once more for good measure!
+ begin
+ sock.write_nonblock "X" * 1024
+ rescue Errno::EWOULDBLOCK
+ end
+
+ # Sanity check to make sure we actually produced an unwritable socket
+ if select([], [sock], [], 0)
+ pending "Failed to produce an unwritable socket"
+ end
+
+ sock
+ end
+
+ let :pair do
+ server = TCPServer.new("localhost", tcp_port)
+ client = TCPSocket.open("localhost", tcp_port)
+ [client, server.accept]
+ end
+
+ it_behaves_like "an NIO selectable"
+ it_behaves_like "an NIO selectable stream"
+ it_behaves_like "an NIO bidirectional stream"
+
+ context :connect do
+ it "selects writable when connected" do
+ selector = NIO::Selector.new
+ server = TCPServer.new('127.0.0.1', tcp_port)
+
+ client = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ monitor = selector.register(client, :w)
+
+ expect do
+ client.connect_nonblock Socket.sockaddr_in(tcp_port, '127.0.0.1')
+ end.to raise_exception Errno::EINPROGRESS
+
+ selector.select(0).should include monitor
+ result = client.getsockopt(::Socket::SOL_SOCKET, ::Socket::SO_ERROR)
+ result.unpack('i').first.should be_zero
+ end
+ end
+end
diff --git a/spec/nio/selectables/udp_socket_spec.rb b/spec/nio/selectables/udp_socket_spec.rb
new file mode 100644
index 0000000..76e86ec
--- /dev/null
+++ b/spec/nio/selectables/udp_socket_spec.rb
@@ -0,0 +1,31 @@
+require 'spec_helper'
+
+describe UDPSocket do
+ let(:udp_port) { 23456 }
+
+ let :readable_subject do
+ sock = UDPSocket.new
+ sock.bind('localhost', udp_port)
+
+ peer = UDPSocket.new
+ peer.send("hi there", 0, 'localhost', udp_port)
+
+ sock
+ end
+
+ let :unreadable_subject do
+ sock = UDPSocket.new
+ sock.bind('localhost', udp_port + 1)
+ sock
+ end
+
+ let :writable_subject do
+ pending "come up with a writable UDPSocket example"
+ end
+
+ let :unwritable_subject do
+ pending "come up with a UDPSocket that's blocked on writing"
+ end
+
+ it_behaves_like "an NIO selectable"
+end
diff --git a/spec/nio/selector_spec.rb b/spec/nio/selector_spec.rb
new file mode 100644
index 0000000..33de4ad
--- /dev/null
+++ b/spec/nio/selector_spec.rb
@@ -0,0 +1,170 @@
+require 'spec_helper'
+
+# Timeouts should be at least this precise (in seconds) to pass the tests
+# Typical precision should be better than this, but if it's worse it will fail
+# the tests
+TIMEOUT_PRECISION = 0.1
+
+describe NIO::Selector do
+ let(:pair) { IO.pipe }
+ let(:reader) { pair.first }
+ let(:writer) { pair.last }
+
+ context "register" do
+ it "registers IO objects" do
+ monitor = subject.register(reader, :r)
+ monitor.should_not be_closed
+ end
+
+ it "raises TypeError if asked to register non-IO objects" do
+ expect { subject.register(42, :r) }.to raise_exception TypeError
+ end
+
+ it "raises when asked to register after closing" do
+ subject.close
+ expect { subject.register(reader, :r) }.to raise_exception IOError
+ end
+ end
+
+ it "knows which IO objects are registered" do
+ subject.register(reader, :r)
+ subject.should be_registered(reader)
+ subject.should_not be_registered(writer)
+ end
+
+ it "deregisters IO objects" do
+ subject.register(reader, :r)
+
+ monitor = subject.deregister(reader)
+ subject.should_not be_registered(reader)
+ monitor.should be_closed
+ end
+
+ it "reports if it is empty" do
+ subject.should be_empty
+
+ monitor = subject.register(reader, :r)
+
+ subject.should_not be_empty
+ end
+
+ # This spec might seem a bit silly, but this actually something the
+ # Java NIO API specifically precludes that we need to work around
+ it "allows reregistration of the same IO object across select calls" do
+ monitor = subject.register(reader, :r)
+ writer << "ohai"
+
+ subject.select.should include monitor
+ reader.read(4).should == "ohai"
+ subject.deregister(reader)
+
+ new_monitor = subject.register(reader, :r)
+ writer << "thar"
+ subject.select.should include new_monitor
+ reader.read(4).should == "thar"
+ end
+
+ context "timeouts" do
+ it "waits for a timeout when selecting" do
+ monitor = subject.register(reader, :r)
+
+ payload = "hi there"
+ writer << payload
+
+ timeout = 0.5
+ started_at = Time.now
+ subject.select(timeout).should include monitor
+ (Time.now - started_at).should be_within(TIMEOUT_PRECISION).of(0)
+ reader.read_nonblock(payload.size)
+
+ started_at = Time.now
+ subject.select(timeout).should be_nil
+ (Time.now - started_at).should be_within(TIMEOUT_PRECISION).of(timeout)
+ end
+
+ it "raises ArgumentError if given a negative timeout" do
+ subject.register(reader, :r)
+
+ expect { subject.select(-1) }.to raise_exception(ArgumentError)
+ end
+ end
+
+ context "wakeup" do
+ it "wakes up if signaled to from another thread" do
+ subject.register(reader, :r)
+
+ thread = Thread.new do
+ started_at = Time.now
+ subject.select.should be_nil
+ Time.now - started_at
+ end
+
+ timeout = 0.1
+ sleep timeout
+ subject.wakeup
+
+ thread.value.should be_within(TIMEOUT_PRECISION).of(timeout)
+ end
+
+ it "raises IOError if asked to wake up a closed selector" do
+ subject.close
+ subject.should be_closed
+
+ expect { subject.wakeup }.to raise_exception IOError
+ end
+ end
+
+ context "select" do
+ it "selects IO objects" do
+ writer << "ohai"
+ unready, _ = IO.pipe
+
+ reader_monitor = subject.register(reader, :r)
+ unready_monitor = subject.register(unready, :r)
+
+ selected = subject.select(0)
+ selected.size.should == 1
+ selected.should include reader_monitor
+ selected.should_not include unready_monitor
+ end
+
+ it "selects closed IO objects" do
+ monitor = subject.register(reader, :r)
+ subject.select(0).should be_nil
+
+ thread = Thread.new { subject.select }
+ Thread.pass while thread.status && thread.status != "sleep"
+
+ writer.close
+ selected = thread.value
+ selected.should include monitor
+ end
+
+ it "iterates across selected objects with a block" do
+ readable1, writer = IO.pipe
+ writer << "ohai"
+
+ readable2, writer = IO.pipe
+ writer << "ohai"
+
+ unreadable, _ = IO.pipe
+
+ monitor1 = subject.register(readable1, :r)
+ monitor2 = subject.register(readable2, :r)
+ monitor3 = subject.register(unreadable, :r)
+
+ readables = []
+ result = subject.select { |monitor| readables << monitor }
+ result.should == 2
+
+ readables.should include monitor1
+ readables.should include monitor2
+ readables.should_not include monitor3
+ end
+ end
+
+ it "closes" do
+ subject.close
+ subject.should be_closed
+ end
+end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..c5ea239
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,7 @@
+require 'coveralls'
+Coveralls.wear!
+
+require 'rubygems'
+require 'bundler/setup'
+require 'nio'
+require 'support/selectable_examples'
diff --git a/spec/support/selectable_examples.rb b/spec/support/selectable_examples.rb
new file mode 100644
index 0000000..6537e47
--- /dev/null
+++ b/spec/support/selectable_examples.rb
@@ -0,0 +1,55 @@
+shared_context "an NIO selectable" do
+ let(:selector) { NIO::Selector.new }
+
+ it "selects readable objects" do
+ monitor = selector.register(readable_subject, :r)
+ ready = selector.select(0)
+ ready.should be_an Enumerable
+ ready.should include monitor
+ end
+
+ it "does not select unreadable objects" do
+ monitor = selector.register(unreadable_subject, :r)
+ selector.select(0).should be_nil
+ end
+
+ it "selects writable objects" do
+ monitor = selector.register(writable_subject, :w)
+ ready = selector.select(0)
+ ready.should be_an Enumerable
+ ready.should include monitor
+ end
+
+ it "does not select unwritable objects" do
+ monitor = selector.register(unwritable_subject, :w)
+ selector.select(0).should be_nil
+ end
+end
+
+shared_context "an NIO selectable stream" do
+ let(:selector) { NIO::Selector.new }
+ let(:stream) { pair.first }
+ let(:peer) { pair.last }
+
+ it "selects readable when the other end closes" do
+ monitor = selector.register(stream, :r)
+ selector.select(0).should be_nil
+
+ peer.close
+ #Wait and give the TCP session time to close
+ selector.select(0.1).should include monitor
+ end
+end
+
+shared_context "an NIO bidirectional stream" do
+ let(:selector) { NIO::Selector.new }
+ let(:stream) { pair.first }
+ let(:peer) { pair.last }
+
+ it "selects readable and writable" do
+ monitor = selector.register(readable_subject, :rw)
+ selector.select(0) do |m|
+ m.readiness.should == :rw
+ end
+ end
+end
diff --git a/tasks/extension.rake b/tasks/extension.rake
new file mode 100644
index 0000000..064a938
--- /dev/null
+++ b/tasks/extension.rake
@@ -0,0 +1,11 @@
+if defined? JRUBY_VERSION
+ require 'rake/javaextensiontask'
+ Rake::JavaExtensionTask.new('nio4r_ext') do |ext|
+ ext.ext_dir = 'ext/nio4r'
+ end
+else
+ require 'rake/extensiontask'
+ Rake::ExtensionTask.new('nio4r_ext') do |ext|
+ ext.ext_dir = 'ext/nio4r'
+ end
+end
\ No newline at end of file
diff --git a/tasks/rspec.rake b/tasks/rspec.rake
new file mode 100644
index 0000000..bd2a9d8
--- /dev/null
+++ b/tasks/rspec.rake
@@ -0,0 +1,7 @@
+require 'rspec/core/rake_task'
+
+RSpec::Core::RakeTask.new
+
+RSpec::Core::RakeTask.new(:rcov) do |task|
+ task.rcov = true
+end
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-ruby-extras/ruby-nio4r.git
More information about the Pkg-ruby-extras-commits
mailing list