summaryrefslogtreecommitdiff
path: root/regress/sys/kern/fork-exit/fork-exit.c
blob: 6295b00b100ffd1e410097470cfda5c3bba1a24f (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*	$OpenBSD: fork-exit.c,v 1.5 2021/05/21 20:42:21 bluhm Exp $	*/

/*
 * Copyright (c) 2021 Alexander Bluhm <bluhm@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/mman.h>
#include <sys/select.h>
#include <sys/wait.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int execute = 0;
int daemonize = 0;
int heap = 0;
int procs = 1;
int stack = 0;
int threads = 0;
int timeout = 30;

pthread_barrier_t thread_barrier;
char timeoutstr[sizeof("-2147483647")];

static void __dead
usage(void)
{
	fprintf(stderr, "fork-exit [-ed] [-p procs] [-t threads] [-T timeout]\n"
	    "    -e          child execs sleep(1), default call sleep(3)\n"
	    "    -d          daemonize, use if already process group leader\n"
	    "    -h heap     allocate pages of heap memory, default 0\n"
	    "    -p procs    number of processes to fork, default 1\n"
	    "    -s stack    allocate pages of stack memory, default 0\n"
	    "    -t threads  number of threads to create, default 0\n"
	    "    -T timeout  parent and children will exit, default 30 sec\n");
	exit(2);
}

static void
recurse_page(int depth)
{
	int p[4096 / sizeof(int)];

	if (depth == 0)
		return;
	p[1] = 0x9abcdef0;
	explicit_bzero(p, sizeof(int));
	recurse_page(depth - 1);
}

static void
alloc_stack(void)
{
	recurse_page(stack);
}

static void
alloc_heap(void)
{
	int *p;
	int i;

	for(i = 0; i < heap; i++) {
		p = mmap(0, 4096, PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
		if (p == MAP_FAILED)
			err(1, "mmap");
		p[1] = 0x12345678;
		explicit_bzero(p, sizeof(int));
	}
}

static void * __dead
run_thread(void *arg)
{
	int error;

	if (heap)
		alloc_heap();
	if (stack)
		alloc_stack();

	error = pthread_barrier_wait(&thread_barrier);
	if (error && error != PTHREAD_BARRIER_SERIAL_THREAD)
		errc(1, error, "pthread_barrier_wait");

	if (sleep(timeout) != 0)
		err(1, "sleep %d", timeout);

	/* should not happen */
	_exit(0);
}

static void
create_threads(void)
{
	pthread_attr_t tattr;
	pthread_t *thrs;
	int i, error;

	error = pthread_attr_init(&tattr);
	if (error)
		errc(1, error, "pthread_attr_init");
	if (stack) {
		/* thread start and function call overhead needs a bit more */
		error = pthread_attr_setstacksize(&tattr,
		    (stack + 2) * (4096 + 32));
		if (error)
			errc(1, error, "pthread_attr_setstacksize");
	}

	error = pthread_barrier_init(&thread_barrier, NULL, threads + 1);
	if (error)
		errc(1, error, "pthread_barrier_init");

	thrs = reallocarray(NULL, threads, sizeof(pthread_t));
	if (thrs == NULL)
		err(1, "thrs");

	for (i = 0; i < threads; i++) {
		error = pthread_create(&thrs[i], &tattr, run_thread, NULL);
		if (error)
			errc(1, error, "pthread_create");
	}

	error = pthread_barrier_wait(&thread_barrier);
	if (error && error != PTHREAD_BARRIER_SERIAL_THREAD)
		errc(1, error, "pthread_barrier_wait");

	/* return to close child's pipe and sleep */
}

static void __dead
exec_sleep(void)
{
	execl("/bin/sleep", "sleep", timeoutstr, NULL);
	err(1, "exec sleep");
}

static void __dead
run_child(int fd)
{
	/* close pipe to parent and sleep until killed */
	if (execute) {
		if (fcntl(fd, F_SETFD, FD_CLOEXEC))
			err(1, "fcntl FD_CLOEXEC");
		exec_sleep();
	} else {
		if (threads) {
			create_threads();
		} else {
			if (heap)
				alloc_heap();
			if (stack)
				alloc_stack();
		}
		if (close(fd) == -1)
			err(1, "close child");
		if (sleep(timeout) != 0)
			err(1, "sleep %d", timeout);
	}

	/* should not happen */
	_exit(0);
}

static void
sigexit(int sig)
{
	int i, status;
	pid_t pid;

	/* all children must terminate in time */
	if ((int)alarm(timeout) == -1)
		err(1, "alarm");

	for (i = 0; i < procs; i++) {
		pid = wait(&status);
		if (pid == -1)
			err(1, "wait");
		if (!WIFSIGNALED(status))
			errx(1, "child %d not killed", pid);
		if(WTERMSIG(status) != SIGTERM)
			errx(1, "child %d signal %d", pid, WTERMSIG(status));
	}
	exit(0);
}

