1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//
8// Implements setjump-longjump based C++ exceptions
9//
10//===----------------------------------------------------------------------===//
11
12#include <unwind.h>
13
14#include <inttypes.h>
15#include <stdint.h>
16#include <stdbool.h>
17#include <stdlib.h>
18
19#include "config.h"
20
21/// With SJLJ based exceptions, any function that has a catch clause or needs to
22/// do any clean up when an exception propagates through it, needs to call
23/// \c _Unwind_SjLj_Register at the start of the function and
24/// \c _Unwind_SjLj_Unregister at the end. The register function is called with
25/// the address of a block of memory in the function's stack frame. The runtime
26/// keeps a linked list (stack) of these blocks - one per thread. The calling
27/// function also sets the personality and lsda fields of the block.
28
29#if defined(_LIBUNWIND_BUILD_SJLJ_APIS)
30
31typedef unsigned _Unwind_SjLj_Word __attribute__((__mode__(__unwind_word__)));
32
33struct _Unwind_FunctionContext {
34 // next function in stack of handlers
35 struct _Unwind_FunctionContext *prev;
36
37 // set by calling function before registering to be the landing pad
38 int resumeLocation;
39
40 // set by personality handler to be parameters passed to landing pad function
41 _Unwind_SjLj_Word resumeParameters[4];
42
43 // set by calling function before registering
44 _Unwind_Personality_Fn personality; // arm offset=24
45 uintptr_t lsda; // arm offset=28
46
47 // variable length array, contains registers to restore
48 // 0 = r7, 1 = pc, 2 = sp
49 void *jbuf[];
50};
51
52#if defined(_LIBUNWIND_HAS_NO_THREADS)
53# define _LIBUNWIND_THREAD_LOCAL
54#else
55# if __STDC_VERSION__ >= 201112L
56# define _LIBUNWIND_THREAD_LOCAL _Thread_local
57# elif defined(_MSC_VER)
58# define _LIBUNWIND_THREAD_LOCAL __declspec(thread)
59# elif defined(__GNUC__) || defined(__clang__)
60# define _LIBUNWIND_THREAD_LOCAL __thread
61# else
62# error Unable to create thread local storage
63# endif
64#endif
65
66
67#if !defined(FOR_DYLD)
68
69#if defined(__APPLE__)
70#include <System/pthread_machdep.h>
71#else
72static _LIBUNWIND_THREAD_LOCAL struct _Unwind_FunctionContext *stack = NULL;
73#endif
74
75static struct _Unwind_FunctionContext *
76__Unwind_SjLj_GetTopOfFunctionStack(void) {
77#if defined(__APPLE__)
78 return _pthread_getspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key);
79#else
80 return stack;
81#endif
82}
83
84static void
85__Unwind_SjLj_SetTopOfFunctionStack(struct _Unwind_FunctionContext *fc) {
86#if defined(__APPLE__)
87 _pthread_setspecific_direct(__PTK_LIBC_DYLD_Unwind_SjLj_Key, fc);
88#else
89 stack = fc;
90#endif
91}
92
93#endif
94
95
96/// Called at start of each function that catches exceptions
97_LIBUNWIND_EXPORT void
98_Unwind_SjLj_Register(struct _Unwind_FunctionContext *fc) {
99 fc->prev = __Unwind_SjLj_GetTopOfFunctionStack();
100 __Unwind_SjLj_SetTopOfFunctionStack(fc);
101}
102
103
104/// Called at end of each function that catches exceptions
105_LIBUNWIND_EXPORT void
106_Unwind_SjLj_Unregister(struct _Unwind_FunctionContext *fc) {
107 __Unwind_SjLj_SetTopOfFunctionStack(fc->prev);
108}
109
110
111static _Unwind_Reason_Code
112unwind_phase1(struct _Unwind_Exception *exception_object) {
113 _Unwind_FunctionContext_t c = __Unwind_SjLj_GetTopOfFunctionStack();
114 _LIBUNWIND_TRACE_UNWINDING("unwind_phase1: initial function-context=%p",
115 (void *)c);
116
117 // walk each frame looking for a place to stop
118 for (bool handlerNotFound = true; handlerNotFound; c = c->prev) {
119
120 // check for no more frames
121 if (c == NULL) {
122 _LIBUNWIND_TRACE_UNWINDING("unwind_phase1(ex_ojb=%p): reached "
123 "bottom => _URC_END_OF_STACK",
124 (void *)exception_object);
125 return _URC_END_OF_STACK;
126 }
127
128 _LIBUNWIND_TRACE_UNWINDING("unwind_phase1: function-context=%p", (void *)c);
129 // if there is a personality routine, ask it if it will want to stop at this
130 // frame
131 if (c->personality != NULL) {
132 _LIBUNWIND_TRACE_UNWINDING("unwind_phase1(ex_ojb=%p): calling "
133 "personality function %p",
134 (void *)exception_object,
135 (void *)c->personality);
136 _Unwind_Reason_Code personalityResult = (*c->personality)(
137 1, _UA_SEARCH_PHASE, exception_object->exception_class,
138 exception_object, (struct _Unwind_Context *)c);
139 switch (personalityResult) {
140 case _URC_HANDLER_FOUND:
141 // found a catch clause or locals that need destructing in this frame
142 // stop search and remember function context
143 handlerNotFound = false;
144 exception_object->private_2 = (uintptr_t) c;
145 _LIBUNWIND_TRACE_UNWINDING("unwind_phase1(ex_ojb=%p): "
146 "_URC_HANDLER_FOUND",
147 (void *)exception_object);
148 return _URC_NO_REASON;
149
150 case _URC_CONTINUE_UNWIND:
151 _LIBUNWIND_TRACE_UNWINDING("unwind_phase1(ex_ojb=%p): "
152 "_URC_CONTINUE_UNWIND",
153 (void *)exception_object);
154 // continue unwinding
155 break;
156
157 default:
158 // something went wrong
159 _LIBUNWIND_TRACE_UNWINDING(
160 "unwind_phase1(ex_ojb=%p): _URC_FATAL_PHASE1_ERROR",
161 (void *)exception_object);
162 return _URC_FATAL_PHASE1_ERROR;
163 }
164 }
165 }
166 return _URC_NO_REASON;
167}
168
169
170static _Unwind_Reason_Code
171unwind_phase2(struct _Unwind_Exception *exception_object) {
172 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p)",
173 (void *)exception_object);
174
175 // walk each frame until we reach where search phase said to stop
176 _Unwind_FunctionContext_t c = __Unwind_SjLj_GetTopOfFunctionStack();
177 while (true) {
178 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2s(ex_ojb=%p): context=%p",
179 (void *)exception_object, (void *)c);
180
181 // check for no more frames
182 if (c == NULL) {
183 _LIBUNWIND_TRACE_UNWINDING(
184 "unwind_phase2(ex_ojb=%p): __unw_step() reached "
185 "bottom => _URC_END_OF_STACK",
186 (void *)exception_object);
187 return _URC_END_OF_STACK;
188 }
189
190 // if there is a personality routine, tell it we are unwinding
191 if (c->personality != NULL) {
192 _Unwind_Action action = _UA_CLEANUP_PHASE;
193 if ((uintptr_t) c == exception_object->private_2)
194 action = (_Unwind_Action)(
195 _UA_CLEANUP_PHASE |
196 _UA_HANDLER_FRAME); // tell personality this was the frame it marked
197 // in phase 1
198 _Unwind_Reason_Code personalityResult =
199 (*c->personality)(1, action, exception_object->exception_class,
200 exception_object, (struct _Unwind_Context *)c);
201 switch (personalityResult) {
202 case _URC_CONTINUE_UNWIND:
203 // continue unwinding
204 _LIBUNWIND_TRACE_UNWINDING(
205 "unwind_phase2(ex_ojb=%p): _URC_CONTINUE_UNWIND",
206 (void *)exception_object);
207 if ((uintptr_t) c == exception_object->private_2) {
208 // phase 1 said we would stop at this frame, but we did not...
209 _LIBUNWIND_ABORT("during phase1 personality function said it would "
210 "stop here, but now if phase2 it did not stop here");
211 }
212 break;
213 case _URC_INSTALL_CONTEXT:
214 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p): "
215 "_URC_INSTALL_CONTEXT, will resume at "
216 "landing pad %p",
217 (void *)exception_object, c->jbuf[1]);
218 // personality routine says to transfer control to landing pad
219 // we may get control back if landing pad calls _Unwind_Resume()
220 __Unwind_SjLj_SetTopOfFunctionStack(c);
221 __builtin_longjmp(c->jbuf, 1);
222 // __unw_resume() only returns if there was an error
223 return _URC_FATAL_PHASE2_ERROR;
224 default:
225 // something went wrong
226 _LIBUNWIND_DEBUG_LOG("personality function returned unknown result %d",
227 personalityResult);
228 return _URC_FATAL_PHASE2_ERROR;
229 }
230 }
231 c = c->prev;
232 }
233
234 // clean up phase did not resume at the frame that the search phase said it
235 // would
236 return _URC_FATAL_PHASE2_ERROR;
237}
238
239
240static _Unwind_Reason_Code
241unwind_phase2_forced(struct _Unwind_Exception *exception_object,
242 _Unwind_Stop_Fn stop, void *stop_parameter) {
243 // walk each frame until we reach where search phase said to stop
244 _Unwind_FunctionContext_t c = __Unwind_SjLj_GetTopOfFunctionStack();
245 while (true) {
246
247 // get next frame (skip over first which is _Unwind_RaiseException)
248 if (c == NULL) {
249 _LIBUNWIND_TRACE_UNWINDING(
250 "unwind_phase2(ex_ojb=%p): __unw_step() reached "
251 "bottom => _URC_END_OF_STACK",
252 (void *)exception_object);
253 return _URC_END_OF_STACK;
254 }
255
256 // call stop function at each frame
257 _Unwind_Action action =
258 (_Unwind_Action)(_UA_FORCE_UNWIND | _UA_CLEANUP_PHASE);
259 _Unwind_Reason_Code stopResult =
260 (*stop)(1, action, exception_object->exception_class, exception_object,
261 (struct _Unwind_Context *)c, stop_parameter);
262 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
263 "stop function returned %d",
264 (void *)exception_object, stopResult);
265 if (stopResult != _URC_NO_REASON) {
266 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
267 "stopped by stop function",
268 (void *)exception_object);
269 return _URC_FATAL_PHASE2_ERROR;
270 }
271
272 // if there is a personality routine, tell it we are unwinding
273 if (c->personality != NULL) {
274 _Unwind_Personality_Fn p = (_Unwind_Personality_Fn)c->personality;
275 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
276 "calling personality function %p",
277 (void *)exception_object, (void *)p);
278 _Unwind_Reason_Code personalityResult =
279 (*p)(1, action, exception_object->exception_class, exception_object,
280 (struct _Unwind_Context *)c);
281 switch (personalityResult) {
282 case _URC_CONTINUE_UNWIND:
283 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
284 "personality returned _URC_CONTINUE_UNWIND",
285 (void *)exception_object);
286 // destructors called, continue unwinding
287 break;
288 case _URC_INSTALL_CONTEXT:
289 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
290 "personality returned _URC_INSTALL_CONTEXT",
291 (void *)exception_object);
292 // we may get control back if landing pad calls _Unwind_Resume()
293 __Unwind_SjLj_SetTopOfFunctionStack(c);
294 __builtin_longjmp(c->jbuf, 1);
295 break;
296 default:
297 // something went wrong
298 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
299 "personality returned %d, "
300 "_URC_FATAL_PHASE2_ERROR",
301 (void *)exception_object, personalityResult);
302 return _URC_FATAL_PHASE2_ERROR;
303 }
304 }
305 c = c->prev;
306 }
307
308 // call stop function one last time and tell it we've reached the end of the
309 // stack
310 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): calling stop "
311 "function with _UA_END_OF_STACK",
312 (void *)exception_object);
313 _Unwind_Action lastAction =
314 (_Unwind_Action)(_UA_FORCE_UNWIND | _UA_CLEANUP_PHASE | _UA_END_OF_STACK);
315 (*stop)(1, lastAction, exception_object->exception_class, exception_object,
316 (struct _Unwind_Context *)c, stop_parameter);
317
318 // clean up phase did not resume at the frame that the search phase said it
319 // would
320 return _URC_FATAL_PHASE2_ERROR;
321}
322
323
324/// Called by __cxa_throw. Only returns if there is a fatal error
325_LIBUNWIND_EXPORT _Unwind_Reason_Code
326_Unwind_SjLj_RaiseException(struct _Unwind_Exception *exception_object) {
327 _LIBUNWIND_TRACE_API("_Unwind_SjLj_RaiseException(ex_obj=%p)",
328 (void *)exception_object);
329
330 // mark that this is a non-forced unwind, so _Unwind_Resume() can do the right
331 // thing
332 exception_object->private_1 = 0;
333 exception_object->private_2 = 0;
334
335 // phase 1: the search phase
336 _Unwind_Reason_Code phase1 = unwind_phase1(exception_object);
337 if (phase1 != _URC_NO_REASON)
338 return phase1;
339
340 // phase 2: the clean up phase
341 return unwind_phase2(exception_object);
342}
343
344
345
346/// When _Unwind_RaiseException() is in phase2, it hands control
347/// to the personality function at each frame. The personality
348/// may force a jump to a landing pad in that function, the landing
349/// pad code may then call _Unwind_Resume() to continue with the
350/// unwinding. Note: the call to _Unwind_Resume() is from compiler
351/// generated user code. All other _Unwind_* routines are called
352/// by the C++ runtime __cxa_* routines.
353///
354/// Re-throwing an exception is implemented by having the code call
355/// __cxa_rethrow() which in turn calls _Unwind_Resume_or_Rethrow()
356_LIBUNWIND_EXPORT void
357_Unwind_SjLj_Resume(struct _Unwind_Exception *exception_object) {
358 _LIBUNWIND_TRACE_API("_Unwind_SjLj_Resume(ex_obj=%p)",
359 (void *)exception_object);
360
361 if (exception_object->private_1 != 0)
362 unwind_phase2_forced(exception_object,
363 (_Unwind_Stop_Fn) exception_object->private_1,
364 (void *)exception_object->private_2);
365 else
366 unwind_phase2(exception_object);
367
368 // clients assume _Unwind_Resume() does not return, so all we can do is abort.
369 _LIBUNWIND_ABORT("_Unwind_SjLj_Resume() can't return");
370}
371
372
373/// Called by __cxa_rethrow().
374_LIBUNWIND_EXPORT _Unwind_Reason_Code
375_Unwind_SjLj_Resume_or_Rethrow(struct _Unwind_Exception *exception_object) {
376 _LIBUNWIND_TRACE_API("__Unwind_SjLj_Resume_or_Rethrow(ex_obj=%p), "
377 "private_1=%" PRIuPTR,
378 (void *)exception_object, exception_object->private_1);
379 // If this is non-forced and a stopping place was found, then this is a
380 // re-throw.
381 // Call _Unwind_RaiseException() as if this was a new exception.
382 if (exception_object->private_1 == 0) {
383 return _Unwind_SjLj_RaiseException(exception_object);
384 // should return if there is no catch clause, so that __cxa_rethrow can call
385 // std::terminate()
386 }
387
388 // Call through to _Unwind_Resume() which distinguishes between forced and
389 // regular exceptions.
390 _Unwind_SjLj_Resume(exception_object);
391 _LIBUNWIND_ABORT("__Unwind_SjLj_Resume_or_Rethrow() called "
392 "_Unwind_SjLj_Resume() which unexpectedly returned");
393}
394
395
396/// Called by personality handler during phase 2 to get LSDA for current frame.
397_LIBUNWIND_EXPORT uintptr_t
398_Unwind_GetLanguageSpecificData(struct _Unwind_Context *context) {
399 _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
400 _LIBUNWIND_TRACE_API("_Unwind_GetLanguageSpecificData(context=%p) "
401 "=> 0x%" PRIxPTR,
402 (void *)context, ufc->lsda);
403 return ufc->lsda;
404}
405
406
407/// Called by personality handler during phase 2 to get register values.
408_LIBUNWIND_EXPORT uintptr_t _Unwind_GetGR(struct _Unwind_Context *context,
409 int index) {
410 _LIBUNWIND_TRACE_API("_Unwind_GetGR(context=%p, reg=%d)", (void *)context,
411 index);
412 _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
413 return (uintptr_t)ufc->resumeParameters[index];
414}
415
416
417/// Called by personality handler during phase 2 to alter register values.
418_LIBUNWIND_EXPORT void _Unwind_SetGR(struct _Unwind_Context *context, int index,
419 uintptr_t new_value) {
420 _LIBUNWIND_TRACE_API("_Unwind_SetGR(context=%p, reg=%d, value=0x%" PRIxPTR
421 ")",
422 (void *)context, index, new_value);
423 _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
424 ufc->resumeParameters[index] = new_value;
425}
426
427
428/// Called by personality handler during phase 2 to get instruction pointer.
429_LIBUNWIND_EXPORT uintptr_t _Unwind_GetIP(struct _Unwind_Context *context) {
430 _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
431 _LIBUNWIND_TRACE_API("_Unwind_GetIP(context=%p) => 0x%" PRIxPTR,
432 (void *)context, (uintptr_t)(ufc->resumeLocation + 1));
433 return (uintptr_t)(ufc->resumeLocation + 1);
434}
435
436
437/// Called by personality handler during phase 2 to get instruction pointer.
438/// ipBefore is a boolean that says if IP is already adjusted to be the call
439/// site address. Normally IP is the return address.
440_LIBUNWIND_EXPORT uintptr_t _Unwind_GetIPInfo(struct _Unwind_Context *context,
441 int *ipBefore) {
442 _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
443 *ipBefore = 0;
444 _LIBUNWIND_TRACE_API("_Unwind_GetIPInfo(context=%p, %p) => 0x%" PRIxPTR,
445 (void *)context, (void *)ipBefore,
446 (uintptr_t)(ufc->resumeLocation + 1));
447 return (uintptr_t)(ufc->resumeLocation + 1);
448}
449
450
451/// Called by personality handler during phase 2 to alter instruction pointer.
452_LIBUNWIND_EXPORT void _Unwind_SetIP(struct _Unwind_Context *context,
453 uintptr_t new_value) {
454 _LIBUNWIND_TRACE_API("_Unwind_SetIP(context=%p, value=0x%" PRIxPTR ")",
455 (void *)context, new_value);
456 _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
457 ufc->resumeLocation = (int)(new_value - 1);
458}
459
460
461/// Called by personality handler during phase 2 to find the start of the
462/// function.
463_LIBUNWIND_EXPORT uintptr_t
464_Unwind_GetRegionStart(struct _Unwind_Context *context) {
465 // Not supported or needed for sjlj based unwinding
466 (void)context;
467 _LIBUNWIND_TRACE_API("_Unwind_GetRegionStart(context=%p)", (void *)context);
468 return 0;
469}
470
471
472/// Called by personality handler during phase 2 if a foreign exception
473/// is caught.
474_LIBUNWIND_EXPORT void
475_Unwind_DeleteException(struct _Unwind_Exception *exception_object) {
476 _LIBUNWIND_TRACE_API("_Unwind_DeleteException(ex_obj=%p)",
477 (void *)exception_object);
478 if (exception_object->exception_cleanup != NULL)
479 (*exception_object->exception_cleanup)(_URC_FOREIGN_EXCEPTION_CAUGHT,
480 exception_object);
481}
482
483
484
485/// Called by personality handler during phase 2 to get base address for data
486/// relative encodings.
487_LIBUNWIND_EXPORT uintptr_t
488_Unwind_GetDataRelBase(struct _Unwind_Context *context) {
489 // Not supported or needed for sjlj based unwinding
490 (void)context;
491 _LIBUNWIND_TRACE_API("_Unwind_GetDataRelBase(context=%p)", (void *)context);
492 _LIBUNWIND_ABORT("_Unwind_GetDataRelBase() not implemented");
493}
494
495
496/// Called by personality handler during phase 2 to get base address for text
497/// relative encodings.
498_LIBUNWIND_EXPORT uintptr_t
499_Unwind_GetTextRelBase(struct _Unwind_Context *context) {
500 // Not supported or needed for sjlj based unwinding
501 (void)context;
502 _LIBUNWIND_TRACE_API("_Unwind_GetTextRelBase(context=%p)", (void *)context);
503 _LIBUNWIND_ABORT("_Unwind_GetTextRelBase() not implemented");
504}
505
506
507/// Called by personality handler to get "Call Frame Area" for current frame.
508_LIBUNWIND_EXPORT uintptr_t _Unwind_GetCFA(struct _Unwind_Context *context) {
509 _LIBUNWIND_TRACE_API("_Unwind_GetCFA(context=%p)", (void *)context);
510 if (context != NULL) {
511 _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
512 // Setjmp/longjmp based exceptions don't have a true CFA.
513 // Instead, the SP in the jmpbuf is the closest approximation.
514 return (uintptr_t) ufc->jbuf[2];
515 }
516 return 0;
517}
518
519#endif // defined(_LIBUNWIND_BUILD_SJLJ_APIS)
520