xref: /freebsd/lib/libthr/thread/thr_exit.c (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
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 "namespace.h"
33 #include <errno.h>
34 #ifdef _PTHREAD_FORCED_UNWIND
35 #include <dlfcn.h>
36 #endif
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <pthread.h>
41 #include <sys/types.h>
42 #include <sys/signalvar.h>
43 #include "un-namespace.h"
44 
45 #include "libc_private.h"
46 #include "thr_private.h"
47 
48 static void	exit_thread(void) __dead2;
49 
50 __weak_reference(_Tthr_exit, pthread_exit);
51 __weak_reference(_Tthr_exit, _pthread_exit);
52 
53 #ifdef _PTHREAD_FORCED_UNWIND
54 static int message_printed;
55 
56 static void thread_unwind(void) __dead2;
57 #ifdef PIC
58 static void thread_uw_init(void);
59 static _Unwind_Reason_Code thread_unwind_stop(int version,
60 	_Unwind_Action actions,
61 	uint64_t exc_class,
62 	struct _Unwind_Exception *exc_obj,
63 	struct _Unwind_Context *context, void *stop_parameter);
64 /* unwind library pointers */
65 static _Unwind_Reason_Code (*uwl_forcedunwind)(struct _Unwind_Exception *,
66 	_Unwind_Stop_Fn, void *);
67 static uintptr_t (*uwl_getcfa)(struct _Unwind_Context *);
68 
69 static void
70 thread_uw_init(void)
71 {
72 	static int inited = 0;
73 	Dl_info dli;
74 	void *handle;
75 	void *forcedunwind, *getcfa;
76 
77 	if (inited)
78 	    return;
79 	handle = RTLD_DEFAULT;
80 	if ((forcedunwind = dlsym(handle, "_Unwind_ForcedUnwind")) != NULL) {
81 	    if (dladdr(forcedunwind, &dli)) {
82 		/*
83 		 * Make sure the address is always valid by holding the library,
84 		 * also assume functions are in same library.
85 		 */
86 		if ((handle = dlopen(dli.dli_fname, RTLD_LAZY)) != NULL) {
87 		    forcedunwind = dlsym(handle, "_Unwind_ForcedUnwind");
88 		    getcfa = dlsym(handle, "_Unwind_GetCFA");
89 		    if (forcedunwind != NULL && getcfa != NULL) {
90 			uwl_getcfa = getcfa;
91 			atomic_store_rel_ptr((volatile void *)&uwl_forcedunwind,
92 				(uintptr_t)forcedunwind);
93 		    } else {
94 			dlclose(handle);
95 		    }
96 		}
97 	    }
98 	}
99 	inited = 1;
100 }
101 
102 _Unwind_Reason_Code
103 _Unwind_ForcedUnwind(struct _Unwind_Exception *ex, _Unwind_Stop_Fn stop_func,
104 	void *stop_arg)
105 {
106 	return (*uwl_forcedunwind)(ex, stop_func, stop_arg);
107 }
108 
109 uintptr_t
110 _Unwind_GetCFA(struct _Unwind_Context *context)
111 {
112 	return (*uwl_getcfa)(context);
113 }
114 #else
115 #pragma weak _Unwind_GetCFA
116 #pragma weak _Unwind_ForcedUnwind
117 #endif /* PIC */
118 
119 static void
120 thread_unwind_cleanup(_Unwind_Reason_Code code __unused,
121     struct _Unwind_Exception *e __unused)
122 {
123 	/*
124 	 * Specification said that _Unwind_Resume should not be used here,
125 	 * instead, user should rethrow the exception. For C++ user, they
126 	 * should put "throw" sentence in catch(...) block.
127 	 */
128 	PANIC("exception should be rethrown");
129 }
130 
131 static _Unwind_Reason_Code
132 thread_unwind_stop(int version __unused, _Unwind_Action actions,
133 	uint64_t exc_class __unused,
134 	struct _Unwind_Exception *exc_obj __unused,
135 	struct _Unwind_Context *context, void *stop_parameter __unused)
136 {
137 	struct pthread *curthread = _get_curthread();
138 	struct pthread_cleanup *cur;
139 	uintptr_t cfa;
140 	int done = 0;
141 
142 	/* XXX assume stack grows down to lower address */
143 
144 	cfa = _Unwind_GetCFA(context);
145 	if (actions & _UA_END_OF_STACK ||
146 	    cfa >= (uintptr_t)curthread->unwind_stackend) {
147 		done = 1;
148 	}
149 
150 	while ((cur = curthread->cleanup) != NULL &&
151 	       (done || (uintptr_t)cur <= cfa)) {
152 		__pthread_cleanup_pop_imp(1);
153 	}
154 
155 	if (done) {
156 		/* Tell libc that it should call non-trivial TLS dtors. */
157 		__cxa_thread_call_dtors();
158 
159 		exit_thread(); /* Never return! */
160 	}
161 
162 	return (_URC_NO_REASON);
163 }
164 
165 static void
166 thread_unwind(void)
167 {
168 	struct pthread  *curthread = _get_curthread();
169 
170 	curthread->ex.exception_class = 0;
171 	curthread->ex.exception_cleanup = thread_unwind_cleanup;
172 	_Unwind_ForcedUnwind(&curthread->ex, thread_unwind_stop, NULL);
173 	PANIC("_Unwind_ForcedUnwind returned");
174 }
175 
176 #endif
177 
178 void
179 _thread_exitf(const char *fname, int lineno, const char *fmt, ...)
180 {
181 	va_list ap;
182 
183 	/* Write an error message to the standard error file descriptor: */
184 	_thread_printf(STDERR_FILENO, "Fatal error '");
185 
186 	va_start(ap, fmt);
187 	_thread_vprintf(STDERR_FILENO, fmt, ap);
188 	va_end(ap);
189 
190 	_thread_printf(STDERR_FILENO, "' at line %d in file %s (errno = %d)\n",
191 	    lineno, fname, errno);
192 
193 	abort();
194 }
195 
196 void
197 _thread_exit(const char *fname, int lineno, const char *msg)
198 {
199 
200 	_thread_exitf(fname, lineno, "%s", msg);
201 }
202 
203 void
204 _Tthr_exit(void *status)
205 {
206 	_pthread_exit_mask(status, NULL);
207 }
208 
209 void
210 _pthread_exit_mask(void *status, sigset_t *mask)
211 {
212 	struct pthread *curthread = _get_curthread();
213 
214 	/* Check if this thread is already in the process of exiting: */
215 	if (curthread->cancelling)
216 		PANIC("Thread %p has called "
217 		    "pthread_exit() from a destructor. POSIX 1003.1 "
218 		    "1996 s16.2.5.2 does not allow this!", curthread);
219 
220 	/* Flag this thread as exiting. */
221 	curthread->cancelling = 1;
222 	curthread->no_cancel = 1;
223 	curthread->cancel_async = 0;
224 	curthread->cancel_point = 0;
225 	if (mask != NULL)
226 		__sys_sigprocmask(SIG_SETMASK, mask, NULL);
227 	if (curthread->unblock_sigcancel) {
228 		sigset_t set;
229 
230 		curthread->unblock_sigcancel = 0;
231 		SIGEMPTYSET(set);
232 		SIGADDSET(set, SIGCANCEL);
233 		__sys_sigprocmask(SIG_UNBLOCK, mask, NULL);
234 	}
235 
236 	/* Save the return value: */
237 	curthread->ret = status;
238 #ifdef _PTHREAD_FORCED_UNWIND
239 
240 #ifdef PIC
241 	thread_uw_init();
242 	if (uwl_forcedunwind != NULL) {
243 #else
244 	if (_Unwind_ForcedUnwind != NULL) {
245 #endif
246 		if (curthread->unwind_disabled) {
247 			if (message_printed == 0) {
248 				message_printed = 1;
249 				_thread_printf(2, "Warning: old _pthread_cleanup_push was called, "
250 				  	"stack unwinding is disabled.\n");
251 			}
252 			goto cleanup;
253 		}
254 		thread_unwind();
255 
256 	} else {
257 cleanup:
258 		while (curthread->cleanup != NULL) {
259 			__pthread_cleanup_pop_imp(1);
260 		}
261 		__cxa_thread_call_dtors();
262 
263 		exit_thread();
264 	}
265 
266 #else
267 	while (curthread->cleanup != NULL) {
268 		__pthread_cleanup_pop_imp(1);
269 	}
270 	__cxa_thread_call_dtors();
271 
272 	exit_thread();
273 #endif /* _PTHREAD_FORCED_UNWIND */
274 }
275 
276 static void
277 exit_thread(void)
278 {
279 	struct pthread *curthread = _get_curthread();
280 
281 	free(curthread->name);
282 	curthread->name = NULL;
283 
284 	/* Check if there is thread specific data: */
285 	if (curthread->specific != NULL) {
286 		/* Run the thread-specific data destructors: */
287 		_thread_cleanupspecific();
288 	}
289 
290 	if (!_thr_isthreaded())
291 		exit(0);
292 
293 	if (atomic_fetchadd_int(&_thread_active_threads, -1) == 1) {
294 		exit(0);
295 		/* Never reach! */
296 	}
297 
298 	/* Tell malloc that the thread is exiting. */
299 	_malloc_thread_cleanup();
300 
301 	THR_LOCK(curthread);
302 	curthread->state = PS_DEAD;
303 	if (curthread->flags & THR_FLAGS_NEED_SUSPEND) {
304 		curthread->cycle++;
305 		_thr_umtx_wake(&curthread->cycle, INT_MAX, 0);
306 	}
307 	if (!curthread->force_exit && SHOULD_REPORT_EVENT(curthread, TD_DEATH))
308 		_thr_report_death(curthread);
309 	/*
310 	 * Thread was created with initial refcount 1, we drop the
311 	 * reference count to allow it to be garbage collected.
312 	 */
313 	curthread->refcount--;
314 	_thr_try_gc(curthread, curthread); /* thread lock released */
315 
316 #if defined(_PTHREADS_INVARIANTS)
317 	if (THR_IN_CRITICAL(curthread))
318 		PANIC("thread %p exits with resources held!", curthread);
319 #endif
320 	/*
321 	 * Kernel will do wakeup at the address, so joiner thread
322 	 * will be resumed if it is sleeping at the address.
323 	 */
324 	thr_exit(&curthread->tid);
325 	PANIC("thr_exit() returned");
326 	/* Never reach! */
327 }
328