int
main(int argc, char *argv[])
{
	const char *errstr;
	int ch, i, fdmax, fdlen, *rfds, waiting;
	fd_set *fdset;
	pid_t pgrp;
	struct timeval tv;

	while ((ch = getopt(argc, argv, "edh:p:s:T:t:")) != -1) {
	switch (ch) {
		case 'e':
			execute = 1;
			break;
		case 'd':
			daemonize = 1;
			break;
		case 'h':
			heap = strtonum(optarg, 0, INT_MAX, &errstr);
			if (errstr != NULL)
				errx(1, "number of heap allocations is %s: %s",
				    errstr, optarg);
			break;
		case 'p':
			procs = strtonum(optarg, 0, INT_MAX / 4096, &errstr);
			if (errstr != NULL)
				errx(1, "number of procs is %s: %s", errstr,
				    optarg);
			break;
		case 's':
			stack = strtonum(optarg, 0,
			    (INT_MAX / (4096 + 32)) - 2, &errstr);
			if (errstr != NULL)
				errx(1, "number of stack allocations is %s: %s",
				    errstr, optarg);
			break;
		case 't':
			threads = strtonum(optarg, 0, INT_MAX, &errstr);
			if (errstr != NULL)
				errx(1, "number of threads is %s: %s", errstr,
				    optarg);
			break;
		case 'T':
			timeout = strtonum(optarg, 0, INT_MAX, &errstr);
			if (errstr != NULL)
				errx(1, "timeout is %s: %s", errstr, optarg);
			break;
		default:
			usage();
		}
	}
	if (execute) {
		int ret;

		if (threads > 0)
			errx(1, "execute sleep cannot be used with threads");

		ret = snprintf(timeoutstr, sizeof(timeoutstr), "%d", timeout);
		if (ret < 0 || (size_t)ret >= sizeof(timeoutstr))
			err(1, "snprintf");
	}

	/* become process group leader */
	if (daemonize) {
		/* get rid of process leadership */
		switch (fork()) {
		case -1:
			err(1, "fork parent");
		case 0:
			break;
		default:
			/* parent leaves orphan behind to do the work */
			_exit(0);
		}
	}
	pgrp = setsid();
	if (pgrp == -1) {
		if (!daemonize)
			warnx("try -d to become process group leader");
		err(1, "setsid");
	}

	/* create pipes to keep in contact with children */
	rfds = reallocarray(NULL, procs, sizeof(int));
	if (rfds == NULL)
		err(1, "rfds");
	fdmax = 0;

	/* fork child processes and pass writing end of pipe */
	for (i = 0; i < procs; i++) {
		int pipefds[2], error;

		if (pipe(pipefds) == -1)
			err(1, "pipe");
		if (fdmax < pipefds[0])
			fdmax = pipefds[0];
		rfds[i] = pipefds[0];

		switch (fork()) {
		case -1:
			/* resource temporarily unavailable may happen */
			error = errno;
			/* reap children, but not parent */
			signal(SIGTERM, SIG_IGN);
			kill(-pgrp, SIGTERM);
			errc(1, error, "fork child");
		case 0:
			/* child closes reading end, read is for the parent */
			if (close(pipefds[0]) == -1)
				err(1, "close read");
			run_child(pipefds[1]);
			/* cannot happen */
			_exit(0);
		default:
			/* parent closes writing end, write is for the child */
			if (close(pipefds[1]) == -1)
				err(1, "close write");
			break;
		}
	}

	/* create select mask with all reading ends of child pipes */
	fdlen = howmany(fdmax + 1, NFDBITS);
	fdset = calloc(fdlen, sizeof(fd_mask));
	if (fdset == NULL)
		err(1, "fdset");
	waiting = 0;
	for (i = 0; i < procs; i++) {
		FD_SET(rfds[i], fdset);
		waiting = 1;
	}

	/* wait until all child processes are waiting */
	while (waiting) {
		tv.tv_sec = timeout;
		tv.tv_usec = 0;
		errno = ETIMEDOUT;
		if (select(fdmax + 1, fdset, NULL, NULL, &tv) <= 0)
			err(1, "select");

		waiting = 0;
		/* remove fd of children that closed their end  */
		for (i = 0; i < procs; i++) {
			if (rfds[i] >= 0) {
				if (FD_ISSET(rfds[i], fdset)) {
					if (close(rfds[i]) == -1)
						err(1, "close parent");
					FD_CLR(rfds[i], fdset);
					rfds[i] = -1;
				} else {
					FD_SET(rfds[i], fdset);
					waiting = 1;
				}
			}
		}
	}

	/* kill all children simultaneously, parent exits in signal handler */
	if (signal(SIGTERM, sigexit) == SIG_ERR)
		err(1, "signal SIGTERM");
	if (kill(-pgrp, SIGTERM) == -1)
		err(1, "kill %d", -pgrp);

	errx(1, "alive");
}