xref: /minix/external/bsd/libevent/dist/test/regress.c (revision 366d18b2)
1 /*	$NetBSD: regress.c,v 1.8 2015/01/29 07:26:02 spz Exp $	*/
2 /*
3  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
4  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #ifdef WIN32
30 #include <winsock2.h>
31 #include <windows.h>
32 #endif
33 
34 #include "event2/event-config.h"
35 #include <sys/cdefs.h>
36 __RCSID("$NetBSD: regress.c,v 1.8 2015/01/29 07:26:02 spz Exp $");
37 
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #ifdef _EVENT_HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #include <sys/queue.h>
44 #ifndef WIN32
45 #include <sys/socket.h>
46 #include <sys/wait.h>
47 #include <signal.h>
48 #include <unistd.h>
49 #include <netdb.h>
50 #endif
51 #include <fcntl.h>
52 #include <signal.h>
53 #include <stdlib.h>
54 #include <stdio.h>
55 #include <string.h>
56 #include <errno.h>
57 #include <assert.h>
58 #include <ctype.h>
59 
60 #include "event2/event.h"
61 #include "event2/event_struct.h"
62 #include "event2/event_compat.h"
63 #include "event2/tag.h"
64 #include "event2/buffer.h"
65 #include "event2/buffer_compat.h"
66 #include "event2/util.h"
67 #include "event-internal.h"
68 #include "evthread-internal.h"
69 #include "util-internal.h"
70 #include "log-internal.h"
71 
72 #include "regress.h"
73 
74 #ifndef WIN32
75 #include "regress.gen.h"
76 #endif
77 
78 evutil_socket_t pair[2];
79 int test_ok;
80 int called;
81 struct event_base *global_base;
82 
83 static char wbuf[4096];
84 static char rbuf[4096];
85 static int woff;
86 static int roff;
87 static int usepersist;
88 static struct timeval tset;
89 static struct timeval tcalled;
90 
91 
92 #define TEST1	"this is a test"
93 #define SECONDS	1
94 
95 #ifndef SHUT_WR
96 #define SHUT_WR 1
97 #endif
98 
99 #ifdef WIN32
100 #define write(fd,buf,len) send((fd),(buf),(int)(len),0)
101 #define read(fd,buf,len) recv((fd),(buf),(int)(len),0)
102 #endif
103 
104 struct basic_cb_args
105 {
106 	struct event_base *eb;
107 	struct event *ev;
108 	unsigned int callcount;
109 };
110 
111 static void
112 simple_read_cb(evutil_socket_t fd, short event, void *arg)
113 {
114 	char buf[256];
115 	int len;
116 
117 	len = read(fd, buf, sizeof(buf));
118 
119 	if (len) {
120 		if (!called) {
121 			if (event_add(arg, NULL) == -1)
122 				exit(1);
123 		}
124 	} else if (called == 1)
125 		test_ok = 1;
126 
127 	called++;
128 }
129 
130 static void
131 basic_read_cb(evutil_socket_t fd, short event, void *data)
132 {
133 	char buf[256];
134 	int len;
135 	struct basic_cb_args *arg = data;
136 
137 	len = read(fd, buf, sizeof(buf));
138 
139 	if (len < 0) {
140 		tt_fail_perror("read (callback)");
141 	} else {
142 		switch (arg->callcount++) {
143 		case 0:	 /* first call: expect to read data; cycle */
144 			if (len > 0)
145 				return;
146 
147 			tt_fail_msg("EOF before data read");
148 			break;
149 
150 		case 1:	 /* second call: expect EOF; stop */
151 			if (len > 0)
152 				tt_fail_msg("not all data read on first cycle");
153 			break;
154 
155 		default:  /* third call: should not happen */
156 			tt_fail_msg("too many cycles");
157 		}
158 	}
159 
160 	event_del(arg->ev);
161 	event_base_loopexit(arg->eb, NULL);
162 }
163 
164 static void
165 dummy_read_cb(evutil_socket_t fd, short event, void *arg)
166 {
167 }
168 
169 static void
170 simple_write_cb(evutil_socket_t fd, short event, void *arg)
171 {
172 	int len;
173 
174 	len = write(fd, TEST1, strlen(TEST1) + 1);
175 	if (len == -1)
176 		test_ok = 0;
177 	else
178 		test_ok = 1;
179 }
180 
181 static void
182 multiple_write_cb(evutil_socket_t fd, short event, void *arg)
183 {
184 	struct event *ev = arg;
185 	int len;
186 
187 	len = 128;
188 	if (woff + len >= (int)sizeof(wbuf))
189 		len = sizeof(wbuf) - woff;
190 
191 	len = write(fd, wbuf + woff, len);
192 	if (len == -1) {
193 		fprintf(stderr, "%s: write\n", __func__);
194 		if (usepersist)
195 			event_del(ev);
196 		return;
197 	}
198 
199 	woff += len;
200 
201 	if (woff >= (int)sizeof(wbuf)) {
202 		shutdown(fd, SHUT_WR);
203 		if (usepersist)
204 			event_del(ev);
205 		return;
206 	}
207 
208 	if (!usepersist) {
209 		if (event_add(ev, NULL) == -1)
210 			exit(1);
211 	}
212 }
213 
214 static void
215 multiple_read_cb(evutil_socket_t fd, short event, void *arg)
216 {
217 	struct event *ev = arg;
218 	int len;
219 
220 	len = read(fd, rbuf + roff, sizeof(rbuf) - roff);
221 	if (len == -1)
222 		fprintf(stderr, "%s: read\n", __func__);
223 	if (len <= 0) {
224 		if (usepersist)
225 			event_del(ev);
226 		return;
227 	}
228 
229 	roff += len;
230 	if (!usepersist) {
231 		if (event_add(ev, NULL) == -1)
232 			exit(1);
233 	}
234 }
235 
236 static void
237 timeout_cb(evutil_socket_t fd, short event, void *arg)
238 {
239 	struct timeval tv;
240 	int diff;
241 
242 	evutil_gettimeofday(&tcalled, NULL);
243 	if (evutil_timercmp(&tcalled, &tset, >))
244 		evutil_timersub(&tcalled, &tset, &tv);
245 	else
246 		evutil_timersub(&tset, &tcalled, &tv);
247 
248 	diff = tv.tv_sec*1000 + tv.tv_usec/1000 - SECONDS * 1000;
249 	if (diff < 0)
250 		diff = -diff;
251 
252 	if (diff < 100)
253 		test_ok = 1;
254 }
255 
256 struct both {
257 	struct event ev;
258 	int nread;
259 };
260 
261 static void
262 combined_read_cb(evutil_socket_t fd, short event, void *arg)
263 {
264 	struct both *both = arg;
265 	char buf[128];
266 	int len;
267 
268 	len = read(fd, buf, sizeof(buf));
269 	if (len == -1)
270 		fprintf(stderr, "%s: read\n", __func__);
271 	if (len <= 0)
272 		return;
273 
274 	both->nread += len;
275 	if (event_add(&both->ev, NULL) == -1)
276 		exit(1);
277 }
278 
279 static void
280 combined_write_cb(evutil_socket_t fd, short event, void *arg)
281 {
282 	struct both *both = arg;
283 	char buf[128];
284 	int len;
285 
286 	len = sizeof(buf);
287 	if (len > both->nread)
288 		len = both->nread;
289 
290 	memset(buf, 'q', len);
291 
292 	len = write(fd, buf, len);
293 	if (len == -1)
294 		fprintf(stderr, "%s: write\n", __func__);
295 	if (len <= 0) {
296 		shutdown(fd, SHUT_WR);
297 		return;
298 	}
299 
300 	both->nread -= len;
301 	if (event_add(&both->ev, NULL) == -1)
302 		exit(1);
303 }
304 
305 /* These macros used to replicate the work of the legacy test wrapper code */
306 #define setup_test(x) do {						\
307 	if (!in_legacy_test_wrapper) {					\
308 		TT_FAIL(("Legacy test %s not wrapped properly", x));	\
309 		return;							\
310 	}								\
311 	} while (/*CONSTCOND*/0)
312 #define cleanup_test() setup_test("cleanup")
313 
314 static void
315 test_simpleread(void)
316 {
317 	struct event ev;
318 
319 	/* Very simple read test */
320 	setup_test("Simple read: ");
321 
322 	if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
323 		tt_fail_perror("write");
324 	}
325 
326 	shutdown(pair[0], SHUT_WR);
327 
328 	event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
329 	if (event_add(&ev, NULL) == -1)
330 		exit(1);
331 	event_dispatch();
332 
333 	cleanup_test();
334 }
335 
336 static void
337 test_simplewrite(void)
338 {
339 	struct event ev;
340 
341 	/* Very simple write test */
342 	setup_test("Simple write: ");
343 
344 	event_set(&ev, pair[0], EV_WRITE, simple_write_cb, &ev);
345 	if (event_add(&ev, NULL) == -1)
346 		exit(1);
347 	event_dispatch();
348 
349 	cleanup_test();
350 }
351 
352 static void
353 simpleread_multiple_cb(evutil_socket_t fd, short event, void *arg)
354 {
355 	if (++called == 2)
356 		test_ok = 1;
357 }
358 
359 static void
360 test_simpleread_multiple(void)
361 {
362 	struct event one, two;
363 
364 	/* Very simple read test */
365 	setup_test("Simple read to multiple evens: ");
366 
367 	if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
368 		tt_fail_perror("write");
369 	}
370 
371 	shutdown(pair[0], SHUT_WR);
372 
373 	event_set(&one, pair[1], EV_READ, simpleread_multiple_cb, NULL);
374 	if (event_add(&one, NULL) == -1)
375 		exit(1);
376 	event_set(&two, pair[1], EV_READ, simpleread_multiple_cb, NULL);
377 	if (event_add(&two, NULL) == -1)
378 		exit(1);
379 	event_dispatch();
380 
381 	cleanup_test();
382 }
383 
384 static int have_closed = 0;
385 static int premature_event = 0;
386 static void
387 simpleclose_close_fd_cb(evutil_socket_t s, short what, void *ptr)
388 {
389 	evutil_socket_t **fds = ptr;
390 	TT_BLATHER(("Closing"));
391 	evutil_closesocket(*fds[0]);
392 	evutil_closesocket(*fds[1]);
393 	*fds[0] = -1;
394 	*fds[1] = -1;
395 	have_closed = 1;
396 }
397 
398 static void
399 record_event_cb(evutil_socket_t s, short what, void *ptr)
400 {
401 	short *whatp = ptr;
402 	if (!have_closed)
403 		premature_event = 1;
404 	*whatp = what;
405 	TT_BLATHER(("Recorded %d on socket %d", (int)what, (int)s));
406 }
407 
408 static void
409 test_simpleclose(void *ptr)
410 {
411 	/* Test that a close of FD is detected as a read and as a write. */
412 	struct event_base *base = event_base_new();
413 	evutil_socket_t pair1[2]={-1,-1}, pair2[2] = {-1, -1};
414 	evutil_socket_t *to_close[2];
415 	struct event *rev=NULL, *wev=NULL, *closeev=NULL;
416 	struct timeval tv;
417 	short got_read_on_close = 0, got_write_on_close = 0;
418 	char buf[1024];
419 	memset(buf, 99, sizeof(buf));
420 #ifdef WIN32
421 #define LOCAL_SOCKETPAIR_AF AF_INET
422 #else
423 #define LOCAL_SOCKETPAIR_AF AF_UNIX
424 #endif
425 	if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair1)<0)
426 		TT_DIE(("socketpair: %s", strerror(errno)));
427 	if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair2)<0)
428 		TT_DIE(("socketpair: %s", strerror(errno)));
429 	if (evutil_make_socket_nonblocking(pair1[1]) < 0)
430 		TT_DIE(("make_socket_nonblocking"));
431 	if (evutil_make_socket_nonblocking(pair2[1]) < 0)
432 		TT_DIE(("make_socket_nonblocking"));
433 
434 	/** Stuff pair2[1] full of data, until write fails */
435 	while (1) {
436 		int r = write(pair2[1], buf, sizeof(buf));
437 		if (r<0) {
438 			int err = evutil_socket_geterror(pair2[1]);
439 			if (! EVUTIL_ERR_RW_RETRIABLE(err))
440 				TT_DIE(("write failed strangely: %s",
441 					evutil_socket_error_to_string(err)));
442 			break;
443 		}
444 	}
445 	to_close[0] = &pair1[0];
446 	to_close[1] = &pair2[0];
447 
448 	closeev = event_new(base, -1, EV_TIMEOUT, simpleclose_close_fd_cb,
449 	    to_close);
450 	rev = event_new(base, pair1[1], EV_READ, record_event_cb,
451 	    &got_read_on_close);
452 	TT_BLATHER(("Waiting for read on %d", (int)pair1[1]));
453 	wev = event_new(base, pair2[1], EV_WRITE, record_event_cb,
454 	    &got_write_on_close);
455 	TT_BLATHER(("Waiting for write on %d", (int)pair2[1]));
456 	tv.tv_sec = 0;
457 	tv.tv_usec = 100*1000; /* Close pair1[0] after a little while, and make
458 			       * sure we get a read event. */
459 	event_add(closeev, &tv);
460 	event_add(rev, NULL);
461 	event_add(wev, NULL);
462 	/* Don't let the test go on too long. */
463 	tv.tv_sec = 0;
464 	tv.tv_usec = 200*1000;
465 	event_base_loopexit(base, &tv);
466 	event_base_loop(base, 0);
467 
468 	tt_int_op(got_read_on_close, ==, EV_READ);
469 	tt_int_op(got_write_on_close, ==, EV_WRITE);
470 	tt_int_op(premature_event, ==, 0);
471 
472 end:
473 	if (pair1[0] >= 0)
474 		evutil_closesocket(pair1[0]);
475 	if (pair1[1] >= 0)
476 		evutil_closesocket(pair1[1]);
477 	if (pair2[0] >= 0)
478 		evutil_closesocket(pair2[0]);
479 	if (pair2[1] >= 0)
480 		evutil_closesocket(pair2[1]);
481 	if (rev)
482 		event_free(rev);
483 	if (wev)
484 		event_free(wev);
485 	if (closeev)
486 		event_free(closeev);
487 	if (base)
488 		event_base_free(base);
489 }
490 
491 
492 static void
493 test_multiple(void)
494 {
495 	struct event ev, ev2;
496 	int i;
497 
498 	/* Multiple read and write test */
499 	setup_test("Multiple read/write: ");
500 	memset(rbuf, 0, sizeof(rbuf));
501 	for (i = 0; i < (int)sizeof(wbuf); i++)
502 		wbuf[i] = i;
503 
504 	roff = woff = 0;
505 	usepersist = 0;
506 
507 	event_set(&ev, pair[0], EV_WRITE, multiple_write_cb, &ev);
508 	if (event_add(&ev, NULL) == -1)
509 		exit(1);
510 	event_set(&ev2, pair[1], EV_READ, multiple_read_cb, &ev2);
511 	if (event_add(&ev2, NULL) == -1)
512 		exit(1);
513 	event_dispatch();
514 
515 	if (roff == woff)
516 		test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
517 
518 	cleanup_test();
519 }
520 
521 static void
522 test_persistent(void)
523 {
524 	struct event ev, ev2;
525 	int i;
526 
527 	/* Multiple read and write test with persist */
528 	setup_test("Persist read/write: ");
529 	memset(rbuf, 0, sizeof(rbuf));
530 	for (i = 0; i < (int)sizeof(wbuf); i++)
531 		wbuf[i] = i;
532 
533 	roff = woff = 0;
534 	usepersist = 1;
535 
536 	event_set(&ev, pair[0], EV_WRITE|EV_PERSIST, multiple_write_cb, &ev);
537 	if (event_add(&ev, NULL) == -1)
538 		exit(1);
539 	event_set(&ev2, pair[1], EV_READ|EV_PERSIST, multiple_read_cb, &ev2);
540 	if (event_add(&ev2, NULL) == -1)
541 		exit(1);
542 	event_dispatch();
543 
544 	if (roff == woff)
545 		test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
546 
547 	cleanup_test();
548 }
549 
550 static void
551 test_combined(void)
552 {
553 	struct both r1, r2, w1, w2;
554 
555 	setup_test("Combined read/write: ");
556 	memset(&r1, 0, sizeof(r1));
557 	memset(&r2, 0, sizeof(r2));
558 	memset(&w1, 0, sizeof(w1));
559 	memset(&w2, 0, sizeof(w2));
560 
561 	w1.nread = 4096;
562 	w2.nread = 8192;
563 
564 	event_set(&r1.ev, pair[0], EV_READ, combined_read_cb, &r1);
565 	event_set(&w1.ev, pair[0], EV_WRITE, combined_write_cb, &w1);
566 	event_set(&r2.ev, pair[1], EV_READ, combined_read_cb, &r2);
567 	event_set(&w2.ev, pair[1], EV_WRITE, combined_write_cb, &w2);
568 	tt_assert(event_add(&r1.ev, NULL) != -1);
569 	tt_assert(!event_add(&w1.ev, NULL));
570 	tt_assert(!event_add(&r2.ev, NULL));
571 	tt_assert(!event_add(&w2.ev, NULL));
572 	event_dispatch();
573 
574 	if (r1.nread == 8192 && r2.nread == 4096)
575 		test_ok = 1;
576 
577 end:
578 	cleanup_test();
579 }
580 
581 static void
582 test_simpletimeout(void)
583 {
584 	struct timeval tv;
585 	struct event ev;
586 
587 	setup_test("Simple timeout: ");
588 
589 	tv.tv_usec = 0;
590 	tv.tv_sec = SECONDS;
591 	evtimer_set(&ev, timeout_cb, NULL);
592 	evtimer_add(&ev, &tv);
593 
594 	evutil_gettimeofday(&tset, NULL);
595 	event_dispatch();
596 
597 	cleanup_test();
598 }
599 
600 static void
601 periodic_timeout_cb(evutil_socket_t fd, short event, void *arg)
602 {
603 	int *count = arg;
604 
605 	(*count)++;
606 	if (*count == 6) {
607 		/* call loopexit only once - on slow machines(?), it is
608 		 * apparently possible for this to get called twice. */
609 		test_ok = 1;
610 		event_base_loopexit(global_base, NULL);
611 	}
612 }
613 
614 static void
615 test_persistent_timeout(void)
616 {
617 	struct timeval tv;
618 	struct event ev;
619 	int count = 0;
620 
621 	evutil_timerclear(&tv);
622 	tv.tv_usec = 10000;
623 
624 	event_assign(&ev, global_base, -1, EV_TIMEOUT|EV_PERSIST,
625 	    periodic_timeout_cb, &count);
626 	event_add(&ev, &tv);
627 
628 	event_dispatch();
629 
630 	event_del(&ev);
631 }
632 
633 static void
634 test_persistent_timeout_jump(void *ptr)
635 {
636 	struct basic_test_data *data = ptr;
637 	struct event ev;
638 	int count = 0;
639 	struct timeval msec100 = { 0, 100 * 1000 };
640 	struct timeval msec50 = { 0, 50 * 1000 };
641 
642 	event_assign(&ev, data->base, -1, EV_PERSIST, periodic_timeout_cb, &count);
643 	event_add(&ev, &msec100);
644 	/* Wait for a bit */
645 #ifdef _WIN32
646 	Sleep(1000);
647 #else
648 	sleep(1);
649 #endif
650 	event_base_loopexit(data->base, &msec50);
651 	event_base_dispatch(data->base);
652 	tt_int_op(count, ==, 1);
653 
654 end:
655 	event_del(&ev);
656 }
657 
658 struct persist_active_timeout_called {
659 	int n;
660 	short events[16];
661 	struct timeval tvs[16];
662 };
663 
664 static void
665 activate_cb(evutil_socket_t fd, short event, void *arg)
666 {
667 	struct event *ev = arg;
668 	event_active(ev, EV_READ, 1);
669 }
670 
671 static void
672 persist_active_timeout_cb(evutil_socket_t fd, short event, void *arg)
673 {
674 	struct persist_active_timeout_called *c = arg;
675 	if (c->n < 15) {
676 		c->events[c->n] = event;
677 		evutil_gettimeofday(&c->tvs[c->n], NULL);
678 		++c->n;
679 	}
680 }
681 
682 static void
683 test_persistent_active_timeout(void *ptr)
684 {
685 	struct timeval tv, tv2, tv_exit, start;
686 	struct event ev;
687 	struct persist_active_timeout_called res;
688 
689 	struct basic_test_data *data = ptr;
690 	struct event_base *base = data->base;
691 
692 	memset(&res, 0, sizeof(res));
693 
694 	tv.tv_sec = 0;
695 	tv.tv_usec = 200 * 1000;
696 	event_assign(&ev, base, -1, EV_TIMEOUT|EV_PERSIST,
697 	    persist_active_timeout_cb, &res);
698 	event_add(&ev, &tv);
699 
700 	tv2.tv_sec = 0;
701 	tv2.tv_usec = 100 * 1000;
702 	event_base_once(base, -1, EV_TIMEOUT, activate_cb, &ev, &tv2);
703 
704 	tv_exit.tv_sec = 0;
705 	tv_exit.tv_usec = 600 * 1000;
706 	event_base_loopexit(base, &tv_exit);
707 
708 	event_base_assert_ok(base);
709 	evutil_gettimeofday(&start, NULL);
710 
711 	event_base_dispatch(base);
712 	event_base_assert_ok(base);
713 
714 	tt_int_op(res.n, ==, 3);
715 	tt_int_op(res.events[0], ==, EV_READ);
716 	tt_int_op(res.events[1], ==, EV_TIMEOUT);
717 	tt_int_op(res.events[2], ==, EV_TIMEOUT);
718 	test_timeval_diff_eq(&start, &res.tvs[0], 100);
719 	test_timeval_diff_eq(&start, &res.tvs[1], 300);
720 	test_timeval_diff_eq(&start, &res.tvs[2], 500);
721 end:
722 	event_del(&ev);
723 }
724 
725 struct common_timeout_info {
726 	struct event ev;
727 	struct timeval called_at;
728 	int which;
729 	int count;
730 };
731 
732 static void
733 common_timeout_cb(evutil_socket_t fd, short event, void *arg)
734 {
735 	struct common_timeout_info *ti = arg;
736 	++ti->count;
737 	evutil_gettimeofday(&ti->called_at, NULL);
738 	if (ti->count >= 6)
739 		event_del(&ti->ev);
740 }
741 
742 static void
743 test_common_timeout(void *ptr)
744 {
745 	struct basic_test_data *data = ptr;
746 
747 	struct event_base *base = data->base;
748 	int i;
749 	struct common_timeout_info info[100];
750 
751 	struct timeval now;
752 	struct timeval tmp_100_ms = { 0, 100*1000 };
753 	struct timeval tmp_200_ms = { 0, 200*1000 };
754 
755 	const struct timeval *ms_100, *ms_200;
756 
757 	ms_100 = event_base_init_common_timeout(base, &tmp_100_ms);
758 	ms_200 = event_base_init_common_timeout(base, &tmp_200_ms);
759 	tt_assert(ms_100);
760 	tt_assert(ms_200);
761 	tt_ptr_op(event_base_init_common_timeout(base, &tmp_200_ms),
762 	    ==, ms_200);
763 	tt_int_op(ms_100->tv_sec, ==, 0);
764 	tt_int_op(ms_200->tv_sec, ==, 0);
765 	tt_int_op(ms_100->tv_usec, ==, 100000|0x50000000);
766 	tt_int_op(ms_200->tv_usec, ==, 200000|0x50100000);
767 
768 	memset(info, 0, sizeof(info));
769 
770 	for (i=0; i<100; ++i) {
771 		info[i].which = i;
772 		event_assign(&info[i].ev, base, -1, EV_TIMEOUT|EV_PERSIST,
773 		    common_timeout_cb, &info[i]);
774 		if (i % 2) {
775 			event_add(&info[i].ev, ms_100);
776 		} else {
777 			event_add(&info[i].ev, ms_200);
778 		}
779 	}
780 
781 	event_base_assert_ok(base);
782 	event_base_dispatch(base);
783 
784 	evutil_gettimeofday(&now, NULL);
785 	event_base_assert_ok(base);
786 
787 	for (i=0; i<10; ++i) {
788 		struct timeval tmp;
789 		int ms_diff;
790 		tt_int_op(info[i].count, ==, 6);
791 		evutil_timersub(&now, &info[i].called_at, &tmp);
792 		ms_diff = tmp.tv_usec/1000 + tmp.tv_sec*1000;
793 		if (i % 2) {
794 			tt_int_op(ms_diff, >, 500);
795 			tt_int_op(ms_diff, <, 700);
796 		} else {
797 			tt_int_op(ms_diff, >, -100);
798 			tt_int_op(ms_diff, <, 100);
799 		}
800 	}
801 
802 	/* Make sure we can free the base with some events in. */
803 	for (i=0; i<100; ++i) {
804 		if (i % 2) {
805 			event_add(&info[i].ev, ms_100);
806 		} else {
807 			event_add(&info[i].ev, ms_200);
808 		}
809 	}
810 
811 end:
812 	event_base_free(data->base); /* need to do this here before info is
813 				      * out-of-scope */
814 	data->base = NULL;
815 }
816 
817 #ifndef WIN32
818 static void signal_cb(evutil_socket_t fd, short event, void *arg);
819 
820 #define current_base event_global_current_base_
821 extern struct event_base *current_base;
822 
823 static void
824 child_signal_cb(evutil_socket_t fd, short event, void *arg)
825 {
826 	struct timeval tv;
827 	int *pint = arg;
828 
829 	*pint = 1;
830 
831 	tv.tv_usec = 500000;
832 	tv.tv_sec = 0;
833 	event_loopexit(&tv);
834 }
835 
836 static void
837 test_fork(void)
838 {
839 	int status, got_sigchld = 0;
840 	struct event ev, sig_ev;
841 	pid_t pid;
842 
843 	setup_test("After fork: ");
844 
845 	tt_assert(current_base);
846 	evthread_make_base_notifiable(current_base);
847 
848 	if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
849 		tt_fail_perror("write");
850 	}
851 
852 	event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
853 	if (event_add(&ev, NULL) == -1)
854 		exit(1);
855 
856 	evsignal_set(&sig_ev, SIGCHLD, child_signal_cb, &got_sigchld);
857 	evsignal_add(&sig_ev, NULL);
858 
859 	event_base_assert_ok(current_base);
860 	TT_BLATHER(("Before fork"));
861 	if ((pid = regress_fork()) == 0) {
862 		/* in the child */
863 		TT_BLATHER(("In child, before reinit"));
864 		event_base_assert_ok(current_base);
865 		if (event_reinit(current_base) == -1) {
866 			fprintf(stdout, "FAILED (reinit)\n");
867 			exit(1);
868 		}
869 		TT_BLATHER(("After reinit"));
870 		event_base_assert_ok(current_base);
871 		TT_BLATHER(("After assert-ok"));
872 
873 		evsignal_del(&sig_ev);
874 
875 		called = 0;
876 
877 		event_dispatch();
878 
879 		event_base_free(current_base);
880 
881 		/* we do not send an EOF; simple_read_cb requires an EOF
882 		 * to set test_ok.  we just verify that the callback was
883 		 * called. */
884 		exit(test_ok != 0 || called != 2 ? -2 : 76);
885 	}
886 
887 	/* wait for the child to read the data */
888 	sleep(1);
889 
890 	if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
891 		tt_fail_perror("write");
892 	}
893 
894 	TT_BLATHER(("Before waitpid"));
895 	if (waitpid(pid, &status, 0) == -1) {
896 		fprintf(stdout, "FAILED (fork)\n");
897 		exit(1);
898 	}
899 	TT_BLATHER(("After waitpid"));
900 
901 	if (WEXITSTATUS(status) != 76) {
902 		fprintf(stdout, "FAILED (exit): %d\n", WEXITSTATUS(status));
903 		exit(1);
904 	}
905 
906 	/* test that the current event loop still works */
907 	if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
908 		fprintf(stderr, "%s: write\n", __func__);
909 	}
910 
911 	shutdown(pair[0], SHUT_WR);
912 
913 	event_dispatch();
914 
915 	if (!got_sigchld) {
916 		fprintf(stdout, "FAILED (sigchld)\n");
917 		exit(1);
918 	}
919 
920 	evsignal_del(&sig_ev);
921 
922 	end:
923 	cleanup_test();
924 }
925 
926 static void
927 signal_cb_sa(int sig)
928 {
929 	test_ok = 2;
930 }
931 
932 static void
933 signal_cb(evutil_socket_t fd, short event, void *arg)
934 {
935 	struct event *ev = arg;
936 
937 	evsignal_del(ev);
938 	test_ok = 1;
939 }
940 
941 static void
942 test_simplesignal(void)
943 {
944 	struct event ev;
945 	struct itimerval itv;
946 
947 	setup_test("Simple signal: ");
948 	evsignal_set(&ev, SIGALRM, signal_cb, &ev);
949 	evsignal_add(&ev, NULL);
950 	/* find bugs in which operations are re-ordered */
951 	evsignal_del(&ev);
952 	evsignal_add(&ev, NULL);
953 
954 	memset(&itv, 0, sizeof(itv));
955 	itv.it_value.tv_sec = 1;
956 	if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
957 		goto skip_simplesignal;
958 
959 	event_dispatch();
960  skip_simplesignal:
961 	if (evsignal_del(&ev) == -1)
962 		test_ok = 0;
963 
964 	cleanup_test();
965 }
966 
967 static void
968 test_multiplesignal(void)
969 {
970 	struct event ev_one, ev_two;
971 	struct itimerval itv;
972 
973 	setup_test("Multiple signal: ");
974 
975 	evsignal_set(&ev_one, SIGALRM, signal_cb, &ev_one);
976 	evsignal_add(&ev_one, NULL);
977 
978 	evsignal_set(&ev_two, SIGALRM, signal_cb, &ev_two);
979 	evsignal_add(&ev_two, NULL);
980 
981 	memset(&itv, 0, sizeof(itv));
982 	itv.it_value.tv_sec = 1;
983 	if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
984 		goto skip_simplesignal;
985 
986 	event_dispatch();
987 
988  skip_simplesignal:
989 	if (evsignal_del(&ev_one) == -1)
990 		test_ok = 0;
991 	if (evsignal_del(&ev_two) == -1)
992 		test_ok = 0;
993 
994 	cleanup_test();
995 }
996 
997 static void
998 test_immediatesignal(void)
999 {
1000 	struct event ev;
1001 
1002 	test_ok = 0;
1003 	evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
1004 	evsignal_add(&ev, NULL);
1005 	raise(SIGUSR1);
1006 	event_loop(EVLOOP_NONBLOCK);
1007 	evsignal_del(&ev);
1008 	cleanup_test();
1009 }
1010 
1011 static void
1012 test_signal_dealloc(void)
1013 {
1014 	/* make sure that evsignal_event is event_del'ed and pipe closed */
1015 	struct event ev;
1016 	struct event_base *base = event_init();
1017 	evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
1018 	evsignal_add(&ev, NULL);
1019 	evsignal_del(&ev);
1020 	event_base_free(base);
1021 	/* If we got here without asserting, we're fine. */
1022 	test_ok = 1;
1023 	cleanup_test();
1024 }
1025 
1026 static void
1027 test_signal_pipeloss(void)
1028 {
1029 	/* make sure that the base1 pipe is closed correctly. */
1030 	struct event_base *base1, *base2;
1031 	int pipe1;
1032 	test_ok = 0;
1033 	base1 = event_init();
1034 	pipe1 = base1->sig.ev_signal_pair[0];
1035 	base2 = event_init();
1036 	event_base_free(base2);
1037 	event_base_free(base1);
1038 	if (close(pipe1) != -1 || errno!=EBADF) {
1039 		/* fd must be closed, so second close gives -1, EBADF */
1040 		printf("signal pipe not closed. ");
1041 		test_ok = 0;
1042 	} else {
1043 		test_ok = 1;
1044 	}
1045 	cleanup_test();
1046 }
1047 
1048 /*
1049  * make two bases to catch signals, use both of them.  this only works
1050  * for event mechanisms that use our signal pipe trick.	 kqueue handles
1051  * signals internally, and all interested kqueues get all the signals.
1052  */
1053 static void
1054 test_signal_switchbase(void)
1055 {
1056 	struct event ev1, ev2;
1057 	struct event_base *base1, *base2;
1058 	int is_kqueue;
1059 	test_ok = 0;
1060 	base1 = event_init();
1061 	base2 = event_init();
1062 	is_kqueue = !strcmp(event_get_method(),"kqueue");
1063 	evsignal_set(&ev1, SIGUSR1, signal_cb, &ev1);
1064 	evsignal_set(&ev2, SIGUSR1, signal_cb, &ev2);
1065 	if (event_base_set(base1, &ev1) ||
1066 	    event_base_set(base2, &ev2) ||
1067 	    event_add(&ev1, NULL) ||
1068 	    event_add(&ev2, NULL)) {
1069 		fprintf(stderr, "%s: cannot set base, add\n", __func__);
1070 		exit(1);
1071 	}
1072 
1073 	tt_ptr_op(event_get_base(&ev1), ==, base1);
1074 	tt_ptr_op(event_get_base(&ev2), ==, base2);
1075 
1076 	test_ok = 0;
1077 	/* can handle signal before loop is called */
1078 	raise(SIGUSR1);
1079 	event_base_loop(base2, EVLOOP_NONBLOCK);
1080 	if (is_kqueue) {
1081 		if (!test_ok)
1082 			goto end;
1083 		test_ok = 0;
1084 	}
1085 	event_base_loop(base1, EVLOOP_NONBLOCK);
1086 	if (test_ok && !is_kqueue) {
1087 		test_ok = 0;
1088 
1089 		/* set base1 to handle signals */
1090 		event_base_loop(base1, EVLOOP_NONBLOCK);
1091 		raise(SIGUSR1);
1092 		event_base_loop(base1, EVLOOP_NONBLOCK);
1093 		event_base_loop(base2, EVLOOP_NONBLOCK);
1094 	}
1095 end:
1096 	event_base_free(base1);
1097 	event_base_free(base2);
1098 	cleanup_test();
1099 }
1100 
1101 /*
1102  * assert that a signal event removed from the event queue really is
1103  * removed - with no possibility of it's parent handler being fired.
1104  */
1105 static void
1106 test_signal_assert(void)
1107 {
1108 	struct event ev;
1109 	struct event_base *base = event_init();
1110 	test_ok = 0;
1111 	/* use SIGCONT so we don't kill ourselves when we signal to nowhere */
1112 	evsignal_set(&ev, SIGCONT, signal_cb, &ev);
1113 	evsignal_add(&ev, NULL);
1114 	/*
1115 	 * if evsignal_del() fails to reset the handler, it's current handler
1116 	 * will still point to evsig_handler().
1117 	 */
1118 	evsignal_del(&ev);
1119 
1120 	raise(SIGCONT);
1121 #if 0
1122 	/* only way to verify we were in evsig_handler() */
1123 	/* XXXX Now there's no longer a good way. */
1124 	if (base->sig.evsig_caught)
1125 		test_ok = 0;
1126 	else
1127 		test_ok = 1;
1128 #else
1129 	test_ok = 1;
1130 #endif
1131 
1132 	event_base_free(base);
1133 	cleanup_test();
1134 	return;
1135 }
1136 
1137 /*
1138  * assert that we restore our previous signal handler properly.
1139  */
1140 static void
1141 test_signal_restore(void)
1142 {
1143 	struct event ev;
1144 	struct event_base *base = event_init();
1145 #ifdef _EVENT_HAVE_SIGACTION
1146 	struct sigaction sa;
1147 #endif
1148 
1149 	test_ok = 0;
1150 #ifdef _EVENT_HAVE_SIGACTION
1151 	sa.sa_handler = signal_cb_sa;
1152 	sa.sa_flags = 0x0;
1153 	sigemptyset(&sa.sa_mask);
1154 	if (sigaction(SIGUSR1, &sa, NULL) == -1)
1155 		goto out;
1156 #else
1157 	if (signal(SIGUSR1, signal_cb_sa) == SIG_ERR)
1158 		goto out;
1159 #endif
1160 	evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
1161 	evsignal_add(&ev, NULL);
1162 	evsignal_del(&ev);
1163 
1164 	raise(SIGUSR1);
1165 	/* 1 == signal_cb, 2 == signal_cb_sa, we want our previous handler */
1166 	if (test_ok != 2)
1167 		test_ok = 0;
1168 out:
1169 	event_base_free(base);
1170 	cleanup_test();
1171 	return;
1172 }
1173 
1174 static void
1175 signal_cb_swp(int sig, short event, void *arg)
1176 {
1177 	called++;
1178 	if (called < 5)
1179 		raise(sig);
1180 	else
1181 		event_loopexit(NULL);
1182 }
1183 static void
1184 timeout_cb_swp(evutil_socket_t fd, short event, void *arg)
1185 {
1186 	if (called == -1) {
1187 		struct timeval tv = {5, 0};
1188 
1189 		called = 0;
1190 		evtimer_add((struct event *)arg, &tv);
1191 		raise(SIGUSR1);
1192 		return;
1193 	}
1194 	test_ok = 0;
1195 	event_loopexit(NULL);
1196 }
1197 
1198 static void
1199 test_signal_while_processing(void)
1200 {
1201 	struct event_base *base = event_init();
1202 	struct event ev, ev_timer;
1203 	struct timeval tv = {0, 0};
1204 
1205 	setup_test("Receiving a signal while processing other signal: ");
1206 
1207 	called = -1;
1208 	test_ok = 1;
1209 	signal_set(&ev, SIGUSR1, signal_cb_swp, NULL);
1210 	signal_add(&ev, NULL);
1211 	evtimer_set(&ev_timer, timeout_cb_swp, &ev_timer);
1212 	evtimer_add(&ev_timer, &tv);
1213 	event_dispatch();
1214 
1215 	event_base_free(base);
1216 	cleanup_test();
1217 	return;
1218 }
1219 #endif
1220 
1221 static void
1222 test_free_active_base(void *ptr)
1223 {
1224 	struct basic_test_data *data = ptr;
1225 	struct event_base *base1;
1226 	struct event ev1;
1227 
1228 	base1 = event_init();
1229 	if (base1) {
1230 		event_assign(&ev1, base1, data->pair[1], EV_READ,
1231 			     dummy_read_cb, NULL);
1232 		event_add(&ev1, NULL);
1233 		event_base_free(base1);	 /* should not crash */
1234 	} else {
1235 		tt_fail_msg("failed to create event_base for test");
1236 	}
1237 
1238 	base1 = event_init();
1239 	tt_assert(base1);
1240 	event_assign(&ev1, base1, 0, 0, dummy_read_cb, NULL);
1241 	event_active(&ev1, EV_READ, 1);
1242 	event_base_free(base1);
1243 end:
1244 	;
1245 }
1246 
1247 static void
1248 test_manipulate_active_events(void *ptr)
1249 {
1250 	struct basic_test_data *data = ptr;
1251 	struct event_base *base = data->base;
1252 	struct event ev1;
1253 
1254 	event_assign(&ev1, base, -1, EV_TIMEOUT, dummy_read_cb, NULL);
1255 
1256 	/* Make sure an active event is pending. */
1257 	event_active(&ev1, EV_READ, 1);
1258 	tt_int_op(event_pending(&ev1, EV_READ|EV_TIMEOUT|EV_WRITE, NULL),
1259 	    ==, EV_READ);
1260 
1261 	/* Make sure that activating an event twice works. */
1262 	event_active(&ev1, EV_WRITE, 1);
1263 	tt_int_op(event_pending(&ev1, EV_READ|EV_TIMEOUT|EV_WRITE, NULL),
1264 	    ==, EV_READ|EV_WRITE);
1265 
1266 end:
1267 	event_del(&ev1);
1268 }
1269 
1270 static void
1271 test_bad_assign(void *ptr)
1272 {
1273 	struct event ev;
1274 	int r;
1275 	/* READ|SIGNAL is not allowed */
1276 	r = event_assign(&ev, NULL, -1, EV_SIGNAL|EV_READ, dummy_read_cb, NULL);
1277 	tt_int_op(r,==,-1);
1278 
1279 end:
1280 	;
1281 }
1282 
1283 static int reentrant_cb_run = 0;
1284 
1285 static void
1286 bad_reentrant_run_loop_cb(evutil_socket_t fd, short what, void *ptr)
1287 {
1288 	struct event_base *base = ptr;
1289 	int r;
1290 	reentrant_cb_run = 1;
1291 	/* This reentrant call to event_base_loop should be detected and
1292 	 * should fail */
1293 	r = event_base_loop(base, 0);
1294 	tt_int_op(r, ==, -1);
1295 end:
1296 	;
1297 }
1298 
1299 static void
1300 test_bad_reentrant(void *ptr)
1301 {
1302 	struct basic_test_data *data = ptr;
1303 	struct event_base *base = data->base;
1304 	struct event ev;
1305 	int r;
1306 	event_assign(&ev, base, -1,
1307 	    0, bad_reentrant_run_loop_cb, base);
1308 
1309 	event_active(&ev, EV_WRITE, 1);
1310 	r = event_base_loop(base, 0);
1311 	tt_int_op(r, ==, 1);
1312 	tt_int_op(reentrant_cb_run, ==, 1);
1313 end:
1314 	;
1315 }
1316 
1317 static void
1318 test_event_base_new(void *ptr)
1319 {
1320 	struct basic_test_data *data = ptr;
1321 	struct event_base *base = 0;
1322 	struct event ev1;
1323 	struct basic_cb_args args;
1324 
1325 	int towrite = (int)strlen(TEST1)+1;
1326 	int len = write(data->pair[0], TEST1, towrite);
1327 
1328 	if (len < 0)
1329 		tt_abort_perror("initial write");
1330 	else if (len != towrite)
1331 		tt_abort_printf(("initial write fell short (%d of %d bytes)",
1332 				 len, towrite));
1333 
1334 	if (shutdown(data->pair[0], SHUT_WR))
1335 		tt_abort_perror("initial write shutdown");
1336 
1337 	base = event_base_new();
1338 	if (!base)
1339 		tt_abort_msg("failed to create event base");
1340 
1341 	args.eb = base;
1342 	args.ev = &ev1;
1343 	args.callcount = 0;
1344 	event_assign(&ev1, base, data->pair[1],
1345 		     EV_READ|EV_PERSIST, basic_read_cb, &args);
1346 
1347 	if (event_add(&ev1, NULL))
1348 		tt_abort_perror("initial event_add");
1349 
1350 	if (event_base_loop(base, 0))
1351 		tt_abort_msg("unsuccessful exit from event loop");
1352 
1353 end:
1354 	if (base)
1355 		event_base_free(base);
1356 }
1357 
1358 static void
1359 test_loopexit(void)
1360 {
1361 	struct timeval tv, tv_start, tv_end;
1362 	struct event ev;
1363 
1364 	setup_test("Loop exit: ");
1365 
1366 	tv.tv_usec = 0;
1367 	tv.tv_sec = 60*60*24;
1368 	evtimer_set(&ev, timeout_cb, NULL);
1369 	evtimer_add(&ev, &tv);
1370 
1371 	tv.tv_usec = 0;
1372 	tv.tv_sec = 1;
1373 	event_loopexit(&tv);
1374 
1375 	evutil_gettimeofday(&tv_start, NULL);
1376 	event_dispatch();
1377 	evutil_gettimeofday(&tv_end, NULL);
1378 	evutil_timersub(&tv_end, &tv_start, &tv_end);
1379 
1380 	evtimer_del(&ev);
1381 
1382 	tt_assert(event_base_got_exit(global_base));
1383 	tt_assert(!event_base_got_break(global_base));
1384 
1385 	if (tv.tv_sec < 2)
1386 		test_ok = 1;
1387 
1388 end:
1389 	cleanup_test();
1390 }
1391 
1392 static void
1393 test_loopexit_multiple(void)
1394 {
1395 	struct timeval tv;
1396 	struct event_base *base;
1397 
1398 	setup_test("Loop Multiple exit: ");
1399 
1400 	base = event_base_new();
1401 
1402 	tv.tv_usec = 0;
1403 	tv.tv_sec = 1;
1404 	event_base_loopexit(base, &tv);
1405 
1406 	tv.tv_usec = 0;
1407 	tv.tv_sec = 2;
1408 	event_base_loopexit(base, &tv);
1409 
1410 	event_base_dispatch(base);
1411 
1412 	tt_assert(event_base_got_exit(base));
1413 	tt_assert(!event_base_got_break(base));
1414 
1415 	event_base_free(base);
1416 
1417 	test_ok = 1;
1418 
1419 end:
1420 	cleanup_test();
1421 }
1422 
1423 static void
1424 break_cb(evutil_socket_t fd, short events, void *arg)
1425 {
1426 	test_ok = 1;
1427 	event_loopbreak();
1428 }
1429 
1430 static void
1431 fail_cb(evutil_socket_t fd, short events, void *arg)
1432 {
1433 	test_ok = 0;
1434 }
1435 
1436 static void
1437 test_loopbreak(void)
1438 {
1439 	struct event ev1, ev2;
1440 	struct timeval tv;
1441 
1442 	setup_test("Loop break: ");
1443 
1444 	tv.tv_sec = 0;
1445 	tv.tv_usec = 0;
1446 	evtimer_set(&ev1, break_cb, NULL);
1447 	evtimer_add(&ev1, &tv);
1448 	evtimer_set(&ev2, fail_cb, NULL);
1449 	evtimer_add(&ev2, &tv);
1450 
1451 	event_dispatch();
1452 
1453 	tt_assert(!event_base_got_exit(global_base));
1454 	tt_assert(event_base_got_break(global_base));
1455 
1456 	evtimer_del(&ev1);
1457 	evtimer_del(&ev2);
1458 
1459 end:
1460 	cleanup_test();
1461 }
1462 
1463 static struct event *readd_test_event_last_added = NULL;
1464 static void
1465 re_add_read_cb(evutil_socket_t fd, short event, void *arg)
1466 {
1467 	char buf[256];
1468 	struct event *ev_other = arg;
1469 	readd_test_event_last_added = ev_other;
1470 
1471 	if (read(fd, buf, sizeof(buf)) < 0) {
1472 		tt_fail_perror("read");
1473 	}
1474 
1475 	event_add(ev_other, NULL);
1476 	++test_ok;
1477 }
1478 
1479 static void
1480 test_nonpersist_readd(void)
1481 {
1482 	struct event ev1, ev2;
1483 
1484 	setup_test("Re-add nonpersistent events: ");
1485 	event_set(&ev1, pair[0], EV_READ, re_add_read_cb, &ev2);
1486 	event_set(&ev2, pair[1], EV_READ, re_add_read_cb, &ev1);
1487 
1488 	if (write(pair[0], "Hello", 5) < 0) {
1489 		tt_fail_perror("write(pair[0])");
1490 	}
1491 
1492 	if (write(pair[1], "Hello", 5) < 0) {
1493 		tt_fail_perror("write(pair[1])\n");
1494 	}
1495 
1496 	if (event_add(&ev1, NULL) == -1 ||
1497 	    event_add(&ev2, NULL) == -1) {
1498 		test_ok = 0;
1499 	}
1500 	if (test_ok != 0)
1501 		exit(1);
1502 	event_loop(EVLOOP_ONCE);
1503 	if (test_ok != 2)
1504 		exit(1);
1505 	/* At this point, we executed both callbacks.  Whichever one got
1506 	 * called first added the second, but the second then immediately got
1507 	 * deleted before its callback was called.  At this point, though, it
1508 	 * re-added the first.
1509 	 */
1510 	if (!readd_test_event_last_added) {
1511 		test_ok = 0;
1512 	} else if (readd_test_event_last_added == &ev1) {
1513 		if (!event_pending(&ev1, EV_READ, NULL) ||
1514 		    event_pending(&ev2, EV_READ, NULL))
1515 			test_ok = 0;
1516 	} else {
1517 		if (event_pending(&ev1, EV_READ, NULL) ||
1518 		    !event_pending(&ev2, EV_READ, NULL))
1519 			test_ok = 0;
1520 	}
1521 
1522 	event_del(&ev1);
1523 	event_del(&ev2);
1524 
1525 	cleanup_test();
1526 }
1527 
1528 struct test_pri_event {
1529 	struct event ev;
1530 	int count;
1531 };
1532 
1533 static void
1534 test_priorities_cb(evutil_socket_t fd, short what, void *arg)
1535 {
1536 	struct test_pri_event *pri = arg;
1537 	struct timeval tv;
1538 
1539 	if (pri->count == 3) {
1540 		event_loopexit(NULL);
1541 		return;
1542 	}
1543 
1544 	pri->count++;
1545 
1546 	evutil_timerclear(&tv);
1547 	event_add(&pri->ev, &tv);
1548 }
1549 
1550 static void
1551 test_priorities_impl(int npriorities)
1552 {
1553 	struct test_pri_event one, two;
1554 	struct timeval tv;
1555 
1556 	TT_BLATHER(("Testing Priorities %d: ", npriorities));
1557 
1558 	event_base_priority_init(global_base, npriorities);
1559 
1560 	memset(&one, 0, sizeof(one));
1561 	memset(&two, 0, sizeof(two));
1562 
1563 	timeout_set(&one.ev, test_priorities_cb, &one);
1564 	if (event_priority_set(&one.ev, 0) == -1) {
1565 		fprintf(stderr, "%s: failed to set priority", __func__);
1566 		exit(1);
1567 	}
1568 
1569 	timeout_set(&two.ev, test_priorities_cb, &two);
1570 	if (event_priority_set(&two.ev, npriorities - 1) == -1) {
1571 		fprintf(stderr, "%s: failed to set priority", __func__);
1572 		exit(1);
1573 	}
1574 
1575 	evutil_timerclear(&tv);
1576 
1577 	if (event_add(&one.ev, &tv) == -1)
1578 		exit(1);
1579 	if (event_add(&two.ev, &tv) == -1)
1580 		exit(1);
1581 
1582 	event_dispatch();
1583 
1584 	event_del(&one.ev);
1585 	event_del(&two.ev);
1586 
1587 	if (npriorities == 1) {
1588 		if (one.count == 3 && two.count == 3)
1589 			test_ok = 1;
1590 	} else if (npriorities == 2) {
1591 		/* Two is called once because event_loopexit is priority 1 */
1592 		if (one.count == 3 && two.count == 1)
1593 			test_ok = 1;
1594 	} else {
1595 		if (one.count == 3 && two.count == 0)
1596 			test_ok = 1;
1597 	}
1598 }
1599 
1600 static void
1601 test_priorities(void)
1602 {
1603 	test_priorities_impl(1);
1604 	if (test_ok)
1605 		test_priorities_impl(2);
1606 	if (test_ok)
1607 		test_priorities_impl(3);
1608 }
1609 
1610 /* priority-active-inversion: activate a higher-priority event, and make sure
1611  * it keeps us from running a lower-priority event first. */
1612 static int n_pai_calls = 0;
1613 static struct event pai_events[3];
1614 
1615 static void
1616 prio_active_inversion_cb(evutil_socket_t fd, short what, void *arg)
1617 {
1618 	int *call_order = arg;
1619 	*call_order = n_pai_calls++;
1620 	if (n_pai_calls == 1) {
1621 		/* This should activate later, even though it shares a
1622 		   priority with us. */
1623 		event_active(&pai_events[1], EV_READ, 1);
1624 		/* This should activate next, since its priority is higher,
1625 		   even though we activated it second. */
1626 		event_active(&pai_events[2], EV_TIMEOUT, 1);
1627 	}
1628 }
1629 
1630 static void
1631 test_priority_active_inversion(void *data_)
1632 {
1633 	struct basic_test_data *data = data_;
1634 	struct event_base *base = data->base;
1635 	int call_order[3];
1636 	int i;
1637 	tt_int_op(event_base_priority_init(base, 8), ==, 0);
1638 
1639 	n_pai_calls = 0;
1640 	memset(call_order, 0, sizeof(call_order));
1641 
1642 	for (i=0;i<3;++i) {
1643 		event_assign(&pai_events[i], data->base, -1, 0,
1644 		    prio_active_inversion_cb, &call_order[i]);
1645 	}
1646 
1647 	event_priority_set(&pai_events[0], 4);
1648 	event_priority_set(&pai_events[1], 4);
1649 	event_priority_set(&pai_events[2], 0);
1650 
1651 	event_active(&pai_events[0], EV_WRITE, 1);
1652 
1653 	event_base_dispatch(base);
1654 	tt_int_op(n_pai_calls, ==, 3);
1655 	tt_int_op(call_order[0], ==, 0);
1656 	tt_int_op(call_order[1], ==, 2);
1657 	tt_int_op(call_order[2], ==, 1);
1658 end:
1659 	;
1660 }
1661 
1662 
1663 static void
1664 test_multiple_cb(evutil_socket_t fd, short event, void *arg)
1665 {
1666 	if (event & EV_READ)
1667 		test_ok |= 1;
1668 	else if (event & EV_WRITE)
1669 		test_ok |= 2;
1670 }
1671 
1672 static void
1673 test_multiple_events_for_same_fd(void)
1674 {
1675    struct event e1, e2;
1676 
1677    setup_test("Multiple events for same fd: ");
1678 
1679    event_set(&e1, pair[0], EV_READ, test_multiple_cb, NULL);
1680    event_add(&e1, NULL);
1681    event_set(&e2, pair[0], EV_WRITE, test_multiple_cb, NULL);
1682    event_add(&e2, NULL);
1683    event_loop(EVLOOP_ONCE);
1684    event_del(&e2);
1685 
1686    if (write(pair[1], TEST1, strlen(TEST1)+1) < 0) {
1687 	   tt_fail_perror("write");
1688    }
1689 
1690    event_loop(EVLOOP_ONCE);
1691    event_del(&e1);
1692 
1693    if (test_ok != 3)
1694 	   test_ok = 0;
1695 
1696    cleanup_test();
1697 }
1698 
1699 int evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf);
1700 int evtag_decode_int64(ev_uint64_t *pnumber, struct evbuffer *evbuf);
1701 int evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t number);
1702 int evtag_decode_tag(ev_uint32_t *pnumber, struct evbuffer *evbuf);
1703 
1704 static void
1705 read_once_cb(evutil_socket_t fd, short event, void *arg)
1706 {
1707 	char buf[256];
1708 	int len;
1709 
1710 	len = read(fd, buf, sizeof(buf));
1711 
1712 	if (called) {
1713 		test_ok = 0;
1714 	} else if (len) {
1715 		/* Assumes global pair[0] can be used for writing */
1716 		if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
1717 			tt_fail_perror("write");
1718 			test_ok = 0;
1719 		} else {
1720 			test_ok = 1;
1721 		}
1722 	}
1723 
1724 	called++;
1725 }
1726 
1727 static void
1728 test_want_only_once(void)
1729 {
1730 	struct event ev;
1731 	struct timeval tv;
1732 
1733 	/* Very simple read test */
1734 	setup_test("Want read only once: ");
1735 
1736 	if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
1737 		tt_fail_perror("write");
1738 	}
1739 
1740 	/* Setup the loop termination */
1741 	evutil_timerclear(&tv);
1742 	tv.tv_sec = 1;
1743 	event_loopexit(&tv);
1744 
1745 	event_set(&ev, pair[1], EV_READ, read_once_cb, &ev);
1746 	if (event_add(&ev, NULL) == -1)
1747 		exit(1);
1748 	event_dispatch();
1749 
1750 	cleanup_test();
1751 }
1752 
1753 #define TEST_MAX_INT	6
1754 
1755 static void
1756 evtag_int_test(void *ptr)
1757 {
1758 	struct evbuffer *tmp = evbuffer_new();
1759 	ev_uint32_t integers[TEST_MAX_INT] = {
1760 		0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
1761 	};
1762 	ev_uint32_t integer;
1763 	ev_uint64_t big_int;
1764 	int i;
1765 
1766 	evtag_init();
1767 
1768 	for (i = 0; i < TEST_MAX_INT; i++) {
1769 		int oldlen, newlen;
1770 		oldlen = (int)EVBUFFER_LENGTH(tmp);
1771 		evtag_encode_int(tmp, integers[i]);
1772 		newlen = (int)EVBUFFER_LENGTH(tmp);
1773 		TT_BLATHER(("encoded 0x%08x with %d bytes",
1774 			(unsigned)integers[i], newlen - oldlen));
1775 		big_int = integers[i];
1776 		big_int *= 1000000000; /* 1 billion */
1777 		evtag_encode_int64(tmp, big_int);
1778 	}
1779 
1780 	for (i = 0; i < TEST_MAX_INT; i++) {
1781 		tt_int_op(evtag_decode_int(&integer, tmp), !=, -1);
1782 		tt_uint_op(integer, ==, integers[i]);
1783 		tt_int_op(evtag_decode_int64(&big_int, tmp), !=, -1);
1784 		tt_assert((big_int / 1000000000) == integers[i]);
1785 	}
1786 
1787 	tt_uint_op(EVBUFFER_LENGTH(tmp), ==, 0);
1788 end:
1789 	evbuffer_free(tmp);
1790 }
1791 
1792 static void
1793 evtag_fuzz(void *ptr)
1794 {
1795 	u_char buffer[4096];
1796 	struct evbuffer *tmp = evbuffer_new();
1797 	struct timeval tv;
1798 	int i, j;
1799 
1800 	int not_failed = 0;
1801 
1802 	evtag_init();
1803 
1804 	for (j = 0; j < 100; j++) {
1805 		for (i = 0; i < (int)sizeof(buffer); i++)
1806 			buffer[i] = rand();
1807 		evbuffer_drain(tmp, -1);
1808 		evbuffer_add(tmp, buffer, sizeof(buffer));
1809 
1810 		if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1)
1811 			not_failed++;
1812 	}
1813 
1814 	/* The majority of decodes should fail */
1815 	tt_int_op(not_failed, <, 10);
1816 
1817 	/* Now insert some corruption into the tag length field */
1818 	evbuffer_drain(tmp, -1);
1819 	evutil_timerclear(&tv);
1820 	tv.tv_sec = 1;
1821 	evtag_marshal_timeval(tmp, 0, &tv);
1822 	evbuffer_add(tmp, buffer, sizeof(buffer));
1823 
1824 	((char *)EVBUFFER_DATA(tmp))[1] = '\xff';
1825 	if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1) {
1826 		tt_abort_msg("evtag_unmarshal_timeval should have failed");
1827 	}
1828 
1829 end:
1830 	evbuffer_free(tmp);
1831 }
1832 
1833 static void
1834 evtag_tag_encoding(void *ptr)
1835 {
1836 	struct evbuffer *tmp = evbuffer_new();
1837 	ev_uint32_t integers[TEST_MAX_INT] = {
1838 		0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
1839 	};
1840 	ev_uint32_t integer;
1841 	int i;
1842 
1843 	evtag_init();
1844 
1845 	for (i = 0; i < TEST_MAX_INT; i++) {
1846 		int oldlen, newlen;
1847 		oldlen = (int)EVBUFFER_LENGTH(tmp);
1848 		evtag_encode_tag(tmp, integers[i]);
1849 		newlen = (int)EVBUFFER_LENGTH(tmp);
1850 		TT_BLATHER(("encoded 0x%08x with %d bytes",
1851 			(unsigned)integers[i], newlen - oldlen));
1852 	}
1853 
1854 	for (i = 0; i < TEST_MAX_INT; i++) {
1855 		tt_int_op(evtag_decode_tag(&integer, tmp), !=, -1);
1856 		tt_uint_op(integer, ==, integers[i]);
1857 	}
1858 
1859 	tt_uint_op(EVBUFFER_LENGTH(tmp), ==, 0);
1860 
1861 end:
1862 	evbuffer_free(tmp);
1863 }
1864 
1865 static void
1866 evtag_test_peek(void *ptr)
1867 {
1868 	struct evbuffer *tmp = evbuffer_new();
1869 	ev_uint32_t u32;
1870 
1871 	evtag_marshal_int(tmp, 30, 0);
1872 	evtag_marshal_string(tmp, 40, "Hello world");
1873 
1874 	tt_int_op(evtag_peek(tmp, &u32), ==, 1);
1875 	tt_int_op(u32, ==, 30);
1876 	tt_int_op(evtag_peek_length(tmp, &u32), ==, 0);
1877 	tt_int_op(u32, ==, 1+1+1);
1878 	tt_int_op(evtag_consume(tmp), ==, 0);
1879 
1880 	tt_int_op(evtag_peek(tmp, &u32), ==, 1);
1881 	tt_int_op(u32, ==, 40);
1882 	tt_int_op(evtag_peek_length(tmp, &u32), ==, 0);
1883 	tt_int_op(u32, ==, 1+1+11);
1884 	tt_int_op(evtag_payload_length(tmp, &u32), ==, 0);
1885 	tt_int_op(u32, ==, 11);
1886 
1887 end:
1888 	evbuffer_free(tmp);
1889 }
1890 
1891 
1892 static void
1893 test_methods(void *ptr)
1894 {
1895 	const char **methods = event_get_supported_methods();
1896 	struct event_config *cfg = NULL;
1897 	struct event_base *base = NULL;
1898 	const char *backend;
1899 	int n_methods = 0;
1900 
1901 	tt_assert(methods);
1902 
1903 	backend = methods[0];
1904 	while (*methods != NULL) {
1905 		TT_BLATHER(("Support method: %s", *methods));
1906 		++methods;
1907 		++n_methods;
1908 	}
1909 
1910 	cfg = event_config_new();
1911 	assert(cfg != NULL);
1912 
1913 	tt_int_op(event_config_avoid_method(cfg, backend), ==, 0);
1914 	event_config_set_flag(cfg, EVENT_BASE_FLAG_IGNORE_ENV);
1915 
1916 	base = event_base_new_with_config(cfg);
1917 	if (n_methods > 1) {
1918 		tt_assert(base);
1919 		tt_str_op(backend, !=, event_base_get_method(base));
1920 	} else {
1921 		tt_assert(base == NULL);
1922 	}
1923 
1924 end:
1925 	if (base)
1926 		event_base_free(base);
1927 	if (cfg)
1928 		event_config_free(cfg);
1929 }
1930 
1931 static void
1932 test_version(void *arg)
1933 {
1934 	const char *vstr;
1935 	ev_uint32_t vint;
1936 	int major, minor, patch, n;
1937 
1938 	vstr = event_get_version();
1939 	vint = event_get_version_number();
1940 
1941 	tt_assert(vstr);
1942 	tt_assert(vint);
1943 
1944 	tt_str_op(vstr, ==, LIBEVENT_VERSION);
1945 	tt_int_op(vint, ==, LIBEVENT_VERSION_NUMBER);
1946 
1947 	n = sscanf(vstr, "%d.%d.%d", &major, &minor, &patch);
1948 	tt_assert(3 == n);
1949 	tt_int_op((vint&0xffffff00), ==, ((major<<24)|(minor<<16)|(patch<<8)));
1950 end:
1951 	;
1952 }
1953 
1954 static void
1955 test_base_features(void *arg)
1956 {
1957 	struct event_base *base = NULL;
1958 	struct event_config *cfg = NULL;
1959 
1960 	cfg = event_config_new();
1961 
1962 	tt_assert(0 == event_config_require_features(cfg, EV_FEATURE_ET));
1963 
1964 	base = event_base_new_with_config(cfg);
1965 	if (base) {
1966 		tt_int_op(EV_FEATURE_ET, ==,
1967 		    event_base_get_features(base) & EV_FEATURE_ET);
1968 	} else {
1969 		base = event_base_new();
1970 		tt_int_op(0, ==, event_base_get_features(base) & EV_FEATURE_ET);
1971 	}
1972 
1973 end:
1974 	if (base)
1975 		event_base_free(base);
1976 	if (cfg)
1977 		event_config_free(cfg);
1978 }
1979 
1980 #ifdef _EVENT_HAVE_SETENV
1981 #define SETENV_OK
1982 #elif !defined(_EVENT_HAVE_SETENV) && defined(_EVENT_HAVE_PUTENV)
1983 static void setenv(const char *k, const char *v, int _o)
1984 {
1985 	char b[256];
1986 	evutil_snprintf(b, sizeof(b), "%s=%s",k,v);
1987 	putenv(b);
1988 }
1989 #define SETENV_OK
1990 #endif
1991 
1992 #ifdef _EVENT_HAVE_UNSETENV
1993 #define UNSETENV_OK
1994 #elif !defined(_EVENT_HAVE_UNSETENV) && defined(_EVENT_HAVE_PUTENV)
1995 static void unsetenv(const char *k)
1996 {
1997 	char b[256];
1998 	evutil_snprintf(b, sizeof(b), "%s=",k);
1999 	putenv(b);
2000 }
2001 #define UNSETENV_OK
2002 #endif
2003 
2004 #if defined(SETENV_OK) && defined(UNSETENV_OK)
2005 static void
2006 methodname_to_envvar(const char *mname, char *buf, size_t buflen)
2007 {
2008 	char *cp;
2009 	evutil_snprintf(buf, buflen, "EVENT_NO%s", mname);
2010 	for (cp = buf; *cp; ++cp) {
2011 		*cp = EVUTIL_TOUPPER(*cp);
2012 	}
2013 }
2014 #endif
2015 
2016 static void
2017 test_base_environ(void *arg)
2018 {
2019 	struct event_base *base = NULL;
2020 	struct event_config *cfg = NULL;
2021 
2022 #if defined(SETENV_OK) && defined(UNSETENV_OK)
2023 	const char **basenames;
2024 	int i, n_methods=0;
2025 	char varbuf[128];
2026 	const char *defaultname, *ignoreenvname;
2027 
2028 	/* See if unsetenv works before we rely on it. */
2029 	setenv("EVENT_NOWAFFLES", "1", 1);
2030 	unsetenv("EVENT_NOWAFFLES");
2031 	if (getenv("EVENT_NOWAFFLES") != NULL) {
2032 #ifndef _EVENT_HAVE_UNSETENV
2033 		TT_DECLARE("NOTE", ("Can't fake unsetenv; skipping test"));
2034 #else
2035 		TT_DECLARE("NOTE", ("unsetenv doesn't work; skipping test"));
2036 #endif
2037 		tt_skip();
2038 	}
2039 
2040 	basenames = event_get_supported_methods();
2041 	for (i = 0; basenames[i]; ++i) {
2042 		methodname_to_envvar(basenames[i], varbuf, sizeof(varbuf));
2043 		unsetenv(varbuf);
2044 		++n_methods;
2045 	}
2046 
2047 	base = event_base_new();
2048 	tt_assert(base);
2049 
2050 	defaultname = event_base_get_method(base);
2051 	TT_BLATHER(("default is <%s>", defaultname));
2052 	event_base_free(base);
2053 	base = NULL;
2054 
2055 	/* Can we disable the method with EVENT_NOfoo ? */
2056 	if (!strcmp(defaultname, "epoll (with changelist)")) {
2057  		setenv("EVENT_NOEPOLL", "1", 1);
2058 		ignoreenvname = "epoll";
2059 	} else {
2060 		methodname_to_envvar(defaultname, varbuf, sizeof(varbuf));
2061 		setenv(varbuf, "1", 1);
2062 		ignoreenvname = defaultname;
2063 	}
2064 
2065 	/* Use an empty cfg rather than NULL so a failure doesn't exit() */
2066 	cfg = event_config_new();
2067 	base = event_base_new_with_config(cfg);
2068 	event_config_free(cfg);
2069 	cfg = NULL;
2070 	if (n_methods == 1) {
2071 		tt_assert(!base);
2072 	} else {
2073 		tt_assert(base);
2074 		tt_str_op(defaultname, !=, event_base_get_method(base));
2075 		event_base_free(base);
2076 		base = NULL;
2077 	}
2078 
2079 	/* Can we disable looking at the environment with IGNORE_ENV ? */
2080 	cfg = event_config_new();
2081 	event_config_set_flag(cfg, EVENT_BASE_FLAG_IGNORE_ENV);
2082 	base = event_base_new_with_config(cfg);
2083 	tt_assert(base);
2084 	tt_str_op(ignoreenvname, ==, event_base_get_method(base));
2085 #else
2086 	tt_skip();
2087 #endif
2088 
2089 end:
2090 	if (base)
2091 		event_base_free(base);
2092 	if (cfg)
2093 		event_config_free(cfg);
2094 }
2095 
2096 static void
2097 read_called_once_cb(evutil_socket_t fd, short event, void *arg)
2098 {
2099 	tt_int_op(event, ==, EV_READ);
2100 	called += 1;
2101 end:
2102 	;
2103 }
2104 
2105 static void
2106 timeout_called_once_cb(evutil_socket_t fd, short event, void *arg)
2107 {
2108 	tt_int_op(event, ==, EV_TIMEOUT);
2109 	called += 100;
2110 end:
2111 	;
2112 }
2113 
2114 static void
2115 test_event_once(void *ptr)
2116 {
2117 	struct basic_test_data *data = ptr;
2118 	struct timeval tv;
2119 	int r;
2120 
2121 	tv.tv_sec = 0;
2122 	tv.tv_usec = 50*1000;
2123 	called = 0;
2124 	r = event_base_once(data->base, data->pair[0], EV_READ,
2125 	    read_called_once_cb, NULL, NULL);
2126 	tt_int_op(r, ==, 0);
2127 	r = event_base_once(data->base, -1, EV_TIMEOUT,
2128 	    timeout_called_once_cb, NULL, &tv);
2129 	tt_int_op(r, ==, 0);
2130 	r = event_base_once(data->base, -1, 0, NULL, NULL, NULL);
2131 	tt_int_op(r, <, 0);
2132 
2133 	if (write(data->pair[1], TEST1, strlen(TEST1)+1) < 0) {
2134 		tt_fail_perror("write");
2135 	}
2136 
2137 	shutdown(data->pair[1], SHUT_WR);
2138 
2139 	event_base_dispatch(data->base);
2140 
2141 	tt_int_op(called, ==, 101);
2142 end:
2143 	;
2144 }
2145 
2146 static void
2147 test_event_pending(void *ptr)
2148 {
2149 	struct basic_test_data *data = ptr;
2150 	struct event *r=NULL, *w=NULL, *t=NULL;
2151 	struct timeval tv, now, tv2, diff;
2152 
2153 	tv.tv_sec = 0;
2154 	tv.tv_usec = 500 * 1000;
2155 	r = event_new(data->base, data->pair[0], EV_READ, simple_read_cb,
2156 	    NULL);
2157 	w = event_new(data->base, data->pair[1], EV_WRITE, simple_write_cb,
2158 	    NULL);
2159 	t = evtimer_new(data->base, timeout_cb, NULL);
2160 
2161 	tt_assert(r);
2162 	tt_assert(w);
2163 	tt_assert(t);
2164 
2165 	evutil_gettimeofday(&now, NULL);
2166 	event_add(r, NULL);
2167 	event_add(t, &tv);
2168 
2169 	tt_assert( event_pending(r, EV_READ, NULL));
2170 	tt_assert(!event_pending(w, EV_WRITE, NULL));
2171 	tt_assert(!event_pending(r, EV_WRITE, NULL));
2172 	tt_assert( event_pending(r, EV_READ|EV_WRITE, NULL));
2173 	tt_assert(!event_pending(r, EV_TIMEOUT, NULL));
2174 	tt_assert( event_pending(t, EV_TIMEOUT, NULL));
2175 	tt_assert( event_pending(t, EV_TIMEOUT, &tv2));
2176 
2177 	tt_assert(evutil_timercmp(&tv2, &now, >));
2178 	evutil_timeradd(&now, &tv, &tv);
2179 	evutil_timersub(&tv2, &tv, &diff);
2180 	tt_int_op(diff.tv_sec, ==, 0);
2181 	tt_int_op(labs(diff.tv_usec), <, 1000);
2182 
2183 end:
2184 	if (r) {
2185 		event_del(r);
2186 		event_free(r);
2187 	}
2188 	if (w) {
2189 		event_del(w);
2190 		event_free(w);
2191 	}
2192 	if (t) {
2193 		event_del(t);
2194 		event_free(t);
2195 	}
2196 }
2197 
2198 #ifndef WIN32
2199 /* You can't do this test on windows, since dup2 doesn't work on sockets */
2200 
2201 static void
2202 dfd_cb(evutil_socket_t fd, short e, void *data)
2203 {
2204 	*(int*)data = (int)e;
2205 }
2206 
2207 /* Regression test for our workaround for a fun epoll/linux related bug
2208  * where fd2 = dup(fd1); add(fd2); close(fd2); dup2(fd1,fd2); add(fd2)
2209  * will get you an EEXIST */
2210 static void
2211 test_dup_fd(void *arg)
2212 {
2213 	struct basic_test_data *data = arg;
2214 	struct event_base *base = data->base;
2215 	struct event *ev1=NULL, *ev2=NULL;
2216 	int fd, dfd=-1;
2217 	int ev1_got, ev2_got;
2218 
2219 	tt_int_op(write(data->pair[0], "Hello world",
2220 		strlen("Hello world")), >, 0);
2221 	fd = data->pair[1];
2222 
2223 	dfd = dup(fd);
2224 	tt_int_op(dfd, >=, 0);
2225 
2226 	ev1 = event_new(base, fd, EV_READ|EV_PERSIST, dfd_cb, &ev1_got);
2227 	ev2 = event_new(base, dfd, EV_READ|EV_PERSIST, dfd_cb, &ev2_got);
2228 	ev1_got = ev2_got = 0;
2229 	event_add(ev1, NULL);
2230 	event_add(ev2, NULL);
2231 	event_base_loop(base, EVLOOP_ONCE);
2232 	tt_int_op(ev1_got, ==, EV_READ);
2233 	tt_int_op(ev2_got, ==, EV_READ);
2234 
2235 	/* Now close and delete dfd then dispatch.  We need to do the
2236 	 * dispatch here so that when we add it later, we think there
2237 	 * was an intermediate delete. */
2238 	close(dfd);
2239 	event_del(ev2);
2240 	ev1_got = ev2_got = 0;
2241 	event_base_loop(base, EVLOOP_ONCE);
2242 	tt_want_int_op(ev1_got, ==, EV_READ);
2243 	tt_int_op(ev2_got, ==, 0);
2244 
2245 	/* Re-duplicate the fd.  We need to get the same duplicated
2246 	 * value that we closed to provoke the epoll quirk.  Also, we
2247 	 * need to change the events to write, or else the old lingering
2248 	 * read event will make the test pass whether the change was
2249 	 * successful or not. */
2250 	tt_int_op(dup2(fd, dfd), ==, dfd);
2251 	event_free(ev2);
2252 	ev2 = event_new(base, dfd, EV_WRITE|EV_PERSIST, dfd_cb, &ev2_got);
2253 	event_add(ev2, NULL);
2254 	ev1_got = ev2_got = 0;
2255 	event_base_loop(base, EVLOOP_ONCE);
2256 	tt_want_int_op(ev1_got, ==, EV_READ);
2257 	tt_int_op(ev2_got, ==, EV_WRITE);
2258 
2259 end:
2260 	if (ev1)
2261 		event_free(ev1);
2262 	if (ev2)
2263 		event_free(ev2);
2264 	if (dfd >= 0)
2265 		close(dfd);
2266 }
2267 #endif
2268 
2269 #ifdef _EVENT_DISABLE_MM_REPLACEMENT
2270 static void
2271 test_mm_functions(void *arg)
2272 {
2273 	_tinytest_set_test_skipped();
2274 }
2275 #else
2276 static int
2277 check_dummy_mem_ok(void *_mem)
2278 {
2279 	char *mem = _mem;
2280 	mem -= 16;
2281 	return !memcmp(mem, "{[<guardedram>]}", 16);
2282 }
2283 
2284 static void *
2285 dummy_malloc(size_t len)
2286 {
2287 	char *mem = malloc(len+16);
2288 	memcpy(mem, "{[<guardedram>]}", 16);
2289 	return mem+16;
2290 }
2291 
2292 static void *
2293 dummy_realloc(void *_mem, size_t len)
2294 {
2295 	char *mem = _mem;
2296 	if (!mem)
2297 		return dummy_malloc(len);
2298 	tt_want(check_dummy_mem_ok(_mem));
2299 	mem -= 16;
2300 	mem = realloc(mem, len+16);
2301 	return mem+16;
2302 }
2303 
2304 static void
2305 dummy_free(void *_mem)
2306 {
2307 	char *mem = _mem;
2308 	tt_want(check_dummy_mem_ok(_mem));
2309 	mem -= 16;
2310 	free(mem);
2311 }
2312 
2313 static void
2314 test_mm_functions(void *arg)
2315 {
2316 	struct event_base *b = NULL;
2317 	struct event_config *cfg = NULL;
2318 	event_set_mem_functions(dummy_malloc, dummy_realloc, dummy_free);
2319 	cfg = event_config_new();
2320 	event_config_avoid_method(cfg, "Nonesuch");
2321 	b = event_base_new_with_config(cfg);
2322 	tt_assert(b);
2323 	tt_assert(check_dummy_mem_ok(b));
2324 end:
2325 	if (cfg)
2326 		event_config_free(cfg);
2327 	if (b)
2328 		event_base_free(b);
2329 }
2330 #endif
2331 
2332 static void
2333 many_event_cb(evutil_socket_t fd, short event, void *arg)
2334 {
2335 	int *calledp = arg;
2336 	*calledp += 1;
2337 }
2338 
2339 static void
2340 test_many_events(void *arg)
2341 {
2342 	/* Try 70 events that should all be ready at once.  This will
2343 	 * exercise the "resize" code on most of the backends, and will make
2344 	 * sure that we can get past the 64-handle limit of some windows
2345 	 * functions. */
2346 #define MANY 70
2347 
2348 	struct basic_test_data *data = arg;
2349 	struct event_base *base = data->base;
2350 	int one_at_a_time = data->setup_data != NULL;
2351 	evutil_socket_t sock[MANY];
2352 	struct event *ev[MANY];
2353 	int xcalled[MANY];
2354 	int i;
2355 	int loopflags = EVLOOP_NONBLOCK, evflags=0;
2356 	const int is_evport = !strcmp(event_base_get_method(base),"evport");
2357 	if (one_at_a_time) {
2358 		loopflags |= EVLOOP_ONCE;
2359 		evflags = EV_PERSIST;
2360 	}
2361 
2362 	memset(sock, 0xff, sizeof(sock));
2363 	memset(ev, 0, sizeof(ev));
2364 	memset(xcalled, 0, sizeof(xcalled));
2365 	if (is_evport && one_at_a_time) {
2366 		TT_DECLARE("NOTE", ("evport can't pass this in 2.0; skipping\n"));
2367 		tt_skip();
2368 	}
2369 
2370 	for (i = 0; i < MANY; ++i) {
2371 		/* We need an event that will hit the backend, and that will
2372 		 * be ready immediately.  "Send a datagram" is an easy
2373 		 * instance of that. */
2374 		sock[i] = socket(AF_INET, SOCK_DGRAM, 0);
2375 		tt_assert(sock[i] >= 0);
2376 		xcalled[i] = 0;
2377 		ev[i] = event_new(base, sock[i], EV_WRITE|evflags,
2378 		    many_event_cb, &xcalled[i]);
2379 		event_add(ev[i], NULL);
2380 		if (one_at_a_time)
2381 			event_base_loop(base, EVLOOP_NONBLOCK|EVLOOP_ONCE);
2382 	}
2383 
2384 	event_base_loop(base, loopflags);
2385 
2386 	for (i = 0; i < MANY; ++i) {
2387 		if (one_at_a_time)
2388 			tt_int_op(xcalled[i], ==, MANY - i + 1);
2389 		else
2390 			tt_int_op(xcalled[i], ==, 1);
2391 	}
2392 
2393 end:
2394 	for (i = 0; i < MANY; ++i) {
2395 		if (ev[i])
2396 			event_free(ev[i]);
2397 		if (sock[i] >= 0)
2398 			evutil_closesocket(sock[i]);
2399 	}
2400 #undef MANY
2401 }
2402 
2403 static void
2404 test_struct_event_size(void *arg)
2405 {
2406 	tt_int_op(event_get_struct_event_size(), <=, sizeof(struct event));
2407 end:
2408 	;
2409 }
2410 
2411 struct testcase_t main_testcases[] = {
2412 	/* Some converted-over tests */
2413 	{ "methods", test_methods, TT_FORK, NULL, NULL },
2414 	{ "version", test_version, 0, NULL, NULL },
2415 	BASIC(base_features, TT_FORK|TT_NO_LOGS),
2416 	{ "base_environ", test_base_environ, TT_FORK, NULL, NULL },
2417 
2418 	BASIC(event_base_new, TT_FORK|TT_NEED_SOCKETPAIR),
2419 	BASIC(free_active_base, TT_FORK|TT_NEED_SOCKETPAIR),
2420 
2421 	BASIC(manipulate_active_events, TT_FORK|TT_NEED_BASE),
2422 
2423 	BASIC(bad_assign, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
2424 	BASIC(bad_reentrant, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
2425 
2426 	LEGACY(persistent_timeout, TT_FORK|TT_NEED_BASE),
2427 	{ "persistent_timeout_jump", test_persistent_timeout_jump, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
2428 	{ "persistent_active_timeout", test_persistent_active_timeout,
2429 	  TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
2430 	LEGACY(priorities, TT_FORK|TT_NEED_BASE),
2431 	BASIC(priority_active_inversion, TT_FORK|TT_NEED_BASE),
2432 	{ "common_timeout", test_common_timeout, TT_FORK|TT_NEED_BASE,
2433 	  &basic_setup, NULL },
2434 
2435 	/* These legacy tests may not all need all of these flags. */
2436 	LEGACY(simpleread, TT_ISOLATED),
2437 	LEGACY(simpleread_multiple, TT_ISOLATED),
2438 	LEGACY(simplewrite, TT_ISOLATED),
2439 	{ "simpleclose", test_simpleclose, TT_FORK, &basic_setup,
2440 	  NULL },
2441 	LEGACY(multiple, TT_ISOLATED),
2442 	LEGACY(persistent, TT_ISOLATED),
2443 	LEGACY(combined, TT_ISOLATED),
2444 	LEGACY(simpletimeout, TT_ISOLATED),
2445 	LEGACY(loopbreak, TT_ISOLATED),
2446 	LEGACY(loopexit, TT_ISOLATED),
2447 	LEGACY(loopexit_multiple, TT_ISOLATED),
2448 	LEGACY(nonpersist_readd, TT_ISOLATED),
2449 	LEGACY(multiple_events_for_same_fd, TT_ISOLATED),
2450 	LEGACY(want_only_once, TT_ISOLATED),
2451 	{ "event_once", test_event_once, TT_ISOLATED, &basic_setup, NULL },
2452 	{ "event_pending", test_event_pending, TT_ISOLATED, &basic_setup,
2453 	  NULL },
2454 #ifndef WIN32
2455 	{ "dup_fd", test_dup_fd, TT_ISOLATED, &basic_setup, NULL },
2456 #endif
2457 	{ "mm_functions", test_mm_functions, TT_FORK, NULL, NULL },
2458 	{ "many_events", test_many_events, TT_ISOLATED, &basic_setup, NULL },
2459 	{ "many_events_slow_add", test_many_events, TT_ISOLATED, &basic_setup, (void*)1 },
2460 
2461 	{ "struct_event_size", test_struct_event_size, 0, NULL, NULL },
2462 
2463 #ifndef WIN32
2464 	LEGACY(fork, TT_ISOLATED),
2465 #endif
2466 	END_OF_TESTCASES
2467 };
2468 
2469 struct testcase_t evtag_testcases[] = {
2470 	{ "int", evtag_int_test, TT_FORK, NULL, NULL },
2471 	{ "fuzz", evtag_fuzz, TT_FORK, NULL, NULL },
2472 	{ "encoding", evtag_tag_encoding, TT_FORK, NULL, NULL },
2473 	{ "peek", evtag_test_peek, 0, NULL, NULL },
2474 
2475 	END_OF_TESTCASES
2476 };
2477 
2478 struct testcase_t signal_testcases[] = {
2479 #ifndef WIN32
2480 	LEGACY(simplesignal, TT_ISOLATED),
2481 	LEGACY(multiplesignal, TT_ISOLATED),
2482 	LEGACY(immediatesignal, TT_ISOLATED),
2483 	LEGACY(signal_dealloc, TT_ISOLATED),
2484 	LEGACY(signal_pipeloss, TT_ISOLATED),
2485 	LEGACY(signal_switchbase, TT_ISOLATED|TT_NO_LOGS),
2486 	LEGACY(signal_restore, TT_ISOLATED),
2487 	LEGACY(signal_assert, TT_ISOLATED),
2488 	LEGACY(signal_while_processing, TT_ISOLATED),
2489 #endif
2490 	END_OF_TESTCASES
2491 };
2492 
2493