xref: /openbsd-src/gnu/llvm/libunwind/src/UnwindCursor.hpp (revision f1dd7b858388b4a23f4f67a4957ec5ff656ebbe8)
1 //===------------------------- UnwindCursor.hpp ---------------------------===//
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 // C++ interface to lower levels of libunwind
9 //===----------------------------------------------------------------------===//
10 
11 #ifndef __UNWINDCURSOR_HPP__
12 #define __UNWINDCURSOR_HPP__
13 
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <unwind.h>
18 
19 #ifdef _WIN32
20   #include <windows.h>
21   #include <ntverp.h>
22 #endif
23 #ifdef __APPLE__
24   #include <mach-o/dyld.h>
25 #endif
26 
27 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
28 // Provide a definition for the DISPATCHER_CONTEXT struct for old (Win7 and
29 // earlier) SDKs.
30 // MinGW-w64 has always provided this struct.
31   #if defined(_WIN32) && defined(_LIBUNWIND_TARGET_X86_64) && \
32       !defined(__MINGW32__) && VER_PRODUCTBUILD < 8000
33 struct _DISPATCHER_CONTEXT {
34   ULONG64 ControlPc;
35   ULONG64 ImageBase;
36   PRUNTIME_FUNCTION FunctionEntry;
37   ULONG64 EstablisherFrame;
38   ULONG64 TargetIp;
39   PCONTEXT ContextRecord;
40   PEXCEPTION_ROUTINE LanguageHandler;
41   PVOID HandlerData;
42   PUNWIND_HISTORY_TABLE HistoryTable;
43   ULONG ScopeIndex;
44   ULONG Fill0;
45 };
46   #endif
47 
48 struct UNWIND_INFO {
49   uint8_t Version : 3;
50   uint8_t Flags : 5;
51   uint8_t SizeOfProlog;
52   uint8_t CountOfCodes;
53   uint8_t FrameRegister : 4;
54   uint8_t FrameOffset : 4;
55   uint16_t UnwindCodes[2];
56 };
57 
58 extern "C" _Unwind_Reason_Code __libunwind_seh_personality(
59     int, _Unwind_Action, uint64_t, _Unwind_Exception *,
60     struct _Unwind_Context *);
61 
62 #endif
63 
64 #include "config.h"
65 
66 #include "AddressSpace.hpp"
67 #include "CompactUnwinder.hpp"
68 #include "config.h"
69 #include "DwarfInstructions.hpp"
70 #include "EHHeaderParser.hpp"
71 #include "libunwind.h"
72 #include "Registers.hpp"
73 #include "RWMutex.hpp"
74 #include "Unwind-EHABI.h"
75 
76 namespace libunwind {
77 
78 static thread_local UnwindInfoSectionsCache uwis_cache;
79 
80 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
81 /// Cache of recently found FDEs.
82 template <typename A>
83 class _LIBUNWIND_HIDDEN DwarfFDECache {
84   typedef typename A::pint_t pint_t;
85 public:
86   static pint_t findFDE(pint_t mh, pint_t pc);
87   static void add(pint_t mh, pint_t ip_start, pint_t ip_end, pint_t fde);
88   static void removeAllIn(pint_t mh);
89   static void iterateCacheEntries(void (*func)(unw_word_t ip_start,
90                                                unw_word_t ip_end,
91                                                unw_word_t fde, unw_word_t mh));
92 
93 private:
94 
95   struct entry {
96     pint_t mh;
97     pint_t ip_start;
98     pint_t ip_end;
99     pint_t fde;
100   };
101 
102   // These fields are all static to avoid needing an initializer.
103   // There is only one instance of this class per process.
104   static RWMutex _lock;
105 #ifdef __APPLE__
106   static void dyldUnloadHook(const struct mach_header *mh, intptr_t slide);
107   static bool _registeredForDyldUnloads;
108 #endif
109   static entry *_buffer;
110   static entry *_bufferUsed;
111   static entry *_bufferEnd;
112   static entry _initialBuffer[64];
113 };
114 
115 template <typename A>
116 typename DwarfFDECache<A>::entry *
117 DwarfFDECache<A>::_buffer = _initialBuffer;
118 
119 template <typename A>
120 typename DwarfFDECache<A>::entry *
121 DwarfFDECache<A>::_bufferUsed = _initialBuffer;
122 
123 template <typename A>
124 typename DwarfFDECache<A>::entry *
125 DwarfFDECache<A>::_bufferEnd = &_initialBuffer[64];
126 
127 template <typename A>
128 typename DwarfFDECache<A>::entry DwarfFDECache<A>::_initialBuffer[64];
129 
130 template <typename A>
131 RWMutex DwarfFDECache<A>::_lock;
132 
133 #ifdef __APPLE__
134 template <typename A>
135 bool DwarfFDECache<A>::_registeredForDyldUnloads = false;
136 #endif
137 
138 template <typename A>
139 typename A::pint_t DwarfFDECache<A>::findFDE(pint_t mh, pint_t pc) {
140   pint_t result = 0;
141   _LIBUNWIND_LOG_IF_FALSE(_lock.lock_shared());
142   for (entry *p = _buffer; p < _bufferUsed; ++p) {
143     if ((mh == p->mh) || (mh == 0)) {
144       if ((p->ip_start <= pc) && (pc < p->ip_end)) {
145         result = p->fde;
146         break;
147       }
148     }
149   }
150   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock_shared());
151   return result;
152 }
153 
154 template <typename A>
155 void DwarfFDECache<A>::add(pint_t mh, pint_t ip_start, pint_t ip_end,
156                            pint_t fde) {
157 #if !defined(_LIBUNWIND_NO_HEAP)
158   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
159   if (_bufferUsed >= _bufferEnd) {
160     size_t oldSize = (size_t)(_bufferEnd - _buffer);
161     size_t newSize = oldSize * 4;
162     // Can't use operator new (we are below it).
163     entry *newBuffer = (entry *)malloc(newSize * sizeof(entry));
164     memcpy(newBuffer, _buffer, oldSize * sizeof(entry));
165     if (_buffer != _initialBuffer)
166       free(_buffer);
167     _buffer = newBuffer;
168     _bufferUsed = &newBuffer[oldSize];
169     _bufferEnd = &newBuffer[newSize];
170   }
171   _bufferUsed->mh = mh;
172   _bufferUsed->ip_start = ip_start;
173   _bufferUsed->ip_end = ip_end;
174   _bufferUsed->fde = fde;
175   ++_bufferUsed;
176 #ifdef __APPLE__
177   if (!_registeredForDyldUnloads) {
178     _dyld_register_func_for_remove_image(&dyldUnloadHook);
179     _registeredForDyldUnloads = true;
180   }
181 #endif
182   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
183 #endif
184 }
185 
186 template <typename A>
187 void DwarfFDECache<A>::removeAllIn(pint_t mh) {
188   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
189   entry *d = _buffer;
190   for (const entry *s = _buffer; s < _bufferUsed; ++s) {
191     if (s->mh != mh) {
192       if (d != s)
193         *d = *s;
194       ++d;
195     }
196   }
197   _bufferUsed = d;
198   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
199 }
200 
201 #ifdef __APPLE__
202 template <typename A>
203 void DwarfFDECache<A>::dyldUnloadHook(const struct mach_header *mh, intptr_t ) {
204   removeAllIn((pint_t) mh);
205 }
206 #endif
207 
208 template <typename A>
209 void DwarfFDECache<A>::iterateCacheEntries(void (*func)(
210     unw_word_t ip_start, unw_word_t ip_end, unw_word_t fde, unw_word_t mh)) {
211   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
212   for (entry *p = _buffer; p < _bufferUsed; ++p) {
213     (*func)(p->ip_start, p->ip_end, p->fde, p->mh);
214   }
215   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
216 }
217 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
218 
219 
220 #define arrayoffsetof(type, index, field) ((size_t)(&((type *)0)[index].field))
221 
222 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
223 template <typename A> class UnwindSectionHeader {
224 public:
225   UnwindSectionHeader(A &addressSpace, typename A::pint_t addr)
226       : _addressSpace(addressSpace), _addr(addr) {}
227 
228   uint32_t version() const {
229     return _addressSpace.get32(_addr +
230                                offsetof(unwind_info_section_header, version));
231   }
232   uint32_t commonEncodingsArraySectionOffset() const {
233     return _addressSpace.get32(_addr +
234                                offsetof(unwind_info_section_header,
235                                         commonEncodingsArraySectionOffset));
236   }
237   uint32_t commonEncodingsArrayCount() const {
238     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
239                                                 commonEncodingsArrayCount));
240   }
241   uint32_t personalityArraySectionOffset() const {
242     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
243                                                 personalityArraySectionOffset));
244   }
245   uint32_t personalityArrayCount() const {
246     return _addressSpace.get32(
247         _addr + offsetof(unwind_info_section_header, personalityArrayCount));
248   }
249   uint32_t indexSectionOffset() const {
250     return _addressSpace.get32(
251         _addr + offsetof(unwind_info_section_header, indexSectionOffset));
252   }
253   uint32_t indexCount() const {
254     return _addressSpace.get32(
255         _addr + offsetof(unwind_info_section_header, indexCount));
256   }
257 
258 private:
259   A                     &_addressSpace;
260   typename A::pint_t     _addr;
261 };
262 
263 template <typename A> class UnwindSectionIndexArray {
264 public:
265   UnwindSectionIndexArray(A &addressSpace, typename A::pint_t addr)
266       : _addressSpace(addressSpace), _addr(addr) {}
267 
268   uint32_t functionOffset(uint32_t index) const {
269     return _addressSpace.get32(
270         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
271                               functionOffset));
272   }
273   uint32_t secondLevelPagesSectionOffset(uint32_t index) const {
274     return _addressSpace.get32(
275         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
276                               secondLevelPagesSectionOffset));
277   }
278   uint32_t lsdaIndexArraySectionOffset(uint32_t index) const {
279     return _addressSpace.get32(
280         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
281                               lsdaIndexArraySectionOffset));
282   }
283 
284 private:
285   A                   &_addressSpace;
286   typename A::pint_t   _addr;
287 };
288 
289 template <typename A> class UnwindSectionRegularPageHeader {
290 public:
291   UnwindSectionRegularPageHeader(A &addressSpace, typename A::pint_t addr)
292       : _addressSpace(addressSpace), _addr(addr) {}
293 
294   uint32_t kind() const {
295     return _addressSpace.get32(
296         _addr + offsetof(unwind_info_regular_second_level_page_header, kind));
297   }
298   uint16_t entryPageOffset() const {
299     return _addressSpace.get16(
300         _addr + offsetof(unwind_info_regular_second_level_page_header,
301                          entryPageOffset));
302   }
303   uint16_t entryCount() const {
304     return _addressSpace.get16(
305         _addr +
306         offsetof(unwind_info_regular_second_level_page_header, entryCount));
307   }
308 
309 private:
310   A &_addressSpace;
311   typename A::pint_t _addr;
312 };
313 
314 template <typename A> class UnwindSectionRegularArray {
315 public:
316   UnwindSectionRegularArray(A &addressSpace, typename A::pint_t addr)
317       : _addressSpace(addressSpace), _addr(addr) {}
318 
319   uint32_t functionOffset(uint32_t index) const {
320     return _addressSpace.get32(
321         _addr + arrayoffsetof(unwind_info_regular_second_level_entry, index,
322                               functionOffset));
323   }
324   uint32_t encoding(uint32_t index) const {
325     return _addressSpace.get32(
326         _addr +
327         arrayoffsetof(unwind_info_regular_second_level_entry, index, encoding));
328   }
329 
330 private:
331   A &_addressSpace;
332   typename A::pint_t _addr;
333 };
334 
335 template <typename A> class UnwindSectionCompressedPageHeader {
336 public:
337   UnwindSectionCompressedPageHeader(A &addressSpace, typename A::pint_t addr)
338       : _addressSpace(addressSpace), _addr(addr) {}
339 
340   uint32_t kind() const {
341     return _addressSpace.get32(
342         _addr +
343         offsetof(unwind_info_compressed_second_level_page_header, kind));
344   }
345   uint16_t entryPageOffset() const {
346     return _addressSpace.get16(
347         _addr + offsetof(unwind_info_compressed_second_level_page_header,
348                          entryPageOffset));
349   }
350   uint16_t entryCount() const {
351     return _addressSpace.get16(
352         _addr +
353         offsetof(unwind_info_compressed_second_level_page_header, entryCount));
354   }
355   uint16_t encodingsPageOffset() const {
356     return _addressSpace.get16(
357         _addr + offsetof(unwind_info_compressed_second_level_page_header,
358                          encodingsPageOffset));
359   }
360   uint16_t encodingsCount() const {
361     return _addressSpace.get16(
362         _addr + offsetof(unwind_info_compressed_second_level_page_header,
363                          encodingsCount));
364   }
365 
366 private:
367   A &_addressSpace;
368   typename A::pint_t _addr;
369 };
370 
371 template <typename A> class UnwindSectionCompressedArray {
372 public:
373   UnwindSectionCompressedArray(A &addressSpace, typename A::pint_t addr)
374       : _addressSpace(addressSpace), _addr(addr) {}
375 
376   uint32_t functionOffset(uint32_t index) const {
377     return UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(
378         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
379   }
380   uint16_t encodingIndex(uint32_t index) const {
381     return UNWIND_INFO_COMPRESSED_ENTRY_ENCODING_INDEX(
382         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
383   }
384 
385 private:
386   A &_addressSpace;
387   typename A::pint_t _addr;
388 };
389 
390 template <typename A> class UnwindSectionLsdaArray {
391 public:
392   UnwindSectionLsdaArray(A &addressSpace, typename A::pint_t addr)
393       : _addressSpace(addressSpace), _addr(addr) {}
394 
395   uint32_t functionOffset(uint32_t index) const {
396     return _addressSpace.get32(
397         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
398                               index, functionOffset));
399   }
400   uint32_t lsdaOffset(uint32_t index) const {
401     return _addressSpace.get32(
402         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
403                               index, lsdaOffset));
404   }
405 
406 private:
407   A                   &_addressSpace;
408   typename A::pint_t   _addr;
409 };
410 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
411 
412 class _LIBUNWIND_HIDDEN AbstractUnwindCursor {
413 public:
414   // NOTE: provide a class specific placement deallocation function (S5.3.4 p20)
415   // This avoids an unnecessary dependency to libc++abi.
416   void operator delete(void *, size_t) {}
417 
418   virtual ~AbstractUnwindCursor() {}
419   virtual bool validReg(int) { _LIBUNWIND_ABORT("validReg not implemented"); }
420   virtual unw_word_t getReg(int) { _LIBUNWIND_ABORT("getReg not implemented"); }
421   virtual void setReg(int, unw_word_t) {
422     _LIBUNWIND_ABORT("setReg not implemented");
423   }
424   virtual bool validFloatReg(int) {
425     _LIBUNWIND_ABORT("validFloatReg not implemented");
426   }
427   virtual unw_fpreg_t getFloatReg(int) {
428     _LIBUNWIND_ABORT("getFloatReg not implemented");
429   }
430   virtual void setFloatReg(int, unw_fpreg_t) {
431     _LIBUNWIND_ABORT("setFloatReg not implemented");
432   }
433   virtual int step() { _LIBUNWIND_ABORT("step not implemented"); }
434   virtual void getInfo(unw_proc_info_t *) {
435     _LIBUNWIND_ABORT("getInfo not implemented");
436   }
437   virtual void jumpto() { _LIBUNWIND_ABORT("jumpto not implemented"); }
438   virtual bool isSignalFrame() {
439     _LIBUNWIND_ABORT("isSignalFrame not implemented");
440   }
441   virtual bool getFunctionName(char *, size_t, unw_word_t *) {
442     _LIBUNWIND_ABORT("getFunctionName not implemented");
443   }
444   virtual void setInfoBasedOnIPRegister(bool = false) {
445     _LIBUNWIND_ABORT("setInfoBasedOnIPRegister not implemented");
446   }
447   virtual const char *getRegisterName(int) {
448     _LIBUNWIND_ABORT("getRegisterName not implemented");
449   }
450 #ifdef __arm__
451   virtual void saveVFPAsX() { _LIBUNWIND_ABORT("saveVFPAsX not implemented"); }
452 #endif
453 };
454 
455 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) && defined(_WIN32)
456 
457 /// \c UnwindCursor contains all state (including all register values) during
458 /// an unwind.  This is normally stack-allocated inside a unw_cursor_t.
459 template <typename A, typename R>
460 class UnwindCursor : public AbstractUnwindCursor {
461   typedef typename A::pint_t pint_t;
462 public:
463                       UnwindCursor(unw_context_t *context, A &as);
464                       UnwindCursor(CONTEXT *context, A &as);
465                       UnwindCursor(A &as, void *threadArg);
466   virtual             ~UnwindCursor() {}
467   virtual bool        validReg(int);
468   virtual unw_word_t  getReg(int);
469   virtual void        setReg(int, unw_word_t);
470   virtual bool        validFloatReg(int);
471   virtual unw_fpreg_t getFloatReg(int);
472   virtual void        setFloatReg(int, unw_fpreg_t);
473   virtual int         step();
474   virtual void        getInfo(unw_proc_info_t *);
475   virtual void        jumpto();
476   virtual bool        isSignalFrame();
477   virtual bool        getFunctionName(char *buf, size_t len, unw_word_t *off);
478   virtual void        setInfoBasedOnIPRegister(bool isReturnAddress = false);
479   virtual const char *getRegisterName(int num);
480 #ifdef __arm__
481   virtual void        saveVFPAsX();
482 #endif
483 
484   DISPATCHER_CONTEXT *getDispatcherContext() { return &_dispContext; }
485   void setDispatcherContext(DISPATCHER_CONTEXT *disp) { _dispContext = *disp; }
486 
487   // libunwind does not and should not depend on C++ library which means that we
488   // need our own defition of inline placement new.
489   static void *operator new(size_t, UnwindCursor<A, R> *p) { return p; }
490 
491 private:
492 
493   pint_t getLastPC() const { return _dispContext.ControlPc; }
494   void setLastPC(pint_t pc) { _dispContext.ControlPc = pc; }
495   RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
496     _dispContext.FunctionEntry = RtlLookupFunctionEntry(pc,
497                                                         &_dispContext.ImageBase,
498                                                         _dispContext.HistoryTable);
499     *base = _dispContext.ImageBase;
500     return _dispContext.FunctionEntry;
501   }
502   bool getInfoFromSEH(pint_t pc);
503   int stepWithSEHData() {
504     _dispContext.LanguageHandler = RtlVirtualUnwind(UNW_FLAG_UHANDLER,
505                                                     _dispContext.ImageBase,
506                                                     _dispContext.ControlPc,
507                                                     _dispContext.FunctionEntry,
508                                                     _dispContext.ContextRecord,
509                                                     &_dispContext.HandlerData,
510                                                     &_dispContext.EstablisherFrame,
511                                                     NULL);
512     // Update some fields of the unwind info now, since we have them.
513     _info.lsda = reinterpret_cast<unw_word_t>(_dispContext.HandlerData);
514     if (_dispContext.LanguageHandler) {
515       _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
516     } else
517       _info.handler = 0;
518     return UNW_STEP_SUCCESS;
519   }
520 
521   A                   &_addressSpace;
522   unw_proc_info_t      _info;
523   DISPATCHER_CONTEXT   _dispContext;
524   CONTEXT              _msContext;
525   UNWIND_HISTORY_TABLE _histTable;
526   bool                 _unwindInfoMissing;
527 };
528 
529 
530 template <typename A, typename R>
531 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
532     : _addressSpace(as), _unwindInfoMissing(false) {
533   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
534                 "UnwindCursor<> does not fit in unw_cursor_t");
535   memset(&_info, 0, sizeof(_info));
536   memset(&_histTable, 0, sizeof(_histTable));
537   _dispContext.ContextRecord = &_msContext;
538   _dispContext.HistoryTable = &_histTable;
539   // Initialize MS context from ours.
540   R r(context);
541   _msContext.ContextFlags = CONTEXT_CONTROL|CONTEXT_INTEGER|CONTEXT_FLOATING_POINT;
542 #if defined(_LIBUNWIND_TARGET_X86_64)
543   _msContext.Rax = r.getRegister(UNW_X86_64_RAX);
544   _msContext.Rcx = r.getRegister(UNW_X86_64_RCX);
545   _msContext.Rdx = r.getRegister(UNW_X86_64_RDX);
546   _msContext.Rbx = r.getRegister(UNW_X86_64_RBX);
547   _msContext.Rsp = r.getRegister(UNW_X86_64_RSP);
548   _msContext.Rbp = r.getRegister(UNW_X86_64_RBP);
549   _msContext.Rsi = r.getRegister(UNW_X86_64_RSI);
550   _msContext.Rdi = r.getRegister(UNW_X86_64_RDI);
551   _msContext.R8 = r.getRegister(UNW_X86_64_R8);
552   _msContext.R9 = r.getRegister(UNW_X86_64_R9);
553   _msContext.R10 = r.getRegister(UNW_X86_64_R10);
554   _msContext.R11 = r.getRegister(UNW_X86_64_R11);
555   _msContext.R12 = r.getRegister(UNW_X86_64_R12);
556   _msContext.R13 = r.getRegister(UNW_X86_64_R13);
557   _msContext.R14 = r.getRegister(UNW_X86_64_R14);
558   _msContext.R15 = r.getRegister(UNW_X86_64_R15);
559   _msContext.Rip = r.getRegister(UNW_REG_IP);
560   union {
561     v128 v;
562     M128A m;
563   } t;
564   t.v = r.getVectorRegister(UNW_X86_64_XMM0);
565   _msContext.Xmm0 = t.m;
566   t.v = r.getVectorRegister(UNW_X86_64_XMM1);
567   _msContext.Xmm1 = t.m;
568   t.v = r.getVectorRegister(UNW_X86_64_XMM2);
569   _msContext.Xmm2 = t.m;
570   t.v = r.getVectorRegister(UNW_X86_64_XMM3);
571   _msContext.Xmm3 = t.m;
572   t.v = r.getVectorRegister(UNW_X86_64_XMM4);
573   _msContext.Xmm4 = t.m;
574   t.v = r.getVectorRegister(UNW_X86_64_XMM5);
575   _msContext.Xmm5 = t.m;
576   t.v = r.getVectorRegister(UNW_X86_64_XMM6);
577   _msContext.Xmm6 = t.m;
578   t.v = r.getVectorRegister(UNW_X86_64_XMM7);
579   _msContext.Xmm7 = t.m;
580   t.v = r.getVectorRegister(UNW_X86_64_XMM8);
581   _msContext.Xmm8 = t.m;
582   t.v = r.getVectorRegister(UNW_X86_64_XMM9);
583   _msContext.Xmm9 = t.m;
584   t.v = r.getVectorRegister(UNW_X86_64_XMM10);
585   _msContext.Xmm10 = t.m;
586   t.v = r.getVectorRegister(UNW_X86_64_XMM11);
587   _msContext.Xmm11 = t.m;
588   t.v = r.getVectorRegister(UNW_X86_64_XMM12);
589   _msContext.Xmm12 = t.m;
590   t.v = r.getVectorRegister(UNW_X86_64_XMM13);
591   _msContext.Xmm13 = t.m;
592   t.v = r.getVectorRegister(UNW_X86_64_XMM14);
593   _msContext.Xmm14 = t.m;
594   t.v = r.getVectorRegister(UNW_X86_64_XMM15);
595   _msContext.Xmm15 = t.m;
596 #elif defined(_LIBUNWIND_TARGET_ARM)
597   _msContext.R0 = r.getRegister(UNW_ARM_R0);
598   _msContext.R1 = r.getRegister(UNW_ARM_R1);
599   _msContext.R2 = r.getRegister(UNW_ARM_R2);
600   _msContext.R3 = r.getRegister(UNW_ARM_R3);
601   _msContext.R4 = r.getRegister(UNW_ARM_R4);
602   _msContext.R5 = r.getRegister(UNW_ARM_R5);
603   _msContext.R6 = r.getRegister(UNW_ARM_R6);
604   _msContext.R7 = r.getRegister(UNW_ARM_R7);
605   _msContext.R8 = r.getRegister(UNW_ARM_R8);
606   _msContext.R9 = r.getRegister(UNW_ARM_R9);
607   _msContext.R10 = r.getRegister(UNW_ARM_R10);
608   _msContext.R11 = r.getRegister(UNW_ARM_R11);
609   _msContext.R12 = r.getRegister(UNW_ARM_R12);
610   _msContext.Sp = r.getRegister(UNW_ARM_SP);
611   _msContext.Lr = r.getRegister(UNW_ARM_LR);
612   _msContext.Pc = r.getRegister(UNW_ARM_IP);
613   for (int i = UNW_ARM_D0; i <= UNW_ARM_D31; ++i) {
614     union {
615       uint64_t w;
616       double d;
617     } d;
618     d.d = r.getFloatRegister(i);
619     _msContext.D[i - UNW_ARM_D0] = d.w;
620   }
621 #elif defined(_LIBUNWIND_TARGET_AARCH64)
622   for (int i = UNW_ARM64_X0; i <= UNW_ARM64_X30; ++i)
623     _msContext.X[i - UNW_ARM64_X0] = r.getRegister(i);
624   _msContext.Sp = r.getRegister(UNW_REG_SP);
625   _msContext.Pc = r.getRegister(UNW_REG_IP);
626   for (int i = UNW_ARM64_D0; i <= UNW_ARM64_D31; ++i)
627     _msContext.V[i - UNW_ARM64_D0].D[0] = r.getFloatRegister(i);
628 #endif
629 }
630 
631 template <typename A, typename R>
632 UnwindCursor<A, R>::UnwindCursor(CONTEXT *context, A &as)
633     : _addressSpace(as), _unwindInfoMissing(false) {
634   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
635                 "UnwindCursor<> does not fit in unw_cursor_t");
636   memset(&_info, 0, sizeof(_info));
637   memset(&_histTable, 0, sizeof(_histTable));
638   _dispContext.ContextRecord = &_msContext;
639   _dispContext.HistoryTable = &_histTable;
640   _msContext = *context;
641 }
642 
643 
644 template <typename A, typename R>
645 bool UnwindCursor<A, R>::validReg(int regNum) {
646   if (regNum == UNW_REG_IP || regNum == UNW_REG_SP) return true;
647 #if defined(_LIBUNWIND_TARGET_X86_64)
648   if (regNum >= UNW_X86_64_RAX && regNum <= UNW_X86_64_R15) return true;
649 #elif defined(_LIBUNWIND_TARGET_ARM)
650   if (regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) return true;
651 #elif defined(_LIBUNWIND_TARGET_AARCH64)
652   if (regNum >= UNW_ARM64_X0 && regNum <= UNW_ARM64_X30) return true;
653 #endif
654   return false;
655 }
656 
657 template <typename A, typename R>
658 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
659   switch (regNum) {
660 #if defined(_LIBUNWIND_TARGET_X86_64)
661   case UNW_REG_IP: return _msContext.Rip;
662   case UNW_X86_64_RAX: return _msContext.Rax;
663   case UNW_X86_64_RDX: return _msContext.Rdx;
664   case UNW_X86_64_RCX: return _msContext.Rcx;
665   case UNW_X86_64_RBX: return _msContext.Rbx;
666   case UNW_REG_SP:
667   case UNW_X86_64_RSP: return _msContext.Rsp;
668   case UNW_X86_64_RBP: return _msContext.Rbp;
669   case UNW_X86_64_RSI: return _msContext.Rsi;
670   case UNW_X86_64_RDI: return _msContext.Rdi;
671   case UNW_X86_64_R8: return _msContext.R8;
672   case UNW_X86_64_R9: return _msContext.R9;
673   case UNW_X86_64_R10: return _msContext.R10;
674   case UNW_X86_64_R11: return _msContext.R11;
675   case UNW_X86_64_R12: return _msContext.R12;
676   case UNW_X86_64_R13: return _msContext.R13;
677   case UNW_X86_64_R14: return _msContext.R14;
678   case UNW_X86_64_R15: return _msContext.R15;
679 #elif defined(_LIBUNWIND_TARGET_ARM)
680   case UNW_ARM_R0: return _msContext.R0;
681   case UNW_ARM_R1: return _msContext.R1;
682   case UNW_ARM_R2: return _msContext.R2;
683   case UNW_ARM_R3: return _msContext.R3;
684   case UNW_ARM_R4: return _msContext.R4;
685   case UNW_ARM_R5: return _msContext.R5;
686   case UNW_ARM_R6: return _msContext.R6;
687   case UNW_ARM_R7: return _msContext.R7;
688   case UNW_ARM_R8: return _msContext.R8;
689   case UNW_ARM_R9: return _msContext.R9;
690   case UNW_ARM_R10: return _msContext.R10;
691   case UNW_ARM_R11: return _msContext.R11;
692   case UNW_ARM_R12: return _msContext.R12;
693   case UNW_REG_SP:
694   case UNW_ARM_SP: return _msContext.Sp;
695   case UNW_ARM_LR: return _msContext.Lr;
696   case UNW_REG_IP:
697   case UNW_ARM_IP: return _msContext.Pc;
698 #elif defined(_LIBUNWIND_TARGET_AARCH64)
699   case UNW_REG_SP: return _msContext.Sp;
700   case UNW_REG_IP: return _msContext.Pc;
701   default: return _msContext.X[regNum - UNW_ARM64_X0];
702 #endif
703   }
704   _LIBUNWIND_ABORT("unsupported register");
705 }
706 
707 template <typename A, typename R>
708 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
709   switch (regNum) {
710 #if defined(_LIBUNWIND_TARGET_X86_64)
711   case UNW_REG_IP: _msContext.Rip = value; break;
712   case UNW_X86_64_RAX: _msContext.Rax = value; break;
713   case UNW_X86_64_RDX: _msContext.Rdx = value; break;
714   case UNW_X86_64_RCX: _msContext.Rcx = value; break;
715   case UNW_X86_64_RBX: _msContext.Rbx = value; break;
716   case UNW_REG_SP:
717   case UNW_X86_64_RSP: _msContext.Rsp = value; break;
718   case UNW_X86_64_RBP: _msContext.Rbp = value; break;
719   case UNW_X86_64_RSI: _msContext.Rsi = value; break;
720   case UNW_X86_64_RDI: _msContext.Rdi = value; break;
721   case UNW_X86_64_R8: _msContext.R8 = value; break;
722   case UNW_X86_64_R9: _msContext.R9 = value; break;
723   case UNW_X86_64_R10: _msContext.R10 = value; break;
724   case UNW_X86_64_R11: _msContext.R11 = value; break;
725   case UNW_X86_64_R12: _msContext.R12 = value; break;
726   case UNW_X86_64_R13: _msContext.R13 = value; break;
727   case UNW_X86_64_R14: _msContext.R14 = value; break;
728   case UNW_X86_64_R15: _msContext.R15 = value; break;
729 #elif defined(_LIBUNWIND_TARGET_ARM)
730   case UNW_ARM_R0: _msContext.R0 = value; break;
731   case UNW_ARM_R1: _msContext.R1 = value; break;
732   case UNW_ARM_R2: _msContext.R2 = value; break;
733   case UNW_ARM_R3: _msContext.R3 = value; break;
734   case UNW_ARM_R4: _msContext.R4 = value; break;
735   case UNW_ARM_R5: _msContext.R5 = value; break;
736   case UNW_ARM_R6: _msContext.R6 = value; break;
737   case UNW_ARM_R7: _msContext.R7 = value; break;
738   case UNW_ARM_R8: _msContext.R8 = value; break;
739   case UNW_ARM_R9: _msContext.R9 = value; break;
740   case UNW_ARM_R10: _msContext.R10 = value; break;
741   case UNW_ARM_R11: _msContext.R11 = value; break;
742   case UNW_ARM_R12: _msContext.R12 = value; break;
743   case UNW_REG_SP:
744   case UNW_ARM_SP: _msContext.Sp = value; break;
745   case UNW_ARM_LR: _msContext.Lr = value; break;
746   case UNW_REG_IP:
747   case UNW_ARM_IP: _msContext.Pc = value; break;
748 #elif defined(_LIBUNWIND_TARGET_AARCH64)
749   case UNW_REG_SP: _msContext.Sp = value; break;
750   case UNW_REG_IP: _msContext.Pc = value; break;
751   case UNW_ARM64_X0:
752   case UNW_ARM64_X1:
753   case UNW_ARM64_X2:
754   case UNW_ARM64_X3:
755   case UNW_ARM64_X4:
756   case UNW_ARM64_X5:
757   case UNW_ARM64_X6:
758   case UNW_ARM64_X7:
759   case UNW_ARM64_X8:
760   case UNW_ARM64_X9:
761   case UNW_ARM64_X10:
762   case UNW_ARM64_X11:
763   case UNW_ARM64_X12:
764   case UNW_ARM64_X13:
765   case UNW_ARM64_X14:
766   case UNW_ARM64_X15:
767   case UNW_ARM64_X16:
768   case UNW_ARM64_X17:
769   case UNW_ARM64_X18:
770   case UNW_ARM64_X19:
771   case UNW_ARM64_X20:
772   case UNW_ARM64_X21:
773   case UNW_ARM64_X22:
774   case UNW_ARM64_X23:
775   case UNW_ARM64_X24:
776   case UNW_ARM64_X25:
777   case UNW_ARM64_X26:
778   case UNW_ARM64_X27:
779   case UNW_ARM64_X28:
780   case UNW_ARM64_FP:
781   case UNW_ARM64_LR: _msContext.X[regNum - UNW_ARM64_X0] = value; break;
782 #endif
783   default:
784     _LIBUNWIND_ABORT("unsupported register");
785   }
786 }
787 
788 template <typename A, typename R>
789 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
790 #if defined(_LIBUNWIND_TARGET_ARM)
791   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) return true;
792   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) return true;
793 #elif defined(_LIBUNWIND_TARGET_AARCH64)
794   if (regNum >= UNW_ARM64_D0 && regNum <= UNW_ARM64_D31) return true;
795 #else
796   (void)regNum;
797 #endif
798   return false;
799 }
800 
801 template <typename A, typename R>
802 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
803 #if defined(_LIBUNWIND_TARGET_ARM)
804   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
805     union {
806       uint32_t w;
807       float f;
808     } d;
809     d.w = _msContext.S[regNum - UNW_ARM_S0];
810     return d.f;
811   }
812   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
813     union {
814       uint64_t w;
815       double d;
816     } d;
817     d.w = _msContext.D[regNum - UNW_ARM_D0];
818     return d.d;
819   }
820   _LIBUNWIND_ABORT("unsupported float register");
821 #elif defined(_LIBUNWIND_TARGET_AARCH64)
822   return _msContext.V[regNum - UNW_ARM64_D0].D[0];
823 #else
824   (void)regNum;
825   _LIBUNWIND_ABORT("float registers unimplemented");
826 #endif
827 }
828 
829 template <typename A, typename R>
830 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
831 #if defined(_LIBUNWIND_TARGET_ARM)
832   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
833     union {
834       uint32_t w;
835       float f;
836     } d;
837     d.f = value;
838     _msContext.S[regNum - UNW_ARM_S0] = d.w;
839   }
840   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
841     union {
842       uint64_t w;
843       double d;
844     } d;
845     d.d = value;
846     _msContext.D[regNum - UNW_ARM_D0] = d.w;
847   }
848   _LIBUNWIND_ABORT("unsupported float register");
849 #elif defined(_LIBUNWIND_TARGET_AARCH64)
850   _msContext.V[regNum - UNW_ARM64_D0].D[0] = value;
851 #else
852   (void)regNum;
853   (void)value;
854   _LIBUNWIND_ABORT("float registers unimplemented");
855 #endif
856 }
857 
858 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
859   RtlRestoreContext(&_msContext, nullptr);
860 }
861 
862 #ifdef __arm__
863 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {}
864 #endif
865 
866 template <typename A, typename R>
867 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
868   return R::getRegisterName(regNum);
869 }
870 
871 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
872   return false;
873 }
874 
875 #else  // !defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) || !defined(_WIN32)
876 
877 /// UnwindCursor contains all state (including all register values) during
878 /// an unwind.  This is normally stack allocated inside a unw_cursor_t.
879 template <typename A, typename R>
880 class UnwindCursor : public AbstractUnwindCursor{
881   typedef typename A::pint_t pint_t;
882 public:
883                       UnwindCursor(unw_context_t *context, A &as);
884                       UnwindCursor(A &as, void *threadArg);
885   virtual             ~UnwindCursor() {}
886   virtual bool        validReg(int);
887   virtual unw_word_t  getReg(int);
888   virtual void        setReg(int, unw_word_t);
889   virtual bool        validFloatReg(int);
890   virtual unw_fpreg_t getFloatReg(int);
891   virtual void        setFloatReg(int, unw_fpreg_t);
892   virtual int         step();
893   virtual void        getInfo(unw_proc_info_t *);
894   virtual void        jumpto();
895   virtual bool        isSignalFrame();
896   virtual bool        getFunctionName(char *buf, size_t len, unw_word_t *off);
897   virtual void        setInfoBasedOnIPRegister(bool isReturnAddress = false);
898   virtual const char *getRegisterName(int num);
899 #ifdef __arm__
900   virtual void        saveVFPAsX();
901 #endif
902 
903   // libunwind does not and should not depend on C++ library which means that we
904   // need our own defition of inline placement new.
905   static void *operator new(size_t, UnwindCursor<A, R> *p) { return p; }
906 
907 private:
908 
909 #if defined(_LIBUNWIND_ARM_EHABI)
910   bool getInfoFromEHABISection(pint_t pc, const UnwindInfoSections &sects);
911 
912   int stepWithEHABI() {
913     size_t len = 0;
914     size_t off = 0;
915     // FIXME: Calling decode_eht_entry() here is violating the libunwind
916     // abstraction layer.
917     const uint32_t *ehtp =
918         decode_eht_entry(reinterpret_cast<const uint32_t *>(_info.unwind_info),
919                          &off, &len);
920     if (_Unwind_VRS_Interpret((_Unwind_Context *)this, ehtp, off, len) !=
921             _URC_CONTINUE_UNWIND)
922       return UNW_STEP_END;
923     return UNW_STEP_SUCCESS;
924   }
925 #endif
926 
927 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
928   bool getInfoFromDwarfSection(pint_t pc, const UnwindInfoSections &sects,
929                                             uint32_t fdeSectionOffsetHint=0);
930   int stepWithDwarfFDE() {
931     return DwarfInstructions<A, R>::stepWithDwarf(_addressSpace,
932                                               (pint_t)this->getReg(UNW_REG_IP),
933                                               (pint_t)_info.unwind_info,
934                                               _registers, _isSignalFrame);
935   }
936 #endif
937 
938 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
939   bool getInfoFromCompactEncodingSection(pint_t pc,
940                                             const UnwindInfoSections &sects);
941   int stepWithCompactEncoding() {
942   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
943     if ( compactSaysUseDwarf() )
944       return stepWithDwarfFDE();
945   #endif
946     R dummy;
947     return stepWithCompactEncoding(dummy);
948   }
949 
950 #if defined(_LIBUNWIND_TARGET_X86_64)
951   int stepWithCompactEncoding(Registers_x86_64 &) {
952     return CompactUnwinder_x86_64<A>::stepWithCompactEncoding(
953         _info.format, _info.start_ip, _addressSpace, _registers);
954   }
955 #endif
956 
957 #if defined(_LIBUNWIND_TARGET_I386)
958   int stepWithCompactEncoding(Registers_x86 &) {
959     return CompactUnwinder_x86<A>::stepWithCompactEncoding(
960         _info.format, (uint32_t)_info.start_ip, _addressSpace, _registers);
961   }
962 #endif
963 
964 #if defined(_LIBUNWIND_TARGET_PPC)
965   int stepWithCompactEncoding(Registers_ppc &) {
966     return UNW_EINVAL;
967   }
968 #endif
969 
970 #if defined(_LIBUNWIND_TARGET_PPC64)
971   int stepWithCompactEncoding(Registers_ppc64 &) {
972     return UNW_EINVAL;
973   }
974 #endif
975 
976 
977 #if defined(_LIBUNWIND_TARGET_AARCH64)
978   int stepWithCompactEncoding(Registers_arm64 &) {
979     return CompactUnwinder_arm64<A>::stepWithCompactEncoding(
980         _info.format, _info.start_ip, _addressSpace, _registers);
981   }
982 #endif
983 
984 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
985   int stepWithCompactEncoding(Registers_mips_o32 &) {
986     return UNW_EINVAL;
987   }
988 #endif
989 
990 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
991   int stepWithCompactEncoding(Registers_mips_newabi &) {
992     return UNW_EINVAL;
993   }
994 #endif
995 
996 #if defined(_LIBUNWIND_TARGET_SPARC)
997   int stepWithCompactEncoding(Registers_sparc &) { return UNW_EINVAL; }
998 #endif
999 
1000 #if defined (_LIBUNWIND_TARGET_RISCV)
1001   int stepWithCompactEncoding(Registers_riscv &) {
1002     return UNW_EINVAL;
1003   }
1004 #endif
1005 
1006   bool compactSaysUseDwarf(uint32_t *offset=NULL) const {
1007     R dummy;
1008     return compactSaysUseDwarf(dummy, offset);
1009   }
1010 
1011 #if defined(_LIBUNWIND_TARGET_X86_64)
1012   bool compactSaysUseDwarf(Registers_x86_64 &, uint32_t *offset) const {
1013     if ((_info.format & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF) {
1014       if (offset)
1015         *offset = (_info.format & UNWIND_X86_64_DWARF_SECTION_OFFSET);
1016       return true;
1017     }
1018     return false;
1019   }
1020 #endif
1021 
1022 #if defined(_LIBUNWIND_TARGET_I386)
1023   bool compactSaysUseDwarf(Registers_x86 &, uint32_t *offset) const {
1024     if ((_info.format & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF) {
1025       if (offset)
1026         *offset = (_info.format & UNWIND_X86_DWARF_SECTION_OFFSET);
1027       return true;
1028     }
1029     return false;
1030   }
1031 #endif
1032 
1033 #if defined(_LIBUNWIND_TARGET_PPC)
1034   bool compactSaysUseDwarf(Registers_ppc &, uint32_t *) const {
1035     return true;
1036   }
1037 #endif
1038 
1039 #if defined(_LIBUNWIND_TARGET_PPC64)
1040   bool compactSaysUseDwarf(Registers_ppc64 &, uint32_t *) const {
1041     return true;
1042   }
1043 #endif
1044 
1045 #if defined(_LIBUNWIND_TARGET_AARCH64)
1046   bool compactSaysUseDwarf(Registers_arm64 &, uint32_t *offset) const {
1047     if ((_info.format & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF) {
1048       if (offset)
1049         *offset = (_info.format & UNWIND_ARM64_DWARF_SECTION_OFFSET);
1050       return true;
1051     }
1052     return false;
1053   }
1054 #endif
1055 
1056 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
1057   bool compactSaysUseDwarf(Registers_mips_o32 &, uint32_t *) const {
1058     return true;
1059   }
1060 #endif
1061 
1062 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1063   bool compactSaysUseDwarf(Registers_mips_newabi &, uint32_t *) const {
1064     return true;
1065   }
1066 #endif
1067 
1068 #if defined(_LIBUNWIND_TARGET_SPARC)
1069   bool compactSaysUseDwarf(Registers_sparc &, uint32_t *) const { return true; }
1070 #endif
1071 
1072 #if defined (_LIBUNWIND_TARGET_RISCV)
1073   bool compactSaysUseDwarf(Registers_riscv &, uint32_t *) const {
1074     return true;
1075   }
1076 #endif
1077 
1078 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1079 
1080 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1081   compact_unwind_encoding_t dwarfEncoding() const {
1082     R dummy;
1083     return dwarfEncoding(dummy);
1084   }
1085 
1086 #if defined(_LIBUNWIND_TARGET_X86_64)
1087   compact_unwind_encoding_t dwarfEncoding(Registers_x86_64 &) const {
1088     return UNWIND_X86_64_MODE_DWARF;
1089   }
1090 #endif
1091 
1092 #if defined(_LIBUNWIND_TARGET_I386)
1093   compact_unwind_encoding_t dwarfEncoding(Registers_x86 &) const {
1094     return UNWIND_X86_MODE_DWARF;
1095   }
1096 #endif
1097 
1098 #if defined(_LIBUNWIND_TARGET_PPC)
1099   compact_unwind_encoding_t dwarfEncoding(Registers_ppc &) const {
1100     return 0;
1101   }
1102 #endif
1103 
1104 #if defined(_LIBUNWIND_TARGET_PPC64)
1105   compact_unwind_encoding_t dwarfEncoding(Registers_ppc64 &) const {
1106     return 0;
1107   }
1108 #endif
1109 
1110 #if defined(_LIBUNWIND_TARGET_AARCH64)
1111   compact_unwind_encoding_t dwarfEncoding(Registers_arm64 &) const {
1112     return UNWIND_ARM64_MODE_DWARF;
1113   }
1114 #endif
1115 
1116 #if defined(_LIBUNWIND_TARGET_ARM)
1117   compact_unwind_encoding_t dwarfEncoding(Registers_arm &) const {
1118     return 0;
1119   }
1120 #endif
1121 
1122 #if defined (_LIBUNWIND_TARGET_OR1K)
1123   compact_unwind_encoding_t dwarfEncoding(Registers_or1k &) const {
1124     return 0;
1125   }
1126 #endif
1127 
1128 #if defined (_LIBUNWIND_TARGET_HEXAGON)
1129   compact_unwind_encoding_t dwarfEncoding(Registers_hexagon &) const {
1130     return 0;
1131   }
1132 #endif
1133 
1134 #if defined (_LIBUNWIND_TARGET_MIPS_O32)
1135   compact_unwind_encoding_t dwarfEncoding(Registers_mips_o32 &) const {
1136     return 0;
1137   }
1138 #endif
1139 
1140 #if defined (_LIBUNWIND_TARGET_MIPS_NEWABI)
1141   compact_unwind_encoding_t dwarfEncoding(Registers_mips_newabi &) const {
1142     return 0;
1143   }
1144 #endif
1145 
1146 #if defined(_LIBUNWIND_TARGET_SPARC)
1147   compact_unwind_encoding_t dwarfEncoding(Registers_sparc &) const { return 0; }
1148 #endif
1149 
1150 #if defined (_LIBUNWIND_TARGET_SPARC64)
1151   compact_unwind_encoding_t dwarfEncoding(Registers_sparc64 &) const {
1152     return 0;
1153   }
1154 #endif
1155 
1156 #if defined (_LIBUNWIND_TARGET_RISCV)
1157   compact_unwind_encoding_t dwarfEncoding(Registers_riscv &) const {
1158     return 0;
1159   }
1160 #endif
1161 
1162 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1163 
1164 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1165   // For runtime environments using SEH unwind data without Windows runtime
1166   // support.
1167   pint_t getLastPC() const { /* FIXME: Implement */ return 0; }
1168   void setLastPC(pint_t pc) { /* FIXME: Implement */ }
1169   RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
1170     /* FIXME: Implement */
1171     *base = 0;
1172     return nullptr;
1173   }
1174   bool getInfoFromSEH(pint_t pc);
1175   int stepWithSEHData() { /* FIXME: Implement */ return 0; }
1176 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1177 
1178 
1179   A               &_addressSpace;
1180   R                _registers;
1181   unw_proc_info_t  _info;
1182   bool             _unwindInfoMissing;
1183   bool             _isSignalFrame;
1184 };
1185 
1186 
1187 template <typename A, typename R>
1188 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
1189     : _addressSpace(as), _registers(context), _unwindInfoMissing(false),
1190       _isSignalFrame(false) {
1191   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
1192                 "UnwindCursor<> does not fit in unw_cursor_t");
1193   memset(&_info, 0, sizeof(_info));
1194 }
1195 
1196 template <typename A, typename R>
1197 UnwindCursor<A, R>::UnwindCursor(A &as, void *)
1198     : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) {
1199   memset(&_info, 0, sizeof(_info));
1200   // FIXME
1201   // fill in _registers from thread arg
1202 }
1203 
1204 
1205 template <typename A, typename R>
1206 bool UnwindCursor<A, R>::validReg(int regNum) {
1207   return _registers.validRegister(regNum);
1208 }
1209 
1210 template <typename A, typename R>
1211 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
1212   return _registers.getRegister(regNum);
1213 }
1214 
1215 template <typename A, typename R>
1216 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
1217   _registers.setRegister(regNum, (typename A::pint_t)value);
1218 }
1219 
1220 template <typename A, typename R>
1221 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
1222   return _registers.validFloatRegister(regNum);
1223 }
1224 
1225 template <typename A, typename R>
1226 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
1227   return _registers.getFloatRegister(regNum);
1228 }
1229 
1230 template <typename A, typename R>
1231 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
1232   _registers.setFloatRegister(regNum, value);
1233 }
1234 
1235 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
1236   _registers.jumpto();
1237 }
1238 
1239 #ifdef __arm__
1240 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {
1241   _registers.saveVFPAsX();
1242 }
1243 #endif
1244 
1245 template <typename A, typename R>
1246 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
1247   return _registers.getRegisterName(regNum);
1248 }
1249 
1250 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
1251   return _isSignalFrame;
1252 }
1253 
1254 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1255 
1256 #if defined(_LIBUNWIND_ARM_EHABI)
1257 template<typename A>
1258 struct EHABISectionIterator {
1259   typedef EHABISectionIterator _Self;
1260 
1261   typedef typename A::pint_t value_type;
1262   typedef typename A::pint_t* pointer;
1263   typedef typename A::pint_t& reference;
1264   typedef size_t size_type;
1265   typedef size_t difference_type;
1266 
1267   static _Self begin(A& addressSpace, const UnwindInfoSections& sects) {
1268     return _Self(addressSpace, sects, 0);
1269   }
1270   static _Self end(A& addressSpace, const UnwindInfoSections& sects) {
1271     return _Self(addressSpace, sects,
1272                  sects.arm_section_length / sizeof(EHABIIndexEntry));
1273   }
1274 
1275   EHABISectionIterator(A& addressSpace, const UnwindInfoSections& sects, size_t i)
1276       : _i(i), _addressSpace(&addressSpace), _sects(&sects) {}
1277 
1278   _Self& operator++() { ++_i; return *this; }
1279   _Self& operator+=(size_t a) { _i += a; return *this; }
1280   _Self& operator--() { assert(_i > 0); --_i; return *this; }
1281   _Self& operator-=(size_t a) { assert(_i >= a); _i -= a; return *this; }
1282 
1283   _Self operator+(size_t a) { _Self out = *this; out._i += a; return out; }
1284   _Self operator-(size_t a) { assert(_i >= a); _Self out = *this; out._i -= a; return out; }
1285 
1286   size_t operator-(const _Self& other) const { return _i - other._i; }
1287 
1288   bool operator==(const _Self& other) const {
1289     assert(_addressSpace == other._addressSpace);
1290     assert(_sects == other._sects);
1291     return _i == other._i;
1292   }
1293 
1294   bool operator!=(const _Self& other) const {
1295     assert(_addressSpace == other._addressSpace);
1296     assert(_sects == other._sects);
1297     return _i != other._i;
1298   }
1299 
1300   typename A::pint_t operator*() const { return functionAddress(); }
1301 
1302   typename A::pint_t functionAddress() const {
1303     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1304         EHABIIndexEntry, _i, functionOffset);
1305     return indexAddr + signExtendPrel31(_addressSpace->get32(indexAddr));
1306   }
1307 
1308   typename A::pint_t dataAddress() {
1309     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1310         EHABIIndexEntry, _i, data);
1311     return indexAddr;
1312   }
1313 
1314  private:
1315   size_t _i;
1316   A* _addressSpace;
1317   const UnwindInfoSections* _sects;
1318 };
1319 
1320 namespace {
1321 
1322 template <typename A>
1323 EHABISectionIterator<A> EHABISectionUpperBound(
1324     EHABISectionIterator<A> first,
1325     EHABISectionIterator<A> last,
1326     typename A::pint_t value) {
1327   size_t len = last - first;
1328   while (len > 0) {
1329     size_t l2 = len / 2;
1330     EHABISectionIterator<A> m = first + l2;
1331     if (value < *m) {
1332         len = l2;
1333     } else {
1334         first = ++m;
1335         len -= l2 + 1;
1336     }
1337   }
1338   return first;
1339 }
1340 
1341 }
1342 
1343 template <typename A, typename R>
1344 bool UnwindCursor<A, R>::getInfoFromEHABISection(
1345     pint_t pc,
1346     const UnwindInfoSections &sects) {
1347   EHABISectionIterator<A> begin =
1348       EHABISectionIterator<A>::begin(_addressSpace, sects);
1349   EHABISectionIterator<A> end =
1350       EHABISectionIterator<A>::end(_addressSpace, sects);
1351   if (begin == end)
1352     return false;
1353 
1354   EHABISectionIterator<A> itNextPC = EHABISectionUpperBound(begin, end, pc);
1355   if (itNextPC == begin)
1356     return false;
1357   EHABISectionIterator<A> itThisPC = itNextPC - 1;
1358 
1359   pint_t thisPC = itThisPC.functionAddress();
1360   // If an exception is thrown from a function, corresponding to the last entry
1361   // in the table, we don't really know the function extent and have to choose a
1362   // value for nextPC. Choosing max() will allow the range check during trace to
1363   // succeed.
1364   pint_t nextPC = (itNextPC == end) ? UINTPTR_MAX : itNextPC.functionAddress();
1365   pint_t indexDataAddr = itThisPC.dataAddress();
1366 
1367   if (indexDataAddr == 0)
1368     return false;
1369 
1370   uint32_t indexData = _addressSpace.get32(indexDataAddr);
1371   if (indexData == UNW_EXIDX_CANTUNWIND)
1372     return false;
1373 
1374   // If the high bit is set, the exception handling table entry is inline inside
1375   // the index table entry on the second word (aka |indexDataAddr|). Otherwise,
1376   // the table points at an offset in the exception handling table (section 5
1377   // EHABI).
1378   pint_t exceptionTableAddr;
1379   uint32_t exceptionTableData;
1380   bool isSingleWordEHT;
1381   if (indexData & 0x80000000) {
1382     exceptionTableAddr = indexDataAddr;
1383     // TODO(ajwong): Should this data be 0?
1384     exceptionTableData = indexData;
1385     isSingleWordEHT = true;
1386   } else {
1387     exceptionTableAddr = indexDataAddr + signExtendPrel31(indexData);
1388     exceptionTableData = _addressSpace.get32(exceptionTableAddr);
1389     isSingleWordEHT = false;
1390   }
1391 
1392   // Now we know the 3 things:
1393   //   exceptionTableAddr -- exception handler table entry.
1394   //   exceptionTableData -- the data inside the first word of the eht entry.
1395   //   isSingleWordEHT -- whether the entry is in the index.
1396   unw_word_t personalityRoutine = 0xbadf00d;
1397   bool scope32 = false;
1398   uintptr_t lsda;
1399 
1400   // If the high bit in the exception handling table entry is set, the entry is
1401   // in compact form (section 6.3 EHABI).
1402   if (exceptionTableData & 0x80000000) {
1403     // Grab the index of the personality routine from the compact form.
1404     uint32_t choice = (exceptionTableData & 0x0f000000) >> 24;
1405     uint32_t extraWords = 0;
1406     switch (choice) {
1407       case 0:
1408         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr0;
1409         extraWords = 0;
1410         scope32 = false;
1411         lsda = isSingleWordEHT ? 0 : (exceptionTableAddr + 4);
1412         break;
1413       case 1:
1414         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr1;
1415         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1416         scope32 = false;
1417         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1418         break;
1419       case 2:
1420         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr2;
1421         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1422         scope32 = true;
1423         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1424         break;
1425       default:
1426         _LIBUNWIND_ABORT("unknown personality routine");
1427         return false;
1428     }
1429 
1430     if (isSingleWordEHT) {
1431       if (extraWords != 0) {
1432         _LIBUNWIND_ABORT("index inlined table detected but pr function "
1433                          "requires extra words");
1434         return false;
1435       }
1436     }
1437   } else {
1438     pint_t personalityAddr =
1439         exceptionTableAddr + signExtendPrel31(exceptionTableData);
1440     personalityRoutine = personalityAddr;
1441 
1442     // ARM EHABI # 6.2, # 9.2
1443     //
1444     //  +---- ehtp
1445     //  v
1446     // +--------------------------------------+
1447     // | +--------+--------+--------+-------+ |
1448     // | |0| prel31 to personalityRoutine   | |
1449     // | +--------+--------+--------+-------+ |
1450     // | |      N |      unwind opcodes     | |  <-- UnwindData
1451     // | +--------+--------+--------+-------+ |
1452     // | | Word 2        unwind opcodes     | |
1453     // | +--------+--------+--------+-------+ |
1454     // | ...                                  |
1455     // | +--------+--------+--------+-------+ |
1456     // | | Word N        unwind opcodes     | |
1457     // | +--------+--------+--------+-------+ |
1458     // | | LSDA                             | |  <-- lsda
1459     // | | ...                              | |
1460     // | +--------+--------+--------+-------+ |
1461     // +--------------------------------------+
1462 
1463     uint32_t *UnwindData = reinterpret_cast<uint32_t*>(exceptionTableAddr) + 1;
1464     uint32_t FirstDataWord = *UnwindData;
1465     size_t N = ((FirstDataWord >> 24) & 0xff);
1466     size_t NDataWords = N + 1;
1467     lsda = reinterpret_cast<uintptr_t>(UnwindData + NDataWords);
1468   }
1469 
1470   _info.start_ip = thisPC;
1471   _info.end_ip = nextPC;
1472   _info.handler = personalityRoutine;
1473   _info.unwind_info = exceptionTableAddr;
1474   _info.lsda = lsda;
1475   // flags is pr_cache.additional. See EHABI #7.2 for definition of bit 0.
1476   _info.flags = (isSingleWordEHT ? 1 : 0) | (scope32 ? 0x2 : 0);  // Use enum?
1477 
1478   return true;
1479 }
1480 #endif
1481 
1482 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1483 template <typename A, typename R>
1484 bool UnwindCursor<A, R>::getInfoFromDwarfSection(pint_t pc,
1485                                                 const UnwindInfoSections &sects,
1486                                                 uint32_t fdeSectionOffsetHint) {
1487   typename CFI_Parser<A>::FDE_Info fdeInfo;
1488   typename CFI_Parser<A>::CIE_Info cieInfo;
1489   bool foundFDE = false;
1490   bool foundInCache = false;
1491   // If compact encoding table gave offset into dwarf section, go directly there
1492   if (fdeSectionOffsetHint != 0) {
1493     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1494                                     (uint32_t)sects.dwarf_section_length,
1495                                     sects.dwarf_section + fdeSectionOffsetHint,
1496                                     &fdeInfo, &cieInfo);
1497   }
1498 #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1499   if (!foundFDE && (sects.dwarf_index_section != 0)) {
1500     foundFDE = EHHeaderParser<A>::findFDE(
1501         _addressSpace, pc, sects.dwarf_index_section,
1502         (uint32_t)sects.dwarf_index_section_length, &fdeInfo, &cieInfo);
1503   }
1504 #endif
1505   if (!foundFDE) {
1506     // otherwise, search cache of previously found FDEs.
1507     pint_t cachedFDE = DwarfFDECache<A>::findFDE(sects.dso_base, pc);
1508     if (cachedFDE != 0) {
1509       foundFDE =
1510           CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1511                                  (uint32_t)sects.dwarf_section_length,
1512                                  cachedFDE, &fdeInfo, &cieInfo);
1513       foundInCache = foundFDE;
1514     }
1515   }
1516   if (!foundFDE) {
1517     // Still not found, do full scan of __eh_frame section.
1518     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1519                                       (uint32_t)sects.dwarf_section_length, 0,
1520                                       &fdeInfo, &cieInfo);
1521   }
1522   if (foundFDE) {
1523     typename CFI_Parser<A>::PrologInfo prolog;
1524     if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo, pc,
1525                                             R::getArch(), &prolog)) {
1526       // Save off parsed FDE info
1527       _info.start_ip          = fdeInfo.pcStart;
1528       _info.end_ip            = fdeInfo.pcEnd;
1529       _info.lsda              = fdeInfo.lsda;
1530       _info.handler           = cieInfo.personality;
1531       _info.gp                = prolog.spExtraArgSize;
1532       _info.flags             = 0;
1533       _info.format            = dwarfEncoding();
1534       _info.unwind_info       = fdeInfo.fdeStart;
1535       _info.unwind_info_size  = (uint32_t)fdeInfo.fdeLength;
1536       _info.extra             = (unw_word_t) sects.dso_base;
1537 
1538       // Add to cache (to make next lookup faster) if we had no hint
1539       // and there was no index.
1540       if (!foundInCache && (fdeSectionOffsetHint == 0)) {
1541   #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1542         if (sects.dwarf_index_section == 0)
1543   #endif
1544         DwarfFDECache<A>::add(sects.dso_base, fdeInfo.pcStart, fdeInfo.pcEnd,
1545                               fdeInfo.fdeStart);
1546       }
1547       return true;
1548     }
1549   }
1550   //_LIBUNWIND_DEBUG_LOG("can't find/use FDE for pc=0x%llX", (uint64_t)pc);
1551   return false;
1552 }
1553 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1554 
1555 
1556 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1557 template <typename A, typename R>
1558 bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
1559                                               const UnwindInfoSections &sects) {
1560   const bool log = false;
1561   if (log)
1562     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX, mh=0x%llX)\n",
1563             (uint64_t)pc, (uint64_t)sects.dso_base);
1564 
1565   const UnwindSectionHeader<A> sectionHeader(_addressSpace,
1566                                                 sects.compact_unwind_section);
1567   if (sectionHeader.version() != UNWIND_SECTION_VERSION)
1568     return false;
1569 
1570   // do a binary search of top level index to find page with unwind info
1571   pint_t targetFunctionOffset = pc - sects.dso_base;
1572   const UnwindSectionIndexArray<A> topIndex(_addressSpace,
1573                                            sects.compact_unwind_section
1574                                          + sectionHeader.indexSectionOffset());
1575   uint32_t low = 0;
1576   uint32_t high = sectionHeader.indexCount();
1577   uint32_t last = high - 1;
1578   while (low < high) {
1579     uint32_t mid = (low + high) / 2;
1580     //if ( log ) fprintf(stderr, "\tmid=%d, low=%d, high=%d, *mid=0x%08X\n",
1581     //mid, low, high, topIndex.functionOffset(mid));
1582     if (topIndex.functionOffset(mid) <= targetFunctionOffset) {
1583       if ((mid == last) ||
1584           (topIndex.functionOffset(mid + 1) > targetFunctionOffset)) {
1585         low = mid;
1586         break;
1587       } else {
1588         low = mid + 1;
1589       }
1590     } else {
1591       high = mid;
1592     }
1593   }
1594   const uint32_t firstLevelFunctionOffset = topIndex.functionOffset(low);
1595   const uint32_t firstLevelNextPageFunctionOffset =
1596       topIndex.functionOffset(low + 1);
1597   const pint_t secondLevelAddr =
1598       sects.compact_unwind_section + topIndex.secondLevelPagesSectionOffset(low);
1599   const pint_t lsdaArrayStartAddr =
1600       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low);
1601   const pint_t lsdaArrayEndAddr =
1602       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low+1);
1603   if (log)
1604     fprintf(stderr, "\tfirst level search for result index=%d "
1605                     "to secondLevelAddr=0x%llX\n",
1606                     low, (uint64_t) secondLevelAddr);
1607   // do a binary search of second level page index
1608   uint32_t encoding = 0;
1609   pint_t funcStart = 0;
1610   pint_t funcEnd = 0;
1611   pint_t lsda = 0;
1612   pint_t personality = 0;
1613   uint32_t pageKind = _addressSpace.get32(secondLevelAddr);
1614   if (pageKind == UNWIND_SECOND_LEVEL_REGULAR) {
1615     // regular page
1616     UnwindSectionRegularPageHeader<A> pageHeader(_addressSpace,
1617                                                  secondLevelAddr);
1618     UnwindSectionRegularArray<A> pageIndex(
1619         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1620     // binary search looks for entry with e where index[e].offset <= pc <
1621     // index[e+1].offset
1622     if (log)
1623       fprintf(stderr, "\tbinary search for targetFunctionOffset=0x%08llX in "
1624                       "regular page starting at secondLevelAddr=0x%llX\n",
1625               (uint64_t) targetFunctionOffset, (uint64_t) secondLevelAddr);
1626     low = 0;
1627     high = pageHeader.entryCount();
1628     while (low < high) {
1629       uint32_t mid = (low + high) / 2;
1630       if (pageIndex.functionOffset(mid) <= targetFunctionOffset) {
1631         if (mid == (uint32_t)(pageHeader.entryCount() - 1)) {
1632           // at end of table
1633           low = mid;
1634           funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1635           break;
1636         } else if (pageIndex.functionOffset(mid + 1) > targetFunctionOffset) {
1637           // next is too big, so we found it
1638           low = mid;
1639           funcEnd = pageIndex.functionOffset(low + 1) + sects.dso_base;
1640           break;
1641         } else {
1642           low = mid + 1;
1643         }
1644       } else {
1645         high = mid;
1646       }
1647     }
1648     encoding = pageIndex.encoding(low);
1649     funcStart = pageIndex.functionOffset(low) + sects.dso_base;
1650     if (pc < funcStart) {
1651       if (log)
1652         fprintf(
1653             stderr,
1654             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1655             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1656       return false;
1657     }
1658     if (pc > funcEnd) {
1659       if (log)
1660         fprintf(
1661             stderr,
1662             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1663             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1664       return false;
1665     }
1666   } else if (pageKind == UNWIND_SECOND_LEVEL_COMPRESSED) {
1667     // compressed page
1668     UnwindSectionCompressedPageHeader<A> pageHeader(_addressSpace,
1669                                                     secondLevelAddr);
1670     UnwindSectionCompressedArray<A> pageIndex(
1671         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1672     const uint32_t targetFunctionPageOffset =
1673         (uint32_t)(targetFunctionOffset - firstLevelFunctionOffset);
1674     // binary search looks for entry with e where index[e].offset <= pc <
1675     // index[e+1].offset
1676     if (log)
1677       fprintf(stderr, "\tbinary search of compressed page starting at "
1678                       "secondLevelAddr=0x%llX\n",
1679               (uint64_t) secondLevelAddr);
1680     low = 0;
1681     last = pageHeader.entryCount() - 1;
1682     high = pageHeader.entryCount();
1683     while (low < high) {
1684       uint32_t mid = (low + high) / 2;
1685       if (pageIndex.functionOffset(mid) <= targetFunctionPageOffset) {
1686         if ((mid == last) ||
1687             (pageIndex.functionOffset(mid + 1) > targetFunctionPageOffset)) {
1688           low = mid;
1689           break;
1690         } else {
1691           low = mid + 1;
1692         }
1693       } else {
1694         high = mid;
1695       }
1696     }
1697     funcStart = pageIndex.functionOffset(low) + firstLevelFunctionOffset
1698                                                               + sects.dso_base;
1699     if (low < last)
1700       funcEnd =
1701           pageIndex.functionOffset(low + 1) + firstLevelFunctionOffset
1702                                                               + sects.dso_base;
1703     else
1704       funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1705     if (pc < funcStart) {
1706       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
1707                            "level compressed unwind table. funcStart=0x%llX",
1708                             (uint64_t) pc, (uint64_t) funcStart);
1709       return false;
1710     }
1711     if (pc > funcEnd) {
1712       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
1713                           "level compressed unwind table. funcEnd=0x%llX",
1714                            (uint64_t) pc, (uint64_t) funcEnd);
1715       return false;
1716     }
1717     uint16_t encodingIndex = pageIndex.encodingIndex(low);
1718     if (encodingIndex < sectionHeader.commonEncodingsArrayCount()) {
1719       // encoding is in common table in section header
1720       encoding = _addressSpace.get32(
1721           sects.compact_unwind_section +
1722           sectionHeader.commonEncodingsArraySectionOffset() +
1723           encodingIndex * sizeof(uint32_t));
1724     } else {
1725       // encoding is in page specific table
1726       uint16_t pageEncodingIndex =
1727           encodingIndex - (uint16_t)sectionHeader.commonEncodingsArrayCount();
1728       encoding = _addressSpace.get32(secondLevelAddr +
1729                                      pageHeader.encodingsPageOffset() +
1730                                      pageEncodingIndex * sizeof(uint32_t));
1731     }
1732   } else {
1733     _LIBUNWIND_DEBUG_LOG("malformed __unwind_info at 0x%0llX bad second "
1734                          "level page",
1735                           (uint64_t) sects.compact_unwind_section);
1736     return false;
1737   }
1738 
1739   // look up LSDA, if encoding says function has one
1740   if (encoding & UNWIND_HAS_LSDA) {
1741     UnwindSectionLsdaArray<A> lsdaIndex(_addressSpace, lsdaArrayStartAddr);
1742     uint32_t funcStartOffset = (uint32_t)(funcStart - sects.dso_base);
1743     low = 0;
1744     high = (uint32_t)(lsdaArrayEndAddr - lsdaArrayStartAddr) /
1745                     sizeof(unwind_info_section_header_lsda_index_entry);
1746     // binary search looks for entry with exact match for functionOffset
1747     if (log)
1748       fprintf(stderr,
1749               "\tbinary search of lsda table for targetFunctionOffset=0x%08X\n",
1750               funcStartOffset);
1751     while (low < high) {
1752       uint32_t mid = (low + high) / 2;
1753       if (lsdaIndex.functionOffset(mid) == funcStartOffset) {
1754         lsda = lsdaIndex.lsdaOffset(mid) + sects.dso_base;
1755         break;
1756       } else if (lsdaIndex.functionOffset(mid) < funcStartOffset) {
1757         low = mid + 1;
1758       } else {
1759         high = mid;
1760       }
1761     }
1762     if (lsda == 0) {
1763       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with HAS_LSDA bit set for "
1764                     "pc=0x%0llX, but lsda table has no entry",
1765                     encoding, (uint64_t) pc);
1766       return false;
1767     }
1768   }
1769 
1770   // extact personality routine, if encoding says function has one
1771   uint32_t personalityIndex = (encoding & UNWIND_PERSONALITY_MASK) >>
1772                               (__builtin_ctz(UNWIND_PERSONALITY_MASK));
1773   if (personalityIndex != 0) {
1774     --personalityIndex; // change 1-based to zero-based index
1775     if (personalityIndex > sectionHeader.personalityArrayCount()) {
1776       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with personality index %d,  "
1777                             "but personality table has only %d entries",
1778                             encoding, personalityIndex,
1779                             sectionHeader.personalityArrayCount());
1780       return false;
1781     }
1782     int32_t personalityDelta = (int32_t)_addressSpace.get32(
1783         sects.compact_unwind_section +
1784         sectionHeader.personalityArraySectionOffset() +
1785         personalityIndex * sizeof(uint32_t));
1786     pint_t personalityPointer = sects.dso_base + (pint_t)personalityDelta;
1787     personality = _addressSpace.getP(personalityPointer);
1788     if (log)
1789       fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1790                       "personalityDelta=0x%08X, personality=0x%08llX\n",
1791               (uint64_t) pc, personalityDelta, (uint64_t) personality);
1792   }
1793 
1794   if (log)
1795     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1796                     "encoding=0x%08X, lsda=0x%08llX for funcStart=0x%llX\n",
1797             (uint64_t) pc, encoding, (uint64_t) lsda, (uint64_t) funcStart);
1798   _info.start_ip = funcStart;
1799   _info.end_ip = funcEnd;
1800   _info.lsda = lsda;
1801   _info.handler = personality;
1802   _info.gp = 0;
1803   _info.flags = 0;
1804   _info.format = encoding;
1805   _info.unwind_info = 0;
1806   _info.unwind_info_size = 0;
1807   _info.extra = sects.dso_base;
1808   return true;
1809 }
1810 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1811 
1812 
1813 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1814 template <typename A, typename R>
1815 bool UnwindCursor<A, R>::getInfoFromSEH(pint_t pc) {
1816   pint_t base;
1817   RUNTIME_FUNCTION *unwindEntry = lookUpSEHUnwindInfo(pc, &base);
1818   if (!unwindEntry) {
1819     _LIBUNWIND_DEBUG_LOG("\tpc not in table, pc=0x%llX", (uint64_t) pc);
1820     return false;
1821   }
1822   _info.gp = 0;
1823   _info.flags = 0;
1824   _info.format = 0;
1825   _info.unwind_info_size = sizeof(RUNTIME_FUNCTION);
1826   _info.unwind_info = reinterpret_cast<unw_word_t>(unwindEntry);
1827   _info.extra = base;
1828   _info.start_ip = base + unwindEntry->BeginAddress;
1829 #ifdef _LIBUNWIND_TARGET_X86_64
1830   _info.end_ip = base + unwindEntry->EndAddress;
1831   // Only fill in the handler and LSDA if they're stale.
1832   if (pc != getLastPC()) {
1833     UNWIND_INFO *xdata = reinterpret_cast<UNWIND_INFO *>(base + unwindEntry->UnwindData);
1834     if (xdata->Flags & (UNW_FLAG_EHANDLER|UNW_FLAG_UHANDLER)) {
1835       // The personality is given in the UNWIND_INFO itself. The LSDA immediately
1836       // follows the UNWIND_INFO. (This follows how both Clang and MSVC emit
1837       // these structures.)
1838       // N.B. UNWIND_INFO structs are DWORD-aligned.
1839       uint32_t lastcode = (xdata->CountOfCodes + 1) & ~1;
1840       const uint32_t *handler = reinterpret_cast<uint32_t *>(&xdata->UnwindCodes[lastcode]);
1841       _info.lsda = reinterpret_cast<unw_word_t>(handler+1);
1842       if (*handler) {
1843         _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
1844       } else
1845         _info.handler = 0;
1846     } else {
1847       _info.lsda = 0;
1848       _info.handler = 0;
1849     }
1850   }
1851 #elif defined(_LIBUNWIND_TARGET_ARM)
1852   _info.end_ip = _info.start_ip + unwindEntry->FunctionLength;
1853   _info.lsda = 0; // FIXME
1854   _info.handler = 0; // FIXME
1855 #endif
1856   setLastPC(pc);
1857   return true;
1858 }
1859 #endif
1860 
1861 
1862 template <typename A, typename R>
1863 void UnwindCursor<A, R>::setInfoBasedOnIPRegister(bool isReturnAddress) {
1864   pint_t pc = (pint_t)this->getReg(UNW_REG_IP);
1865 #if defined(_LIBUNWIND_ARM_EHABI)
1866   // Remove the thumb bit so the IP represents the actual instruction address.
1867   // This matches the behaviour of _Unwind_GetIP on arm.
1868   pc &= (pint_t)~0x1;
1869 #endif
1870 
1871   // Exit early if at the top of the stack.
1872   if (pc == 0) {
1873     _unwindInfoMissing = true;
1874     return;
1875   }
1876 
1877   // If the last line of a function is a "throw" the compiler sometimes
1878   // emits no instructions after the call to __cxa_throw.  This means
1879   // the return address is actually the start of the next function.
1880   // To disambiguate this, back up the pc when we know it is a return
1881   // address.
1882   if (isReturnAddress)
1883     --pc;
1884 
1885   // Ask address space object to find unwind sections for this pc.
1886   UnwindInfoSections sects;
1887   bool have_sects = false;
1888   if (uwis_cache.getUnwindInfoSectionsForPC(pc, sects))
1889     have_sects = true;
1890   else if (_addressSpace.findUnwindSections(pc, sects)) {
1891     uwis_cache.setUnwindInfoSectionsForPC(pc, sects);
1892     have_sects = true;
1893   }
1894   if (have_sects) {
1895 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1896     // If there is a compact unwind encoding table, look there first.
1897     if (sects.compact_unwind_section != 0) {
1898       if (this->getInfoFromCompactEncodingSection(pc, sects)) {
1899   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1900         // Found info in table, done unless encoding says to use dwarf.
1901         uint32_t dwarfOffset;
1902         if ((sects.dwarf_section != 0) && compactSaysUseDwarf(&dwarfOffset)) {
1903           if (this->getInfoFromDwarfSection(pc, sects, dwarfOffset)) {
1904             // found info in dwarf, done
1905             return;
1906           }
1907         }
1908   #endif
1909         // If unwind table has entry, but entry says there is no unwind info,
1910         // record that we have no unwind info.
1911         if (_info.format == 0)
1912           _unwindInfoMissing = true;
1913         return;
1914       }
1915     }
1916 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1917 
1918 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1919     // If there is SEH unwind info, look there next.
1920     if (this->getInfoFromSEH(pc))
1921       return;
1922 #endif
1923 
1924 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1925     // If there is dwarf unwind info, look there next.
1926     if (sects.dwarf_section != 0) {
1927       if (this->getInfoFromDwarfSection(pc, sects)) {
1928         // found info in dwarf, done
1929         return;
1930       }
1931     }
1932 #endif
1933 
1934 #if defined(_LIBUNWIND_ARM_EHABI)
1935     // If there is ARM EHABI unwind info, look there next.
1936     if (sects.arm_section != 0 && this->getInfoFromEHABISection(pc, sects))
1937       return;
1938 #endif
1939   }
1940 
1941 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1942   // There is no static unwind info for this pc. Look to see if an FDE was
1943   // dynamically registered for it.
1944   pint_t cachedFDE = DwarfFDECache<A>::findFDE(0, pc);
1945   if (cachedFDE != 0) {
1946     CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;
1947     CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;
1948     const char *msg = CFI_Parser<A>::decodeFDE(_addressSpace,
1949                                                 cachedFDE, &fdeInfo, &cieInfo);
1950     if (msg == NULL) {
1951       typename CFI_Parser<A>::PrologInfo prolog;
1952       if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo,
1953                                               pc, R::getArch(), &prolog)) {
1954         // save off parsed FDE info
1955         _info.start_ip         = fdeInfo.pcStart;
1956         _info.end_ip           = fdeInfo.pcEnd;
1957         _info.lsda             = fdeInfo.lsda;
1958         _info.handler          = cieInfo.personality;
1959         _info.gp               = prolog.spExtraArgSize;
1960                                   // Some frameless functions need SP
1961                                   // altered when resuming in function.
1962         _info.flags            = 0;
1963         _info.format           = dwarfEncoding();
1964         _info.unwind_info      = fdeInfo.fdeStart;
1965         _info.unwind_info_size = (uint32_t)fdeInfo.fdeLength;
1966         _info.extra            = 0;
1967         return;
1968       }
1969     }
1970   }
1971 
1972   // Lastly, ask AddressSpace object about platform specific ways to locate
1973   // other FDEs.
1974   pint_t fde;
1975   if (_addressSpace.findOtherFDE(pc, fde)) {
1976     CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;
1977     CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;
1978     if (!CFI_Parser<A>::decodeFDE(_addressSpace, fde, &fdeInfo, &cieInfo)) {
1979       // Double check this FDE is for a function that includes the pc.
1980       if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd)) {
1981         typename CFI_Parser<A>::PrologInfo prolog;
1982         if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo,
1983                                                 pc, R::getArch(), &prolog)) {
1984           // save off parsed FDE info
1985           _info.start_ip         = fdeInfo.pcStart;
1986           _info.end_ip           = fdeInfo.pcEnd;
1987           _info.lsda             = fdeInfo.lsda;
1988           _info.handler          = cieInfo.personality;
1989           _info.gp               = prolog.spExtraArgSize;
1990           _info.flags            = 0;
1991           _info.format           = dwarfEncoding();
1992           _info.unwind_info      = fdeInfo.fdeStart;
1993           _info.unwind_info_size = (uint32_t)fdeInfo.fdeLength;
1994           _info.extra            = 0;
1995           return;
1996         }
1997       }
1998     }
1999   }
2000 #endif // #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2001 
2002   // no unwind info, flag that we can't reliably unwind
2003   _unwindInfoMissing = true;
2004 }
2005 
2006 template <typename A, typename R>
2007 int UnwindCursor<A, R>::step() {
2008   // Bottom of stack is defined is when unwind info cannot be found.
2009   if (_unwindInfoMissing)
2010     return UNW_STEP_END;
2011 
2012   // Use unwinding info to modify register set as if function returned.
2013   int result;
2014 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
2015   result = this->stepWithCompactEncoding();
2016 #elif defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
2017   result = this->stepWithSEHData();
2018 #elif defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2019   result = this->stepWithDwarfFDE();
2020 #elif defined(_LIBUNWIND_ARM_EHABI)
2021   result = this->stepWithEHABI();
2022 #else
2023   #error Need _LIBUNWIND_SUPPORT_COMPACT_UNWIND or \
2024               _LIBUNWIND_SUPPORT_SEH_UNWIND or \
2025               _LIBUNWIND_SUPPORT_DWARF_UNWIND or \
2026               _LIBUNWIND_ARM_EHABI
2027 #endif
2028 
2029   // update info based on new PC
2030   if (result == UNW_STEP_SUCCESS) {
2031     this->setInfoBasedOnIPRegister(true);
2032     if (_unwindInfoMissing)
2033       return UNW_STEP_END;
2034   }
2035 
2036   return result;
2037 }
2038 
2039 template <typename A, typename R>
2040 void UnwindCursor<A, R>::getInfo(unw_proc_info_t *info) {
2041   if (_unwindInfoMissing)
2042     memset(info, 0, sizeof(*info));
2043   else
2044     *info = _info;
2045 }
2046 
2047 template <typename A, typename R>
2048 bool UnwindCursor<A, R>::getFunctionName(char *buf, size_t bufLen,
2049                                                            unw_word_t *offset) {
2050   return _addressSpace.findFunctionName((pint_t)this->getReg(UNW_REG_IP),
2051                                          buf, bufLen, offset);
2052 }
2053 
2054 } // namespace libunwind
2055 
2056 #endif // __UNWINDCURSOR_HPP__
2057