xref: /freebsd/lib/libthr/thread/thr_exit.c (revision 6f1af0d7d2af54b339b5212434cd6d4fda628d80)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the author nor the names of any co-contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #include "namespace.h"
34 #include <errno.h>
35 #ifdef _PTHREAD_FORCED_UNWIND
36 #include <dlfcn.h>
37 #endif
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <pthread.h>
42 #include <sys/types.h>
43 #include <sys/signalvar.h>
44 #include "un-namespace.h"
45 
46 #include "libc_private.h"
47 #include "thr_private.h"
48 
49 static void	exit_thread(void) __dead2;
50 
51 __weak_reference(_Tthr_exit, pthread_exit);
52 __weak_reference(_Tthr_exit, _pthread_exit);
53 
54 #ifdef _PTHREAD_FORCED_UNWIND
55 static int message_printed;
56 
57 static void thread_unwind(void) __dead2;
58 #ifdef PIC
59 static void thread_uw_init(void);
60 static _Unwind_Reason_Code thread_unwind_stop(int version,
61 	_Unwind_Action actions,
62 	uint64_t exc_class,
63 	struct _Unwind_Exception *exc_obj,
64 	struct _Unwind_Context *context, void *stop_parameter);
65 /* unwind library pointers */
66 static _Unwind_Reason_Code (*uwl_forcedunwind)(struct _Unwind_Exception *,
67 	_Unwind_Stop_Fn, void *);
68 static uintptr_t (*uwl_getcfa)(struct _Unwind_Context *);
69 
70 static void
71 thread_uw_init(void)
72 {
73 	static int inited = 0;
74 	Dl_info dli;
75 	void *handle;
76 	void *forcedunwind, *getcfa;
77 
78 	if (inited)
79 	    return;
80 	handle = RTLD_DEFAULT;
81 	if ((forcedunwind = dlsym(handle, "_Unwind_ForcedUnwind")) != NULL) {
82 	    if (dladdr(forcedunwind, &dli)) {
83 		/*
84 		 * Make sure the address is always valid by holding the library,
85 		 * also assume functions are in same library.
86 		 */
87 		if ((handle = dlopen(dli.dli_fname, RTLD_LAZY)) != NULL) {
88 		    forcedunwind = dlsym(handle, "_Unwind_ForcedUnwind");
89 		    getcfa = dlsym(handle, "_Unwind_GetCFA");
90 		    if (forcedunwind != NULL && getcfa != NULL) {
91 			uwl_getcfa = getcfa;
92 			atomic_store_rel_ptr((volatile void *)&uwl_forcedunwind,
93 				(uintptr_t)forcedunwind);
94 		    } else {
95 			dlclose(handle);
96 		    }
97 		}
98 	    }
99 	}
100 	inited = 1;
101 }
102 
103 _Unwind_Reason_Code
104 _Unwind_ForcedUnwind(struct _Unwind_Exception *ex, _Unwind_Stop_Fn stop_func,
105 	void *stop_arg)
106 {
107 	return (*uwl_forcedunwind)(ex, stop_func, stop_arg);
108 }
109 
110 uintptr_t
111 _Unwind_GetCFA(struct _Unwind_Context *context)
112 {
113 	return (*uwl_getcfa)(context);
114 }
115 #else
116 #pragma weak _Unwind_GetCFA
117 #pragma weak _Unwind_ForcedUnwind
118 #endif /* PIC */
119 
120 static void
121 thread_unwind_cleanup(_Unwind_Reason_Code code __unused,
122     struct _Unwind_Exception *e __unused)
123 {
124 	/*
125 	 * Specification said that _Unwind_Resume should not be used here,
126 	 * instead, user should rethrow the exception. For C++ user, they
127 	 * should put "throw" sentence in catch(...) block.
128 	 */
129 	PANIC("exception should be rethrown");
130 }
131 
132 static _Unwind_Reason_Code
133 thread_unwind_stop(int version __unused, _Unwind_Action actions,
134 	uint64_t exc_class __unused,
135 	struct _Unwind_Exception *exc_obj __unused,
136 	struct _Unwind_Context *context, void *stop_parameter __unused)
137 {
138 	struct pthread *curthread = _get_curthread();
139 	struct pthread_cleanup *cur;
140 	uintptr_t cfa;
141 	int done = 0;
142 
143 	/* XXX assume stack grows down to lower address */
144 
145 	cfa = _Unwind_GetCFA(context);
146 	if (actions & _UA_END_OF_STACK ||
147 	    cfa >= (uintptr_t)curthread->unwind_stackend) {
148 		done = 1;
149 	}
150 
151 	while ((cur = curthread->cleanup) != NULL &&
152 	       (done || (uintptr_t)cur <= cfa)) {
153 		__pthread_cleanup_pop_imp(1);
154 	}
155 
156 	if (done) {
157 		/* Tell libc that it should call non-trivial TLS dtors. */
158 		__cxa_thread_call_dtors();
159 
160 		exit_thread(); /* Never return! */
161 	}
162 
163 	return (_URC_NO_REASON);
164 }
165 
166 static void
167 thread_unwind(void)
168 {
169 	struct pthread  *curthread = _get_curthread();
170 
171 	curthread->ex.exception_class = 0;
172 	curthread->ex.exception_cleanup = thread_unwind_cleanup;
173 	_Unwind_ForcedUnwind(&curthread->ex, thread_unwind_stop, NULL);
174 	PANIC("_Unwind_ForcedUnwind returned");
175 }
176 
177 #endif
178 
179 void
180 _thread_exitf(const char *fname, int lineno, const char *fmt, ...)
181 {
182 	va_list ap;
183 
184 	/* Write an error message to the standard error file descriptor: */
185 	_thread_printf(STDERR_FILENO, "Fatal error '");
186 
187 	va_start(ap, fmt);
188 	_thread_vprintf(STDERR_FILENO, fmt, ap);
189 	va_end(ap);
190 
191 	_thread_printf(STDERR_FILENO, "' at line %d in file %s (errno = %d)\n",
192 	    lineno, fname, errno);
193 
194 	abort();
195 }
196 
197 void
198 _thread_exit(const char *fname, int lineno, const char *msg)
199 {
200 
201 	_thread_exitf(fname, lineno, "%s", msg);
202 }
203 
204 void
205 _Tthr_exit(void *status)
206 {
207 	_pthread_exit_mask(status, NULL);
208 }
209 
210 void
211 _pthread_exit_mask(void *status, sigset_t *mask)
212 {
213 	struct pthread *curthread = _get_curthread();
214 
215 	/* Check if this thread is already in the process of exiting: */
216 	if (curthread->cancelling)
217 		PANIC("Thread %p has called "
218 		    "pthread_exit() from a destructor. POSIX 1003.1 "
219 		    "1996 s16.2.5.2 does not allow this!", curthread);
220 
221 	/* Flag this thread as exiting. */
222 	curthread->cancelling = 1;
223 	curthread->no_cancel = 1;
224 	curthread->cancel_async = 0;
225 	curthread->cancel_point = 0;
226 	if (mask != NULL)
227 		__sys_sigprocmask(SIG_SETMASK, mask, NULL);
228 	if (curthread->unblock_sigcancel) {
229 		sigset_t set;
230 
231 		curthread->unblock_sigcancel = 0;
232 		SIGEMPTYSET(set);
233 		SIGADDSET(set, SIGCANCEL);
234 		__sys_sigprocmask(SIG_UNBLOCK, mask, NULL);
235 	}
236 
237 	/* Save the return value: */
238 	curthread->ret = status;
239 #ifdef _PTHREAD_FORCED_UNWIND
240 
241 #ifdef PIC
242 	thread_uw_init();
243 	if (uwl_forcedunwind != NULL) {
244 #else
245 	if (_Unwind_ForcedUnwind != NULL) {
246 #endif
247 		if (curthread->unwind_disabled) {
248 			if (message_printed == 0) {
249 				message_printed = 1;
250 				_thread_printf(2, "Warning: old _pthread_cleanup_push was called, "
251 				  	"stack unwinding is disabled.\n");
252 			}
253 			goto cleanup;
254 		}
255 		thread_unwind();
256 
257 	} else {
258 cleanup:
259 		while (curthread->cleanup != NULL) {
260 			__pthread_cleanup_pop_imp(1);
261 		}
262 		__cxa_thread_call_dtors();
263 
264 		exit_thread();
265 	}
266 
267 #else
268 	while (curthread->cleanup != NULL) {
269 		__pthread_cleanup_pop_imp(1);
270 	}
271 	__cxa_thread_call_dtors();
272 
273 	exit_thread();
274 #endif /* _PTHREAD_FORCED_UNWIND */
275 }
276 
277 static void
278 exit_thread(void)
279 {
280 	struct pthread *curthread = _get_curthread();
281 
282 	free(curthread->name);
283 	curthread->name = NULL;
284 
285 	/* Check if there is thread specific data: */
286 	if (curthread->specific != NULL) {
287 		/* Run the thread-specific data destructors: */
288 		_thread_cleanupspecific();
289 	}
290 
291 	if (!_thr_isthreaded())
292 		exit(0);
293 
294 	if (atomic_fetchadd_int(&_thread_active_threads, -1) == 1) {
295 		exit(0);
296 		/* Never reach! */
297 	}
298 
299 	/* Tell malloc that the thread is exiting. */
300 	_malloc_thread_cleanup();
301 
302 	THR_LOCK(curthread);
303 	curthread->state = PS_DEAD;
304 	if (curthread->flags & THR_FLAGS_NEED_SUSPEND) {
305 		curthread->cycle++;
306 		_thr_umtx_wake(&curthread->cycle, INT_MAX, 0);
307 	}
308 	if (!curthread->force_exit && SHOULD_REPORT_EVENT(curthread, TD_DEATH))
309 		_thr_report_death(curthread);
310 	/*
311 	 * Thread was created with initial refcount 1, we drop the
312 	 * reference count to allow it to be garbage collected.
313 	 */
314 	curthread->refcount--;
315 	_thr_try_gc(curthread, curthread); /* thread lock released */
316 
317 #if defined(_PTHREADS_INVARIANTS)
318 	if (THR_IN_CRITICAL(curthread))
319 		PANIC("thread %p exits with resources held!", curthread);
320 #endif
321 	/*
322 	 * Kernel will do wakeup at the address, so joiner thread
323 	 * will be resumed if it is sleeping at the address.
324 	 */
325 	thr_exit(&curthread->tid);
326 	PANIC("thr_exit() returned");
327 	/* Never reach! */
328 }
329