1 //===------------------------- UnwindCursor.hpp ---------------------------===//
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 // C++ interface to lower levels of libuwind
10 //===----------------------------------------------------------------------===//
11 
12 #ifndef __UNWINDCURSOR_HPP__
13 #define __UNWINDCURSOR_HPP__
14 
15 #include <algorithm>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <pthread.h>
20 #include <unwind.h>
21 
22 #ifdef __APPLE__
23   #include <mach-o/dyld.h>
24 #endif
25 
26 #include "config.h"
27 
28 #include "AddressSpace.hpp"
29 #include "CompactUnwinder.hpp"
30 #include "config.h"
31 #include "DwarfInstructions.hpp"
32 #include "EHHeaderParser.hpp"
33 #include "libunwind.h"
34 #include "Registers.hpp"
35 #include "Unwind-EHABI.h"
36 
37 namespace libunwind {
38 
39 #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
40 /// Cache of recently found FDEs.
41 template <typename A>
42 class _LIBUNWIND_HIDDEN DwarfFDECache {
43   typedef typename A::pint_t pint_t;
44 public:
45   static pint_t findFDE(pint_t mh, pint_t pc);
46   static void add(pint_t mh, pint_t ip_start, pint_t ip_end, pint_t fde);
47   static void removeAllIn(pint_t mh);
48   static void iterateCacheEntries(void (*func)(unw_word_t ip_start,
49                                                unw_word_t ip_end,
50                                                unw_word_t fde, unw_word_t mh));
51 
52 private:
53 
54   struct entry {
55     pint_t mh;
56     pint_t ip_start;
57     pint_t ip_end;
58     pint_t fde;
59   };
60 
61   // These fields are all static to avoid needing an initializer.
62   // There is only one instance of this class per process.
63   static pthread_rwlock_t _lock;
64 #ifdef __APPLE__
65   static void dyldUnloadHook(const struct mach_header *mh, intptr_t slide);
66   static bool _registeredForDyldUnloads;
67 #endif
68   // Can't use std::vector<> here because this code is below libc++.
69   static entry *_buffer;
70   static entry *_bufferUsed;
71   static entry *_bufferEnd;
72   static entry _initialBuffer[64];
73 };
74 
75 template <typename A>
76 typename DwarfFDECache<A>::entry *
77 DwarfFDECache<A>::_buffer = _initialBuffer;
78 
79 template <typename A>
80 typename DwarfFDECache<A>::entry *
81 DwarfFDECache<A>::_bufferUsed = _initialBuffer;
82 
83 template <typename A>
84 typename DwarfFDECache<A>::entry *
85 DwarfFDECache<A>::_bufferEnd = &_initialBuffer[64];
86 
87 template <typename A>
88 typename DwarfFDECache<A>::entry DwarfFDECache<A>::_initialBuffer[64];
89 
90 template <typename A>
91 pthread_rwlock_t DwarfFDECache<A>::_lock = PTHREAD_RWLOCK_INITIALIZER;
92 
93 #ifdef __APPLE__
94 template <typename A>
95 bool DwarfFDECache<A>::_registeredForDyldUnloads = false;
96 #endif
97 
98 template <typename A>
99 typename A::pint_t DwarfFDECache<A>::findFDE(pint_t mh, pint_t pc) {
100   pint_t result = 0;
101   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_rdlock(&_lock));
102   for (entry *p = _buffer; p < _bufferUsed; ++p) {
103     if ((mh == p->mh) || (mh == 0)) {
104       if ((p->ip_start <= pc) && (pc < p->ip_end)) {
105         result = p->fde;
106         break;
107       }
108     }
109   }
110   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_unlock(&_lock));
111   return result;
112 }
113 
114 template <typename A>
115 void DwarfFDECache<A>::add(pint_t mh, pint_t ip_start, pint_t ip_end,
116                            pint_t fde) {
117 #if !defined(_LIBUNWIND_NO_HEAP)
118   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_wrlock(&_lock));
119   if (_bufferUsed >= _bufferEnd) {
120     size_t oldSize = (size_t)(_bufferEnd - _buffer);
121     size_t newSize = oldSize * 4;
122     // Can't use operator new (we are below it).
123     entry *newBuffer = (entry *)malloc(newSize * sizeof(entry));
124     memcpy(newBuffer, _buffer, oldSize * sizeof(entry));
125     if (_buffer != _initialBuffer)
126       free(_buffer);
127     _buffer = newBuffer;
128     _bufferUsed = &newBuffer[oldSize];
129     _bufferEnd = &newBuffer[newSize];
130   }
131   _bufferUsed->mh = mh;
132   _bufferUsed->ip_start = ip_start;
133   _bufferUsed->ip_end = ip_end;
134   _bufferUsed->fde = fde;
135   ++_bufferUsed;
136 #ifdef __APPLE__
137   if (!_registeredForDyldUnloads) {
138     _dyld_register_func_for_remove_image(&dyldUnloadHook);
139     _registeredForDyldUnloads = true;
140   }
141 #endif
142   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_unlock(&_lock));
143 #endif
144 }
145 
146 template <typename A>
147 void DwarfFDECache<A>::removeAllIn(pint_t mh) {
148   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_wrlock(&_lock));
149   entry *d = _buffer;
150   for (const entry *s = _buffer; s < _bufferUsed; ++s) {
151     if (s->mh != mh) {
152       if (d != s)
153         *d = *s;
154       ++d;
155     }
156   }
157   _bufferUsed = d;
158   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_unlock(&_lock));
159 }
160 
161 #ifdef __APPLE__
162 template <typename A>
163 void DwarfFDECache<A>::dyldUnloadHook(const struct mach_header *mh, intptr_t ) {
164   removeAllIn((pint_t) mh);
165 }
166 #endif
167 
168 template <typename A>
169 void DwarfFDECache<A>::iterateCacheEntries(void (*func)(
170     unw_word_t ip_start, unw_word_t ip_end, unw_word_t fde, unw_word_t mh)) {
171   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_wrlock(&_lock));
172   for (entry *p = _buffer; p < _bufferUsed; ++p) {
173     (*func)(p->ip_start, p->ip_end, p->fde, p->mh);
174   }
175   _LIBUNWIND_LOG_NON_ZERO(::pthread_rwlock_unlock(&_lock));
176 }
177 #endif // _LIBUNWIND_SUPPORT_DWARF_UNWIND
178 
179 
180 #define arrayoffsetof(type, index, field) ((size_t)(&((type *)0)[index].field))
181 
182 #if _LIBUNWIND_SUPPORT_COMPACT_UNWIND
183 template <typename A> class UnwindSectionHeader {
184 public:
185   UnwindSectionHeader(A &addressSpace, typename A::pint_t addr)
186       : _addressSpace(addressSpace), _addr(addr) {}
187 
188   uint32_t version() const {
189     return _addressSpace.get32(_addr +
190                                offsetof(unwind_info_section_header, version));
191   }
192   uint32_t commonEncodingsArraySectionOffset() const {
193     return _addressSpace.get32(_addr +
194                                offsetof(unwind_info_section_header,
195                                         commonEncodingsArraySectionOffset));
196   }
197   uint32_t commonEncodingsArrayCount() const {
198     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
199                                                 commonEncodingsArrayCount));
200   }
201   uint32_t personalityArraySectionOffset() const {
202     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
203                                                 personalityArraySectionOffset));
204   }
205   uint32_t personalityArrayCount() const {
206     return _addressSpace.get32(
207         _addr + offsetof(unwind_info_section_header, personalityArrayCount));
208   }
209   uint32_t indexSectionOffset() const {
210     return _addressSpace.get32(
211         _addr + offsetof(unwind_info_section_header, indexSectionOffset));
212   }
213   uint32_t indexCount() const {
214     return _addressSpace.get32(
215         _addr + offsetof(unwind_info_section_header, indexCount));
216   }
217 
218 private:
219   A                     &_addressSpace;
220   typename A::pint_t     _addr;
221 };
222 
223 template <typename A> class UnwindSectionIndexArray {
224 public:
225   UnwindSectionIndexArray(A &addressSpace, typename A::pint_t addr)
226       : _addressSpace(addressSpace), _addr(addr) {}
227 
228   uint32_t functionOffset(uint32_t index) const {
229     return _addressSpace.get32(
230         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
231                               functionOffset));
232   }
233   uint32_t secondLevelPagesSectionOffset(uint32_t index) const {
234     return _addressSpace.get32(
235         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
236                               secondLevelPagesSectionOffset));
237   }
238   uint32_t lsdaIndexArraySectionOffset(uint32_t index) const {
239     return _addressSpace.get32(
240         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
241                               lsdaIndexArraySectionOffset));
242   }
243 
244 private:
245   A                   &_addressSpace;
246   typename A::pint_t   _addr;
247 };
248 
249 template <typename A> class UnwindSectionRegularPageHeader {
250 public:
251   UnwindSectionRegularPageHeader(A &addressSpace, typename A::pint_t addr)
252       : _addressSpace(addressSpace), _addr(addr) {}
253 
254   uint32_t kind() const {
255     return _addressSpace.get32(
256         _addr + offsetof(unwind_info_regular_second_level_page_header, kind));
257   }
258   uint16_t entryPageOffset() const {
259     return _addressSpace.get16(
260         _addr + offsetof(unwind_info_regular_second_level_page_header,
261                          entryPageOffset));
262   }
263   uint16_t entryCount() const {
264     return _addressSpace.get16(
265         _addr +
266         offsetof(unwind_info_regular_second_level_page_header, entryCount));
267   }
268 
269 private:
270   A &_addressSpace;
271   typename A::pint_t _addr;
272 };
273 
274 template <typename A> class UnwindSectionRegularArray {
275 public:
276   UnwindSectionRegularArray(A &addressSpace, typename A::pint_t addr)
277       : _addressSpace(addressSpace), _addr(addr) {}
278 
279   uint32_t functionOffset(uint32_t index) const {
280     return _addressSpace.get32(
281         _addr + arrayoffsetof(unwind_info_regular_second_level_entry, index,
282                               functionOffset));
283   }
284   uint32_t encoding(uint32_t index) const {
285     return _addressSpace.get32(
286         _addr +
287         arrayoffsetof(unwind_info_regular_second_level_entry, index, encoding));
288   }
289 
290 private:
291   A &_addressSpace;
292   typename A::pint_t _addr;
293 };
294 
295 template <typename A> class UnwindSectionCompressedPageHeader {
296 public:
297   UnwindSectionCompressedPageHeader(A &addressSpace, typename A::pint_t addr)
298       : _addressSpace(addressSpace), _addr(addr) {}
299 
300   uint32_t kind() const {
301     return _addressSpace.get32(
302         _addr +
303         offsetof(unwind_info_compressed_second_level_page_header, kind));
304   }
305   uint16_t entryPageOffset() const {
306     return _addressSpace.get16(
307         _addr + offsetof(unwind_info_compressed_second_level_page_header,
308                          entryPageOffset));
309   }
310   uint16_t entryCount() const {
311     return _addressSpace.get16(
312         _addr +
313         offsetof(unwind_info_compressed_second_level_page_header, entryCount));
314   }
315   uint16_t encodingsPageOffset() const {
316     return _addressSpace.get16(
317         _addr + offsetof(unwind_info_compressed_second_level_page_header,
318                          encodingsPageOffset));
319   }
320   uint16_t encodingsCount() const {
321     return _addressSpace.get16(
322         _addr + offsetof(unwind_info_compressed_second_level_page_header,
323                          encodingsCount));
324   }
325 
326 private:
327   A &_addressSpace;
328   typename A::pint_t _addr;
329 };
330 
331 template <typename A> class UnwindSectionCompressedArray {
332 public:
333   UnwindSectionCompressedArray(A &addressSpace, typename A::pint_t addr)
334       : _addressSpace(addressSpace), _addr(addr) {}
335 
336   uint32_t functionOffset(uint32_t index) const {
337     return UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(
338         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
339   }
340   uint16_t encodingIndex(uint32_t index) const {
341     return UNWIND_INFO_COMPRESSED_ENTRY_ENCODING_INDEX(
342         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
343   }
344 
345 private:
346   A &_addressSpace;
347   typename A::pint_t _addr;
348 };
349 
350 template <typename A> class UnwindSectionLsdaArray {
351 public:
352   UnwindSectionLsdaArray(A &addressSpace, typename A::pint_t addr)
353       : _addressSpace(addressSpace), _addr(addr) {}
354 
355   uint32_t functionOffset(uint32_t index) const {
356     return _addressSpace.get32(
357         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
358                               index, functionOffset));
359   }
360   uint32_t lsdaOffset(uint32_t index) const {
361     return _addressSpace.get32(
362         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
363                               index, lsdaOffset));
364   }
365 
366 private:
367   A                   &_addressSpace;
368   typename A::pint_t   _addr;
369 };
370 #endif // _LIBUNWIND_SUPPORT_COMPACT_UNWIND
371 
372 class _LIBUNWIND_HIDDEN AbstractUnwindCursor {
373 public:
374   // NOTE: provide a class specific placement deallocation function (S5.3.4 p20)
375   // This avoids an unnecessary dependency to libc++abi.
376   void operator delete(void *, size_t) {}
377 
378   virtual ~AbstractUnwindCursor() {}
379   virtual bool validReg(int) { _LIBUNWIND_ABORT("validReg not implemented"); }
380   virtual unw_word_t getReg(int) { _LIBUNWIND_ABORT("getReg not implemented"); }
381   virtual void setReg(int, unw_word_t) {
382     _LIBUNWIND_ABORT("setReg not implemented");
383   }
384   virtual bool validFloatReg(int) {
385     _LIBUNWIND_ABORT("validFloatReg not implemented");
386   }
387   virtual unw_fpreg_t getFloatReg(int) {
388     _LIBUNWIND_ABORT("getFloatReg not implemented");
389   }
390   virtual void setFloatReg(int, unw_fpreg_t) {
391     _LIBUNWIND_ABORT("setFloatReg not implemented");
392   }
393   virtual int step() { _LIBUNWIND_ABORT("step not implemented"); }
394   virtual void getInfo(unw_proc_info_t *) {
395     _LIBUNWIND_ABORT("getInfo not implemented");
396   }
397   virtual void jumpto() { _LIBUNWIND_ABORT("jumpto not implemented"); }
398   virtual bool isSignalFrame() {
399     _LIBUNWIND_ABORT("isSignalFrame not implemented");
400   }
401   virtual bool getFunctionName(char *, size_t, unw_word_t *) {
402     _LIBUNWIND_ABORT("getFunctionName not implemented");
403   }
404   virtual void setInfoBasedOnIPRegister(bool = false) {
405     _LIBUNWIND_ABORT("setInfoBasedOnIPRegister not implemented");
406   }
407   virtual const char *getRegisterName(int) {
408     _LIBUNWIND_ABORT("getRegisterName not implemented");
409   }
410 #ifdef __arm__
411   virtual void saveVFPAsX() { _LIBUNWIND_ABORT("saveVFPAsX not implemented"); }
412 #endif
413 };
414 
415 /// UnwindCursor contains all state (including all register values) during
416 /// an unwind.  This is normally stack allocated inside a unw_cursor_t.
417 template <typename A, typename R>
418 class UnwindCursor : public AbstractUnwindCursor{
419   typedef typename A::pint_t pint_t;
420 public:
421                       UnwindCursor(unw_context_t *context, A &as);
422                       UnwindCursor(A &as, void *threadArg);
423   virtual             ~UnwindCursor() {}
424   virtual bool        validReg(int);
425   virtual unw_word_t  getReg(int);
426   virtual void        setReg(int, unw_word_t);
427   virtual bool        validFloatReg(int);
428   virtual unw_fpreg_t getFloatReg(int);
429   virtual void        setFloatReg(int, unw_fpreg_t);
430   virtual int         step();
431   virtual void        getInfo(unw_proc_info_t *);
432   virtual void        jumpto();
433   virtual bool        isSignalFrame();
434   virtual bool        getFunctionName(char *buf, size_t len, unw_word_t *off);
435   virtual void        setInfoBasedOnIPRegister(bool isReturnAddress = false);
436   virtual const char *getRegisterName(int num);
437 #ifdef __arm__
438   virtual void        saveVFPAsX();
439 #endif
440 
441 private:
442 
443 #if _LIBUNWIND_ARM_EHABI
444   bool getInfoFromEHABISection(pint_t pc, const UnwindInfoSections &sects);
445 
446   int stepWithEHABI() {
447     size_t len = 0;
448     size_t off = 0;
449     // FIXME: Calling decode_eht_entry() here is violating the libunwind
450     // abstraction layer.
451     const uint32_t *ehtp =
452         decode_eht_entry(reinterpret_cast<const uint32_t *>(_info.unwind_info),
453                          &off, &len);
454     if (_Unwind_VRS_Interpret((_Unwind_Context *)this, ehtp, off, len) !=
455             _URC_CONTINUE_UNWIND)
456       return UNW_STEP_END;
457     return UNW_STEP_SUCCESS;
458   }
459 #endif
460 
461 #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
462   bool getInfoFromDwarfSection(pint_t pc, const UnwindInfoSections &sects,
463                                             uint32_t fdeSectionOffsetHint=0);
464   int stepWithDwarfFDE() {
465     return DwarfInstructions<A, R>::stepWithDwarf(_addressSpace,
466                                               (pint_t)this->getReg(UNW_REG_IP),
467                                               (pint_t)_info.unwind_info,
468                                               _registers);
469   }
470 #endif
471 
472 #if _LIBUNWIND_SUPPORT_COMPACT_UNWIND
473   bool getInfoFromCompactEncodingSection(pint_t pc,
474                                             const UnwindInfoSections &sects);
475   int stepWithCompactEncoding() {
476   #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
477     if ( compactSaysUseDwarf() )
478       return stepWithDwarfFDE();
479   #endif
480     R dummy;
481     return stepWithCompactEncoding(dummy);
482   }
483 
484   int stepWithCompactEncoding(Registers_x86_64 &) {
485     return CompactUnwinder_x86_64<A>::stepWithCompactEncoding(
486         _info.format, _info.start_ip, _addressSpace, _registers);
487   }
488 
489   int stepWithCompactEncoding(Registers_x86 &) {
490     return CompactUnwinder_x86<A>::stepWithCompactEncoding(
491         _info.format, (uint32_t)_info.start_ip, _addressSpace, _registers);
492   }
493 
494   int stepWithCompactEncoding(Registers_ppc &) {
495     return UNW_EINVAL;
496   }
497 
498   int stepWithCompactEncoding(Registers_arm64 &) {
499     return CompactUnwinder_arm64<A>::stepWithCompactEncoding(
500         _info.format, _info.start_ip, _addressSpace, _registers);
501   }
502 
503   bool compactSaysUseDwarf(uint32_t *offset=NULL) const {
504     R dummy;
505     return compactSaysUseDwarf(dummy, offset);
506   }
507 
508   bool compactSaysUseDwarf(Registers_x86_64 &, uint32_t *offset) const {
509     if ((_info.format & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF) {
510       if (offset)
511         *offset = (_info.format & UNWIND_X86_64_DWARF_SECTION_OFFSET);
512       return true;
513     }
514     return false;
515   }
516 
517   bool compactSaysUseDwarf(Registers_x86 &, uint32_t *offset) const {
518     if ((_info.format & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF) {
519       if (offset)
520         *offset = (_info.format & UNWIND_X86_DWARF_SECTION_OFFSET);
521       return true;
522     }
523     return false;
524   }
525 
526   bool compactSaysUseDwarf(Registers_ppc &, uint32_t *) const {
527     return true;
528   }
529 
530   bool compactSaysUseDwarf(Registers_arm64 &, uint32_t *offset) const {
531     if ((_info.format & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF) {
532       if (offset)
533         *offset = (_info.format & UNWIND_ARM64_DWARF_SECTION_OFFSET);
534       return true;
535     }
536     return false;
537   }
538 #endif // _LIBUNWIND_SUPPORT_COMPACT_UNWIND
539 
540 #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
541   compact_unwind_encoding_t dwarfEncoding() const {
542     R dummy;
543     return dwarfEncoding(dummy);
544   }
545 
546   compact_unwind_encoding_t dwarfEncoding(Registers_x86_64 &) const {
547     return UNWIND_X86_64_MODE_DWARF;
548   }
549 
550   compact_unwind_encoding_t dwarfEncoding(Registers_x86 &) const {
551     return UNWIND_X86_MODE_DWARF;
552   }
553 
554   compact_unwind_encoding_t dwarfEncoding(Registers_ppc &) const {
555     return 0;
556   }
557 
558   compact_unwind_encoding_t dwarfEncoding(Registers_arm64 &) const {
559     return UNWIND_ARM64_MODE_DWARF;
560   }
561 
562   compact_unwind_encoding_t dwarfEncoding(Registers_or1k &) const {
563     return 0;
564   }
565 #endif // _LIBUNWIND_SUPPORT_DWARF_UNWIND
566 
567 
568   A               &_addressSpace;
569   R                _registers;
570   unw_proc_info_t  _info;
571   bool             _unwindInfoMissing;
572   bool             _isSignalFrame;
573 };
574 
575 
576 template <typename A, typename R>
577 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
578     : _addressSpace(as), _registers(context), _unwindInfoMissing(false),
579       _isSignalFrame(false) {
580   static_assert(sizeof(UnwindCursor<A, R>) < sizeof(unw_cursor_t),
581                 "UnwindCursor<> does not fit in unw_cursor_t");
582   memset(&_info, 0, sizeof(_info));
583 }
584 
585 template <typename A, typename R>
586 UnwindCursor<A, R>::UnwindCursor(A &as, void *)
587     : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) {
588   memset(&_info, 0, sizeof(_info));
589   // FIXME
590   // fill in _registers from thread arg
591 }
592 
593 
594 template <typename A, typename R>
595 bool UnwindCursor<A, R>::validReg(int regNum) {
596   return _registers.validRegister(regNum);
597 }
598 
599 template <typename A, typename R>
600 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
601   return _registers.getRegister(regNum);
602 }
603 
604 template <typename A, typename R>
605 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
606   _registers.setRegister(regNum, (typename A::pint_t)value);
607 }
608 
609 template <typename A, typename R>
610 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
611   return _registers.validFloatRegister(regNum);
612 }
613 
614 template <typename A, typename R>
615 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
616   return _registers.getFloatRegister(regNum);
617 }
618 
619 template <typename A, typename R>
620 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
621   _registers.setFloatRegister(regNum, value);
622 }
623 
624 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
625   _registers.jumpto();
626 }
627 
628 #ifdef __arm__
629 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {
630   _registers.saveVFPAsX();
631 }
632 #endif
633 
634 template <typename A, typename R>
635 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
636   return _registers.getRegisterName(regNum);
637 }
638 
639 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
640   return _isSignalFrame;
641 }
642 
643 #if _LIBUNWIND_ARM_EHABI
644 struct EHABIIndexEntry {
645   uint32_t functionOffset;
646   uint32_t data;
647 };
648 
649 template<typename A>
650 struct EHABISectionIterator {
651   typedef EHABISectionIterator _Self;
652 
653   typedef std::random_access_iterator_tag iterator_category;
654   typedef typename A::pint_t value_type;
655   typedef typename A::pint_t* pointer;
656   typedef typename A::pint_t& reference;
657   typedef size_t size_type;
658   typedef size_t difference_type;
659 
660   static _Self begin(A& addressSpace, const UnwindInfoSections& sects) {
661     return _Self(addressSpace, sects, 0);
662   }
663   static _Self end(A& addressSpace, const UnwindInfoSections& sects) {
664     return _Self(addressSpace, sects, sects.arm_section_length);
665   }
666 
667   EHABISectionIterator(A& addressSpace, const UnwindInfoSections& sects, size_t i)
668       : _i(i), _addressSpace(&addressSpace), _sects(&sects) {}
669 
670   _Self& operator++() { ++_i; return *this; }
671   _Self& operator+=(size_t a) { _i += a; return *this; }
672   _Self& operator--() { assert(_i > 0); --_i; return *this; }
673   _Self& operator-=(size_t a) { assert(_i >= a); _i -= a; return *this; }
674 
675   _Self operator+(size_t a) { _Self out = *this; out._i += a; return out; }
676   _Self operator-(size_t a) { assert(_i >= a); _Self out = *this; out._i -= a; return out; }
677 
678   size_t operator-(const _Self& other) { return _i - other._i; }
679 
680   bool operator==(const _Self& other) const {
681     assert(_addressSpace == other._addressSpace);
682     assert(_sects == other._sects);
683     return _i == other._i;
684   }
685 
686   typename A::pint_t operator*() const { return functionAddress(); }
687 
688   typename A::pint_t functionAddress() const {
689     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
690         EHABIIndexEntry, _i, functionOffset);
691     return indexAddr + signExtendPrel31(_addressSpace->get32(indexAddr));
692   }
693 
694   typename A::pint_t dataAddress() {
695     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
696         EHABIIndexEntry, _i, data);
697     return indexAddr;
698   }
699 
700  private:
701   size_t _i;
702   A* _addressSpace;
703   const UnwindInfoSections* _sects;
704 };
705 
706 template <typename A, typename R>
707 bool UnwindCursor<A, R>::getInfoFromEHABISection(
708     pint_t pc,
709     const UnwindInfoSections &sects) {
710   EHABISectionIterator<A> begin =
711       EHABISectionIterator<A>::begin(_addressSpace, sects);
712   EHABISectionIterator<A> end =
713       EHABISectionIterator<A>::end(_addressSpace, sects);
714 
715   EHABISectionIterator<A> itNextPC = std::upper_bound(begin, end, pc);
716   if (itNextPC == begin || itNextPC == end)
717     return false;
718   EHABISectionIterator<A> itThisPC = itNextPC - 1;
719 
720   pint_t thisPC = itThisPC.functionAddress();
721   pint_t nextPC = itNextPC.functionAddress();
722   pint_t indexDataAddr = itThisPC.dataAddress();
723 
724   if (indexDataAddr == 0)
725     return false;
726 
727   uint32_t indexData = _addressSpace.get32(indexDataAddr);
728   if (indexData == UNW_EXIDX_CANTUNWIND)
729     return false;
730 
731   // If the high bit is set, the exception handling table entry is inline inside
732   // the index table entry on the second word (aka |indexDataAddr|). Otherwise,
733   // the table points at an offset in the exception handling table (section 5 EHABI).
734   pint_t exceptionTableAddr;
735   uint32_t exceptionTableData;
736   bool isSingleWordEHT;
737   if (indexData & 0x80000000) {
738     exceptionTableAddr = indexDataAddr;
739     // TODO(ajwong): Should this data be 0?
740     exceptionTableData = indexData;
741     isSingleWordEHT = true;
742   } else {
743     exceptionTableAddr = indexDataAddr + signExtendPrel31(indexData);
744     exceptionTableData = _addressSpace.get32(exceptionTableAddr);
745     isSingleWordEHT = false;
746   }
747 
748   // Now we know the 3 things:
749   //   exceptionTableAddr -- exception handler table entry.
750   //   exceptionTableData -- the data inside the first word of the eht entry.
751   //   isSingleWordEHT -- whether the entry is in the index.
752   unw_word_t personalityRoutine = 0xbadf00d;
753   bool scope32 = false;
754   uintptr_t lsda;
755 
756   // If the high bit in the exception handling table entry is set, the entry is
757   // in compact form (section 6.3 EHABI).
758   if (exceptionTableData & 0x80000000) {
759     // Grab the index of the personality routine from the compact form.
760     uint32_t choice = (exceptionTableData & 0x0f000000) >> 24;
761     uint32_t extraWords = 0;
762     switch (choice) {
763       case 0:
764         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr0;
765         extraWords = 0;
766         scope32 = false;
767         lsda = isSingleWordEHT ? 0 : (exceptionTableAddr + 4);
768         break;
769       case 1:
770         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr1;
771         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
772         scope32 = false;
773         lsda = exceptionTableAddr + (extraWords + 1) * 4;
774         break;
775       case 2:
776         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr2;
777         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
778         scope32 = true;
779         lsda = exceptionTableAddr + (extraWords + 1) * 4;
780         break;
781       default:
782         _LIBUNWIND_ABORT("unknown personality routine");
783         return false;
784     }
785 
786     if (isSingleWordEHT) {
787       if (extraWords != 0) {
788         _LIBUNWIND_ABORT("index inlined table detected but pr function "
789                          "requires extra words");
790         return false;
791       }
792     }
793   } else {
794     pint_t personalityAddr =
795         exceptionTableAddr + signExtendPrel31(exceptionTableData);
796     personalityRoutine = personalityAddr;
797 
798     // ARM EHABI # 6.2, # 9.2
799     //
800     //  +---- ehtp
801     //  v
802     // +--------------------------------------+
803     // | +--------+--------+--------+-------+ |
804     // | |0| prel31 to personalityRoutine   | |
805     // | +--------+--------+--------+-------+ |
806     // | |      N |      unwind opcodes     | |  <-- UnwindData
807     // | +--------+--------+--------+-------+ |
808     // | | Word 2        unwind opcodes     | |
809     // | +--------+--------+--------+-------+ |
810     // | ...                                  |
811     // | +--------+--------+--------+-------+ |
812     // | | Word N        unwind opcodes     | |
813     // | +--------+--------+--------+-------+ |
814     // | | LSDA                             | |  <-- lsda
815     // | | ...                              | |
816     // | +--------+--------+--------+-------+ |
817     // +--------------------------------------+
818 
819     uint32_t *UnwindData = reinterpret_cast<uint32_t*>(exceptionTableAddr) + 1;
820     uint32_t FirstDataWord = *UnwindData;
821     size_t N = ((FirstDataWord >> 24) & 0xff);
822     size_t NDataWords = N + 1;
823     lsda = reinterpret_cast<uintptr_t>(UnwindData + NDataWords);
824   }
825 
826   _info.start_ip = thisPC;
827   _info.end_ip = nextPC;
828   _info.handler = personalityRoutine;
829   _info.unwind_info = exceptionTableAddr;
830   _info.lsda = lsda;
831   // flags is pr_cache.additional. See EHABI #7.2 for definition of bit 0.
832   _info.flags = isSingleWordEHT ? 1 : 0 | scope32 ? 0x2 : 0;  // Use enum?
833 
834   return true;
835 }
836 #endif
837 
838 #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
839 template <typename A, typename R>
840 bool UnwindCursor<A, R>::getInfoFromDwarfSection(pint_t pc,
841                                                 const UnwindInfoSections &sects,
842                                                 uint32_t fdeSectionOffsetHint) {
843   typename CFI_Parser<A>::FDE_Info fdeInfo;
844   typename CFI_Parser<A>::CIE_Info cieInfo;
845   bool foundFDE = false;
846   bool foundInCache = false;
847   // If compact encoding table gave offset into dwarf section, go directly there
848   if (fdeSectionOffsetHint != 0) {
849     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
850                                     (uint32_t)sects.dwarf_section_length,
851                                     sects.dwarf_section + fdeSectionOffsetHint,
852                                     &fdeInfo, &cieInfo);
853   }
854 #if _LIBUNWIND_SUPPORT_DWARF_INDEX
855   if (!foundFDE && (sects.dwarf_index_section != 0)) {
856     foundFDE = EHHeaderParser<A>::findFDE(
857         _addressSpace, pc, sects.dwarf_index_section,
858         (uint32_t)sects.dwarf_index_section_length, &fdeInfo, &cieInfo);
859   }
860 #endif
861   if (!foundFDE) {
862     // otherwise, search cache of previously found FDEs.
863     pint_t cachedFDE = DwarfFDECache<A>::findFDE(sects.dso_base, pc);
864     if (cachedFDE != 0) {
865       foundFDE =
866           CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
867                                  (uint32_t)sects.dwarf_section_length,
868                                  cachedFDE, &fdeInfo, &cieInfo);
869       foundInCache = foundFDE;
870     }
871   }
872   if (!foundFDE) {
873     // Still not found, do full scan of __eh_frame section.
874     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
875                                       (uint32_t)sects.dwarf_section_length, 0,
876                                       &fdeInfo, &cieInfo);
877   }
878   if (foundFDE) {
879     typename CFI_Parser<A>::PrologInfo prolog;
880     if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo, pc,
881                                             &prolog)) {
882       // Save off parsed FDE info
883       _info.start_ip          = fdeInfo.pcStart;
884       _info.end_ip            = fdeInfo.pcEnd;
885       _info.lsda              = fdeInfo.lsda;
886       _info.handler           = cieInfo.personality;
887       _info.gp                = prolog.spExtraArgSize;
888       _info.flags             = 0;
889       _info.format            = dwarfEncoding();
890       _info.unwind_info       = fdeInfo.fdeStart;
891       _info.unwind_info_size  = (uint32_t)fdeInfo.fdeLength;
892       _info.extra             = (unw_word_t) sects.dso_base;
893 
894       // Add to cache (to make next lookup faster) if we had no hint
895       // and there was no index.
896       if (!foundInCache && (fdeSectionOffsetHint == 0)) {
897   #if _LIBUNWIND_SUPPORT_DWARF_INDEX
898         if (sects.dwarf_index_section == 0)
899   #endif
900         DwarfFDECache<A>::add(sects.dso_base, fdeInfo.pcStart, fdeInfo.pcEnd,
901                               fdeInfo.fdeStart);
902       }
903       return true;
904     }
905   }
906   //_LIBUNWIND_DEBUG_LOG("can't find/use FDE for pc=0x%llX\n", (uint64_t)pc);
907   return false;
908 }
909 #endif // _LIBUNWIND_SUPPORT_DWARF_UNWIND
910 
911 
912 #if _LIBUNWIND_SUPPORT_COMPACT_UNWIND
913 template <typename A, typename R>
914 bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
915                                               const UnwindInfoSections &sects) {
916   const bool log = false;
917   if (log)
918     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX, mh=0x%llX)\n",
919             (uint64_t)pc, (uint64_t)sects.dso_base);
920 
921   const UnwindSectionHeader<A> sectionHeader(_addressSpace,
922                                                 sects.compact_unwind_section);
923   if (sectionHeader.version() != UNWIND_SECTION_VERSION)
924     return false;
925 
926   // do a binary search of top level index to find page with unwind info
927   pint_t targetFunctionOffset = pc - sects.dso_base;
928   const UnwindSectionIndexArray<A> topIndex(_addressSpace,
929                                            sects.compact_unwind_section
930                                          + sectionHeader.indexSectionOffset());
931   uint32_t low = 0;
932   uint32_t high = sectionHeader.indexCount();
933   uint32_t last = high - 1;
934   while (low < high) {
935     uint32_t mid = (low + high) / 2;
936     //if ( log ) fprintf(stderr, "\tmid=%d, low=%d, high=%d, *mid=0x%08X\n",
937     //mid, low, high, topIndex.functionOffset(mid));
938     if (topIndex.functionOffset(mid) <= targetFunctionOffset) {
939       if ((mid == last) ||
940           (topIndex.functionOffset(mid + 1) > targetFunctionOffset)) {
941         low = mid;
942         break;
943       } else {
944         low = mid + 1;
945       }
946     } else {
947       high = mid;
948     }
949   }
950   const uint32_t firstLevelFunctionOffset = topIndex.functionOffset(low);
951   const uint32_t firstLevelNextPageFunctionOffset =
952       topIndex.functionOffset(low + 1);
953   const pint_t secondLevelAddr =
954       sects.compact_unwind_section + topIndex.secondLevelPagesSectionOffset(low);
955   const pint_t lsdaArrayStartAddr =
956       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low);
957   const pint_t lsdaArrayEndAddr =
958       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low+1);
959   if (log)
960     fprintf(stderr, "\tfirst level search for result index=%d "
961                     "to secondLevelAddr=0x%llX\n",
962                     low, (uint64_t) secondLevelAddr);
963   // do a binary search of second level page index
964   uint32_t encoding = 0;
965   pint_t funcStart = 0;
966   pint_t funcEnd = 0;
967   pint_t lsda = 0;
968   pint_t personality = 0;
969   uint32_t pageKind = _addressSpace.get32(secondLevelAddr);
970   if (pageKind == UNWIND_SECOND_LEVEL_REGULAR) {
971     // regular page
972     UnwindSectionRegularPageHeader<A> pageHeader(_addressSpace,
973                                                  secondLevelAddr);
974     UnwindSectionRegularArray<A> pageIndex(
975         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
976     // binary search looks for entry with e where index[e].offset <= pc <
977     // index[e+1].offset
978     if (log)
979       fprintf(stderr, "\tbinary search for targetFunctionOffset=0x%08llX in "
980                       "regular page starting at secondLevelAddr=0x%llX\n",
981               (uint64_t) targetFunctionOffset, (uint64_t) secondLevelAddr);
982     low = 0;
983     high = pageHeader.entryCount();
984     while (low < high) {
985       uint32_t mid = (low + high) / 2;
986       if (pageIndex.functionOffset(mid) <= targetFunctionOffset) {
987         if (mid == (uint32_t)(pageHeader.entryCount() - 1)) {
988           // at end of table
989           low = mid;
990           funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
991           break;
992         } else if (pageIndex.functionOffset(mid + 1) > targetFunctionOffset) {
993           // next is too big, so we found it
994           low = mid;
995           funcEnd = pageIndex.functionOffset(low + 1) + sects.dso_base;
996           break;
997         } else {
998           low = mid + 1;
999         }
1000       } else {
1001         high = mid;
1002       }
1003     }
1004     encoding = pageIndex.encoding(low);
1005     funcStart = pageIndex.functionOffset(low) + sects.dso_base;
1006     if (pc < funcStart) {
1007       if (log)
1008         fprintf(
1009             stderr,
1010             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1011             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1012       return false;
1013     }
1014     if (pc > funcEnd) {
1015       if (log)
1016         fprintf(
1017             stderr,
1018             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1019             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1020       return false;
1021     }
1022   } else if (pageKind == UNWIND_SECOND_LEVEL_COMPRESSED) {
1023     // compressed page
1024     UnwindSectionCompressedPageHeader<A> pageHeader(_addressSpace,
1025                                                     secondLevelAddr);
1026     UnwindSectionCompressedArray<A> pageIndex(
1027         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1028     const uint32_t targetFunctionPageOffset =
1029         (uint32_t)(targetFunctionOffset - firstLevelFunctionOffset);
1030     // binary search looks for entry with e where index[e].offset <= pc <
1031     // index[e+1].offset
1032     if (log)
1033       fprintf(stderr, "\tbinary search of compressed page starting at "
1034                       "secondLevelAddr=0x%llX\n",
1035               (uint64_t) secondLevelAddr);
1036     low = 0;
1037     last = pageHeader.entryCount() - 1;
1038     high = pageHeader.entryCount();
1039     while (low < high) {
1040       uint32_t mid = (low + high) / 2;
1041       if (pageIndex.functionOffset(mid) <= targetFunctionPageOffset) {
1042         if ((mid == last) ||
1043             (pageIndex.functionOffset(mid + 1) > targetFunctionPageOffset)) {
1044           low = mid;
1045           break;
1046         } else {
1047           low = mid + 1;
1048         }
1049       } else {
1050         high = mid;
1051       }
1052     }
1053     funcStart = pageIndex.functionOffset(low) + firstLevelFunctionOffset
1054                                                               + sects.dso_base;
1055     if (low < last)
1056       funcEnd =
1057           pageIndex.functionOffset(low + 1) + firstLevelFunctionOffset
1058                                                               + sects.dso_base;
1059     else
1060       funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1061     if (pc < funcStart) {
1062       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
1063                            "level compressed unwind table. funcStart=0x%llX\n",
1064                             (uint64_t) pc, (uint64_t) funcStart);
1065       return false;
1066     }
1067     if (pc > funcEnd) {
1068       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
1069                           "level compressed unwind table. funcEnd=0x%llX\n",
1070                            (uint64_t) pc, (uint64_t) funcEnd);
1071       return false;
1072     }
1073     uint16_t encodingIndex = pageIndex.encodingIndex(low);
1074     if (encodingIndex < sectionHeader.commonEncodingsArrayCount()) {
1075       // encoding is in common table in section header
1076       encoding = _addressSpace.get32(
1077           sects.compact_unwind_section +
1078           sectionHeader.commonEncodingsArraySectionOffset() +
1079           encodingIndex * sizeof(uint32_t));
1080     } else {
1081       // encoding is in page specific table
1082       uint16_t pageEncodingIndex =
1083           encodingIndex - (uint16_t)sectionHeader.commonEncodingsArrayCount();
1084       encoding = _addressSpace.get32(secondLevelAddr +
1085                                      pageHeader.encodingsPageOffset() +
1086                                      pageEncodingIndex * sizeof(uint32_t));
1087     }
1088   } else {
1089     _LIBUNWIND_DEBUG_LOG("malformed __unwind_info at 0x%0llX bad second "
1090                          "level page\n",
1091                           (uint64_t) sects.compact_unwind_section);
1092     return false;
1093   }
1094 
1095   // look up LSDA, if encoding says function has one
1096   if (encoding & UNWIND_HAS_LSDA) {
1097     UnwindSectionLsdaArray<A> lsdaIndex(_addressSpace, lsdaArrayStartAddr);
1098     uint32_t funcStartOffset = (uint32_t)(funcStart - sects.dso_base);
1099     low = 0;
1100     high = (uint32_t)(lsdaArrayEndAddr - lsdaArrayStartAddr) /
1101                     sizeof(unwind_info_section_header_lsda_index_entry);
1102     // binary search looks for entry with exact match for functionOffset
1103     if (log)
1104       fprintf(stderr,
1105               "\tbinary search of lsda table for targetFunctionOffset=0x%08X\n",
1106               funcStartOffset);
1107     while (low < high) {
1108       uint32_t mid = (low + high) / 2;
1109       if (lsdaIndex.functionOffset(mid) == funcStartOffset) {
1110         lsda = lsdaIndex.lsdaOffset(mid) + sects.dso_base;
1111         break;
1112       } else if (lsdaIndex.functionOffset(mid) < funcStartOffset) {
1113         low = mid + 1;
1114       } else {
1115         high = mid;
1116       }
1117     }
1118     if (lsda == 0) {
1119       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with HAS_LSDA bit set for "
1120                     "pc=0x%0llX, but lsda table has no entry\n",
1121                     encoding, (uint64_t) pc);
1122       return false;
1123     }
1124   }
1125 
1126   // extact personality routine, if encoding says function has one
1127   uint32_t personalityIndex = (encoding & UNWIND_PERSONALITY_MASK) >>
1128                               (__builtin_ctz(UNWIND_PERSONALITY_MASK));
1129   if (personalityIndex != 0) {
1130     --personalityIndex; // change 1-based to zero-based index
1131     if (personalityIndex > sectionHeader.personalityArrayCount()) {
1132       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with personality index %d,  "
1133                             "but personality table has only %d entires\n",
1134                             encoding, personalityIndex,
1135                             sectionHeader.personalityArrayCount());
1136       return false;
1137     }
1138     int32_t personalityDelta = (int32_t)_addressSpace.get32(
1139         sects.compact_unwind_section +
1140         sectionHeader.personalityArraySectionOffset() +
1141         personalityIndex * sizeof(uint32_t));
1142     pint_t personalityPointer = sects.dso_base + (pint_t)personalityDelta;
1143     personality = _addressSpace.getP(personalityPointer);
1144     if (log)
1145       fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1146                       "personalityDelta=0x%08X, personality=0x%08llX\n",
1147               (uint64_t) pc, personalityDelta, (uint64_t) personality);
1148   }
1149 
1150   if (log)
1151     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1152                     "encoding=0x%08X, lsda=0x%08llX for funcStart=0x%llX\n",
1153             (uint64_t) pc, encoding, (uint64_t) lsda, (uint64_t) funcStart);
1154   _info.start_ip = funcStart;
1155   _info.end_ip = funcEnd;
1156   _info.lsda = lsda;
1157   _info.handler = personality;
1158   _info.gp = 0;
1159   _info.flags = 0;
1160   _info.format = encoding;
1161   _info.unwind_info = 0;
1162   _info.unwind_info_size = 0;
1163   _info.extra = sects.dso_base;
1164   return true;
1165 }
1166 #endif // _LIBUNWIND_SUPPORT_COMPACT_UNWIND
1167 
1168 
1169 template <typename A, typename R>
1170 void UnwindCursor<A, R>::setInfoBasedOnIPRegister(bool isReturnAddress) {
1171   pint_t pc = (pint_t)this->getReg(UNW_REG_IP);
1172 #if _LIBUNWIND_ARM_EHABI
1173   // Remove the thumb bit so the IP represents the actual instruction address.
1174   // This matches the behaviour of _Unwind_GetIP on arm.
1175   pc &= (pint_t)~0x1;
1176 #endif
1177 
1178   // If the last line of a function is a "throw" the compiler sometimes
1179   // emits no instructions after the call to __cxa_throw.  This means
1180   // the return address is actually the start of the next function.
1181   // To disambiguate this, back up the pc when we know it is a return
1182   // address.
1183   if (isReturnAddress)
1184     --pc;
1185 
1186   // Ask address space object to find unwind sections for this pc.
1187   UnwindInfoSections sects;
1188   if (_addressSpace.findUnwindSections(pc, sects)) {
1189 #if _LIBUNWIND_SUPPORT_COMPACT_UNWIND
1190     // If there is a compact unwind encoding table, look there first.
1191     if (sects.compact_unwind_section != 0) {
1192       if (this->getInfoFromCompactEncodingSection(pc, sects)) {
1193   #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
1194         // Found info in table, done unless encoding says to use dwarf.
1195         uint32_t dwarfOffset;
1196         if ((sects.dwarf_section != 0) && compactSaysUseDwarf(&dwarfOffset)) {
1197           if (this->getInfoFromDwarfSection(pc, sects, dwarfOffset)) {
1198             // found info in dwarf, done
1199             return;
1200           }
1201         }
1202   #endif
1203         // If unwind table has entry, but entry says there is no unwind info,
1204         // record that we have no unwind info.
1205         if (_info.format == 0)
1206           _unwindInfoMissing = true;
1207         return;
1208       }
1209     }
1210 #endif // _LIBUNWIND_SUPPORT_COMPACT_UNWIND
1211 
1212 #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
1213     // If there is dwarf unwind info, look there next.
1214     if (sects.dwarf_section != 0) {
1215       if (this->getInfoFromDwarfSection(pc, sects)) {
1216         // found info in dwarf, done
1217         return;
1218       }
1219     }
1220 #endif
1221 
1222 #if _LIBUNWIND_ARM_EHABI
1223     // If there is ARM EHABI unwind info, look there next.
1224     if (sects.arm_section != 0 && this->getInfoFromEHABISection(pc, sects))
1225       return;
1226 #endif
1227   }
1228 
1229 #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
1230   // There is no static unwind info for this pc. Look to see if an FDE was
1231   // dynamically registered for it.
1232   pint_t cachedFDE = DwarfFDECache<A>::findFDE(0, pc);
1233   if (cachedFDE != 0) {
1234     CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;
1235     CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;
1236     const char *msg = CFI_Parser<A>::decodeFDE(_addressSpace,
1237                                                 cachedFDE, &fdeInfo, &cieInfo);
1238     if (msg == NULL) {
1239       typename CFI_Parser<A>::PrologInfo prolog;
1240       if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo,
1241                                                                 pc, &prolog)) {
1242         // save off parsed FDE info
1243         _info.start_ip         = fdeInfo.pcStart;
1244         _info.end_ip           = fdeInfo.pcEnd;
1245         _info.lsda             = fdeInfo.lsda;
1246         _info.handler          = cieInfo.personality;
1247         _info.gp               = prolog.spExtraArgSize;
1248                                   // Some frameless functions need SP
1249                                   // altered when resuming in function.
1250         _info.flags            = 0;
1251         _info.format           = dwarfEncoding();
1252         _info.unwind_info      = fdeInfo.fdeStart;
1253         _info.unwind_info_size = (uint32_t)fdeInfo.fdeLength;
1254         _info.extra            = 0;
1255         return;
1256       }
1257     }
1258   }
1259 
1260   // Lastly, ask AddressSpace object about platform specific ways to locate
1261   // other FDEs.
1262   pint_t fde;
1263   if (_addressSpace.findOtherFDE(pc, fde)) {
1264     CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;
1265     CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;
1266     if (!CFI_Parser<A>::decodeFDE(_addressSpace, fde, &fdeInfo, &cieInfo)) {
1267       // Double check this FDE is for a function that includes the pc.
1268       if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd)) {
1269         typename CFI_Parser<A>::PrologInfo prolog;
1270         if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo,
1271                                                 cieInfo, pc, &prolog)) {
1272           // save off parsed FDE info
1273           _info.start_ip         = fdeInfo.pcStart;
1274           _info.end_ip           = fdeInfo.pcEnd;
1275           _info.lsda             = fdeInfo.lsda;
1276           _info.handler          = cieInfo.personality;
1277           _info.gp               = prolog.spExtraArgSize;
1278           _info.flags            = 0;
1279           _info.format           = dwarfEncoding();
1280           _info.unwind_info      = fdeInfo.fdeStart;
1281           _info.unwind_info_size = (uint32_t)fdeInfo.fdeLength;
1282           _info.extra            = 0;
1283           return;
1284         }
1285       }
1286     }
1287   }
1288 #endif // #if _LIBUNWIND_SUPPORT_DWARF_UNWIND
1289 
1290   // no unwind info, flag that we can't reliably unwind
1291   _unwindInfoMissing = true;
1292 }
1293 
1294 template <typename A, typename R>
1295 int UnwindCursor<A, R>::step() {
1296   // Bottom of stack is defined is when unwind info cannot be found.
1297   if (_unwindInfoMissing)
1298     return UNW_STEP_END;
1299 
1300   // Use unwinding info to modify register set as if function returned.
1301   int result;
1302 #if _LIBUNWIND_SUPPORT_COMPACT_UNWIND
1303   result = this->stepWithCompactEncoding();
1304 #elif _LIBUNWIND_SUPPORT_DWARF_UNWIND
1305   result = this->stepWithDwarfFDE();
1306 #elif _LIBUNWIND_ARM_EHABI
1307   result = this->stepWithEHABI();
1308 #else
1309   #error Need _LIBUNWIND_SUPPORT_COMPACT_UNWIND or \
1310               _LIBUNWIND_SUPPORT_DWARF_UNWIND or \
1311               _LIBUNWIND_ARM_EHABI
1312 #endif
1313 
1314   // update info based on new PC
1315   if (result == UNW_STEP_SUCCESS) {
1316     this->setInfoBasedOnIPRegister(true);
1317     if (_unwindInfoMissing)
1318       return UNW_STEP_END;
1319     if (_info.gp)
1320       setReg(UNW_REG_SP, getReg(UNW_REG_SP) + _info.gp);
1321   }
1322 
1323   return result;
1324 }
1325 
1326 template <typename A, typename R>
1327 void UnwindCursor<A, R>::getInfo(unw_proc_info_t *info) {
1328   *info = _info;
1329 }
1330 
1331 template <typename A, typename R>
1332 bool UnwindCursor<A, R>::getFunctionName(char *buf, size_t bufLen,
1333                                                            unw_word_t *offset) {
1334   return _addressSpace.findFunctionName((pint_t)this->getReg(UNW_REG_IP),
1335                                          buf, bufLen, offset);
1336 }
1337 
1338 } // namespace libunwind
1339 
1340 #endif // __UNWINDCURSOR_HPP__
1341