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