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