summaryrefslogtreecommitdiffstats
path: root/tests/sighook.c
blob: c94526e7d2f916c62295511c37c134f9909f8fbb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright © Tavian Barnes <tavianator@tavianator.com>
// SPDX-License-Identifier: 0BSD

#include "prelude.h"
#include "tests.h"
#include "sighook.h"
#include "atomic.h"
#include "thread.h"
#include <pthread.h>
#include <signal.h>
#include <sys/time.h>

static atomic size_t count = 0;

/** SIGALRM handler. */
static void alrm_hook(int sig, siginfo_t *info, void *arg) {
	fetch_add(&count, 1, relaxed);
}

/** Swap out an old hook for a new hook. */
static int swap_hooks(struct sighook **hook) {
	struct sighook *next = sighook(SIGALRM, alrm_hook, NULL, SH_CONTINUE);
	if (!bfs_echeck(next, "sighook(SIGALRM)")) {
		return -1;
	}

	sigunhook(*hook);
	*hook = next;
	return 0;
}

/** Background thread that rapidly (un)registers signal hooks. */
static void *hook_thread(void *ptr) {
	struct sighook *hook = sighook(SIGALRM, alrm_hook, NULL, SH_CONTINUE);
	if (!bfs_echeck(hook, "sighook(SIGALRM)")) {
		return NULL;
	}

	while (load(&count, relaxed) < 1000) {
		if (swap_hooks(&hook) != 0) {
			sigunhook(hook);
			return NULL;
		}
	}

	sigunhook(hook);
	return &count;
}

bool check_sighook(void) {
	bool ret = true;

	struct sighook *hook = sighook(SIGALRM, alrm_hook, NULL, SH_CONTINUE);
	ret &= bfs_echeck(hook, "sighook(SIGALRM)");
	if (!ret) {
		goto done;
	}

	struct itimerval ival = {
		.it_value = {
			.tv_usec = 100,
		},
		.it_interval = {
			.tv_usec = 100,
		},
	};
	ret &= bfs_echeck(setitimer(ITIMER_REAL, &ival, NULL) == 0);
	if (!ret) {
		goto unhook;
	}

	pthread_t thread;
	ret &= bfs_echeck(thread_create(&thread, NULL, hook_thread, NULL) == 0);
	if (!ret) {
		goto untime;
	}

	while (ret && load(&count, relaxed) < 1000) {
		ret &= swap_hooks(&hook) == 0;
	}

 	void *ptr;
	thread_join(thread, &ptr);
	ret &= bfs_check(ptr);

untime:
	ival.it_value.tv_usec = 0;
	ret &= bfs_echeck(setitimer(ITIMER_REAL, &ival, NULL) == 0);
	if (!ret) {
		goto unhook;
	}

unhook:
	sigunhook(hook);
done:
	return ret;
}