xref: /freebsd/lib/libthr/thread/thr_fork.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 /*
2  * Copyright (c) 2005 David Xu <davidxu@freebsd.org>
3  * Copyright (c) 2003 Daniel Eischen <deischen@freebsd.org>
4  * All rights reserved.
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. Neither the name of the author nor the names of any co-contributors
12  *    may be used to endorse or promote products derived from this software
13  *    without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*-
29  * SPDX-License-Identifier: BSD-3-Clause
30  *
31  * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
32  * All rights reserved.
33  *
34  * Redistribution and use in source and binary forms, with or without
35  * modification, are permitted provided that the following conditions
36  * are met:
37  * 1. Redistributions of source code must retain the above copyright
38  *    notice, this list of conditions and the following disclaimer.
39  * 2. Redistributions in binary form must reproduce the above copyright
40  *    notice, this list of conditions and the following disclaimer in the
41  *    documentation and/or other materials provided with the distribution.
42  * 3. Neither the name of the author nor the names of any co-contributors
43  *    may be used to endorse or promote products derived from this software
44  *    without specific prior written permission.
45  *
46  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56  * SUCH DAMAGE.
57  *
58  */
59 
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
62 
63 #include <sys/syscall.h>
64 #include "namespace.h"
65 #include <errno.h>
66 #include <link.h>
67 #include <string.h>
68 #include <stdlib.h>
69 #include <unistd.h>
70 #include <pthread.h>
71 #include <spinlock.h>
72 #include "un-namespace.h"
73 
74 #include "libc_private.h"
75 #include "rtld_lock.h"
76 #include "thr_private.h"
77 
78 __weak_reference(_thr_atfork, _pthread_atfork);
79 __weak_reference(_thr_atfork, pthread_atfork);
80 
81 bool _thr_after_fork = false;
82 
83 int
84 _thr_atfork(void (*prepare)(void), void (*parent)(void),
85     void (*child)(void))
86 {
87 	struct pthread *curthread;
88 	struct pthread_atfork *af;
89 
90 	_thr_check_init();
91 
92 	if ((af = malloc(sizeof(struct pthread_atfork))) == NULL)
93 		return (ENOMEM);
94 
95 	curthread = _get_curthread();
96 	af->prepare = prepare;
97 	af->parent = parent;
98 	af->child = child;
99 	THR_CRITICAL_ENTER(curthread);
100 	_thr_rwl_wrlock(&_thr_atfork_lock);
101 	TAILQ_INSERT_TAIL(&_thr_atfork_list, af, qe);
102 	_thr_rwl_unlock(&_thr_atfork_lock);
103 	THR_CRITICAL_LEAVE(curthread);
104 	return (0);
105 }
106 
107 void
108 __pthread_cxa_finalize(struct dl_phdr_info *phdr_info)
109 {
110 	atfork_head    temp_list = TAILQ_HEAD_INITIALIZER(temp_list);
111 	struct pthread *curthread;
112 	struct pthread_atfork *af, *af1;
113 
114 	_thr_check_init();
115 
116 	curthread = _get_curthread();
117 	THR_CRITICAL_ENTER(curthread);
118 	_thr_rwl_wrlock(&_thr_atfork_lock);
119 	TAILQ_FOREACH_SAFE(af, &_thr_atfork_list, qe, af1) {
120 		if (__elf_phdr_match_addr(phdr_info, af->prepare) ||
121 		    __elf_phdr_match_addr(phdr_info, af->parent) ||
122 		    __elf_phdr_match_addr(phdr_info, af->child)) {
123 			TAILQ_REMOVE(&_thr_atfork_list, af, qe);
124 			TAILQ_INSERT_TAIL(&temp_list, af, qe);
125 		}
126 	}
127 	_thr_rwl_unlock(&_thr_atfork_lock);
128 	THR_CRITICAL_LEAVE(curthread);
129 	while ((af = TAILQ_FIRST(&temp_list)) != NULL) {
130 		TAILQ_REMOVE(&temp_list, af, qe);
131 		free(af);
132 	}
133 	_thr_tsd_unload(phdr_info);
134 	_thr_sigact_unload(phdr_info);
135 }
136 
137 enum thr_fork_mode {
138 	MODE_FORK,
139 	MODE_PDFORK,
140 };
141 
142 struct thr_fork_args {
143 	enum thr_fork_mode mode;
144 	void *fdp;
145 	int flags;
146 };
147 
148 static pid_t
149 thr_fork_impl(const struct thr_fork_args *a)
150 {
151 	struct pthread *curthread;
152 	struct pthread_atfork *af;
153 	pid_t ret;
154 	int errsave, cancelsave;
155 	int was_threaded;
156 	int rtld_locks[MAX_RTLD_LOCKS];
157 
158 	if (!_thr_is_inited()) {
159 		switch (a->mode) {
160 		case MODE_FORK:
161 			return (__sys_fork());
162 		case MODE_PDFORK:
163 			return (__sys_pdfork(a->fdp, a->flags));
164 		default:
165 			errno = EDOOFUS;
166 			return (-1);
167 		}
168 	}
169 
170 	curthread = _get_curthread();
171 	cancelsave = curthread->no_cancel;
172 	curthread->no_cancel = 1;
173 	_thr_rwl_rdlock(&_thr_atfork_lock);
174 
175 	/* Run down atfork prepare handlers. */
176 	TAILQ_FOREACH_REVERSE(af, &_thr_atfork_list, atfork_head, qe) {
177 		if (af->prepare != NULL)
178 			af->prepare();
179 	}
180 
181 	/*
182 	 * Block all signals until we reach a safe point.
183 	 */
184 	_thr_signal_block(curthread);
185 	_thr_signal_prefork();
186 
187 	/*
188 	 * All bets are off as to what should happen soon if the parent
189 	 * process was not so kindly as to set up pthread fork hooks to
190 	 * relinquish all running threads.
191 	 */
192 	if (_thr_isthreaded() != 0) {
193 		was_threaded = 1;
194 		__thr_malloc_prefork(curthread);
195 		_malloc_prefork();
196 		__thr_pshared_atfork_pre();
197 		_rtld_atfork_pre(rtld_locks);
198 	} else {
199 		was_threaded = 0;
200 	}
201 
202 	/*
203 	 * Fork a new process.
204 	 * There is no easy way to pre-resolve the __sys_fork symbol
205 	 * without performing the fork.  Use the syscall(2)
206 	 * indirection, the syscall symbol is resolved in
207 	 * _thr_rtld_init() with side-effect free call.
208 	 */
209 	switch (a->mode) {
210 	case MODE_FORK:
211 		ret = syscall(SYS_fork);
212 		break;
213 	case MODE_PDFORK:
214 		ret = syscall(SYS_pdfork, a->fdp, a->flags);
215 		break;
216 	default:
217 		ret = -1;
218 		errno = EDOOFUS;
219 		break;
220 	}
221 
222 	if (ret == 0) {
223 		/* Child process */
224 		errsave = errno;
225 		curthread->cancel_pending = 0;
226 		curthread->flags &= ~(THR_FLAGS_NEED_SUSPEND|THR_FLAGS_DETACHED);
227 
228 		/*
229 		 * Thread list will be reinitialized, and later we call
230 		 * _libpthread_init(), it will add us back to list.
231 		 */
232 		curthread->tlflags &= ~TLFLAGS_IN_TDLIST;
233 
234 		/* before thr_self() */
235 		if (was_threaded)
236 			__thr_malloc_postfork(curthread);
237 
238 		/* child is a new kernel thread. */
239 		thr_self(&curthread->tid);
240 
241 		/* clear other threads locked us. */
242 		_thr_umutex_init(&curthread->lock);
243 		_mutex_fork(curthread);
244 
245 		_thr_signal_postfork_child();
246 
247 		if (was_threaded) {
248 			_thr_after_fork = true;
249 			_rtld_atfork_post(rtld_locks);
250 			_thr_after_fork = false;
251 			__thr_pshared_atfork_post();
252 		}
253 		_thr_setthreaded(0);
254 
255 		/* reinitalize library. */
256 		_libpthread_init(curthread);
257 
258 		/* atfork is reinitialized by _libpthread_init()! */
259 		_thr_rwl_rdlock(&_thr_atfork_lock);
260 
261 		if (was_threaded) {
262 			_thr_setthreaded(1);
263 			_malloc_postfork();
264 			_thr_setthreaded(0);
265 		}
266 
267 		/* Ready to continue, unblock signals. */
268 		_thr_signal_unblock(curthread);
269 
270 		/* Run down atfork child handlers. */
271 		TAILQ_FOREACH(af, &_thr_atfork_list, qe) {
272 			if (af->child != NULL)
273 				af->child();
274 		}
275 		_thr_rwlock_unlock(&_thr_atfork_lock);
276 		curthread->no_cancel = cancelsave;
277 	} else {
278 		/* Parent process */
279 		errsave = errno;
280 
281 		_thr_signal_postfork();
282 
283 		if (was_threaded) {
284 			__thr_malloc_postfork(curthread);
285 			_rtld_atfork_post(rtld_locks);
286 			__thr_pshared_atfork_post();
287 			_malloc_postfork();
288 		}
289 
290 		/* Ready to continue, unblock signals. */
291 		_thr_signal_unblock(curthread);
292 
293 		/* Run down atfork parent handlers. */
294 		TAILQ_FOREACH(af, &_thr_atfork_list, qe) {
295 			if (af->parent != NULL)
296 				af->parent();
297 		}
298 
299 		_thr_rwlock_unlock(&_thr_atfork_lock);
300 		curthread->no_cancel = cancelsave;
301 		/* test async cancel */
302 		if (curthread->cancel_async)
303 			_thr_testcancel(curthread);
304 	}
305 	errno = errsave;
306 
307 	return (ret);
308 }
309 
310 __weak_reference(__thr_fork, _fork);
311 
312 pid_t
313 __thr_fork(void)
314 {
315 	struct thr_fork_args a;
316 
317 	a.mode = MODE_FORK;
318 	return (thr_fork_impl(&a));
319 }
320 
321 pid_t
322 __thr_pdfork(int *fdp, int flags)
323 {
324 	struct thr_fork_args a;
325 
326 	a.mode = MODE_PDFORK;
327 	a.fdp = fdp;
328 	a.flags = flags;
329 	return (thr_fork_impl(&a));
330 }
331