xref: /freebsd/lib/libthr/thread/thr_exit.c (revision 2357939bc239bd5334a169b62313806178dd8f30)
1 /*
2  * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by John Birrell.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $FreeBSD$
33  */
34 #include <errno.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <pthread.h>
41 #include "thr_private.h"
42 
43 __weak_reference(_pthread_exit, pthread_exit);
44 
45 /* thr_exit() */
46 extern int _thr_exit(void);
47 
48 static void	deadlist_free_threads();
49 
50 void
51 _thread_exit(char *fname, int lineno, char *string)
52 {
53 	char            s[256];
54 
55 	/* Prepare an error message string: */
56 	snprintf(s, sizeof(s),
57 	    "Fatal error '%s' at line %d in file %s (errno = %d)\n",
58 	    string, lineno, fname, errno);
59 
60 	/* Write the string to the standard error file descriptor: */
61 	__sys_write(2, s, strlen(s));
62 
63 	/* Force this process to exit: */
64 	/* XXX - Do we want abort to be conditional on _PTHREADS_INVARIANTS? */
65 #if defined(_PTHREADS_INVARIANTS)
66 	abort();
67 #else
68 	__sys_exit(1);
69 #endif
70 }
71 
72 /*
73  * Only called when a thread is cancelled.  It may be more useful
74  * to call it from pthread_exit() if other ways of asynchronous or
75  * abnormal thread termination can be found.
76  */
77 void
78 _thread_exit_cleanup(void)
79 {
80 	/*
81 	 * POSIX states that cancellation/termination of a thread should
82 	 * not release any visible resources (such as mutexes) and that
83 	 * it is the applications responsibility.  Resources that are
84 	 * internal to the threads library, including file and fd locks,
85 	 * are not visible to the application and need to be released.
86 	 */
87 	/* Unlock all private mutexes: */
88 	_mutex_unlock_private(curthread);
89 
90 	/*
91 	 * This still isn't quite correct because we don't account
92 	 * for held spinlocks (see libc/stdlib/malloc.c).
93 	 */
94 }
95 
96 void
97 _pthread_exit(void *status)
98 {
99 	pthread_t pthread, joiner;
100 	int exitNow = 0;
101 
102 	/* Check if this thread is already in the process of exiting: */
103 	if ((curthread->flags & PTHREAD_EXITING) != 0) {
104 		char msg[128];
105 		snprintf(msg, sizeof(msg), "Thread %p has called pthread_exit() from a destructor. POSIX 1003.1 1996 s16.2.5.2 does not allow this!",curthread);
106 		PANIC(msg);
107 	}
108 
109 	/* Flag this thread as exiting: */
110 	curthread->flags |= PTHREAD_EXITING;
111 
112 	/* Save the return value: */
113 	curthread->ret = status;
114 
115 	while (curthread->cleanup != NULL) {
116 		pthread_cleanup_pop(1);
117 	}
118 	if (curthread->attr.cleanup_attr != NULL) {
119 		curthread->attr.cleanup_attr(curthread->attr.arg_attr);
120 	}
121 	/* Check if there is thread specific data: */
122 	if (curthread->specific != NULL) {
123 		/* Run the thread-specific data destructors: */
124 		_thread_cleanupspecific();
125 	}
126 
127 	/*
128 	 * Remove read-write lock list. It is allocated as-needed.
129 	 * Therefore, it must be checked for validity before freeing.
130 	 */
131 	if (curthread->rwlockList != NULL)
132 		free(curthread->rwlockList);
133 retry:
134 	/*
135 	 * Proper lock order, to minimize deadlocks, between joining
136 	 * and exiting threads is: DEAD_LIST, THREAD_LIST, exiting, joiner.
137 	 * In order to do this *and* protect from races, we must resort
138 	 * this test-and-retry loop.
139 	 */
140 	joiner = curthread->joiner;
141 
142 	/* Lock the dead list first to maintain correct lock order */
143 	DEAD_LIST_LOCK;
144 	THREAD_LIST_LOCK;
145 	_thread_critical_enter(curthread);
146 
147 	if (joiner != curthread->joiner) {
148 		_thread_critical_exit(curthread);
149 		THREAD_LIST_UNLOCK;
150 		DEAD_LIST_UNLOCK;
151 		goto retry;
152 	}
153 
154 	/* Check if there is a thread joining this one: */
155 	if (curthread->joiner != NULL) {
156 		pthread = curthread->joiner;
157 		UMTX_LOCK(&pthread->lock);
158 		curthread->joiner = NULL;
159 
160 		/* Make the joining thread runnable: */
161 		PTHREAD_NEW_STATE(pthread, PS_RUNNING);
162 
163 		/* Set the return value for the joining thread: */
164 		pthread->join_status.ret = curthread->ret;
165 		pthread->join_status.error = 0;
166 		pthread->join_status.thread = NULL;
167 		UMTX_UNLOCK(&pthread->lock);
168 
169 		/* Make this thread collectable by the garbage collector. */
170 		PTHREAD_ASSERT(((curthread->attr.flags & PTHREAD_DETACHED) ==
171 		    0), "Cannot join a detached thread");
172 		curthread->attr.flags |= PTHREAD_DETACHED;
173 	}
174 
175 	/*
176 	 * Free any memory allocated for dead threads.
177 	 * Add this thread to the list of dead threads, and
178 	 * also remove it from the active threads list.
179 	 */
180 	deadlist_free_threads();
181 	TAILQ_INSERT_HEAD(&_dead_list, curthread, dle);
182 	TAILQ_REMOVE(&_thread_list, curthread, tle);
183 	PTHREAD_SET_STATE(curthread, PS_DEAD);
184 	_thread_critical_exit(curthread);
185 
186 	/* If we're the last thread, call it quits */
187 	if (TAILQ_EMPTY(&_thread_list))
188 		exitNow = 1;
189 
190 	THREAD_LIST_UNLOCK;
191 	DEAD_LIST_UNLOCK;
192 
193 	if (exitNow)
194 		exit(0);
195 
196 	/*
197 	 * This function will not return unless we are the last
198 	 * thread, which we can't be because we've already checked
199 	 * for that.
200 	 */
201 	_thr_exit();
202 
203 	/* This point should not be reached. */
204 	PANIC("Dead thread has resumed");
205 }
206 
207 /*
208  * Note: this function must be called with the dead thread list
209  *	 locked.
210  */
211 static void
212 deadlist_free_threads()
213 {
214 	struct pthread *ptd, *ptdTemp;
215 
216 	TAILQ_FOREACH_SAFE(ptd, &_dead_list, dle, ptdTemp) {
217 		/* Don't destroy the initial thread or non-detached threads. */
218 		if (ptd == _thread_initial ||
219 		    (ptd->attr.flags & PTHREAD_DETACHED) == 0)
220 			continue;
221 		TAILQ_REMOVE(&_dead_list, ptd, dle);
222 		deadlist_free_onethread(ptd);
223 	}
224 }
225 
226 void
227 deadlist_free_onethread(struct pthread *ptd)
228 {
229 
230 	if (ptd->attr.stackaddr_attr == NULL && ptd->stack != NULL) {
231 		STACK_LOCK;
232 		_thread_stack_free(ptd->stack, ptd->attr.stacksize_attr,
233 		    ptd->attr.guardsize_attr);
234 		STACK_UNLOCK;
235 	}
236 	_retire_thread(ptd->arch_id);
237 	free(ptd);
238 }
239