1 //===--------------------------- libunwind.cpp ----------------------------===//
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 unw_* functions from <libunwind.h>
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <libunwind.h>
14 
15 #ifndef NDEBUG
16 #include <cstdlib> // getenv
17 #endif
18 #include <new>
19 #include <algorithm>
20 
21 #include "libunwind_ext.h"
22 #include "config.h"
23 
24 #include <stdlib.h>
25 
26 
27 #if !defined(__USING_SJLJ_EXCEPTIONS__)
28 #include "AddressSpace.hpp"
29 #include "UnwindCursor.hpp"
30 
31 using namespace libunwind;
32 
33 /// internal object to represent this processes address space
34 LocalAddressSpace LocalAddressSpace::sThisAddressSpace;
35 
36 _LIBUNWIND_EXPORT unw_addr_space_t unw_local_addr_space =
37     (unw_addr_space_t)&LocalAddressSpace::sThisAddressSpace;
38 
39 /// record the registers and stack position of the caller
40 extern int unw_getcontext(unw_context_t *);
41 // note: unw_getcontext() implemented in assembly
42 
43 /// Create a cursor of a thread in this process given 'context' recorded by
44 /// unw_getcontext().
45 _LIBUNWIND_EXPORT int unw_init_local(unw_cursor_t *cursor,
46                                      unw_context_t *context) {
47   _LIBUNWIND_TRACE_API("unw_init_local(cursor=%p, context=%p)",
48                        static_cast<void *>(cursor),
49                        static_cast<void *>(context));
50 #if defined(__i386__)
51 # define REGISTER_KIND Registers_x86
52 #elif defined(__x86_64__)
53 # define REGISTER_KIND Registers_x86_64
54 #elif defined(__ppc__)
55 # define REGISTER_KIND Registers_ppc
56 #elif defined(__aarch64__)
57 # define REGISTER_KIND Registers_arm64
58 #elif defined(_LIBUNWIND_ARM_EHABI)
59 # define REGISTER_KIND Registers_arm
60 #elif defined(__or1k__)
61 # define REGISTER_KIND Registers_or1k
62 #elif defined(__mips__)
63 # warning The MIPS architecture is not supported.
64 #else
65 # error Architecture not supported
66 #endif
67   // Use "placement new" to allocate UnwindCursor in the cursor buffer.
68   new ((void *)cursor) UnwindCursor<LocalAddressSpace, REGISTER_KIND>(
69                                  context, LocalAddressSpace::sThisAddressSpace);
70 #undef REGISTER_KIND
71   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
72   co->setInfoBasedOnIPRegister();
73 
74   return UNW_ESUCCESS;
75 }
76 
77 #ifdef UNW_REMOTE
78 /// Create a cursor into a thread in another process.
79 _LIBUNWIND_EXPORT int unw_init_remote_thread(unw_cursor_t *cursor,
80                                              unw_addr_space_t as,
81                                              void *arg) {
82   // special case: unw_init_remote(xx, unw_local_addr_space, xx)
83   if (as == (unw_addr_space_t)&LocalAddressSpace::sThisAddressSpace)
84     return unw_init_local(cursor, NULL); //FIXME
85 
86   // use "placement new" to allocate UnwindCursor in the cursor buffer
87   switch (as->cpuType) {
88   case CPU_TYPE_I386:
89     new ((void *)cursor)
90         UnwindCursor<RemoteAddressSpace<Pointer32<LittleEndian>>,
91                      Registers_x86>(((unw_addr_space_i386 *)as)->oas, arg);
92     break;
93   case CPU_TYPE_X86_64:
94     new ((void *)cursor)
95         UnwindCursor<RemoteAddressSpace<Pointer64<LittleEndian>>,
96                      Registers_x86_64>(((unw_addr_space_x86_64 *)as)->oas, arg);
97     break;
98   case CPU_TYPE_POWERPC:
99     new ((void *)cursor)
100         UnwindCursor<RemoteAddressSpace<Pointer32<BigEndian>>,
101                      Registers_ppc>(((unw_addr_space_ppc *)as)->oas, arg);
102     break;
103   default:
104     return UNW_EUNSPEC;
105   }
106   return UNW_ESUCCESS;
107 }
108 
109 
110 static bool is64bit(task_t task) {
111   return false; // FIXME
112 }
113 
114 /// Create an address_space object for use in examining another task.
115 _LIBUNWIND_EXPORT unw_addr_space_t unw_create_addr_space_for_task(task_t task) {
116 #if __i386__
117   if (is64bit(task)) {
118     unw_addr_space_x86_64 *as = new unw_addr_space_x86_64(task);
119     as->taskPort = task;
120     as->cpuType = CPU_TYPE_X86_64;
121     //as->oas
122   } else {
123     unw_addr_space_i386 *as = new unw_addr_space_i386(task);
124     as->taskPort = task;
125     as->cpuType = CPU_TYPE_I386;
126     //as->oas
127   }
128 #else
129 // FIXME
130 #endif
131 }
132 
133 
134 /// Delete an address_space object.
135 _LIBUNWIND_EXPORT void unw_destroy_addr_space(unw_addr_space_t asp) {
136   switch (asp->cpuType) {
137 #if __i386__ || __x86_64__
138   case CPU_TYPE_I386: {
139     unw_addr_space_i386 *as = (unw_addr_space_i386 *)asp;
140     delete as;
141   }
142   break;
143   case CPU_TYPE_X86_64: {
144     unw_addr_space_x86_64 *as = (unw_addr_space_x86_64 *)asp;
145     delete as;
146   }
147   break;
148 #endif
149   case CPU_TYPE_POWERPC: {
150     unw_addr_space_ppc *as = (unw_addr_space_ppc *)asp;
151     delete as;
152   }
153   break;
154   }
155 }
156 #endif // UNW_REMOTE
157 
158 
159 /// Get value of specified register at cursor position in stack frame.
160 _LIBUNWIND_EXPORT int unw_get_reg(unw_cursor_t *cursor, unw_regnum_t regNum,
161                                   unw_word_t *value) {
162   _LIBUNWIND_TRACE_API("unw_get_reg(cursor=%p, regNum=%d, &value=%p)",
163                        static_cast<void *>(cursor), regNum,
164                        static_cast<void *>(value));
165   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
166   if (co->validReg(regNum)) {
167     *value = co->getReg(regNum);
168     return UNW_ESUCCESS;
169   }
170   return UNW_EBADREG;
171 }
172 
173 
174 /// Set value of specified register at cursor position in stack frame.
175 _LIBUNWIND_EXPORT int unw_set_reg(unw_cursor_t *cursor, unw_regnum_t regNum,
176                                   unw_word_t value) {
177   _LIBUNWIND_TRACE_API("unw_set_reg(cursor=%p, regNum=%d, value=0x%llX)",
178                        static_cast<void *>(cursor), regNum, (long long)value);
179   typedef LocalAddressSpace::pint_t pint_t;
180   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
181   if (co->validReg(regNum)) {
182     co->setReg(regNum, (pint_t)value);
183     // specical case altering IP to re-find info (being called by personality
184     // function)
185     if (regNum == UNW_REG_IP)
186       co->setInfoBasedOnIPRegister(false);
187     return UNW_ESUCCESS;
188   }
189   return UNW_EBADREG;
190 }
191 
192 
193 /// Get value of specified float register at cursor position in stack frame.
194 _LIBUNWIND_EXPORT int unw_get_fpreg(unw_cursor_t *cursor, unw_regnum_t regNum,
195                                     unw_fpreg_t *value) {
196   _LIBUNWIND_TRACE_API("unw_get_fpreg(cursor=%p, regNum=%d, &value=%p)",
197                        static_cast<void *>(cursor), regNum,
198                        static_cast<void *>(value));
199   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
200   if (co->validFloatReg(regNum)) {
201     *value = co->getFloatReg(regNum);
202     return UNW_ESUCCESS;
203   }
204   return UNW_EBADREG;
205 }
206 
207 
208 /// Set value of specified float register at cursor position in stack frame.
209 _LIBUNWIND_EXPORT int unw_set_fpreg(unw_cursor_t *cursor, unw_regnum_t regNum,
210                                     unw_fpreg_t value) {
211 #if defined(_LIBUNWIND_ARM_EHABI)
212   _LIBUNWIND_TRACE_API("unw_set_fpreg(cursor=%p, regNum=%d, value=%llX)",
213                        static_cast<void *>(cursor), regNum, value);
214 #else
215   _LIBUNWIND_TRACE_API("unw_set_fpreg(cursor=%p, regNum=%d, value=%g)",
216                        static_cast<void *>(cursor), regNum, value);
217 #endif
218   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
219   if (co->validFloatReg(regNum)) {
220     co->setFloatReg(regNum, value);
221     return UNW_ESUCCESS;
222   }
223   return UNW_EBADREG;
224 }
225 
226 
227 /// Move cursor to next frame.
228 _LIBUNWIND_EXPORT int unw_step(unw_cursor_t *cursor) {
229   _LIBUNWIND_TRACE_API("unw_step(cursor=%p)", static_cast<void *>(cursor));
230   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
231   return co->step();
232 }
233 
234 
235 /// Get unwind info at cursor position in stack frame.
236 _LIBUNWIND_EXPORT int unw_get_proc_info(unw_cursor_t *cursor,
237                                         unw_proc_info_t *info) {
238   _LIBUNWIND_TRACE_API("unw_get_proc_info(cursor=%p, &info=%p)",
239                        static_cast<void *>(cursor), static_cast<void *>(info));
240   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
241   co->getInfo(info);
242   if (info->end_ip == 0)
243     return UNW_ENOINFO;
244   else
245     return UNW_ESUCCESS;
246 }
247 
248 
249 /// Resume execution at cursor position (aka longjump).
250 _LIBUNWIND_EXPORT int unw_resume(unw_cursor_t *cursor) {
251   _LIBUNWIND_TRACE_API("unw_resume(cursor=%p)", static_cast<void *>(cursor));
252   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
253   co->jumpto();
254   return UNW_EUNSPEC;
255 }
256 
257 
258 /// Get name of function at cursor position in stack frame.
259 _LIBUNWIND_EXPORT int unw_get_proc_name(unw_cursor_t *cursor, char *buf,
260                                         size_t bufLen, unw_word_t *offset) {
261   _LIBUNWIND_TRACE_API("unw_get_proc_name(cursor=%p, &buf=%p, bufLen=%lu)",
262                        static_cast<void *>(cursor), static_cast<void *>(buf),
263                        static_cast<unsigned long>(bufLen));
264   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
265   if (co->getFunctionName(buf, bufLen, offset))
266     return UNW_ESUCCESS;
267   else
268     return UNW_EUNSPEC;
269 }
270 
271 
272 /// Checks if a register is a floating-point register.
273 _LIBUNWIND_EXPORT int unw_is_fpreg(unw_cursor_t *cursor, unw_regnum_t regNum) {
274   _LIBUNWIND_TRACE_API("unw_is_fpreg(cursor=%p, regNum=%d)",
275                        static_cast<void *>(cursor), regNum);
276   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
277   return co->validFloatReg(regNum);
278 }
279 
280 
281 /// Checks if a register is a floating-point register.
282 _LIBUNWIND_EXPORT const char *unw_regname(unw_cursor_t *cursor,
283                                           unw_regnum_t regNum) {
284   _LIBUNWIND_TRACE_API("unw_regname(cursor=%p, regNum=%d)",
285                        static_cast<void *>(cursor), regNum);
286   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
287   return co->getRegisterName(regNum);
288 }
289 
290 
291 /// Checks if current frame is signal trampoline.
292 _LIBUNWIND_EXPORT int unw_is_signal_frame(unw_cursor_t *cursor) {
293   _LIBUNWIND_TRACE_API("unw_is_signal_frame(cursor=%p)",
294                        static_cast<void *>(cursor));
295   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
296   return co->isSignalFrame();
297 }
298 
299 #ifdef __arm__
300 // Save VFP registers d0-d15 using FSTMIADX instead of FSTMIADD
301 _LIBUNWIND_EXPORT void unw_save_vfp_as_X(unw_cursor_t *cursor) {
302   _LIBUNWIND_TRACE_API("unw_fpreg_save_vfp_as_X(cursor=%p)",
303                        static_cast<void *>(cursor));
304   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
305   return co->saveVFPAsX();
306 }
307 #endif
308 
309 
310 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
311 /// SPI: walks cached DWARF entries
312 _LIBUNWIND_EXPORT void unw_iterate_dwarf_unwind_cache(void (*func)(
313     unw_word_t ip_start, unw_word_t ip_end, unw_word_t fde, unw_word_t mh)) {
314   _LIBUNWIND_TRACE_API("unw_iterate_dwarf_unwind_cache(func=%p)",
315                        reinterpret_cast<void *>(func));
316   DwarfFDECache<LocalAddressSpace>::iterateCacheEntries(func);
317 }
318 
319 
320 /// IPI: for __register_frame()
321 void _unw_add_dynamic_fde(unw_word_t fde) {
322   CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;
323   CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;
324   const char *message = CFI_Parser<LocalAddressSpace>::decodeFDE(
325                            LocalAddressSpace::sThisAddressSpace,
326                           (LocalAddressSpace::pint_t) fde, &fdeInfo, &cieInfo);
327   if (message == NULL) {
328     // dynamically registered FDEs don't have a mach_header group they are in.
329     // Use fde as mh_group
330     unw_word_t mh_group = fdeInfo.fdeStart;
331     DwarfFDECache<LocalAddressSpace>::add((LocalAddressSpace::pint_t)mh_group,
332                                           fdeInfo.pcStart, fdeInfo.pcEnd,
333                                           fdeInfo.fdeStart);
334   } else {
335     _LIBUNWIND_DEBUG_LOG("_unw_add_dynamic_fde: bad fde: %s", message);
336   }
337 }
338 
339 /// IPI: for __deregister_frame()
340 void _unw_remove_dynamic_fde(unw_word_t fde) {
341   // fde is own mh_group
342   DwarfFDECache<LocalAddressSpace>::removeAllIn((LocalAddressSpace::pint_t)fde);
343 }
344 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
345 #endif // !defined(__USING_SJLJ_EXCEPTIONS__)
346 
347 
348 
349 // Add logging hooks in Debug builds only
350 #ifndef NDEBUG
351 #include <stdlib.h>
352 
353 _LIBUNWIND_HIDDEN
354 bool logAPIs() {
355   // do manual lock to avoid use of _cxa_guard_acquire or initializers
356   static bool checked = false;
357   static bool log = false;
358   if (!checked) {
359     log = (getenv("LIBUNWIND_PRINT_APIS") != NULL);
360     checked = true;
361   }
362   return log;
363 }
364 
365 _LIBUNWIND_HIDDEN
366 bool logUnwinding() {
367   // do manual lock to avoid use of _cxa_guard_acquire or initializers
368   static bool checked = false;
369   static bool log = false;
370   if (!checked) {
371     log = (getenv("LIBUNWIND_PRINT_UNWINDING") != NULL);
372     checked = true;
373   }
374   return log;
375 }
376 
377 _LIBUNWIND_HIDDEN
378 bool logDWARF() {
379   // do manual lock to avoid use of _cxa_guard_acquire or initializers
380   static bool checked = false;
381   static bool log = false;
382   if (!checked) {
383     log = (getenv("LIBUNWIND_PRINT_DWARF") != NULL);
384     checked = true;
385   }
386   return log;
387 }
388 
389 #endif // NDEBUG
390 
391