xref: /freebsd/contrib/llvm-project/libunwind/src/UnwindLevel1-gcc-ext.c (revision e32fecd0c2c3ee37c47ee100f169e7eb0282a873)
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 gcc extensions to the C++ ABI Exception Handling Level 1.
9 //
10 //===----------------------------------------------------------------------===//
11 
12 #include <inttypes.h>
13 #include <stdbool.h>
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 
19 #include "config.h"
20 #include "libunwind_ext.h"
21 #include "libunwind.h"
22 #include "Unwind-EHABI.h"
23 #include "unwind.h"
24 
25 #if defined(_LIBUNWIND_BUILD_ZERO_COST_APIS)
26 
27 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
28 #define PRIVATE_1 private_[0]
29 #elif defined(_LIBUNWIND_ARM_EHABI)
30 #define PRIVATE_1 unwinder_cache.reserved1
31 #else
32 #define PRIVATE_1 private_1
33 #endif
34 
35 ///  Called by __cxa_rethrow().
36 _LIBUNWIND_EXPORT _Unwind_Reason_Code
37 _Unwind_Resume_or_Rethrow(_Unwind_Exception *exception_object) {
38   _LIBUNWIND_TRACE_API(
39       "_Unwind_Resume_or_Rethrow(ex_obj=%p), private_1=%" PRIdPTR,
40       (void *)exception_object, (intptr_t)exception_object->PRIVATE_1);
41 
42   // If this is non-forced and a stopping place was found, then this is a
43   // re-throw.
44   // Call _Unwind_RaiseException() as if this was a new exception
45   if (exception_object->PRIVATE_1 == 0) {
46     return _Unwind_RaiseException(exception_object);
47     // Will return if there is no catch clause, so that __cxa_rethrow can call
48     // std::terminate().
49   }
50 
51   // Call through to _Unwind_Resume() which distiguishes between forced and
52   // regular exceptions.
53   _Unwind_Resume(exception_object);
54   _LIBUNWIND_ABORT("_Unwind_Resume_or_Rethrow() called _Unwind_RaiseException()"
55                    " which unexpectedly returned");
56 }
57 
58 /// Called by personality handler during phase 2 to get base address for data
59 /// relative encodings.
60 _LIBUNWIND_EXPORT uintptr_t
61 _Unwind_GetDataRelBase(struct _Unwind_Context *context) {
62   _LIBUNWIND_TRACE_API("_Unwind_GetDataRelBase(context=%p)", (void *)context);
63 #if defined(_AIX)
64   return unw_get_data_rel_base((unw_cursor_t *)context);
65 #else
66   (void)context;
67   _LIBUNWIND_ABORT("_Unwind_GetDataRelBase() not implemented");
68 #endif
69 }
70 
71 /// Called by personality handler during phase 2 to get base address for text
72 /// relative encodings.
73 _LIBUNWIND_EXPORT uintptr_t
74 _Unwind_GetTextRelBase(struct _Unwind_Context *context) {
75   (void)context;
76   _LIBUNWIND_TRACE_API("_Unwind_GetTextRelBase(context=%p)", (void *)context);
77   _LIBUNWIND_ABORT("_Unwind_GetTextRelBase() not implemented");
78 }
79 
80 
81 /// Scans unwind information to find the function that contains the
82 /// specified code address "pc".
83 _LIBUNWIND_EXPORT void *_Unwind_FindEnclosingFunction(void *pc) {
84   _LIBUNWIND_TRACE_API("_Unwind_FindEnclosingFunction(pc=%p)", pc);
85   // This is slow, but works.
86   // We create an unwind cursor then alter the IP to be pc
87   unw_cursor_t cursor;
88   unw_context_t uc;
89   unw_proc_info_t info;
90   __unw_getcontext(&uc);
91   __unw_init_local(&cursor, &uc);
92   __unw_set_reg(&cursor, UNW_REG_IP, (unw_word_t)(intptr_t)pc);
93   if (__unw_get_proc_info(&cursor, &info) == UNW_ESUCCESS)
94     return (void *)(intptr_t) info.start_ip;
95   else
96     return NULL;
97 }
98 
99 /// Walk every frame and call trace function at each one.  If trace function
100 /// returns anything other than _URC_NO_REASON, then walk is terminated.
101 _LIBUNWIND_EXPORT _Unwind_Reason_Code
102 _Unwind_Backtrace(_Unwind_Trace_Fn callback, void *ref) {
103   unw_cursor_t cursor;
104   unw_context_t uc;
105   __unw_getcontext(&uc);
106   __unw_init_local(&cursor, &uc);
107 
108   _LIBUNWIND_TRACE_API("_Unwind_Backtrace(callback=%p)",
109                        (void *)(uintptr_t)callback);
110 
111 #if defined(_LIBUNWIND_ARM_EHABI)
112   // Create a mock exception object for force unwinding.
113   _Unwind_Exception ex;
114   memset(&ex, '\0', sizeof(ex));
115   strcpy((char *)&ex.exception_class, "CLNGUNW");
116 #endif
117 
118   // walk each frame
119   while (true) {
120     _Unwind_Reason_Code result;
121 
122 #if !defined(_LIBUNWIND_ARM_EHABI)
123     // ask libunwind to get next frame (skip over first frame which is
124     // _Unwind_Backtrace())
125     if (__unw_step(&cursor) <= 0) {
126       _LIBUNWIND_TRACE_UNWINDING(" _backtrace: ended because cursor reached "
127                                  "bottom of stack, returning %d",
128                                  _URC_END_OF_STACK);
129       return _URC_END_OF_STACK;
130     }
131 #else
132     // Get the information for this frame.
133     unw_proc_info_t frameInfo;
134     if (__unw_get_proc_info(&cursor, &frameInfo) != UNW_ESUCCESS) {
135       return _URC_END_OF_STACK;
136     }
137 
138     // Update the pr_cache in the mock exception object.
139     const uint32_t* unwindInfo = (uint32_t *) frameInfo.unwind_info;
140     ex.pr_cache.fnstart = frameInfo.start_ip;
141     ex.pr_cache.ehtp = (_Unwind_EHT_Header *) unwindInfo;
142     ex.pr_cache.additional= frameInfo.flags;
143 
144     struct _Unwind_Context *context = (struct _Unwind_Context *)&cursor;
145     // Get and call the personality function to unwind the frame.
146     _Unwind_Personality_Fn handler = (_Unwind_Personality_Fn)frameInfo.handler;
147     if (handler == NULL) {
148       return _URC_END_OF_STACK;
149     }
150     if (handler(_US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND, &ex, context) !=
151             _URC_CONTINUE_UNWIND) {
152       return _URC_END_OF_STACK;
153     }
154 #endif // defined(_LIBUNWIND_ARM_EHABI)
155 
156     // debugging
157     if (_LIBUNWIND_TRACING_UNWINDING) {
158       char functionName[512];
159       unw_proc_info_t frame;
160       unw_word_t offset;
161       __unw_get_proc_name(&cursor, functionName, 512, &offset);
162       __unw_get_proc_info(&cursor, &frame);
163       _LIBUNWIND_TRACE_UNWINDING(
164           " _backtrace: start_ip=0x%" PRIxPTR ", func=%s, lsda=0x%" PRIxPTR ", context=%p",
165           frame.start_ip, functionName, frame.lsda,
166           (void *)&cursor);
167     }
168 
169     // call trace function with this frame
170     result = (*callback)((struct _Unwind_Context *)(&cursor), ref);
171     if (result != _URC_NO_REASON) {
172       _LIBUNWIND_TRACE_UNWINDING(
173           " _backtrace: ended because callback returned %d", result);
174       return result;
175     }
176   }
177 }
178 #ifdef __arm__
179 /* Preserve legacy libgcc (pre r318024) ARM ABI mistake */
180 __sym_compat(_Unwind_Backtrace, _Unwind_Backtrace, GCC_3.3);
181 #endif
182 
183 
184 /// Find DWARF unwind info for an address 'pc' in some function.
185 _LIBUNWIND_EXPORT const void *_Unwind_Find_FDE(const void *pc,
186                                                struct dwarf_eh_bases *bases) {
187   // This is slow, but works.
188   // We create an unwind cursor then alter the IP to be pc
189   unw_cursor_t cursor;
190   unw_context_t uc;
191   unw_proc_info_t info;
192   __unw_getcontext(&uc);
193   __unw_init_local(&cursor, &uc);
194   __unw_set_reg(&cursor, UNW_REG_IP, (unw_word_t)(intptr_t)pc);
195   __unw_get_proc_info(&cursor, &info);
196   bases->tbase = (uintptr_t)info.extra;
197   bases->dbase = 0; // dbase not used on Mac OS X
198   bases->func = (uintptr_t)info.start_ip;
199   _LIBUNWIND_TRACE_API("_Unwind_Find_FDE(pc=%p) => %p", pc,
200                   (void *)(intptr_t) info.unwind_info);
201   return (void *)(intptr_t) info.unwind_info;
202 }
203 
204 /// Returns the CFA (call frame area, or stack pointer at start of function)
205 /// for the current context.
206 _LIBUNWIND_EXPORT uintptr_t _Unwind_GetCFA(struct _Unwind_Context *context) {
207   unw_cursor_t *cursor = (unw_cursor_t *)context;
208   unw_word_t result;
209   __unw_get_reg(cursor, UNW_REG_SP, &result);
210   _LIBUNWIND_TRACE_API("_Unwind_GetCFA(context=%p) => 0x%" PRIxPTR,
211                        (void *)context, result);
212   return (uintptr_t)result;
213 }
214 
215 
216 /// Called by personality handler during phase 2 to get instruction pointer.
217 /// ipBefore is a boolean that says if IP is already adjusted to be the call
218 /// site address.  Normally IP is the return address.
219 _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIPInfo(struct _Unwind_Context *context,
220                                               int *ipBefore) {
221   _LIBUNWIND_TRACE_API("_Unwind_GetIPInfo(context=%p)", (void *)context);
222   int isSignalFrame = __unw_is_signal_frame((unw_cursor_t *)context);
223   // Negative means some kind of error (probably UNW_ENOINFO), but we have no
224   // good way to report that, and this maintains backward compatibility with the
225   // implementation that hard-coded zero in every case, even signal frames.
226   if (isSignalFrame <= 0)
227     *ipBefore = 0;
228   else
229     *ipBefore = 1;
230   return _Unwind_GetIP(context);
231 }
232 
233 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
234 
235 #if defined(__FreeBSD__)
236 
237 // Based on LLVM's lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp
238 // and XXX should be fixed to be alignment-safe.
239 static void processFDE(const char *addr, bool isDeregister) {
240   uint64_t length;
241   while ((length = *((const uint32_t *)addr)) != 0) {
242     const char *p = addr + 4;
243     if (length == 0xffffffff) {
244       length = *((const uint64_t *)p);
245       p += 8;
246     }
247     uint32_t offset = *((const uint32_t *)p);
248     if (offset != 0) {
249       if (isDeregister)
250         __unw_remove_dynamic_fde((unw_word_t)(uintptr_t)addr);
251       else
252         __unw_add_dynamic_fde((unw_word_t)(uintptr_t)addr);
253     }
254     addr = p + length;
255   }
256 }
257 
258 /// Called by programs with dynamic code generators that want to register
259 /// dynamically generated FDEs, with a libgcc-compatible API.
260 
261 _LIBUNWIND_EXPORT void __register_frame(const void *addr) {
262   _LIBUNWIND_TRACE_API("__register_frame(%p)", addr);
263   processFDE(addr, false);
264 }
265 
266 /// Called by programs with dynamic code generators that want to unregister
267 /// dynamically generated FDEs, with a libgcc-compatible API.
268 _LIBUNWIND_EXPORT void __deregister_frame(const void *addr) {
269   _LIBUNWIND_TRACE_API("__deregister_frame(%p)", addr);
270   processFDE(addr, true);
271 }
272 
273 #else // defined(__FreeBSD__)
274 
275 /// Called by programs with dynamic code generators that want
276 /// to register a dynamically generated FDE.
277 /// This function has existed on Mac OS X since 10.4, but
278 /// was broken until 10.6.
279 _LIBUNWIND_EXPORT void __register_frame(const void *fde) {
280   _LIBUNWIND_TRACE_API("__register_frame(%p)", fde);
281   __unw_add_dynamic_fde((unw_word_t)(uintptr_t)fde);
282 }
283 
284 /// Called by programs with dynamic code generators that want
285 /// to unregister a dynamically generated FDE.
286 /// This function has existed on Mac OS X since 10.4, but
287 /// was broken until 10.6.
288 _LIBUNWIND_EXPORT void __deregister_frame(const void *fde) {
289   _LIBUNWIND_TRACE_API("__deregister_frame(%p)", fde);
290   __unw_remove_dynamic_fde((unw_word_t)(uintptr_t)fde);
291 }
292 
293 #endif // defined(__FreeBSD__)
294 
295 // The following register/deregister functions are gcc extensions.
296 // They have existed on Mac OS X, but have never worked because Mac OS X
297 // before 10.6 used keymgr to track known FDEs, but these functions
298 // never got updated to use keymgr.
299 // For now, we implement these as do-nothing functions to keep any existing
300 // applications working.  We also add the not in 10.6 symbol so that nwe
301 // application won't be able to use them.
302 
303 #if defined(_LIBUNWIND_SUPPORT_FRAME_APIS)
304 _LIBUNWIND_EXPORT void __register_frame_info_bases(const void *fde, void *ob,
305                                                    void *tb, void *db) {
306   (void)fde;
307   (void)ob;
308   (void)tb;
309   (void)db;
310  _LIBUNWIND_TRACE_API("__register_frame_info_bases(%p,%p, %p, %p)",
311                             fde, ob, tb, db);
312   // do nothing, this function never worked in Mac OS X
313 }
314 
315 _LIBUNWIND_EXPORT void __register_frame_info(const void *fde, void *ob) {
316   (void)fde;
317   (void)ob;
318   _LIBUNWIND_TRACE_API("__register_frame_info(%p, %p)", fde, ob);
319   // do nothing, this function never worked in Mac OS X
320 }
321 
322 _LIBUNWIND_EXPORT void __register_frame_info_table_bases(const void *fde,
323                                                          void *ob, void *tb,
324                                                          void *db) {
325   (void)fde;
326   (void)ob;
327   (void)tb;
328   (void)db;
329   _LIBUNWIND_TRACE_API("__register_frame_info_table_bases"
330                              "(%p,%p, %p, %p)", fde, ob, tb, db);
331   // do nothing, this function never worked in Mac OS X
332 }
333 
334 _LIBUNWIND_EXPORT void __register_frame_info_table(const void *fde, void *ob) {
335   (void)fde;
336   (void)ob;
337   _LIBUNWIND_TRACE_API("__register_frame_info_table(%p, %p)", fde, ob);
338   // do nothing, this function never worked in Mac OS X
339 }
340 
341 _LIBUNWIND_EXPORT void __register_frame_table(const void *fde) {
342   (void)fde;
343   _LIBUNWIND_TRACE_API("__register_frame_table(%p)", fde);
344   // do nothing, this function never worked in Mac OS X
345 }
346 
347 _LIBUNWIND_EXPORT void *__deregister_frame_info(const void *fde) {
348   (void)fde;
349   _LIBUNWIND_TRACE_API("__deregister_frame_info(%p)", fde);
350   // do nothing, this function never worked in Mac OS X
351   return NULL;
352 }
353 
354 _LIBUNWIND_EXPORT void *__deregister_frame_info_bases(const void *fde) {
355   (void)fde;
356   _LIBUNWIND_TRACE_API("__deregister_frame_info_bases(%p)", fde);
357   // do nothing, this function never worked in Mac OS X
358   return NULL;
359 }
360 #endif // defined(_LIBUNWIND_SUPPORT_FRAME_APIS)
361 
362 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
363 
364 #endif // defined(_LIBUNWIND_BUILD_ZERO_COST_APIS)
365