1 //===------------------------- UnwindLevel1.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 C++ ABI Exception Handling Level 1 as documented at:
9 //      https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html
10 // using libunwind
11 //
12 //===----------------------------------------------------------------------===//
13 
14 // ARM EHABI does not specify _Unwind_{Get,Set}{GR,IP}().  Thus, we are
15 // defining inline functions to delegate the function calls to
16 // _Unwind_VRS_{Get,Set}().  However, some applications might declare the
17 // function protetype directly (instead of including <unwind.h>), thus we need
18 // to export these functions from libunwind.so as well.
19 #define _LIBUNWIND_UNWIND_LEVEL1_EXTERNAL_LINKAGE 1
20 
21 #include <inttypes.h>
22 #include <stdint.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 
28 #include "config.h"
29 #include "libunwind.h"
30 #include "libunwind_ext.h"
31 #include "unwind.h"
32 
33 #if !defined(_LIBUNWIND_ARM_EHABI) && !defined(__USING_SJLJ_EXCEPTIONS__)
34 
35 #ifndef _LIBUNWIND_SUPPORT_SEH_UNWIND
36 
37 static _Unwind_Reason_Code
38 unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, _Unwind_Exception *exception_object) {
39   __unw_init_local(cursor, uc);
40 
41   // Walk each frame looking for a place to stop.
42   while (true) {
43     // Ask libunwind to get next frame (skip over first which is
44     // _Unwind_RaiseException).
45     int stepResult = __unw_step(cursor);
46     if (stepResult == 0) {
47       _LIBUNWIND_TRACE_UNWINDING(
48           "unwind_phase1(ex_ojb=%p): __unw_step() reached "
49           "bottom => _URC_END_OF_STACK",
50           (void *)exception_object);
51       return _URC_END_OF_STACK;
52     } else if (stepResult < 0) {
53       _LIBUNWIND_TRACE_UNWINDING(
54           "unwind_phase1(ex_ojb=%p): __unw_step failed => "
55           "_URC_FATAL_PHASE1_ERROR",
56           (void *)exception_object);
57       return _URC_FATAL_PHASE1_ERROR;
58     }
59 
60     // See if frame has code to run (has personality routine).
61     unw_proc_info_t frameInfo;
62     unw_word_t sp;
63     if (__unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
64       _LIBUNWIND_TRACE_UNWINDING(
65           "unwind_phase1(ex_ojb=%p): __unw_get_proc_info "
66           "failed => _URC_FATAL_PHASE1_ERROR",
67           (void *)exception_object);
68       return _URC_FATAL_PHASE1_ERROR;
69     }
70 
71 #ifndef NDEBUG
72     // When tracing, print state information.
73     if (_LIBUNWIND_TRACING_UNWINDING) {
74       char functionBuf[512];
75       const char *functionName = functionBuf;
76       unw_word_t offset;
77       if ((__unw_get_proc_name(cursor, functionBuf, sizeof(functionBuf),
78                                &offset) != UNW_ESUCCESS) ||
79           (frameInfo.start_ip + offset > frameInfo.end_ip))
80         functionName = ".anonymous.";
81       unw_word_t pc;
82       __unw_get_reg(cursor, UNW_REG_IP, &pc);
83       _LIBUNWIND_TRACE_UNWINDING(
84           "unwind_phase1(ex_ojb=%p): pc=0x%" PRIxPTR ", start_ip=0x%" PRIxPTR
85           ", func=%s, lsda=0x%" PRIxPTR ", personality=0x%" PRIxPTR "",
86           (void *)exception_object, pc, frameInfo.start_ip, functionName,
87           frameInfo.lsda, frameInfo.handler);
88     }
89 #endif
90 
91     // If there is a personality routine, ask it if it will want to stop at
92     // this frame.
93     if (frameInfo.handler != 0) {
94       _Unwind_Personality_Fn p =
95           (_Unwind_Personality_Fn)(uintptr_t)(frameInfo.handler);
96       _LIBUNWIND_TRACE_UNWINDING(
97           "unwind_phase1(ex_ojb=%p): calling personality function %p",
98           (void *)exception_object, (void *)(uintptr_t)p);
99       _Unwind_Reason_Code personalityResult =
100           (*p)(1, _UA_SEARCH_PHASE, exception_object->exception_class,
101                exception_object, (struct _Unwind_Context *)(cursor));
102       switch (personalityResult) {
103       case _URC_HANDLER_FOUND:
104         // found a catch clause or locals that need destructing in this frame
105         // stop search and remember stack pointer at the frame
106         __unw_get_reg(cursor, UNW_REG_SP, &sp);
107         exception_object->private_2 = (uintptr_t)sp;
108         _LIBUNWIND_TRACE_UNWINDING(
109             "unwind_phase1(ex_ojb=%p): _URC_HANDLER_FOUND",
110             (void *)exception_object);
111         return _URC_NO_REASON;
112 
113       case _URC_CONTINUE_UNWIND:
114         _LIBUNWIND_TRACE_UNWINDING(
115             "unwind_phase1(ex_ojb=%p): _URC_CONTINUE_UNWIND",
116             (void *)exception_object);
117         // continue unwinding
118         break;
119 
120       default:
121         // something went wrong
122         _LIBUNWIND_TRACE_UNWINDING(
123             "unwind_phase1(ex_ojb=%p): _URC_FATAL_PHASE1_ERROR",
124             (void *)exception_object);
125         return _URC_FATAL_PHASE1_ERROR;
126       }
127     }
128   }
129   return _URC_NO_REASON;
130 }
131 
132 
133 static _Unwind_Reason_Code
134 unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor, _Unwind_Exception *exception_object) {
135   __unw_init_local(cursor, uc);
136 
137   _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p)",
138                              (void *)exception_object);
139 
140   // Walk each frame until we reach where search phase said to stop.
141   while (true) {
142 
143     // Ask libunwind to get next frame (skip over first which is
144     // _Unwind_RaiseException).
145     int stepResult = __unw_step(cursor);
146     if (stepResult == 0) {
147       _LIBUNWIND_TRACE_UNWINDING(
148           "unwind_phase2(ex_ojb=%p): __unw_step() reached "
149           "bottom => _URC_END_OF_STACK",
150           (void *)exception_object);
151       return _URC_END_OF_STACK;
152     } else if (stepResult < 0) {
153       _LIBUNWIND_TRACE_UNWINDING(
154           "unwind_phase2(ex_ojb=%p): __unw_step failed => "
155           "_URC_FATAL_PHASE1_ERROR",
156           (void *)exception_object);
157       return _URC_FATAL_PHASE2_ERROR;
158     }
159 
160     // Get info about this frame.
161     unw_word_t sp;
162     unw_proc_info_t frameInfo;
163     __unw_get_reg(cursor, UNW_REG_SP, &sp);
164     if (__unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
165       _LIBUNWIND_TRACE_UNWINDING(
166           "unwind_phase2(ex_ojb=%p): __unw_get_proc_info "
167           "failed => _URC_FATAL_PHASE1_ERROR",
168           (void *)exception_object);
169       return _URC_FATAL_PHASE2_ERROR;
170     }
171 
172 #ifndef NDEBUG
173     // When tracing, print state information.
174     if (_LIBUNWIND_TRACING_UNWINDING) {
175       char functionBuf[512];
176       const char *functionName = functionBuf;
177       unw_word_t offset;
178       if ((__unw_get_proc_name(cursor, functionBuf, sizeof(functionBuf),
179                                &offset) != UNW_ESUCCESS) ||
180           (frameInfo.start_ip + offset > frameInfo.end_ip))
181         functionName = ".anonymous.";
182       _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p): start_ip=0x%" PRIxPTR
183                                  ", func=%s, sp=0x%" PRIxPTR ", lsda=0x%" PRIxPTR
184                                  ", personality=0x%" PRIxPTR,
185                                  (void *)exception_object, frameInfo.start_ip,
186                                  functionName, sp, frameInfo.lsda,
187                                  frameInfo.handler);
188     }
189 #endif
190 
191     // If there is a personality routine, tell it we are unwinding.
192     if (frameInfo.handler != 0) {
193       _Unwind_Personality_Fn p =
194           (_Unwind_Personality_Fn)(uintptr_t)(frameInfo.handler);
195       _Unwind_Action action = _UA_CLEANUP_PHASE;
196       if (sp == exception_object->private_2) {
197         // Tell personality this was the frame it marked in phase 1.
198         action = (_Unwind_Action)(_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME);
199       }
200        _Unwind_Reason_Code personalityResult =
201           (*p)(1, action, exception_object->exception_class, exception_object,
202                (struct _Unwind_Context *)(cursor));
203       switch (personalityResult) {
204       case _URC_CONTINUE_UNWIND:
205         // Continue unwinding
206         _LIBUNWIND_TRACE_UNWINDING(
207             "unwind_phase2(ex_ojb=%p): _URC_CONTINUE_UNWIND",
208             (void *)exception_object);
209         if (sp == exception_object->private_2) {
210           // Phase 1 said we would stop at this frame, but we did not...
211           _LIBUNWIND_ABORT("during phase1 personality function said it would "
212                            "stop here, but now in phase2 it did not stop here");
213         }
214         break;
215       case _URC_INSTALL_CONTEXT:
216         _LIBUNWIND_TRACE_UNWINDING(
217             "unwind_phase2(ex_ojb=%p): _URC_INSTALL_CONTEXT",
218             (void *)exception_object);
219         // Personality routine says to transfer control to landing pad.
220         // We may get control back if landing pad calls _Unwind_Resume().
221         if (_LIBUNWIND_TRACING_UNWINDING) {
222           unw_word_t pc;
223           __unw_get_reg(cursor, UNW_REG_IP, &pc);
224           __unw_get_reg(cursor, UNW_REG_SP, &sp);
225           _LIBUNWIND_TRACE_UNWINDING("unwind_phase2(ex_ojb=%p): re-entering "
226                                      "user code with ip=0x%" PRIxPTR
227                                      ", sp=0x%" PRIxPTR,
228                                      (void *)exception_object, pc, sp);
229         }
230         __unw_resume(cursor);
231         // __unw_resume() only returns if there was an error.
232         return _URC_FATAL_PHASE2_ERROR;
233       default:
234         // Personality routine returned an unknown result code.
235         _LIBUNWIND_DEBUG_LOG("personality function returned unknown result %d",
236                              personalityResult);
237         return _URC_FATAL_PHASE2_ERROR;
238       }
239     }
240   }
241 
242   // Clean up phase did not resume at the frame that the search phase
243   // said it would...
244   return _URC_FATAL_PHASE2_ERROR;
245 }
246 
247 static _Unwind_Reason_Code
248 unwind_phase2_forced(unw_context_t *uc, unw_cursor_t *cursor,
249                      _Unwind_Exception *exception_object,
250                      _Unwind_Stop_Fn stop, void *stop_parameter) {
251   __unw_init_local(cursor, uc);
252 
253   // Walk each frame until we reach where search phase said to stop
254   while (__unw_step(cursor) > 0) {
255 
256     // Update info about this frame.
257     unw_proc_info_t frameInfo;
258     if (__unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
259       _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): __unw_step "
260                                  "failed => _URC_END_OF_STACK",
261                                  (void *)exception_object);
262       return _URC_FATAL_PHASE2_ERROR;
263     }
264 
265 #ifndef NDEBUG
266     // When tracing, print state information.
267     if (_LIBUNWIND_TRACING_UNWINDING) {
268       char functionBuf[512];
269       const char *functionName = functionBuf;
270       unw_word_t offset;
271       if ((__unw_get_proc_name(cursor, functionBuf, sizeof(functionBuf),
272                                &offset) != UNW_ESUCCESS) ||
273           (frameInfo.start_ip + offset > frameInfo.end_ip))
274         functionName = ".anonymous.";
275       _LIBUNWIND_TRACE_UNWINDING(
276           "unwind_phase2_forced(ex_ojb=%p): start_ip=0x%" PRIxPTR
277           ", func=%s, lsda=0x%" PRIxPTR ", personality=0x%" PRIxPTR,
278           (void *)exception_object, frameInfo.start_ip, functionName,
279           frameInfo.lsda, frameInfo.handler);
280     }
281 #endif
282 
283     // Call stop function at each frame.
284     _Unwind_Action action =
285         (_Unwind_Action)(_UA_FORCE_UNWIND | _UA_CLEANUP_PHASE);
286     _Unwind_Reason_Code stopResult =
287         (*stop)(1, action, exception_object->exception_class, exception_object,
288                 (struct _Unwind_Context *)(cursor), stop_parameter);
289     _LIBUNWIND_TRACE_UNWINDING(
290         "unwind_phase2_forced(ex_ojb=%p): stop function returned %d",
291         (void *)exception_object, stopResult);
292     if (stopResult != _URC_NO_REASON) {
293       _LIBUNWIND_TRACE_UNWINDING(
294           "unwind_phase2_forced(ex_ojb=%p): stopped by stop function",
295           (void *)exception_object);
296       return _URC_FATAL_PHASE2_ERROR;
297     }
298 
299     // If there is a personality routine, tell it we are unwinding.
300     if (frameInfo.handler != 0) {
301       _Unwind_Personality_Fn p =
302           (_Unwind_Personality_Fn)(intptr_t)(frameInfo.handler);
303       _LIBUNWIND_TRACE_UNWINDING(
304           "unwind_phase2_forced(ex_ojb=%p): calling personality function %p",
305           (void *)exception_object, (void *)(uintptr_t)p);
306       _Unwind_Reason_Code personalityResult =
307           (*p)(1, action, exception_object->exception_class, exception_object,
308                (struct _Unwind_Context *)(cursor));
309       switch (personalityResult) {
310       case _URC_CONTINUE_UNWIND:
311         _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
312                                    "personality returned "
313                                    "_URC_CONTINUE_UNWIND",
314                                    (void *)exception_object);
315         // Destructors called, continue unwinding
316         break;
317       case _URC_INSTALL_CONTEXT:
318         _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
319                                    "personality returned "
320                                    "_URC_INSTALL_CONTEXT",
321                                    (void *)exception_object);
322         // We may get control back if landing pad calls _Unwind_Resume().
323         __unw_resume(cursor);
324         break;
325       default:
326         // Personality routine returned an unknown result code.
327         _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
328                                    "personality returned %d, "
329                                    "_URC_FATAL_PHASE2_ERROR",
330                                    (void *)exception_object, personalityResult);
331         return _URC_FATAL_PHASE2_ERROR;
332       }
333     }
334   }
335 
336   // Call stop function one last time and tell it we've reached the end
337   // of the stack.
338   _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): calling stop "
339                              "function with _UA_END_OF_STACK",
340                              (void *)exception_object);
341   _Unwind_Action lastAction =
342       (_Unwind_Action)(_UA_FORCE_UNWIND | _UA_CLEANUP_PHASE | _UA_END_OF_STACK);
343   (*stop)(1, lastAction, exception_object->exception_class, exception_object,
344           (struct _Unwind_Context *)(cursor), stop_parameter);
345 
346   // Clean up phase did not resume at the frame that the search phase said it
347   // would.
348   return _URC_FATAL_PHASE2_ERROR;
349 }
350 
351 
352 /// Called by __cxa_throw.  Only returns if there is a fatal error.
353 _LIBUNWIND_EXPORT _Unwind_Reason_Code
354 _Unwind_RaiseException(_Unwind_Exception *exception_object) {
355   _LIBUNWIND_TRACE_API("_Unwind_RaiseException(ex_obj=%p)",
356                        (void *)exception_object);
357   unw_context_t uc;
358   unw_cursor_t cursor;
359   __unw_getcontext(&uc);
360 
361   // Mark that this is a non-forced unwind, so _Unwind_Resume()
362   // can do the right thing.
363   exception_object->private_1 = 0;
364   exception_object->private_2 = 0;
365 
366   // phase 1: the search phase
367   _Unwind_Reason_Code phase1 = unwind_phase1(&uc, &cursor, exception_object);
368   if (phase1 != _URC_NO_REASON)
369     return phase1;
370 
371   // phase 2: the clean up phase
372   return unwind_phase2(&uc, &cursor, exception_object);
373 }
374 
375 
376 
377 /// When _Unwind_RaiseException() is in phase2, it hands control
378 /// to the personality function at each frame.  The personality
379 /// may force a jump to a landing pad in that function, the landing
380 /// pad code may then call _Unwind_Resume() to continue with the
381 /// unwinding.  Note: the call to _Unwind_Resume() is from compiler
382 /// geneated user code.  All other _Unwind_* routines are called
383 /// by the C++ runtime __cxa_* routines.
384 ///
385 /// Note: re-throwing an exception (as opposed to continuing the unwind)
386 /// is implemented by having the code call __cxa_rethrow() which
387 /// in turn calls _Unwind_Resume_or_Rethrow().
388 _LIBUNWIND_EXPORT void
389 _Unwind_Resume(_Unwind_Exception *exception_object) {
390   _LIBUNWIND_TRACE_API("_Unwind_Resume(ex_obj=%p)", (void *)exception_object);
391   unw_context_t uc;
392   unw_cursor_t cursor;
393   __unw_getcontext(&uc);
394 
395   if (exception_object->private_1 != 0)
396     unwind_phase2_forced(&uc, &cursor, exception_object,
397                          (_Unwind_Stop_Fn) exception_object->private_1,
398                          (void *)exception_object->private_2);
399   else
400     unwind_phase2(&uc, &cursor, exception_object);
401 
402   // Clients assume _Unwind_Resume() does not return, so all we can do is abort.
403   _LIBUNWIND_ABORT("_Unwind_Resume() can't return");
404 }
405 
406 
407 
408 /// Not used by C++.
409 /// Unwinds stack, calling "stop" function at each frame.
410 /// Could be used to implement longjmp().
411 _LIBUNWIND_EXPORT _Unwind_Reason_Code
412 _Unwind_ForcedUnwind(_Unwind_Exception *exception_object,
413                      _Unwind_Stop_Fn stop, void *stop_parameter) {
414   _LIBUNWIND_TRACE_API("_Unwind_ForcedUnwind(ex_obj=%p, stop=%p)",
415                        (void *)exception_object, (void *)(uintptr_t)stop);
416   unw_context_t uc;
417   unw_cursor_t cursor;
418   __unw_getcontext(&uc);
419 
420   // Mark that this is a forced unwind, so _Unwind_Resume() can do
421   // the right thing.
422   exception_object->private_1 = (uintptr_t) stop;
423   exception_object->private_2 = (uintptr_t) stop_parameter;
424 
425   // do it
426   return unwind_phase2_forced(&uc, &cursor, exception_object, stop, stop_parameter);
427 }
428 
429 
430 /// Called by personality handler during phase 2 to get LSDA for current frame.
431 _LIBUNWIND_EXPORT uintptr_t
432 _Unwind_GetLanguageSpecificData(struct _Unwind_Context *context) {
433   unw_cursor_t *cursor = (unw_cursor_t *)context;
434   unw_proc_info_t frameInfo;
435   uintptr_t result = 0;
436   if (__unw_get_proc_info(cursor, &frameInfo) == UNW_ESUCCESS)
437     result = (uintptr_t)frameInfo.lsda;
438   _LIBUNWIND_TRACE_API(
439       "_Unwind_GetLanguageSpecificData(context=%p) => 0x%" PRIxPTR,
440       (void *)context, result);
441   if (result != 0) {
442     if (*((uint8_t *)result) != 0xFF)
443       _LIBUNWIND_DEBUG_LOG("lsda at 0x%" PRIxPTR " does not start with 0xFF",
444                            result);
445   }
446   return result;
447 }
448 
449 
450 /// Called by personality handler during phase 2 to find the start of the
451 /// function.
452 _LIBUNWIND_EXPORT uintptr_t
453 _Unwind_GetRegionStart(struct _Unwind_Context *context) {
454   unw_cursor_t *cursor = (unw_cursor_t *)context;
455   unw_proc_info_t frameInfo;
456   uintptr_t result = 0;
457   if (__unw_get_proc_info(cursor, &frameInfo) == UNW_ESUCCESS)
458     result = (uintptr_t)frameInfo.start_ip;
459   _LIBUNWIND_TRACE_API("_Unwind_GetRegionStart(context=%p) => 0x%" PRIxPTR,
460                        (void *)context, result);
461   return result;
462 }
463 
464 #endif // !_LIBUNWIND_SUPPORT_SEH_UNWIND
465 
466 /// Called by personality handler during phase 2 if a foreign exception
467 // is caught.
468 _LIBUNWIND_EXPORT void
469 _Unwind_DeleteException(_Unwind_Exception *exception_object) {
470   _LIBUNWIND_TRACE_API("_Unwind_DeleteException(ex_obj=%p)",
471                        (void *)exception_object);
472   if (exception_object->exception_cleanup != NULL)
473     (*exception_object->exception_cleanup)(_URC_FOREIGN_EXCEPTION_CAUGHT,
474                                            exception_object);
475 }
476 
477 /// Called by personality handler during phase 2 to get register values.
478 _LIBUNWIND_EXPORT uintptr_t
479 _Unwind_GetGR(struct _Unwind_Context *context, int index) {
480   unw_cursor_t *cursor = (unw_cursor_t *)context;
481   unw_word_t result;
482   __unw_get_reg(cursor, index, &result);
483   _LIBUNWIND_TRACE_API("_Unwind_GetGR(context=%p, reg=%d) => 0x%" PRIxPTR,
484                        (void *)context, index, result);
485   return (uintptr_t)result;
486 }
487 
488 /// Called by personality handler during phase 2 to alter register values.
489 _LIBUNWIND_EXPORT void _Unwind_SetGR(struct _Unwind_Context *context, int index,
490                                      uintptr_t value) {
491   _LIBUNWIND_TRACE_API("_Unwind_SetGR(context=%p, reg=%d, value=0x%0" PRIxPTR
492                        ")",
493                        (void *)context, index, value);
494   unw_cursor_t *cursor = (unw_cursor_t *)context;
495   __unw_set_reg(cursor, index, value);
496 }
497 
498 /// Called by personality handler during phase 2 to get instruction pointer.
499 _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIP(struct _Unwind_Context *context) {
500   unw_cursor_t *cursor = (unw_cursor_t *)context;
501   unw_word_t result;
502   __unw_get_reg(cursor, UNW_REG_IP, &result);
503   _LIBUNWIND_TRACE_API("_Unwind_GetIP(context=%p) => 0x%" PRIxPTR,
504                        (void *)context, result);
505   return (uintptr_t)result;
506 }
507 
508 /// Called by personality handler during phase 2 to alter instruction pointer,
509 /// such as setting where the landing pad is, so _Unwind_Resume() will
510 /// start executing in the landing pad.
511 _LIBUNWIND_EXPORT void _Unwind_SetIP(struct _Unwind_Context *context,
512                                      uintptr_t value) {
513   _LIBUNWIND_TRACE_API("_Unwind_SetIP(context=%p, value=0x%0" PRIxPTR ")",
514                        (void *)context, value);
515   unw_cursor_t *cursor = (unw_cursor_t *)context;
516   __unw_set_reg(cursor, UNW_REG_IP, value);
517 }
518 
519 #endif // !defined(_LIBUNWIND_ARM_EHABI) && !defined(__USING_SJLJ_EXCEPTIONS__)
520