Mirror of :pserver:anonymous@cvs.schmorp.de/schmorpforge libev http://software.schmorp.de/pkg/libev.html
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1595 lines
33 KiB

14 years ago
/*
* libev event processing core, watcher management
*
14 years ago
* Copyright (c) 2007 Marc Alexander Lehmann <libev@schmorp.de>
* All rights reserved.
*
* 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.
*/
#ifndef EV_STANDALONE
# include "config.h"
# if HAVE_CLOCK_GETTIME
# define EV_USE_MONOTONIC 1
# define EV_USE_REALTIME 1
# endif
# if HAVE_SELECT && HAVE_SYS_SELECT_H
# define EV_USE_SELECT 1
# endif
# if HAVE_POLL && HAVE_POLL_H
# define EV_USE_POLL 1
# endif
# if HAVE_EPOLL && HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
# define EV_USE_EPOLL 1
# endif
# if HAVE_KQUEUE && HAVE_WORKING_KQUEUE && HAVE_SYS_EVENT_H && HAVE_SYS_QUEUE_H
# define EV_USE_KQUEUE 1
# endif
#endif
14 years ago
#include <math.h>
#include <stdlib.h>
14 years ago
#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
14 years ago
#include <assert.h>
#include <errno.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
14 years ago
#ifndef WIN32
# include <unistd.h>
# include <sys/time.h>
14 years ago
# include <sys/wait.h>
#endif
/**/
#ifndef EV_USE_MONOTONIC
# define EV_USE_MONOTONIC 1
#endif
#ifndef EV_USE_SELECT
# define EV_USE_SELECT 1
#endif
#ifndef EV_USE_POLL
# define EV_USE_POLL 0 /* poll is usually slower than select, and not as well tested */
#endif
#ifndef EV_USE_EPOLL
# define EV_USE_EPOLL 0
#endif
#ifndef EV_USE_KQUEUE
# define EV_USE_KQUEUE 0
#endif
#ifndef EV_USE_WIN32
# ifdef WIN32
# define EV_USE_WIN32 0 /* it does not exist, use select */
# undef EV_USE_SELECT
# define EV_USE_SELECT 1
# else
# define EV_USE_WIN32 0
# endif
#endif
#ifndef EV_USE_REALTIME
# define EV_USE_REALTIME 1
#endif
/**/
#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
/**/
14 years ago
#define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
#define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detect time jumps) */
#define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
/*#define CLEANUP_INTERVAL 300. /* how often to try to free memory and re-check fds */
#ifdef EV_H
# include EV_H
#else
# include "ev.h"
#endif
#if __GNUC__ >= 3
# define expect(expr,value) __builtin_expect ((expr),(value))
# define inline inline
#else
# define expect(expr,value) (expr)
# define inline static
#endif
#define expect_false(expr) expect ((expr) != 0, 0)
#define expect_true(expr) expect ((expr) != 0, 1)
#define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
#define ABSPRI(w) ((w)->priority - EV_MINPRI)
typedef struct ev_watcher *W;
typedef struct ev_watcher_list *WL;
typedef struct ev_watcher_time *WT;
static int have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
#include "ev_win32.c"
/*****************************************************************************/
14 years ago
static void (*syserr_cb)(const char *msg);
14 years ago
void ev_set_syserr_cb (void (*cb)(const char *msg))
{
syserr_cb = cb;
}
static void
14 years ago
syserr (const char *msg)
{
14 years ago
if (!msg)
msg = "(libev) system error";
if (syserr_cb)
14 years ago
syserr_cb (msg);
else
{
14 years ago
perror (msg);
abort ();
}
}
static void *(*alloc)(void *ptr, long size);
void ev_set_allocator (void *(*cb)(void *ptr, long size))
{
alloc = cb;
}
static void *
ev_realloc (void *ptr, long size)
{
ptr = alloc ? alloc (ptr, size) : realloc (ptr, size);
if (!ptr && size)
{
fprintf (stderr, "libev: cannot allocate %ld bytes, aborting.", size);
abort ();
}
return ptr;
}
#define ev_malloc(size) ev_realloc (0, (size))
#define ev_free(ptr) ev_realloc ((ptr), 0)
/*****************************************************************************/
typedef struct
{
WL head;
unsigned char events;
unsigned char reify;
} ANFD;
typedef struct
{
W w;
int events;
} ANPENDING;
#if EV_MULTIPLICITY
struct ev_loop
{
#define VAR(name,decl) decl;
#include "ev_vars.h"
#undef VAR
};
#include "ev_wrap.h"
struct ev_loop default_loop_struct;
static struct ev_loop *default_loop;
#else
#define VAR(name,decl) static decl;
#include "ev_vars.h"
#undef VAR
static int default_loop;
#endif
/*****************************************************************************/
inline ev_tstamp
ev_time (void)
{
#if EV_USE_REALTIME
struct timespec ts;
clock_gettime (CLOCK_REALTIME, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
#else
struct timeval tv;
gettimeofday (&tv, 0);
return tv.tv_sec + tv.tv_usec * 1e-6;
#endif
}
inline 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 ();
}
ev_tstamp
ev_now (EV_P)
{
return rt_now;
}
#define array_roundsize(type,n) ((n) | 4 & ~3)
#define array_needsize(type,base,cur,cnt,init) \
if (expect_false ((cnt) > cur)) \
{ \
int newcnt = cur; \
do \
{ \
newcnt = array_roundsize (type, newcnt << 1); \
} \
while ((cnt) > newcnt); \
\
base = (type *)ev_realloc (base, sizeof (type) * (newcnt));\
init (base + cur, newcnt - cur); \
cur = newcnt; \
}
#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*/\
}
/* microsoft's pseudo-c is quite far from C as the rest of the world and the standard knows it */
/* bringing us everlasting joy in form of stupid extra macros that are not required in C */
#define array_free_microshit(stem) \
ev_free (stem ## s); stem ## cnt = stem ## max = 0;
#define array_free(stem, idx) \
ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0;
/*****************************************************************************/
static void
anfds_init (ANFD *base, int count)
{
while (count--)
{
base->head = 0;
base->events = EV_NONE;
base->reify = 0;
++base;
}
}
14 years ago
void
ev_feed_event (EV_P_ void *w, int revents)
{
14 years ago
W w_ = (W)w;
if (w_->pending)
{
14 years ago
pendings [ABSPRI (w_)][w_->pending - 1].events |= revents;
return;
}
14 years ago
w_->pending = ++pendingcnt [ABSPRI (w_)];
array_needsize (ANPENDING, pendings [ABSPRI (w_)], pendingmax [ABSPRI (w_)], pendingcnt [ABSPRI (w_)], (void));
pendings [ABSPRI (w_)][w_->pending - 1].w = w_;
pendings [ABSPRI (w_)][w_->pending - 1].events = revents;
}
static void
queue_events (EV_P_ W *events, int eventcnt, int type)
{
int i;
for (i = 0; i < eventcnt; ++i)
14 years ago
ev_feed_event (EV_A_ events [i], type);
}
inline void
fd_event (EV_P_ int fd, int revents)
{
ANFD *anfd = anfds + fd;
struct ev_io *w;
for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
{
int ev = w->events & revents;
if (ev)
14 years ago
ev_feed_event (EV_A_ (W)w, ev);
}
}
void
ev_feed_fd_event (EV_P_ int fd, int revents)
{
fd_event (EV_A_ fd, revents);
}
/*****************************************************************************/
static void
fd_reify (EV_P)
{
int i;
for (i = 0; i < fdchangecnt; ++i)
{
int fd = fdchanges [i];
ANFD *anfd = anfds + fd;
struct ev_io *w;
int events = 0;
for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
events |= w->events;
anfd->reify = 0;
method_modify (EV_A_ fd, anfd->events, events);
anfd->events = events;
}
fdchangecnt = 0;
}
static void
fd_change (EV_P_ int fd)
{
14 years ago
if (anfds [fd].reify)
return;
anfds [fd].reify = 1;
++fdchangecnt;
array_needsize (int, fdchanges, fdchangemax, fdchangecnt, (void));
fdchanges [fdchangecnt - 1] = fd;
}
static void
fd_kill (EV_P_ int fd)
{
struct ev_io *w;
while ((w = (struct ev_io *)anfds [fd].head))
{
ev_io_stop (EV_A_ w);
14 years ago
ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
}
}
static int
fd_valid (int fd)
{
#ifdef WIN32
return !!win32_get_osfhandle (fd);
#else
return fcntl (fd, F_GETFD) != -1;
#endif
}
14 years ago
/* called on EBADF to verify fds */
static void
fd_ebadf (EV_P)
14 years ago
{
int fd;
for (fd = 0; fd < anfdmax; ++fd)
if (anfds [fd].events)
if (!fd_valid (fd) == -1 && errno == EBADF)
fd_kill (EV_A_ fd);
}
/* called on ENOMEM in select/poll to kill some fds and retry */
static void
fd_enomem (EV_P)
{
int fd;
for (fd = anfdmax; fd--; )
if (anfds [fd].events)
{
fd_kill (EV_A_ fd);
return;
}
14 years ago
}
14 years ago
/* usually called after fork if method needs to re-arm all fds from scratch */
static void
fd_rearm_all (EV_P)
{
int fd;
/* this should be highly optimised to not do anything but set a flag */
for (fd = 0; fd < anfdmax; ++fd)
if (anfds [fd].events)
{
anfds [fd].events = 0;
fd_change (EV_A_ fd);
}
}
/*****************************************************************************/
static void
upheap (WT *heap, int k)
{
WT w = heap [k];
while (k && heap [k >> 1]->at > w->at)
{
heap [k] = heap [k >> 1];
((W)heap [k])->active = k + 1;
k >>= 1;
}
heap [k] = w;
((W)heap [k])->active = k + 1;
}
static void
downheap (WT *heap, int N, int k)
{
WT w = heap [k];
14 years ago
while (k < (N >> 1))
{
int j = k << 1;
if (j + 1 < N && heap [j]->at > heap [j + 1]->at)
++j;
if (w->at <= heap [j]->at)
break;
heap [k] = heap [j];
((W)heap [k])->active = k + 1;
k = j;
}
heap [k] = w;
((W)heap [k])->active = k + 1;
}
inline void
adjustheap (WT *heap, int N, int k, ev_tstamp at)
{
ev_tstamp old_at = heap [k]->at;
heap [k]->at = at;
if (old_at < at)
downheap (heap, N, k);
else
upheap (heap, k);
}
/*****************************************************************************/
14 years ago
typedef struct
{
WL head;
sig_atomic_t volatile gotsig;
14 years ago
} ANSIG;
static ANSIG *signals;
14 years ago
static int signalmax;
14 years ago
static int sigpipe [2];
static sig_atomic_t volatile gotsig;
static struct ev_io sigev;
14 years ago
static void
14 years ago
signals_init (ANSIG *base, int count)
{
while (count--)
14 years ago
{
base->head = 0;
base->gotsig = 0;
14 years ago
++base;
}
}
static void
sighandler (int signum)
{
#if WIN32
signal (signum, sighandler);
#endif
14 years ago
signals [signum - 1].gotsig = 1;
if (!gotsig)
{
int old_errno = errno;
14 years ago
gotsig = 1;
#ifdef WIN32
send (sigpipe [1], &signum, 1, MSG_DONTWAIT);
#else
write (sigpipe [1], &signum, 1);
#endif
errno = old_errno;
14 years ago
}
}
void
ev_feed_signal_event (EV_P_ int signum)
{
WL w;
#if EV_MULTIPLICITY
assert (("feeding signal events is only supported in the default loop", loop == default_loop));
#endif
--signum;
if (signum < 0 || signum >= signalmax)
return;
signals [signum].gotsig = 0;
for (w = signals [signum].head; w; w = w->next)
ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
}
14 years ago
static void
sigcb (EV_P_ struct ev_io *iow, int revents)
14 years ago
{
int signum;
14 years ago
#ifdef WIN32
recv (sigpipe [0], &revents, 1, MSG_DONTWAIT);
#else
14 years ago
read (sigpipe [0], &revents, 1);
#endif
gotsig = 0;
14 years ago
for (signum = signalmax; signum--; )
if (signals [signum].gotsig)
ev_feed_signal_event (EV_A_ signum + 1);
14 years ago
}
static void
siginit (EV_P)
14 years ago
{
14 years ago
#ifndef WIN32
14 years ago
fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
/* rather than sort out wether we really need nb, set it */
fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
14 years ago
#endif
14 years ago
14 years ago
ev_io_set (&sigev, sigpipe [0], EV_READ);
ev_io_start (EV_A_ &sigev);
ev_unref (EV_A); /* child watcher should not keep loop alive */
}
/*****************************************************************************/
static struct ev_child *childs [PID_HASHSIZE];
14 years ago
#ifndef WIN32
static struct ev_signal childev;
#ifndef WCONTINUED
# define WCONTINUED 0
#endif
static void
child_reap (EV_P_ struct ev_signal *sw, int chain, int pid, int status)
{
struct ev_child *w;
for (w = (struct ev_child *)childs [chain & (PID_HASHSIZE - 1)]; w; w = (struct ev_child *)((WL)w)->next)
if (w->pid == pid || !w->pid)
{
14 years ago
ev_priority (w) = ev_priority (sw); /* need to do it *now* */
w->rpid = pid;
w->rstatus = status;
14 years ago
ev_feed_event (EV_A_ (W)w, EV_CHILD);
}
}
static void
childcb (EV_P_ struct ev_signal *sw, int revents)
{
int pid, status;
if (0 < (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
{
/* make sure we are called again until all childs have been reaped */
14 years ago
ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
child_reap (EV_A_ sw, pid, pid, status);
child_reap (EV_A_ sw, 0, pid, status); /* this might trigger a watcher twice, but event catches that */
}
}
14 years ago
#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
14 years ago
int
ev_version_major (void)
{
return EV_VERSION_MAJOR;
}
int
ev_version_minor (void)
{
return EV_VERSION_MINOR;
}
/* return true if we are running with elevated privileges and should ignore env variables */
static int
enable_secure (void)
{
#ifdef WIN32
return 0;
#else
return getuid () != geteuid ()
|| getgid () != getegid ();
#endif
}
int
ev_method (EV_P)
{
return method;
}
static void
loop_init (EV_P_ int methods)
{
if (!method)
14 years ago
{
#if EV_USE_MONOTONIC
14 years ago
{
struct timespec ts;
if (!clock_gettime (CLOCK_MONOTONIC, &ts))
have_monotonic = 1;
}
#endif
rt_now = ev_time ();
mn_now = get_clock ();
now_floor = mn_now;
rtmn_diff = rt_now - mn_now;
if (methods == EVMETHOD_AUTO)
if (!enable_secure () && getenv ("LIBEV_METHODS"))
methods = atoi (getenv ("LIBEV_METHODS"));
else
methods = EVMETHOD_ANY;
method = 0;
#if EV_USE_WIN32
if (!method && (methods & EVMETHOD_WIN32 )) method = win32_init (EV_A_ methods);
#endif