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