]> granicus.if.org Git - libevent/blob - event-internal.h
Fix memleak in regress tests
[libevent] / event-internal.h
1 /*
2  * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 #ifndef EVENT_INTERNAL_H_INCLUDED_
28 #define EVENT_INTERNAL_H_INCLUDED_
29
30 #ifdef __cplusplus
31 extern "C" {
32 #endif
33
34 #include "event2/event-config.h"
35 #include "event2/watch.h"
36 #include "evconfig-private.h"
37
38 #include <time.h>
39 #include <sys/queue.h>
40 #include "event2/event_struct.h"
41 #include "minheap-internal.h"
42 #include "evsignal-internal.h"
43 #include "mm-internal.h"
44 #include "defer-internal.h"
45
46 /* map union members back */
47
48 /* mutually exclusive */
49 #define ev_signal_next  ev_.ev_signal.ev_signal_next
50 #define ev_io_next      ev_.ev_io.ev_io_next
51 #define ev_io_timeout   ev_.ev_io.ev_timeout
52
53 /* used only by signals */
54 #define ev_ncalls       ev_.ev_signal.ev_ncalls
55 #define ev_pncalls      ev_.ev_signal.ev_pncalls
56
57 #define ev_pri ev_evcallback.evcb_pri
58 #define ev_flags ev_evcallback.evcb_flags
59 #define ev_closure ev_evcallback.evcb_closure
60 #define ev_callback ev_evcallback.evcb_cb_union.evcb_callback
61 #define ev_arg ev_evcallback.evcb_arg
62
63 /** @name Event closure codes
64
65     Possible values for evcb_closure in struct event_callback
66
67     @{
68  */
69 /** A regular event. Uses the evcb_callback callback */
70 #define EV_CLOSURE_EVENT 0
71 /** A signal event. Uses the evcb_callback callback */
72 #define EV_CLOSURE_EVENT_SIGNAL 1
73 /** A persistent non-signal event. Uses the evcb_callback callback */
74 #define EV_CLOSURE_EVENT_PERSIST 2
75 /** A simple callback. Uses the evcb_selfcb callback. */
76 #define EV_CLOSURE_CB_SELF 3
77 /** A finalizing callback. Uses the evcb_cbfinalize callback. */
78 #define EV_CLOSURE_CB_FINALIZE 4
79 /** A finalizing event. Uses the evcb_evfinalize callback. */
80 #define EV_CLOSURE_EVENT_FINALIZE 5
81 /** A finalizing event that should get freed after. Uses the evcb_evfinalize
82  * callback. */
83 #define EV_CLOSURE_EVENT_FINALIZE_FREE 6
84 /** @} */
85
86 /** Structure to define the backend of a given event_base. */
87 struct eventop {
88         /** The name of this backend. */
89         const char *name;
90         /** Function to set up an event_base to use this backend.  It should
91          * create a new structure holding whatever information is needed to
92          * run the backend, and return it.  The returned pointer will get
93          * stored by event_init into the event_base.evbase field.  On failure,
94          * this function should return NULL. */
95         void *(*init)(struct event_base *);
96         /** Enable reading/writing on a given fd or signal.  'events' will be
97          * the events that we're trying to enable: one or more of EV_READ,
98          * EV_WRITE, EV_SIGNAL, and EV_ET.  'old' will be those events that
99          * were enabled on this fd previously.  'fdinfo' will be a structure
100          * associated with the fd by the evmap; its size is defined by the
101          * fdinfo field below.  It will be set to 0 the first time the fd is
102          * added.  The function should return 0 on success and -1 on error.
103          */
104         int (*add)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
105         /** As "add", except 'events' contains the events we mean to disable. */
106         int (*del)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
107         /** Function to implement the core of an event loop.  It must see which
108             added events are ready, and cause event_active to be called for each
109             active event (usually via event_io_active or such).  It should
110             return 0 on success and -1 on error.
111          */
112         int (*dispatch)(struct event_base *, struct timeval *);
113         /** Function to clean up and free our data from the event_base. */
114         void (*dealloc)(struct event_base *);
115         /** Flag: set if we need to reinitialize the event base after we fork.
116          */
117         int need_reinit;
118         /** Bit-array of supported event_method_features that this backend can
119          * provide. */
120         enum event_method_feature features;
121         /** Length of the extra information we should record for each fd that
122             has one or more active events.  This information is recorded
123             as part of the evmap entry for each fd, and passed as an argument
124             to the add and del functions above.
125          */
126         size_t fdinfo_len;
127 };
128
129 #ifdef _WIN32
130 /* If we're on win32, then file descriptors are not nice low densely packed
131    integers.  Instead, they are pointer-like windows handles, and we want to
132    use a hashtable instead of an array to map fds to events.
133 */
134 #define EVMAP_USE_HT
135 #endif
136
137 /* #define HT_CACHE_HASH_VALS */
138
139 #ifdef EVMAP_USE_HT
140 #define HT_NO_CACHE_HASH_VALUES
141 #include "ht-internal.h"
142 struct event_map_entry;
143 HT_HEAD(event_io_map, event_map_entry);
144 #else
145 #define event_io_map event_signal_map
146 #endif
147
148 /* Used to map signal numbers to a list of events.  If EVMAP_USE_HT is not
149    defined, this structure is also used as event_io_map, which maps fds to a
150    list of events.
151 */
152 struct event_signal_map {
153         /* An array of evmap_io * or of evmap_signal *; empty entries are
154          * set to NULL. */
155         void **entries;
156         /* The number of entries available in entries */
157         int nentries;
158 };
159
160 /* A list of events waiting on a given 'common' timeout value.  Ordinarily,
161  * events waiting for a timeout wait on a minheap.  Sometimes, however, a
162  * queue can be faster.
163  **/
164 struct common_timeout_list {
165         /* List of events currently waiting in the queue. */
166         struct event_list events;
167         /* 'magic' timeval used to indicate the duration of events in this
168          * queue. */
169         struct timeval duration;
170         /* Event that triggers whenever one of the events in the queue is
171          * ready to activate */
172         struct event timeout_event;
173         /* The event_base that this timeout list is part of */
174         struct event_base *base;
175 };
176
177 /** Mask used to get the real tv_usec value from a common timeout. */
178 #define COMMON_TIMEOUT_MICROSECONDS_MASK       0x000fffff
179
180 struct event_change;
181
182 /* List of 'changes' since the last call to eventop.dispatch.  Only maintained
183  * if the backend is using changesets. */
184 struct event_changelist {
185         struct event_change *changes;
186         int n_changes;
187         int changes_size;
188 };
189
190 #ifndef EVENT__DISABLE_DEBUG_MODE
191 /* Global internal flag: set to one if debug mode is on. */
192 extern int event_debug_mode_on_;
193 #define EVENT_DEBUG_MODE_IS_ON() (event_debug_mode_on_)
194 #else
195 #define EVENT_DEBUG_MODE_IS_ON() (0)
196 #endif
197
198 TAILQ_HEAD(evcallback_list, event_callback);
199
200 /* Sets up an event for processing once */
201 struct event_once {
202         LIST_ENTRY(event_once) next_once;
203         struct event ev;
204
205         void (*cb)(evutil_socket_t, short, void *);
206         void *arg;
207 };
208
209 /** Contextual information passed from event_base_loop to the "prepare" watcher
210  * callbacks. We define this as a struct rather than individual parameters to
211  * the callback function for the sake of future extensibility. */
212 struct evwatch_prepare_cb_info {
213         /** The timeout duration passed to the underlying implementation's `dispatch`.
214          * See evwatch_prepare_get_timeout. */
215         const struct timeval *timeout;
216 };
217
218 /** Contextual information passed from event_base_loop to the "check" watcher
219  * callbacks. We define this as a struct rather than individual parameters to
220  * the callback function for the sake of future extensibility. */
221 struct evwatch_check_cb_info {
222         /** Placeholder, since empty struct is not allowed by some compilers. */
223         void *unused;
224 };
225
226 /** Watcher types (prepare and check, perhaps others in the future). */
227 #define EVWATCH_PREPARE 0
228 #define EVWATCH_CHECK   1
229 #define EVWATCH_MAX     2
230
231 /** Handle to a "prepare" or "check" callback, registered in event_base. */
232 union evwatch_cb {
233         evwatch_prepare_cb prepare;
234         evwatch_check_cb check;
235 };
236 struct evwatch {
237         /** Tail queue pointers, called "next" by convention in libevent.
238          * See <sys/queue.h> */
239         TAILQ_ENTRY(evwatch) next;
240
241         /** Pointer to owning event loop */
242         struct event_base *base;
243
244         /** Watcher type (see above) */
245         unsigned type;
246
247         /** Callback function */
248         union evwatch_cb callback;
249
250         /** User-defined argument for callback function */
251         void *arg;
252 };
253 TAILQ_HEAD(evwatch_list, evwatch);
254
255 struct event_base {
256         /** Function pointers and other data to describe this event_base's
257          * backend. */
258         const struct eventop *evsel;
259         /** Pointer to backend-specific data. */
260         void *evbase;
261
262         /** List of changes to tell backend about at next dispatch.  Only used
263          * by the O(1) backends. */
264         struct event_changelist changelist;
265
266         /** Function pointers used to describe the backend that this event_base
267          * uses for signals */
268         const struct eventop *evsigsel;
269         /** Data to implement the common signal handler code. */
270         struct evsig_info sig;
271
272         /** Number of virtual events */
273         int virtual_event_count;
274         /** Maximum number of virtual events active */
275         int virtual_event_count_max;
276         /** Number of total events added to this event_base */
277         int event_count;
278         /** Maximum number of total events added to this event_base */
279         int event_count_max;
280         /** Number of total events active in this event_base */
281         int event_count_active;
282         /** Maximum number of total events active in this event_base */
283         int event_count_active_max;
284
285         /** Set if we should terminate the loop once we're done processing
286          * events. */
287         int event_gotterm;
288         /** Set if we should terminate the loop immediately */
289         int event_break;
290         /** Set if we should start a new instance of the loop immediately. */
291         int event_continue;
292
293         /** The currently running priority of events */
294         int event_running_priority;
295
296         /** Set if we're running the event_base_loop function, to prevent
297          * reentrant invocation. */
298         int running_loop;
299
300         /** Set to the number of deferred_cbs we've made 'active' in the
301          * loop.  This is a hack to prevent starvation; it would be smarter
302          * to just use event_config_set_max_dispatch_interval's max_callbacks
303          * feature */
304         int n_deferreds_queued;
305
306         /* Active event management. */
307         /** An array of nactivequeues queues for active event_callbacks (ones
308          * that have triggered, and whose callbacks need to be called).  Low
309          * priority numbers are more important, and stall higher ones.
310          */
311         struct evcallback_list *activequeues;
312         /** The length of the activequeues array */
313         int nactivequeues;
314         /** A list of event_callbacks that should become active the next time
315          * we process events, but not this time. */
316         struct evcallback_list active_later_queue;
317
318         /* common timeout logic */
319
320         /** An array of common_timeout_list* for all of the common timeout
321          * values we know. */
322         struct common_timeout_list **common_timeout_queues;
323         /** The number of entries used in common_timeout_queues */
324         int n_common_timeouts;
325         /** The total size of common_timeout_queues. */
326         int n_common_timeouts_allocated;
327
328         /** Mapping from file descriptors to enabled (added) events */
329         struct event_io_map io;
330
331         /** Mapping from signal numbers to enabled (added) events. */
332         struct event_signal_map sigmap;
333
334         /** Priority queue of events with timeouts. */
335         struct min_heap timeheap;
336
337         /** Stored timeval: used to avoid calling gettimeofday/clock_gettime
338          * too often. */
339         struct timeval tv_cache;
340
341         struct evutil_monotonic_timer monotonic_timer;
342
343         /** Difference between internal time (maybe from clock_gettime) and
344          * gettimeofday. */
345         struct timeval tv_clock_diff;
346         /** Second in which we last updated tv_clock_diff, in monotonic time. */
347         time_t last_updated_clock_diff;
348
349 #ifndef EVENT__DISABLE_THREAD_SUPPORT
350         /* threading support */
351         /** The thread currently running the event_loop for this base */
352         unsigned long th_owner_id;
353         /** A lock to prevent conflicting accesses to this event_base */
354         void *th_base_lock;
355         /** A condition that gets signalled when we're done processing an
356          * event with waiters on it. */
357         void *current_event_cond;
358         /** Number of threads blocking on current_event_cond. */
359         int current_event_waiters;
360 #endif
361         /** The event whose callback is executing right now */
362         struct event_callback *current_event;
363
364 #ifdef _WIN32
365         /** IOCP support structure, if IOCP is enabled. */
366         struct event_iocp_port *iocp;
367 #endif
368
369         /** Flags that this base was configured with */
370         enum event_base_config_flag flags;
371
372         struct timeval max_dispatch_time;
373         int max_dispatch_callbacks;
374         int limit_callbacks_after_prio;
375
376         /* Notify main thread to wake up break, etc. */
377         /** True if the base already has a pending notify, and we don't need
378          * to add any more. */
379         int is_notify_pending;
380         /** A socketpair used by some th_notify functions to wake up the main
381          * thread. */
382         evutil_socket_t th_notify_fd[2];
383         /** An event used by some th_notify functions to wake up the main
384          * thread. */
385         struct event th_notify;
386         /** A function used to wake up the main thread from another thread. */
387         int (*th_notify_fn)(struct event_base *base);
388
389         /** Saved seed for weak random number generator. Some backends use
390          * this to produce fairness among sockets. Protected by th_base_lock. */
391         struct evutil_weakrand_state weakrand_seed;
392
393         /** List of event_onces that have not yet fired. */
394         LIST_HEAD(once_event_list, event_once) once_events;
395
396         /** "Prepare" and "check" watchers. */
397         struct evwatch_list watchers[EVWATCH_MAX];
398 };
399
400 struct event_config_entry {
401         TAILQ_ENTRY(event_config_entry) next;
402
403         const char *avoid_method;
404 };
405
406 /** Internal structure: describes the configuration we want for an event_base
407  * that we're about to allocate. */
408 struct event_config {
409         TAILQ_HEAD(event_configq, event_config_entry) entries;
410
411         int n_cpus_hint;
412         struct timeval max_dispatch_interval;
413         int max_dispatch_callbacks;
414         int limit_callbacks_after_prio;
415         enum event_method_feature require_features;
416         enum event_base_config_flag flags;
417 };
418
419 /* Internal use only: Functions that might be missing from <sys/queue.h> */
420 #ifndef LIST_END
421 #define LIST_END(head)                  NULL
422 #endif
423
424 #ifndef TAILQ_FIRST
425 #define TAILQ_FIRST(head)               ((head)->tqh_first)
426 #endif
427 #ifndef TAILQ_END
428 #define TAILQ_END(head)                 NULL
429 #endif
430 #ifndef TAILQ_NEXT
431 #define TAILQ_NEXT(elm, field)          ((elm)->field.tqe_next)
432 #endif
433
434 #ifndef TAILQ_FOREACH
435 #define TAILQ_FOREACH(var, head, field)                                 \
436         for ((var) = TAILQ_FIRST(head);                                 \
437              (var) != TAILQ_END(head);                                  \
438              (var) = TAILQ_NEXT(var, field))
439 #endif
440
441 #ifndef TAILQ_INSERT_BEFORE
442 #define TAILQ_INSERT_BEFORE(listelm, elm, field) do {                   \
443         (elm)->field.tqe_prev = (listelm)->field.tqe_prev;              \
444         (elm)->field.tqe_next = (listelm);                              \
445         *(listelm)->field.tqe_prev = (elm);                             \
446         (listelm)->field.tqe_prev = &(elm)->field.tqe_next;             \
447 } while (0)
448 #endif
449
450 #define N_ACTIVE_CALLBACKS(base)                                        \
451         ((base)->event_count_active)
452
453 int evsig_set_handler_(struct event_base *base, int evsignal,
454                           void (*fn)(int));
455 int evsig_restore_handler_(struct event_base *base, int evsignal);
456
457 int event_add_nolock_(struct event *ev,
458     const struct timeval *tv, int tv_is_absolute);
459 /** Argument for event_del_nolock_. Tells event_del not to block on the event
460  * if it's running in another thread. */
461 #define EVENT_DEL_NOBLOCK 0
462 /** Argument for event_del_nolock_. Tells event_del to block on the event
463  * if it's running in another thread, regardless of its value for EV_FINALIZE
464  */
465 #define EVENT_DEL_BLOCK 1
466 /** Argument for event_del_nolock_. Tells event_del to block on the event
467  * if it is running in another thread and it doesn't have EV_FINALIZE set.
468  */
469 #define EVENT_DEL_AUTOBLOCK 2
470 /** Argument for event_del_nolock_. Tells event_del to proceed even if the
471  * event is set up for finalization rather for regular use.*/
472 #define EVENT_DEL_EVEN_IF_FINALIZING 3
473 int event_del_nolock_(struct event *ev, int blocking);
474 int event_remove_timer_nolock_(struct event *ev);
475
476 void event_active_nolock_(struct event *ev, int res, short count);
477 EVENT2_EXPORT_SYMBOL
478 int event_callback_activate_(struct event_base *, struct event_callback *);
479 int event_callback_activate_nolock_(struct event_base *, struct event_callback *);
480 int event_callback_cancel_(struct event_base *base,
481     struct event_callback *evcb);
482
483 void event_callback_finalize_nolock_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *));
484 EVENT2_EXPORT_SYMBOL
485 void event_callback_finalize_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *));
486 int event_callback_finalize_many_(struct event_base *base, int n_cbs, struct event_callback **evcb, void (*cb)(struct event_callback *, void *));
487
488
489 EVENT2_EXPORT_SYMBOL
490 void event_active_later_(struct event *ev, int res);
491 void event_active_later_nolock_(struct event *ev, int res);
492 int event_callback_activate_later_nolock_(struct event_base *base,
493     struct event_callback *evcb);
494 int event_callback_cancel_nolock_(struct event_base *base,
495     struct event_callback *evcb, int even_if_finalizing);
496 void event_callback_init_(struct event_base *base,
497     struct event_callback *cb);
498
499 /* FIXME document. */
500 EVENT2_EXPORT_SYMBOL
501 void event_base_add_virtual_(struct event_base *base);
502 void event_base_del_virtual_(struct event_base *base);
503
504 /** For debugging: unless assertions are disabled, verify the referential
505     integrity of the internal data structures of 'base'.  This operation can
506     be expensive.
507
508     Returns on success; aborts on failure.
509 */
510 EVENT2_EXPORT_SYMBOL
511 void event_base_assert_ok_(struct event_base *base);
512 void event_base_assert_ok_nolock_(struct event_base *base);
513
514
515 /* Helper function: Call 'fn' exactly once every inserted or active event in
516  * the event_base 'base'.
517  *
518  * If fn returns 0, continue on to the next event. Otherwise, return the same
519  * value that fn returned.
520  *
521  * Requires that 'base' be locked.
522  */
523 int event_base_foreach_event_nolock_(struct event_base *base,
524     event_base_foreach_event_cb cb, void *arg);
525
526 /* Cleanup function to reset debug mode during shutdown.
527  *
528  * Calling this function doesn't mean it'll be possible to re-enable
529  * debug mode if any events were added.
530  */
531 void event_disable_debug_mode(void);
532
533 #ifdef __cplusplus
534 }
535 #endif
536
537 #endif /* EVENT_INTERNAL_H_INCLUDED_ */