xref: /netbsd-src/lib/libc/gen/pthread_atfork.c (revision 4724848cf0da353df257f730694b7882798e5daf)
1 /*	$NetBSD: pthread_atfork.c,v 1.17 2022/09/13 10:18:47 riastradh Exp $	*/
2 
3 /*-
4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Nathan J. Williams.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 __RCSID("$NetBSD: pthread_atfork.c,v 1.17 2022/09/13 10:18:47 riastradh Exp $");
35 #endif /* LIBC_SCCS and not lint */
36 
37 #include "namespace.h"
38 
39 #include <errno.h>
40 #include <stdlib.h>
41 #include <unistd.h>
42 #include <sys/queue.h>
43 #include "extern.h"
44 #include "reentrant.h"
45 
46 #ifdef __weak_alias
47 __weak_alias(pthread_atfork, _pthread_atfork)
48 __weak_alias(fork, _fork)
49 #endif /* __weak_alias */
50 
51 pid_t	__fork(void);	/* XXX */
52 pid_t	__locked_fork(int *) __weak; /* XXX */
53 
54 pid_t
55 __locked_fork(int *my_errno)
56 {
57 	return __fork();
58 }
59 
60 struct atfork_callback {
61 	SIMPLEQ_ENTRY(atfork_callback) next;
62 	void (*fn)(void);
63 };
64 
65 /*
66  * Hypothetically, we could protect the queues with a rwlock which is
67  * write-locked by pthread_atfork() and read-locked by fork(), but
68  * since the intended use of the functions is obtaining locks to hold
69  * across the fork, forking is going to be serialized anyway.
70  */
71 static struct atfork_callback atfork_builtin;
72 #ifdef _REENTRANT
73 static mutex_t atfork_lock = MUTEX_INITIALIZER;
74 #endif
75 SIMPLEQ_HEAD(atfork_callback_q, atfork_callback);
76 
77 static struct atfork_callback_q prepareq = SIMPLEQ_HEAD_INITIALIZER(prepareq);
78 static struct atfork_callback_q parentq = SIMPLEQ_HEAD_INITIALIZER(parentq);
79 static struct atfork_callback_q childq = SIMPLEQ_HEAD_INITIALIZER(childq);
80 
81 static struct atfork_callback *
82 af_alloc(void)
83 {
84 
85 	if (atfork_builtin.fn == NULL)
86 		return &atfork_builtin;
87 
88 	return malloc(sizeof(atfork_builtin));
89 }
90 
91 static void
92 af_free(struct atfork_callback *af)
93 {
94 
95 	if (af != &atfork_builtin)
96 		free(af);
97 }
98 
99 int
100 pthread_atfork(void (*prepare)(void), void (*parent)(void),
101     void (*child)(void))
102 {
103 	struct atfork_callback *newprepare, *newparent, *newchild;
104 	sigset_t mask, omask;
105 	int error;
106 
107 	newprepare = newparent = newchild = NULL;
108 
109 	sigfillset(&mask);
110 	thr_sigsetmask(SIG_SETMASK, &mask, &omask);
111 
112 	mutex_lock(&atfork_lock);
113 	if (prepare != NULL) {
114 		newprepare = af_alloc();
115 		if (newprepare == NULL) {
116 			error = ENOMEM;
117 			goto out;
118 		}
119 		newprepare->fn = prepare;
120 	}
121 
122 	if (parent != NULL) {
123 		newparent = af_alloc();
124 		if (newparent == NULL) {
125 			if (newprepare != NULL)
126 				af_free(newprepare);
127 			error = ENOMEM;
128 			goto out;
129 		}
130 		newparent->fn = parent;
131 	}
132 
133 	if (child != NULL) {
134 		newchild = af_alloc();
135 		if (newchild == NULL) {
136 			if (newprepare != NULL)
137 				af_free(newprepare);
138 			if (newparent != NULL)
139 				af_free(newparent);
140 			error = ENOMEM;
141 			goto out;
142 		}
143 		newchild->fn = child;
144 	}
145 
146 	/*
147 	 * The order in which the functions are called is specified as
148 	 * LIFO for the prepare handler and FIFO for the others; insert
149 	 * at the head and tail as appropriate so that SIMPLEQ_FOREACH()
150 	 * produces the right order.
151 	 */
152 	if (prepare)
153 		SIMPLEQ_INSERT_HEAD(&prepareq, newprepare, next);
154 	if (parent)
155 		SIMPLEQ_INSERT_TAIL(&parentq, newparent, next);
156 	if (child)
157 		SIMPLEQ_INSERT_TAIL(&childq, newchild, next);
158 	error = 0;
159 
160 out:	mutex_unlock(&atfork_lock);
161 	thr_sigsetmask(SIG_SETMASK, &omask, NULL);
162 	return error;
163 }
164 
165 pid_t
166 fork(void)
167 {
168 	struct atfork_callback *iter;
169 	pid_t ret;
170 
171 	mutex_lock(&atfork_lock);
172 	SIMPLEQ_FOREACH(iter, &prepareq, next)
173 		(*iter->fn)();
174 	_malloc_prefork();
175 
176 	ret = __locked_fork(&errno);
177 
178 	if (ret != 0) {
179 		/*
180 		 * We are the parent. It doesn't matter here whether
181 		 * the fork call succeeded or failed.
182 		 */
183 		_malloc_postfork();
184 		SIMPLEQ_FOREACH(iter, &parentq, next)
185 			(*iter->fn)();
186 		mutex_unlock(&atfork_lock);
187 	} else {
188 		/* We are the child */
189 		_malloc_postfork_child();
190 		SIMPLEQ_FOREACH(iter, &childq, next)
191 			(*iter->fn)();
192 		/*
193 		 * Note: We are explicitly *not* unlocking
194 		 * atfork_lock.  Unlocking atfork_lock is problematic,
195 		 * because if any threads in the parent blocked on it
196 		 * between the initial lock and the fork() syscall,
197 		 * unlocking in the child will try to schedule
198 		 * threads, and either the internal mutex interlock or
199 		 * the runqueue spinlock could have been held at the
200 		 * moment of fork(). Since the other threads do not
201 		 * exist in this process, the spinlock will never be
202 		 * unlocked, and we would wedge.
203 		 * Instead, we reinitialize atfork_lock, since we know
204 		 * that the state of the atfork lists is consistent here,
205 		 * and that there are no other threads to be affected by
206 		 * the forcible cleaning of the queue.
207 		 * This permits double-forking to work, although
208 		 * it requires knowing that it's "safe" to initialize
209 		 * a locked mutex in this context.
210 		 *
211 		 * The problem exists for users of this interface,
212 		 * too, since the intended use of pthread_atfork() is
213 		 * to acquire locks across the fork call to ensure
214 		 * that the child sees consistent state. There's not
215 		 * much that can usefully be done in a child handler,
216 		 * and conventional wisdom discourages using them, but
217 		 * they're part of the interface, so here we are...
218 		 */
219 		mutex_init(&atfork_lock, NULL);
220 	}
221 
222 	return ret;
223 }
224