xref: /netbsd-src/lib/libc/gen/pthread_atfork.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: pthread_atfork.c,v 1.3 2004/10/21 06:46:36 lukem 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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #if defined(LIBC_SCCS) && !defined(lint)
41 __RCSID("$NetBSD: pthread_atfork.c,v 1.3 2004/10/21 06:46:36 lukem Exp $");
42 #endif /* LIBC_SCCS and not lint */
43 
44 #define __LIBC12_SOURCE__
45 
46 #include "namespace.h"
47 
48 #include <errno.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <sys/queue.h>
52 #include "reentrant.h"
53 
54 #ifdef __weak_alias
55 __weak_alias(pthread_atfork, _pthread_atfork)
56 __weak_alias(fork, _fork)
57 #endif /* __weak_alias */
58 
59 pid_t	__fork __P((void));	/* XXX */
60 
61 struct atfork_callback {
62 	SIMPLEQ_ENTRY(atfork_callback) next;
63 	void (*fn)(void);
64 };
65 
66 /*
67  * Hypothetically, we could protect the queues with a rwlock which is
68  * write-locked by pthread_atfork() and read-locked by fork(), but
69  * since the intended use of the functions is obtaining locks to hold
70  * across the fork, forking is going to be serialized anyway.
71  */
72 static mutex_t atfork_lock = MUTEX_INITIALIZER;
73 SIMPLEQ_HEAD(atfork_callback_q, atfork_callback);
74 
75 static struct atfork_callback_q prepareq = SIMPLEQ_HEAD_INITIALIZER(prepareq);
76 static struct atfork_callback_q parentq = SIMPLEQ_HEAD_INITIALIZER(parentq);
77 static struct atfork_callback_q childq = SIMPLEQ_HEAD_INITIALIZER(childq);
78 
79 int
80 pthread_atfork(void (*prepare)(void), void (*parent)(void),
81     void (*child)(void))
82 {
83 	struct atfork_callback *newprepare, *newparent, *newchild;
84 
85 	if (prepare != NULL) {
86 		newprepare = malloc(sizeof(struct atfork_callback));
87 		if (newprepare == NULL)
88 			return ENOMEM;
89 		newprepare->fn = prepare;
90 	}
91 
92 	if (parent != NULL) {
93 		newparent = malloc(sizeof(struct atfork_callback));
94 		if (newparent == NULL) {
95 			if (newprepare != NULL)
96 				free(newprepare);
97 			return ENOMEM;
98 		}
99 		newparent->fn = parent;
100 	}
101 
102 	if (child != NULL) {
103 		newchild = malloc(sizeof(struct atfork_callback));
104 		if (newchild == NULL) {
105 			if (newprepare != NULL)
106 				free(newprepare);
107 			if (newparent != NULL)
108 				free(newparent);
109 			return ENOMEM;
110 		}
111 		newchild->fn = child;
112 	}
113 
114 	mutex_lock(&atfork_lock);
115 	/*
116 	 * The order in which the functions are called is specified as
117 	 * LIFO for the prepare handler and FIFO for the others; insert
118 	 * at the head and tail as appropriate so that SIMPLEQ_FOREACH()
119 	 * produces the right order.
120 	 */
121 	if (prepare)
122 		SIMPLEQ_INSERT_HEAD(&prepareq, newprepare, next);
123 	if (parent)
124 		SIMPLEQ_INSERT_TAIL(&parentq, newparent, next);
125 	if (child)
126 		SIMPLEQ_INSERT_TAIL(&childq, newchild, next);
127 	mutex_unlock(&atfork_lock);
128 
129 	return 0;
130 }
131 
132 pid_t
133 fork(void)
134 {
135 	struct atfork_callback *iter;
136 	pid_t ret;
137 
138 	mutex_lock(&atfork_lock);
139 	SIMPLEQ_FOREACH(iter, &prepareq, next)
140 	    (*iter->fn)();
141 
142 	ret = __fork();
143 
144 	if (ret != 0) {
145 		/*
146 		 * We are the parent. It doesn't matter here whether
147 		 * the fork call succeeded or failed.
148 		 */
149 		SIMPLEQ_FOREACH(iter, &parentq, next)
150 		    (*iter->fn)();
151 		mutex_unlock(&atfork_lock);
152 	} else {
153 		/* We are the child */
154 		SIMPLEQ_FOREACH(iter, &childq, next)
155 		    (*iter->fn)();
156 		/*
157 		 * Note: We are explicitly *not* unlocking
158 		 * atfork_lock.  Unlocking atfork_lock is problematic,
159 		 * because if any threads in the parent blocked on it
160 		 * between the initial lock and the fork() syscall,
161 		 * unlocking in the child will try to schedule
162 		 * threads, and either the internal mutex interlock or
163 		 * the runqueue spinlock could have been held at the
164 		 * moment of fork(). Since the other threads do not
165 		 * exist in this process, the spinlock will never be
166 		 * unlocked, and we would wedge.
167 		 * Instead, we reinitialize atfork_lock, since we know
168 		 * that the state of the atfork lists is consistent here,
169 		 * and that there are no other threads to be affected by
170 		 * the forcible cleaning of the queue.
171 		 * This permits double-forking to work, although
172 		 * it requires knowing that it's "safe" to initialize
173 		 * a locked mutex in this context.
174 		 *
175 		 * The problem exists for users of this interface,
176 		 * too, since the intented use of pthread_atfork() is
177 		 * to acquire locks across the fork call to ensure
178 		 * that the child sees consistent state. There's not
179 		 * much that can usefully be done in a child handler,
180 		 * and conventional wisdom discourages using them, but
181 		 * they're part of the interface, so here we are...
182 		 */
183 		mutex_init(&atfork_lock, NULL);
184 	}
185 
186 	return ret;
187 }
188