1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //
8 // C++ interface to lower levels of libunwind
9 //===----------------------------------------------------------------------===//
10 
11 #ifndef __UNWINDCURSOR_HPP__
12 #define __UNWINDCURSOR_HPP__
13 
14 #include "cet_unwind.h"
15 #include <stdint.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <unwind.h>
19 
20 #ifdef _WIN32
21   #include <windows.h>
22   #include <ntverp.h>
23 #endif
24 #ifdef __APPLE__
25   #include <mach-o/dyld.h>
26 #endif
27 #ifdef _AIX
28 #include <dlfcn.h>
29 #include <sys/debug.h>
30 #include <sys/pseg.h>
31 #endif
32 
33 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
34 // Provide a definition for the DISPATCHER_CONTEXT struct for old (Win7 and
35 // earlier) SDKs.
36 // MinGW-w64 has always provided this struct.
37   #if defined(_WIN32) && defined(_LIBUNWIND_TARGET_X86_64) && \
38       !defined(__MINGW32__) && VER_PRODUCTBUILD < 8000
39 struct _DISPATCHER_CONTEXT {
40   ULONG64 ControlPc;
41   ULONG64 ImageBase;
42   PRUNTIME_FUNCTION FunctionEntry;
43   ULONG64 EstablisherFrame;
44   ULONG64 TargetIp;
45   PCONTEXT ContextRecord;
46   PEXCEPTION_ROUTINE LanguageHandler;
47   PVOID HandlerData;
48   PUNWIND_HISTORY_TABLE HistoryTable;
49   ULONG ScopeIndex;
50   ULONG Fill0;
51 };
52   #endif
53 
54 struct UNWIND_INFO {
55   uint8_t Version : 3;
56   uint8_t Flags : 5;
57   uint8_t SizeOfProlog;
58   uint8_t CountOfCodes;
59   uint8_t FrameRegister : 4;
60   uint8_t FrameOffset : 4;
61   uint16_t UnwindCodes[2];
62 };
63 
64 extern "C" _Unwind_Reason_Code __libunwind_seh_personality(
65     int, _Unwind_Action, uint64_t, _Unwind_Exception *,
66     struct _Unwind_Context *);
67 
68 #endif
69 
70 #include "config.h"
71 
72 #include "AddressSpace.hpp"
73 #include "CompactUnwinder.hpp"
74 #include "config.h"
75 #include "DwarfInstructions.hpp"
76 #include "EHHeaderParser.hpp"
77 #include "libunwind.h"
78 #include "Registers.hpp"
79 #include "RWMutex.hpp"
80 #include "Unwind-EHABI.h"
81 
82 namespace libunwind {
83 
84 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
85 /// Cache of recently found FDEs.
86 template <typename A>
87 class _LIBUNWIND_HIDDEN DwarfFDECache {
88   typedef typename A::pint_t pint_t;
89 public:
90   static constexpr pint_t kSearchAll = static_cast<pint_t>(-1);
91   static pint_t findFDE(pint_t mh, pint_t pc);
92   static void add(pint_t mh, pint_t ip_start, pint_t ip_end, pint_t fde);
93   static void removeAllIn(pint_t mh);
94   static void iterateCacheEntries(void (*func)(unw_word_t ip_start,
95                                                unw_word_t ip_end,
96                                                unw_word_t fde, unw_word_t mh));
97 
98 private:
99 
100   struct entry {
101     pint_t mh;
102     pint_t ip_start;
103     pint_t ip_end;
104     pint_t fde;
105   };
106 
107   // These fields are all static to avoid needing an initializer.
108   // There is only one instance of this class per process.
109   static RWMutex _lock;
110 #ifdef __APPLE__
111   static void dyldUnloadHook(const struct mach_header *mh, intptr_t slide);
112   static bool _registeredForDyldUnloads;
113 #endif
114   static entry *_buffer;
115   static entry *_bufferUsed;
116   static entry *_bufferEnd;
117   static entry _initialBuffer[64];
118 };
119 
120 template <typename A>
121 typename DwarfFDECache<A>::entry *
122 DwarfFDECache<A>::_buffer = _initialBuffer;
123 
124 template <typename A>
125 typename DwarfFDECache<A>::entry *
126 DwarfFDECache<A>::_bufferUsed = _initialBuffer;
127 
128 template <typename A>
129 typename DwarfFDECache<A>::entry *
130 DwarfFDECache<A>::_bufferEnd = &_initialBuffer[64];
131 
132 template <typename A>
133 typename DwarfFDECache<A>::entry DwarfFDECache<A>::_initialBuffer[64];
134 
135 template <typename A>
136 RWMutex DwarfFDECache<A>::_lock;
137 
138 #ifdef __APPLE__
139 template <typename A>
140 bool DwarfFDECache<A>::_registeredForDyldUnloads = false;
141 #endif
142 
143 template <typename A>
144 typename A::pint_t DwarfFDECache<A>::findFDE(pint_t mh, pint_t pc) {
145   pint_t result = 0;
146   _LIBUNWIND_LOG_IF_FALSE(_lock.lock_shared());
147   for (entry *p = _buffer; p < _bufferUsed; ++p) {
148     if ((mh == p->mh) || (mh == kSearchAll)) {
149       if ((p->ip_start <= pc) && (pc < p->ip_end)) {
150         result = p->fde;
151         break;
152       }
153     }
154   }
155   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock_shared());
156   return result;
157 }
158 
159 template <typename A>
160 void DwarfFDECache<A>::add(pint_t mh, pint_t ip_start, pint_t ip_end,
161                            pint_t fde) {
162 #if !defined(_LIBUNWIND_NO_HEAP)
163   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
164   if (_bufferUsed >= _bufferEnd) {
165     size_t oldSize = (size_t)(_bufferEnd - _buffer);
166     size_t newSize = oldSize * 4;
167     // Can't use operator new (we are below it).
168     entry *newBuffer = (entry *)malloc(newSize * sizeof(entry));
169     memcpy(newBuffer, _buffer, oldSize * sizeof(entry));
170     if (_buffer != _initialBuffer)
171       free(_buffer);
172     _buffer = newBuffer;
173     _bufferUsed = &newBuffer[oldSize];
174     _bufferEnd = &newBuffer[newSize];
175   }
176   _bufferUsed->mh = mh;
177   _bufferUsed->ip_start = ip_start;
178   _bufferUsed->ip_end = ip_end;
179   _bufferUsed->fde = fde;
180   ++_bufferUsed;
181 #ifdef __APPLE__
182   if (!_registeredForDyldUnloads) {
183     _dyld_register_func_for_remove_image(&dyldUnloadHook);
184     _registeredForDyldUnloads = true;
185   }
186 #endif
187   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
188 #endif
189 }
190 
191 template <typename A>
192 void DwarfFDECache<A>::removeAllIn(pint_t mh) {
193   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
194   entry *d = _buffer;
195   for (const entry *s = _buffer; s < _bufferUsed; ++s) {
196     if (s->mh != mh) {
197       if (d != s)
198         *d = *s;
199       ++d;
200     }
201   }
202   _bufferUsed = d;
203   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
204 }
205 
206 #ifdef __APPLE__
207 template <typename A>
208 void DwarfFDECache<A>::dyldUnloadHook(const struct mach_header *mh, intptr_t ) {
209   removeAllIn((pint_t) mh);
210 }
211 #endif
212 
213 template <typename A>
214 void DwarfFDECache<A>::iterateCacheEntries(void (*func)(
215     unw_word_t ip_start, unw_word_t ip_end, unw_word_t fde, unw_word_t mh)) {
216   _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
217   for (entry *p = _buffer; p < _bufferUsed; ++p) {
218     (*func)(p->ip_start, p->ip_end, p->fde, p->mh);
219   }
220   _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
221 }
222 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
223 
224 
225 #define arrayoffsetof(type, index, field) ((size_t)(&((type *)0)[index].field))
226 
227 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
228 template <typename A> class UnwindSectionHeader {
229 public:
230   UnwindSectionHeader(A &addressSpace, typename A::pint_t addr)
231       : _addressSpace(addressSpace), _addr(addr) {}
232 
233   uint32_t version() const {
234     return _addressSpace.get32(_addr +
235                                offsetof(unwind_info_section_header, version));
236   }
237   uint32_t commonEncodingsArraySectionOffset() const {
238     return _addressSpace.get32(_addr +
239                                offsetof(unwind_info_section_header,
240                                         commonEncodingsArraySectionOffset));
241   }
242   uint32_t commonEncodingsArrayCount() const {
243     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
244                                                 commonEncodingsArrayCount));
245   }
246   uint32_t personalityArraySectionOffset() const {
247     return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
248                                                 personalityArraySectionOffset));
249   }
250   uint32_t personalityArrayCount() const {
251     return _addressSpace.get32(
252         _addr + offsetof(unwind_info_section_header, personalityArrayCount));
253   }
254   uint32_t indexSectionOffset() const {
255     return _addressSpace.get32(
256         _addr + offsetof(unwind_info_section_header, indexSectionOffset));
257   }
258   uint32_t indexCount() const {
259     return _addressSpace.get32(
260         _addr + offsetof(unwind_info_section_header, indexCount));
261   }
262 
263 private:
264   A                     &_addressSpace;
265   typename A::pint_t     _addr;
266 };
267 
268 template <typename A> class UnwindSectionIndexArray {
269 public:
270   UnwindSectionIndexArray(A &addressSpace, typename A::pint_t addr)
271       : _addressSpace(addressSpace), _addr(addr) {}
272 
273   uint32_t functionOffset(uint32_t index) const {
274     return _addressSpace.get32(
275         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
276                               functionOffset));
277   }
278   uint32_t secondLevelPagesSectionOffset(uint32_t index) const {
279     return _addressSpace.get32(
280         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
281                               secondLevelPagesSectionOffset));
282   }
283   uint32_t lsdaIndexArraySectionOffset(uint32_t index) const {
284     return _addressSpace.get32(
285         _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
286                               lsdaIndexArraySectionOffset));
287   }
288 
289 private:
290   A                   &_addressSpace;
291   typename A::pint_t   _addr;
292 };
293 
294 template <typename A> class UnwindSectionRegularPageHeader {
295 public:
296   UnwindSectionRegularPageHeader(A &addressSpace, typename A::pint_t addr)
297       : _addressSpace(addressSpace), _addr(addr) {}
298 
299   uint32_t kind() const {
300     return _addressSpace.get32(
301         _addr + offsetof(unwind_info_regular_second_level_page_header, kind));
302   }
303   uint16_t entryPageOffset() const {
304     return _addressSpace.get16(
305         _addr + offsetof(unwind_info_regular_second_level_page_header,
306                          entryPageOffset));
307   }
308   uint16_t entryCount() const {
309     return _addressSpace.get16(
310         _addr +
311         offsetof(unwind_info_regular_second_level_page_header, entryCount));
312   }
313 
314 private:
315   A &_addressSpace;
316   typename A::pint_t _addr;
317 };
318 
319 template <typename A> class UnwindSectionRegularArray {
320 public:
321   UnwindSectionRegularArray(A &addressSpace, typename A::pint_t addr)
322       : _addressSpace(addressSpace), _addr(addr) {}
323 
324   uint32_t functionOffset(uint32_t index) const {
325     return _addressSpace.get32(
326         _addr + arrayoffsetof(unwind_info_regular_second_level_entry, index,
327                               functionOffset));
328   }
329   uint32_t encoding(uint32_t index) const {
330     return _addressSpace.get32(
331         _addr +
332         arrayoffsetof(unwind_info_regular_second_level_entry, index, encoding));
333   }
334 
335 private:
336   A &_addressSpace;
337   typename A::pint_t _addr;
338 };
339 
340 template <typename A> class UnwindSectionCompressedPageHeader {
341 public:
342   UnwindSectionCompressedPageHeader(A &addressSpace, typename A::pint_t addr)
343       : _addressSpace(addressSpace), _addr(addr) {}
344 
345   uint32_t kind() const {
346     return _addressSpace.get32(
347         _addr +
348         offsetof(unwind_info_compressed_second_level_page_header, kind));
349   }
350   uint16_t entryPageOffset() const {
351     return _addressSpace.get16(
352         _addr + offsetof(unwind_info_compressed_second_level_page_header,
353                          entryPageOffset));
354   }
355   uint16_t entryCount() const {
356     return _addressSpace.get16(
357         _addr +
358         offsetof(unwind_info_compressed_second_level_page_header, entryCount));
359   }
360   uint16_t encodingsPageOffset() const {
361     return _addressSpace.get16(
362         _addr + offsetof(unwind_info_compressed_second_level_page_header,
363                          encodingsPageOffset));
364   }
365   uint16_t encodingsCount() const {
366     return _addressSpace.get16(
367         _addr + offsetof(unwind_info_compressed_second_level_page_header,
368                          encodingsCount));
369   }
370 
371 private:
372   A &_addressSpace;
373   typename A::pint_t _addr;
374 };
375 
376 template <typename A> class UnwindSectionCompressedArray {
377 public:
378   UnwindSectionCompressedArray(A &addressSpace, typename A::pint_t addr)
379       : _addressSpace(addressSpace), _addr(addr) {}
380 
381   uint32_t functionOffset(uint32_t index) const {
382     return UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(
383         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
384   }
385   uint16_t encodingIndex(uint32_t index) const {
386     return UNWIND_INFO_COMPRESSED_ENTRY_ENCODING_INDEX(
387         _addressSpace.get32(_addr + index * sizeof(uint32_t)));
388   }
389 
390 private:
391   A &_addressSpace;
392   typename A::pint_t _addr;
393 };
394 
395 template <typename A> class UnwindSectionLsdaArray {
396 public:
397   UnwindSectionLsdaArray(A &addressSpace, typename A::pint_t addr)
398       : _addressSpace(addressSpace), _addr(addr) {}
399 
400   uint32_t functionOffset(uint32_t index) const {
401     return _addressSpace.get32(
402         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
403                               index, functionOffset));
404   }
405   uint32_t lsdaOffset(uint32_t index) const {
406     return _addressSpace.get32(
407         _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
408                               index, lsdaOffset));
409   }
410 
411 private:
412   A                   &_addressSpace;
413   typename A::pint_t   _addr;
414 };
415 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
416 
417 class _LIBUNWIND_HIDDEN AbstractUnwindCursor {
418 public:
419   // NOTE: provide a class specific placement deallocation function (S5.3.4 p20)
420   // This avoids an unnecessary dependency to libc++abi.
421   void operator delete(void *, size_t) {}
422 
423   virtual ~AbstractUnwindCursor() {}
424   virtual bool validReg(int) { _LIBUNWIND_ABORT("validReg not implemented"); }
425   virtual unw_word_t getReg(int) { _LIBUNWIND_ABORT("getReg not implemented"); }
426   virtual void setReg(int, unw_word_t) {
427     _LIBUNWIND_ABORT("setReg not implemented");
428   }
429   virtual bool validFloatReg(int) {
430     _LIBUNWIND_ABORT("validFloatReg not implemented");
431   }
432   virtual unw_fpreg_t getFloatReg(int) {
433     _LIBUNWIND_ABORT("getFloatReg not implemented");
434   }
435   virtual void setFloatReg(int, unw_fpreg_t) {
436     _LIBUNWIND_ABORT("setFloatReg not implemented");
437   }
438   virtual int step() { _LIBUNWIND_ABORT("step not implemented"); }
439   virtual void getInfo(unw_proc_info_t *) {
440     _LIBUNWIND_ABORT("getInfo not implemented");
441   }
442   virtual void jumpto() { _LIBUNWIND_ABORT("jumpto not implemented"); }
443   virtual bool isSignalFrame() {
444     _LIBUNWIND_ABORT("isSignalFrame not implemented");
445   }
446   virtual bool getFunctionName(char *, size_t, unw_word_t *) {
447     _LIBUNWIND_ABORT("getFunctionName not implemented");
448   }
449   virtual void setInfoBasedOnIPRegister(bool = false) {
450     _LIBUNWIND_ABORT("setInfoBasedOnIPRegister not implemented");
451   }
452   virtual const char *getRegisterName(int) {
453     _LIBUNWIND_ABORT("getRegisterName not implemented");
454   }
455 #ifdef __arm__
456   virtual void saveVFPAsX() { _LIBUNWIND_ABORT("saveVFPAsX not implemented"); }
457 #endif
458 
459 #ifdef _AIX
460   virtual uintptr_t getDataRelBase() {
461     _LIBUNWIND_ABORT("getDataRelBase not implemented");
462   }
463 #endif
464 
465 #if defined(_LIBUNWIND_USE_CET)
466   virtual void *get_registers() {
467     _LIBUNWIND_ABORT("get_registers not implemented");
468   }
469 #endif
470 };
471 
472 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) && defined(_WIN32)
473 
474 /// \c UnwindCursor contains all state (including all register values) during
475 /// an unwind.  This is normally stack-allocated inside a unw_cursor_t.
476 template <typename A, typename R>
477 class UnwindCursor : public AbstractUnwindCursor {
478   typedef typename A::pint_t pint_t;
479 public:
480                       UnwindCursor(unw_context_t *context, A &as);
481                       UnwindCursor(CONTEXT *context, A &as);
482                       UnwindCursor(A &as, void *threadArg);
483   virtual             ~UnwindCursor() {}
484   virtual bool        validReg(int);
485   virtual unw_word_t  getReg(int);
486   virtual void        setReg(int, unw_word_t);
487   virtual bool        validFloatReg(int);
488   virtual unw_fpreg_t getFloatReg(int);
489   virtual void        setFloatReg(int, unw_fpreg_t);
490   virtual int         step();
491   virtual void        getInfo(unw_proc_info_t *);
492   virtual void        jumpto();
493   virtual bool        isSignalFrame();
494   virtual bool        getFunctionName(char *buf, size_t len, unw_word_t *off);
495   virtual void        setInfoBasedOnIPRegister(bool isReturnAddress = false);
496   virtual const char *getRegisterName(int num);
497 #ifdef __arm__
498   virtual void        saveVFPAsX();
499 #endif
500 
501   DISPATCHER_CONTEXT *getDispatcherContext() { return &_dispContext; }
502   void setDispatcherContext(DISPATCHER_CONTEXT *disp) { _dispContext = *disp; }
503 
504   // libunwind does not and should not depend on C++ library which means that we
505   // need our own defition of inline placement new.
506   static void *operator new(size_t, UnwindCursor<A, R> *p) { return p; }
507 
508 private:
509 
510   pint_t getLastPC() const { return _dispContext.ControlPc; }
511   void setLastPC(pint_t pc) { _dispContext.ControlPc = pc; }
512   RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
513     _dispContext.FunctionEntry = RtlLookupFunctionEntry(pc,
514                                                         &_dispContext.ImageBase,
515                                                         _dispContext.HistoryTable);
516     *base = _dispContext.ImageBase;
517     return _dispContext.FunctionEntry;
518   }
519   bool getInfoFromSEH(pint_t pc);
520   int stepWithSEHData() {
521     _dispContext.LanguageHandler = RtlVirtualUnwind(UNW_FLAG_UHANDLER,
522                                                     _dispContext.ImageBase,
523                                                     _dispContext.ControlPc,
524                                                     _dispContext.FunctionEntry,
525                                                     _dispContext.ContextRecord,
526                                                     &_dispContext.HandlerData,
527                                                     &_dispContext.EstablisherFrame,
528                                                     NULL);
529     // Update some fields of the unwind info now, since we have them.
530     _info.lsda = reinterpret_cast<unw_word_t>(_dispContext.HandlerData);
531     if (_dispContext.LanguageHandler) {
532       _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
533     } else
534       _info.handler = 0;
535     return UNW_STEP_SUCCESS;
536   }
537 
538   A                   &_addressSpace;
539   unw_proc_info_t      _info;
540   DISPATCHER_CONTEXT   _dispContext;
541   CONTEXT              _msContext;
542   UNWIND_HISTORY_TABLE _histTable;
543   bool                 _unwindInfoMissing;
544 };
545 
546 
547 template <typename A, typename R>
548 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
549     : _addressSpace(as), _unwindInfoMissing(false) {
550   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
551                 "UnwindCursor<> does not fit in unw_cursor_t");
552   static_assert((alignof(UnwindCursor<A, R>) <= alignof(unw_cursor_t)),
553                 "UnwindCursor<> requires more alignment than unw_cursor_t");
554   memset(&_info, 0, sizeof(_info));
555   memset(&_histTable, 0, sizeof(_histTable));
556   _dispContext.ContextRecord = &_msContext;
557   _dispContext.HistoryTable = &_histTable;
558   // Initialize MS context from ours.
559   R r(context);
560   _msContext.ContextFlags = CONTEXT_CONTROL|CONTEXT_INTEGER|CONTEXT_FLOATING_POINT;
561 #if defined(_LIBUNWIND_TARGET_X86_64)
562   _msContext.Rax = r.getRegister(UNW_X86_64_RAX);
563   _msContext.Rcx = r.getRegister(UNW_X86_64_RCX);
564   _msContext.Rdx = r.getRegister(UNW_X86_64_RDX);
565   _msContext.Rbx = r.getRegister(UNW_X86_64_RBX);
566   _msContext.Rsp = r.getRegister(UNW_X86_64_RSP);
567   _msContext.Rbp = r.getRegister(UNW_X86_64_RBP);
568   _msContext.Rsi = r.getRegister(UNW_X86_64_RSI);
569   _msContext.Rdi = r.getRegister(UNW_X86_64_RDI);
570   _msContext.R8 = r.getRegister(UNW_X86_64_R8);
571   _msContext.R9 = r.getRegister(UNW_X86_64_R9);
572   _msContext.R10 = r.getRegister(UNW_X86_64_R10);
573   _msContext.R11 = r.getRegister(UNW_X86_64_R11);
574   _msContext.R12 = r.getRegister(UNW_X86_64_R12);
575   _msContext.R13 = r.getRegister(UNW_X86_64_R13);
576   _msContext.R14 = r.getRegister(UNW_X86_64_R14);
577   _msContext.R15 = r.getRegister(UNW_X86_64_R15);
578   _msContext.Rip = r.getRegister(UNW_REG_IP);
579   union {
580     v128 v;
581     M128A m;
582   } t;
583   t.v = r.getVectorRegister(UNW_X86_64_XMM0);
584   _msContext.Xmm0 = t.m;
585   t.v = r.getVectorRegister(UNW_X86_64_XMM1);
586   _msContext.Xmm1 = t.m;
587   t.v = r.getVectorRegister(UNW_X86_64_XMM2);
588   _msContext.Xmm2 = t.m;
589   t.v = r.getVectorRegister(UNW_X86_64_XMM3);
590   _msContext.Xmm3 = t.m;
591   t.v = r.getVectorRegister(UNW_X86_64_XMM4);
592   _msContext.Xmm4 = t.m;
593   t.v = r.getVectorRegister(UNW_X86_64_XMM5);
594   _msContext.Xmm5 = t.m;
595   t.v = r.getVectorRegister(UNW_X86_64_XMM6);
596   _msContext.Xmm6 = t.m;
597   t.v = r.getVectorRegister(UNW_X86_64_XMM7);
598   _msContext.Xmm7 = t.m;
599   t.v = r.getVectorRegister(UNW_X86_64_XMM8);
600   _msContext.Xmm8 = t.m;
601   t.v = r.getVectorRegister(UNW_X86_64_XMM9);
602   _msContext.Xmm9 = t.m;
603   t.v = r.getVectorRegister(UNW_X86_64_XMM10);
604   _msContext.Xmm10 = t.m;
605   t.v = r.getVectorRegister(UNW_X86_64_XMM11);
606   _msContext.Xmm11 = t.m;
607   t.v = r.getVectorRegister(UNW_X86_64_XMM12);
608   _msContext.Xmm12 = t.m;
609   t.v = r.getVectorRegister(UNW_X86_64_XMM13);
610   _msContext.Xmm13 = t.m;
611   t.v = r.getVectorRegister(UNW_X86_64_XMM14);
612   _msContext.Xmm14 = t.m;
613   t.v = r.getVectorRegister(UNW_X86_64_XMM15);
614   _msContext.Xmm15 = t.m;
615 #elif defined(_LIBUNWIND_TARGET_ARM)
616   _msContext.R0 = r.getRegister(UNW_ARM_R0);
617   _msContext.R1 = r.getRegister(UNW_ARM_R1);
618   _msContext.R2 = r.getRegister(UNW_ARM_R2);
619   _msContext.R3 = r.getRegister(UNW_ARM_R3);
620   _msContext.R4 = r.getRegister(UNW_ARM_R4);
621   _msContext.R5 = r.getRegister(UNW_ARM_R5);
622   _msContext.R6 = r.getRegister(UNW_ARM_R6);
623   _msContext.R7 = r.getRegister(UNW_ARM_R7);
624   _msContext.R8 = r.getRegister(UNW_ARM_R8);
625   _msContext.R9 = r.getRegister(UNW_ARM_R9);
626   _msContext.R10 = r.getRegister(UNW_ARM_R10);
627   _msContext.R11 = r.getRegister(UNW_ARM_R11);
628   _msContext.R12 = r.getRegister(UNW_ARM_R12);
629   _msContext.Sp = r.getRegister(UNW_ARM_SP);
630   _msContext.Lr = r.getRegister(UNW_ARM_LR);
631   _msContext.Pc = r.getRegister(UNW_ARM_IP);
632   for (int i = UNW_ARM_D0; i <= UNW_ARM_D31; ++i) {
633     union {
634       uint64_t w;
635       double d;
636     } d;
637     d.d = r.getFloatRegister(i);
638     _msContext.D[i - UNW_ARM_D0] = d.w;
639   }
640 #elif defined(_LIBUNWIND_TARGET_AARCH64)
641   for (int i = UNW_AARCH64_X0; i <= UNW_ARM64_X30; ++i)
642     _msContext.X[i - UNW_AARCH64_X0] = r.getRegister(i);
643   _msContext.Sp = r.getRegister(UNW_REG_SP);
644   _msContext.Pc = r.getRegister(UNW_REG_IP);
645   for (int i = UNW_AARCH64_V0; i <= UNW_ARM64_D31; ++i)
646     _msContext.V[i - UNW_AARCH64_V0].D[0] = r.getFloatRegister(i);
647 #endif
648 }
649 
650 template <typename A, typename R>
651 UnwindCursor<A, R>::UnwindCursor(CONTEXT *context, A &as)
652     : _addressSpace(as), _unwindInfoMissing(false) {
653   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
654                 "UnwindCursor<> does not fit in unw_cursor_t");
655   memset(&_info, 0, sizeof(_info));
656   memset(&_histTable, 0, sizeof(_histTable));
657   _dispContext.ContextRecord = &_msContext;
658   _dispContext.HistoryTable = &_histTable;
659   _msContext = *context;
660 }
661 
662 
663 template <typename A, typename R>
664 bool UnwindCursor<A, R>::validReg(int regNum) {
665   if (regNum == UNW_REG_IP || regNum == UNW_REG_SP) return true;
666 #if defined(_LIBUNWIND_TARGET_X86_64)
667   if (regNum >= UNW_X86_64_RAX && regNum <= UNW_X86_64_R15) return true;
668 #elif defined(_LIBUNWIND_TARGET_ARM)
669   if ((regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) ||
670       regNum == UNW_ARM_RA_AUTH_CODE)
671     return true;
672 #elif defined(_LIBUNWIND_TARGET_AARCH64)
673   if (regNum >= UNW_AARCH64_X0 && regNum <= UNW_ARM64_X30) return true;
674 #endif
675   return false;
676 }
677 
678 template <typename A, typename R>
679 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
680   switch (regNum) {
681 #if defined(_LIBUNWIND_TARGET_X86_64)
682   case UNW_REG_IP: return _msContext.Rip;
683   case UNW_X86_64_RAX: return _msContext.Rax;
684   case UNW_X86_64_RDX: return _msContext.Rdx;
685   case UNW_X86_64_RCX: return _msContext.Rcx;
686   case UNW_X86_64_RBX: return _msContext.Rbx;
687   case UNW_REG_SP:
688   case UNW_X86_64_RSP: return _msContext.Rsp;
689   case UNW_X86_64_RBP: return _msContext.Rbp;
690   case UNW_X86_64_RSI: return _msContext.Rsi;
691   case UNW_X86_64_RDI: return _msContext.Rdi;
692   case UNW_X86_64_R8: return _msContext.R8;
693   case UNW_X86_64_R9: return _msContext.R9;
694   case UNW_X86_64_R10: return _msContext.R10;
695   case UNW_X86_64_R11: return _msContext.R11;
696   case UNW_X86_64_R12: return _msContext.R12;
697   case UNW_X86_64_R13: return _msContext.R13;
698   case UNW_X86_64_R14: return _msContext.R14;
699   case UNW_X86_64_R15: return _msContext.R15;
700 #elif defined(_LIBUNWIND_TARGET_ARM)
701   case UNW_ARM_R0: return _msContext.R0;
702   case UNW_ARM_R1: return _msContext.R1;
703   case UNW_ARM_R2: return _msContext.R2;
704   case UNW_ARM_R3: return _msContext.R3;
705   case UNW_ARM_R4: return _msContext.R4;
706   case UNW_ARM_R5: return _msContext.R5;
707   case UNW_ARM_R6: return _msContext.R6;
708   case UNW_ARM_R7: return _msContext.R7;
709   case UNW_ARM_R8: return _msContext.R8;
710   case UNW_ARM_R9: return _msContext.R9;
711   case UNW_ARM_R10: return _msContext.R10;
712   case UNW_ARM_R11: return _msContext.R11;
713   case UNW_ARM_R12: return _msContext.R12;
714   case UNW_REG_SP:
715   case UNW_ARM_SP: return _msContext.Sp;
716   case UNW_ARM_LR: return _msContext.Lr;
717   case UNW_REG_IP:
718   case UNW_ARM_IP: return _msContext.Pc;
719 #elif defined(_LIBUNWIND_TARGET_AARCH64)
720   case UNW_REG_SP: return _msContext.Sp;
721   case UNW_REG_IP: return _msContext.Pc;
722   default: return _msContext.X[regNum - UNW_AARCH64_X0];
723 #endif
724   }
725   _LIBUNWIND_ABORT("unsupported register");
726 }
727 
728 template <typename A, typename R>
729 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
730   switch (regNum) {
731 #if defined(_LIBUNWIND_TARGET_X86_64)
732   case UNW_REG_IP: _msContext.Rip = value; break;
733   case UNW_X86_64_RAX: _msContext.Rax = value; break;
734   case UNW_X86_64_RDX: _msContext.Rdx = value; break;
735   case UNW_X86_64_RCX: _msContext.Rcx = value; break;
736   case UNW_X86_64_RBX: _msContext.Rbx = value; break;
737   case UNW_REG_SP:
738   case UNW_X86_64_RSP: _msContext.Rsp = value; break;
739   case UNW_X86_64_RBP: _msContext.Rbp = value; break;
740   case UNW_X86_64_RSI: _msContext.Rsi = value; break;
741   case UNW_X86_64_RDI: _msContext.Rdi = value; break;
742   case UNW_X86_64_R8: _msContext.R8 = value; break;
743   case UNW_X86_64_R9: _msContext.R9 = value; break;
744   case UNW_X86_64_R10: _msContext.R10 = value; break;
745   case UNW_X86_64_R11: _msContext.R11 = value; break;
746   case UNW_X86_64_R12: _msContext.R12 = value; break;
747   case UNW_X86_64_R13: _msContext.R13 = value; break;
748   case UNW_X86_64_R14: _msContext.R14 = value; break;
749   case UNW_X86_64_R15: _msContext.R15 = value; break;
750 #elif defined(_LIBUNWIND_TARGET_ARM)
751   case UNW_ARM_R0: _msContext.R0 = value; break;
752   case UNW_ARM_R1: _msContext.R1 = value; break;
753   case UNW_ARM_R2: _msContext.R2 = value; break;
754   case UNW_ARM_R3: _msContext.R3 = value; break;
755   case UNW_ARM_R4: _msContext.R4 = value; break;
756   case UNW_ARM_R5: _msContext.R5 = value; break;
757   case UNW_ARM_R6: _msContext.R6 = value; break;
758   case UNW_ARM_R7: _msContext.R7 = value; break;
759   case UNW_ARM_R8: _msContext.R8 = value; break;
760   case UNW_ARM_R9: _msContext.R9 = value; break;
761   case UNW_ARM_R10: _msContext.R10 = value; break;
762   case UNW_ARM_R11: _msContext.R11 = value; break;
763   case UNW_ARM_R12: _msContext.R12 = value; break;
764   case UNW_REG_SP:
765   case UNW_ARM_SP: _msContext.Sp = value; break;
766   case UNW_ARM_LR: _msContext.Lr = value; break;
767   case UNW_REG_IP:
768   case UNW_ARM_IP: _msContext.Pc = value; break;
769 #elif defined(_LIBUNWIND_TARGET_AARCH64)
770   case UNW_REG_SP: _msContext.Sp = value; break;
771   case UNW_REG_IP: _msContext.Pc = value; break;
772   case UNW_AARCH64_X0:
773   case UNW_AARCH64_X1:
774   case UNW_AARCH64_X2:
775   case UNW_AARCH64_X3:
776   case UNW_AARCH64_X4:
777   case UNW_AARCH64_X5:
778   case UNW_AARCH64_X6:
779   case UNW_AARCH64_X7:
780   case UNW_AARCH64_X8:
781   case UNW_AARCH64_X9:
782   case UNW_AARCH64_X10:
783   case UNW_AARCH64_X11:
784   case UNW_AARCH64_X12:
785   case UNW_AARCH64_X13:
786   case UNW_AARCH64_X14:
787   case UNW_AARCH64_X15:
788   case UNW_AARCH64_X16:
789   case UNW_AARCH64_X17:
790   case UNW_AARCH64_X18:
791   case UNW_AARCH64_X19:
792   case UNW_AARCH64_X20:
793   case UNW_AARCH64_X21:
794   case UNW_AARCH64_X22:
795   case UNW_AARCH64_X23:
796   case UNW_AARCH64_X24:
797   case UNW_AARCH64_X25:
798   case UNW_AARCH64_X26:
799   case UNW_AARCH64_X27:
800   case UNW_AARCH64_X28:
801   case UNW_AARCH64_FP:
802   case UNW_AARCH64_LR: _msContext.X[regNum - UNW_ARM64_X0] = value; break;
803 #endif
804   default:
805     _LIBUNWIND_ABORT("unsupported register");
806   }
807 }
808 
809 template <typename A, typename R>
810 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
811 #if defined(_LIBUNWIND_TARGET_ARM)
812   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) return true;
813   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) return true;
814 #elif defined(_LIBUNWIND_TARGET_AARCH64)
815   if (regNum >= UNW_AARCH64_V0 && regNum <= UNW_ARM64_D31) return true;
816 #else
817   (void)regNum;
818 #endif
819   return false;
820 }
821 
822 template <typename A, typename R>
823 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
824 #if defined(_LIBUNWIND_TARGET_ARM)
825   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
826     union {
827       uint32_t w;
828       float f;
829     } d;
830     d.w = _msContext.S[regNum - UNW_ARM_S0];
831     return d.f;
832   }
833   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
834     union {
835       uint64_t w;
836       double d;
837     } d;
838     d.w = _msContext.D[regNum - UNW_ARM_D0];
839     return d.d;
840   }
841   _LIBUNWIND_ABORT("unsupported float register");
842 #elif defined(_LIBUNWIND_TARGET_AARCH64)
843   return _msContext.V[regNum - UNW_AARCH64_V0].D[0];
844 #else
845   (void)regNum;
846   _LIBUNWIND_ABORT("float registers unimplemented");
847 #endif
848 }
849 
850 template <typename A, typename R>
851 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
852 #if defined(_LIBUNWIND_TARGET_ARM)
853   if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
854     union {
855       uint32_t w;
856       float f;
857     } d;
858     d.f = value;
859     _msContext.S[regNum - UNW_ARM_S0] = d.w;
860   }
861   if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
862     union {
863       uint64_t w;
864       double d;
865     } d;
866     d.d = value;
867     _msContext.D[regNum - UNW_ARM_D0] = d.w;
868   }
869   _LIBUNWIND_ABORT("unsupported float register");
870 #elif defined(_LIBUNWIND_TARGET_AARCH64)
871   _msContext.V[regNum - UNW_AARCH64_V0].D[0] = value;
872 #else
873   (void)regNum;
874   (void)value;
875   _LIBUNWIND_ABORT("float registers unimplemented");
876 #endif
877 }
878 
879 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
880   RtlRestoreContext(&_msContext, nullptr);
881 }
882 
883 #ifdef __arm__
884 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {}
885 #endif
886 
887 template <typename A, typename R>
888 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
889   return R::getRegisterName(regNum);
890 }
891 
892 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
893   return false;
894 }
895 
896 #else  // !defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) || !defined(_WIN32)
897 
898 /// UnwindCursor contains all state (including all register values) during
899 /// an unwind.  This is normally stack allocated inside a unw_cursor_t.
900 template <typename A, typename R>
901 class UnwindCursor : public AbstractUnwindCursor{
902   typedef typename A::pint_t pint_t;
903 public:
904                       UnwindCursor(unw_context_t *context, A &as);
905                       UnwindCursor(A &as, void *threadArg);
906   virtual             ~UnwindCursor() {}
907   virtual bool        validReg(int);
908   virtual unw_word_t  getReg(int);
909   virtual void        setReg(int, unw_word_t);
910   virtual bool        validFloatReg(int);
911   virtual unw_fpreg_t getFloatReg(int);
912   virtual void        setFloatReg(int, unw_fpreg_t);
913   virtual int         step();
914   virtual void        getInfo(unw_proc_info_t *);
915   virtual void        jumpto();
916   virtual bool        isSignalFrame();
917   virtual bool        getFunctionName(char *buf, size_t len, unw_word_t *off);
918   virtual void        setInfoBasedOnIPRegister(bool isReturnAddress = false);
919   virtual const char *getRegisterName(int num);
920 #ifdef __arm__
921   virtual void        saveVFPAsX();
922 #endif
923 
924 #ifdef _AIX
925   virtual uintptr_t getDataRelBase();
926 #endif
927 
928 #if defined(_LIBUNWIND_USE_CET)
929   virtual void *get_registers() { return &_registers; }
930 #endif
931 
932   // libunwind does not and should not depend on C++ library which means that we
933   // need our own defition of inline placement new.
934   static void *operator new(size_t, UnwindCursor<A, R> *p) { return p; }
935 
936 private:
937 
938 #if defined(_LIBUNWIND_ARM_EHABI)
939   bool getInfoFromEHABISection(pint_t pc, const UnwindInfoSections &sects);
940 
941   int stepWithEHABI() {
942     size_t len = 0;
943     size_t off = 0;
944     // FIXME: Calling decode_eht_entry() here is violating the libunwind
945     // abstraction layer.
946     const uint32_t *ehtp =
947         decode_eht_entry(reinterpret_cast<const uint32_t *>(_info.unwind_info),
948                          &off, &len);
949     if (_Unwind_VRS_Interpret((_Unwind_Context *)this, ehtp, off, len) !=
950             _URC_CONTINUE_UNWIND)
951       return UNW_STEP_END;
952     return UNW_STEP_SUCCESS;
953   }
954 #endif
955 
956 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
957   bool setInfoForSigReturn() {
958     R dummy;
959     return setInfoForSigReturn(dummy);
960   }
961   int stepThroughSigReturn() {
962     R dummy;
963     return stepThroughSigReturn(dummy);
964   }
965   bool setInfoForSigReturn(Registers_arm64 &);
966   int stepThroughSigReturn(Registers_arm64 &);
967   template <typename Registers> bool setInfoForSigReturn(Registers &) {
968     return false;
969   }
970   template <typename Registers> int stepThroughSigReturn(Registers &) {
971     return UNW_STEP_END;
972   }
973 #endif
974 
975 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
976   bool getInfoFromFdeCie(const typename CFI_Parser<A>::FDE_Info &fdeInfo,
977                          const typename CFI_Parser<A>::CIE_Info &cieInfo,
978                          pint_t pc, uintptr_t dso_base);
979   bool getInfoFromDwarfSection(pint_t pc, const UnwindInfoSections &sects,
980                                             uint32_t fdeSectionOffsetHint=0);
981   int stepWithDwarfFDE() {
982     return DwarfInstructions<A, R>::stepWithDwarf(_addressSpace,
983                                               (pint_t)this->getReg(UNW_REG_IP),
984                                               (pint_t)_info.unwind_info,
985                                               _registers, _isSignalFrame);
986   }
987 #endif
988 
989 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
990   bool getInfoFromCompactEncodingSection(pint_t pc,
991                                             const UnwindInfoSections &sects);
992   int stepWithCompactEncoding() {
993   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
994     if ( compactSaysUseDwarf() )
995       return stepWithDwarfFDE();
996   #endif
997     R dummy;
998     return stepWithCompactEncoding(dummy);
999   }
1000 
1001 #if defined(_LIBUNWIND_TARGET_X86_64)
1002   int stepWithCompactEncoding(Registers_x86_64 &) {
1003     return CompactUnwinder_x86_64<A>::stepWithCompactEncoding(
1004         _info.format, _info.start_ip, _addressSpace, _registers);
1005   }
1006 #endif
1007 
1008 #if defined(_LIBUNWIND_TARGET_I386)
1009   int stepWithCompactEncoding(Registers_x86 &) {
1010     return CompactUnwinder_x86<A>::stepWithCompactEncoding(
1011         _info.format, (uint32_t)_info.start_ip, _addressSpace, _registers);
1012   }
1013 #endif
1014 
1015 #if defined(_LIBUNWIND_TARGET_PPC)
1016   int stepWithCompactEncoding(Registers_ppc &) {
1017     return UNW_EINVAL;
1018   }
1019 #endif
1020 
1021 #if defined(_LIBUNWIND_TARGET_PPC64)
1022   int stepWithCompactEncoding(Registers_ppc64 &) {
1023     return UNW_EINVAL;
1024   }
1025 #endif
1026 
1027 
1028 #if defined(_LIBUNWIND_TARGET_AARCH64)
1029   int stepWithCompactEncoding(Registers_arm64 &) {
1030     return CompactUnwinder_arm64<A>::stepWithCompactEncoding(
1031         _info.format, _info.start_ip, _addressSpace, _registers);
1032   }
1033 #endif
1034 
1035 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
1036   int stepWithCompactEncoding(Registers_mips_o32 &) {
1037     return UNW_EINVAL;
1038   }
1039 #endif
1040 
1041 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1042   int stepWithCompactEncoding(Registers_mips_newabi &) {
1043     return UNW_EINVAL;
1044   }
1045 #endif
1046 
1047 #if defined(_LIBUNWIND_TARGET_SPARC)
1048   int stepWithCompactEncoding(Registers_sparc &) { return UNW_EINVAL; }
1049 #endif
1050 
1051 #if defined(_LIBUNWIND_TARGET_SPARC64)
1052   int stepWithCompactEncoding(Registers_sparc64 &) { return UNW_EINVAL; }
1053 #endif
1054 
1055 #if defined (_LIBUNWIND_TARGET_RISCV)
1056   int stepWithCompactEncoding(Registers_riscv &) {
1057     return UNW_EINVAL;
1058   }
1059 #endif
1060 
1061   bool compactSaysUseDwarf(uint32_t *offset=NULL) const {
1062     R dummy;
1063     return compactSaysUseDwarf(dummy, offset);
1064   }
1065 
1066 #if defined(_LIBUNWIND_TARGET_X86_64)
1067   bool compactSaysUseDwarf(Registers_x86_64 &, uint32_t *offset) const {
1068     if ((_info.format & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF) {
1069       if (offset)
1070         *offset = (_info.format & UNWIND_X86_64_DWARF_SECTION_OFFSET);
1071       return true;
1072     }
1073     return false;
1074   }
1075 #endif
1076 
1077 #if defined(_LIBUNWIND_TARGET_I386)
1078   bool compactSaysUseDwarf(Registers_x86 &, uint32_t *offset) const {
1079     if ((_info.format & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF) {
1080       if (offset)
1081         *offset = (_info.format & UNWIND_X86_DWARF_SECTION_OFFSET);
1082       return true;
1083     }
1084     return false;
1085   }
1086 #endif
1087 
1088 #if defined(_LIBUNWIND_TARGET_PPC)
1089   bool compactSaysUseDwarf(Registers_ppc &, uint32_t *) const {
1090     return true;
1091   }
1092 #endif
1093 
1094 #if defined(_LIBUNWIND_TARGET_PPC64)
1095   bool compactSaysUseDwarf(Registers_ppc64 &, uint32_t *) const {
1096     return true;
1097   }
1098 #endif
1099 
1100 #if defined(_LIBUNWIND_TARGET_AARCH64)
1101   bool compactSaysUseDwarf(Registers_arm64 &, uint32_t *offset) const {
1102     if ((_info.format & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF) {
1103       if (offset)
1104         *offset = (_info.format & UNWIND_ARM64_DWARF_SECTION_OFFSET);
1105       return true;
1106     }
1107     return false;
1108   }
1109 #endif
1110 
1111 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
1112   bool compactSaysUseDwarf(Registers_mips_o32 &, uint32_t *) const {
1113     return true;
1114   }
1115 #endif
1116 
1117 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1118   bool compactSaysUseDwarf(Registers_mips_newabi &, uint32_t *) const {
1119     return true;
1120   }
1121 #endif
1122 
1123 #if defined(_LIBUNWIND_TARGET_SPARC)
1124   bool compactSaysUseDwarf(Registers_sparc &, uint32_t *) const { return true; }
1125 #endif
1126 
1127 #if defined(_LIBUNWIND_TARGET_SPARC64)
1128   bool compactSaysUseDwarf(Registers_sparc64 &, uint32_t *) const {
1129     return true;
1130   }
1131 #endif
1132 
1133 #if defined (_LIBUNWIND_TARGET_RISCV)
1134   bool compactSaysUseDwarf(Registers_riscv &, uint32_t *) const {
1135     return true;
1136   }
1137 #endif
1138 
1139 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1140 
1141 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1142   compact_unwind_encoding_t dwarfEncoding() const {
1143     R dummy;
1144     return dwarfEncoding(dummy);
1145   }
1146 
1147 #if defined(_LIBUNWIND_TARGET_X86_64)
1148   compact_unwind_encoding_t dwarfEncoding(Registers_x86_64 &) const {
1149     return UNWIND_X86_64_MODE_DWARF;
1150   }
1151 #endif
1152 
1153 #if defined(_LIBUNWIND_TARGET_I386)
1154   compact_unwind_encoding_t dwarfEncoding(Registers_x86 &) const {
1155     return UNWIND_X86_MODE_DWARF;
1156   }
1157 #endif
1158 
1159 #if defined(_LIBUNWIND_TARGET_PPC)
1160   compact_unwind_encoding_t dwarfEncoding(Registers_ppc &) const {
1161     return 0;
1162   }
1163 #endif
1164 
1165 #if defined(_LIBUNWIND_TARGET_PPC64)
1166   compact_unwind_encoding_t dwarfEncoding(Registers_ppc64 &) const {
1167     return 0;
1168   }
1169 #endif
1170 
1171 #if defined(_LIBUNWIND_TARGET_AARCH64)
1172   compact_unwind_encoding_t dwarfEncoding(Registers_arm64 &) const {
1173     return UNWIND_ARM64_MODE_DWARF;
1174   }
1175 #endif
1176 
1177 #if defined(_LIBUNWIND_TARGET_ARM)
1178   compact_unwind_encoding_t dwarfEncoding(Registers_arm &) const {
1179     return 0;
1180   }
1181 #endif
1182 
1183 #if defined (_LIBUNWIND_TARGET_OR1K)
1184   compact_unwind_encoding_t dwarfEncoding(Registers_or1k &) const {
1185     return 0;
1186   }
1187 #endif
1188 
1189 #if defined (_LIBUNWIND_TARGET_HEXAGON)
1190   compact_unwind_encoding_t dwarfEncoding(Registers_hexagon &) const {
1191     return 0;
1192   }
1193 #endif
1194 
1195 #if defined (_LIBUNWIND_TARGET_MIPS_O32)
1196   compact_unwind_encoding_t dwarfEncoding(Registers_mips_o32 &) const {
1197     return 0;
1198   }
1199 #endif
1200 
1201 #if defined (_LIBUNWIND_TARGET_MIPS_NEWABI)
1202   compact_unwind_encoding_t dwarfEncoding(Registers_mips_newabi &) const {
1203     return 0;
1204   }
1205 #endif
1206 
1207 #if defined(_LIBUNWIND_TARGET_SPARC)
1208   compact_unwind_encoding_t dwarfEncoding(Registers_sparc &) const { return 0; }
1209 #endif
1210 
1211 #if defined(_LIBUNWIND_TARGET_SPARC64)
1212   compact_unwind_encoding_t dwarfEncoding(Registers_sparc64 &) const {
1213     return 0;
1214   }
1215 #endif
1216 
1217 #if defined (_LIBUNWIND_TARGET_RISCV)
1218   compact_unwind_encoding_t dwarfEncoding(Registers_riscv &) const {
1219     return 0;
1220   }
1221 #endif
1222 
1223 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1224 
1225 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1226   // For runtime environments using SEH unwind data without Windows runtime
1227   // support.
1228   pint_t getLastPC() const { /* FIXME: Implement */ return 0; }
1229   void setLastPC(pint_t pc) { /* FIXME: Implement */ }
1230   RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
1231     /* FIXME: Implement */
1232     *base = 0;
1233     return nullptr;
1234   }
1235   bool getInfoFromSEH(pint_t pc);
1236   int stepWithSEHData() { /* FIXME: Implement */ return 0; }
1237 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1238 
1239 #if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1240   bool getInfoFromTBTable(pint_t pc, R &registers);
1241   int stepWithTBTable(pint_t pc, tbtable *TBTable, R &registers,
1242                       bool &isSignalFrame);
1243   int stepWithTBTableData() {
1244     return stepWithTBTable(reinterpret_cast<pint_t>(this->getReg(UNW_REG_IP)),
1245                            reinterpret_cast<tbtable *>(_info.unwind_info),
1246                            _registers, _isSignalFrame);
1247   }
1248 #endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1249 
1250   A               &_addressSpace;
1251   R                _registers;
1252   unw_proc_info_t  _info;
1253   bool             _unwindInfoMissing;
1254   bool             _isSignalFrame;
1255 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
1256   bool             _isSigReturn = false;
1257 #endif
1258 };
1259 
1260 
1261 template <typename A, typename R>
1262 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
1263     : _addressSpace(as), _registers(context), _unwindInfoMissing(false),
1264       _isSignalFrame(false) {
1265   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
1266                 "UnwindCursor<> does not fit in unw_cursor_t");
1267   static_assert((alignof(UnwindCursor<A, R>) <= alignof(unw_cursor_t)),
1268                 "UnwindCursor<> requires more alignment than unw_cursor_t");
1269   memset(&_info, 0, sizeof(_info));
1270 }
1271 
1272 template <typename A, typename R>
1273 UnwindCursor<A, R>::UnwindCursor(A &as, void *)
1274     : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) {
1275   memset(&_info, 0, sizeof(_info));
1276   // FIXME
1277   // fill in _registers from thread arg
1278 }
1279 
1280 
1281 template <typename A, typename R>
1282 bool UnwindCursor<A, R>::validReg(int regNum) {
1283   return _registers.validRegister(regNum);
1284 }
1285 
1286 template <typename A, typename R>
1287 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
1288   return _registers.getRegister(regNum);
1289 }
1290 
1291 template <typename A, typename R>
1292 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
1293   _registers.setRegister(regNum, (typename A::pint_t)value);
1294 }
1295 
1296 template <typename A, typename R>
1297 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
1298   return _registers.validFloatRegister(regNum);
1299 }
1300 
1301 template <typename A, typename R>
1302 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
1303   return _registers.getFloatRegister(regNum);
1304 }
1305 
1306 template <typename A, typename R>
1307 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
1308   _registers.setFloatRegister(regNum, value);
1309 }
1310 
1311 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
1312   _registers.jumpto();
1313 }
1314 
1315 #ifdef __arm__
1316 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {
1317   _registers.saveVFPAsX();
1318 }
1319 #endif
1320 
1321 #ifdef _AIX
1322 template <typename A, typename R>
1323 uintptr_t UnwindCursor<A, R>::getDataRelBase() {
1324   return reinterpret_cast<uintptr_t>(_info.extra);
1325 }
1326 #endif
1327 
1328 template <typename A, typename R>
1329 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
1330   return _registers.getRegisterName(regNum);
1331 }
1332 
1333 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
1334   return _isSignalFrame;
1335 }
1336 
1337 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1338 
1339 #if defined(_LIBUNWIND_ARM_EHABI)
1340 template<typename A>
1341 struct EHABISectionIterator {
1342   typedef EHABISectionIterator _Self;
1343 
1344   typedef typename A::pint_t value_type;
1345   typedef typename A::pint_t* pointer;
1346   typedef typename A::pint_t& reference;
1347   typedef size_t size_type;
1348   typedef size_t difference_type;
1349 
1350   static _Self begin(A& addressSpace, const UnwindInfoSections& sects) {
1351     return _Self(addressSpace, sects, 0);
1352   }
1353   static _Self end(A& addressSpace, const UnwindInfoSections& sects) {
1354     return _Self(addressSpace, sects,
1355                  sects.arm_section_length / sizeof(EHABIIndexEntry));
1356   }
1357 
1358   EHABISectionIterator(A& addressSpace, const UnwindInfoSections& sects, size_t i)
1359       : _i(i), _addressSpace(&addressSpace), _sects(&sects) {}
1360 
1361   _Self& operator++() { ++_i; return *this; }
1362   _Self& operator+=(size_t a) { _i += a; return *this; }
1363   _Self& operator--() { assert(_i > 0); --_i; return *this; }
1364   _Self& operator-=(size_t a) { assert(_i >= a); _i -= a; return *this; }
1365 
1366   _Self operator+(size_t a) { _Self out = *this; out._i += a; return out; }
1367   _Self operator-(size_t a) { assert(_i >= a); _Self out = *this; out._i -= a; return out; }
1368 
1369   size_t operator-(const _Self& other) const { return _i - other._i; }
1370 
1371   bool operator==(const _Self& other) const {
1372     assert(_addressSpace == other._addressSpace);
1373     assert(_sects == other._sects);
1374     return _i == other._i;
1375   }
1376 
1377   bool operator!=(const _Self& other) const {
1378     assert(_addressSpace == other._addressSpace);
1379     assert(_sects == other._sects);
1380     return _i != other._i;
1381   }
1382 
1383   typename A::pint_t operator*() const { return functionAddress(); }
1384 
1385   typename A::pint_t functionAddress() const {
1386     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1387         EHABIIndexEntry, _i, functionOffset);
1388     return indexAddr + signExtendPrel31(_addressSpace->get32(indexAddr));
1389   }
1390 
1391   typename A::pint_t dataAddress() {
1392     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1393         EHABIIndexEntry, _i, data);
1394     return indexAddr;
1395   }
1396 
1397  private:
1398   size_t _i;
1399   A* _addressSpace;
1400   const UnwindInfoSections* _sects;
1401 };
1402 
1403 namespace {
1404 
1405 template <typename A>
1406 EHABISectionIterator<A> EHABISectionUpperBound(
1407     EHABISectionIterator<A> first,
1408     EHABISectionIterator<A> last,
1409     typename A::pint_t value) {
1410   size_t len = last - first;
1411   while (len > 0) {
1412     size_t l2 = len / 2;
1413     EHABISectionIterator<A> m = first + l2;
1414     if (value < *m) {
1415         len = l2;
1416     } else {
1417         first = ++m;
1418         len -= l2 + 1;
1419     }
1420   }
1421   return first;
1422 }
1423 
1424 }
1425 
1426 template <typename A, typename R>
1427 bool UnwindCursor<A, R>::getInfoFromEHABISection(
1428     pint_t pc,
1429     const UnwindInfoSections &sects) {
1430   EHABISectionIterator<A> begin =
1431       EHABISectionIterator<A>::begin(_addressSpace, sects);
1432   EHABISectionIterator<A> end =
1433       EHABISectionIterator<A>::end(_addressSpace, sects);
1434   if (begin == end)
1435     return false;
1436 
1437   EHABISectionIterator<A> itNextPC = EHABISectionUpperBound(begin, end, pc);
1438   if (itNextPC == begin)
1439     return false;
1440   EHABISectionIterator<A> itThisPC = itNextPC - 1;
1441 
1442   pint_t thisPC = itThisPC.functionAddress();
1443   // If an exception is thrown from a function, corresponding to the last entry
1444   // in the table, we don't really know the function extent and have to choose a
1445   // value for nextPC. Choosing max() will allow the range check during trace to
1446   // succeed.
1447   pint_t nextPC = (itNextPC == end) ? UINTPTR_MAX : itNextPC.functionAddress();
1448   pint_t indexDataAddr = itThisPC.dataAddress();
1449 
1450   if (indexDataAddr == 0)
1451     return false;
1452 
1453   uint32_t indexData = _addressSpace.get32(indexDataAddr);
1454   if (indexData == UNW_EXIDX_CANTUNWIND)
1455     return false;
1456 
1457   // If the high bit is set, the exception handling table entry is inline inside
1458   // the index table entry on the second word (aka |indexDataAddr|). Otherwise,
1459   // the table points at an offset in the exception handling table (section 5
1460   // EHABI).
1461   pint_t exceptionTableAddr;
1462   uint32_t exceptionTableData;
1463   bool isSingleWordEHT;
1464   if (indexData & 0x80000000) {
1465     exceptionTableAddr = indexDataAddr;
1466     // TODO(ajwong): Should this data be 0?
1467     exceptionTableData = indexData;
1468     isSingleWordEHT = true;
1469   } else {
1470     exceptionTableAddr = indexDataAddr + signExtendPrel31(indexData);
1471     exceptionTableData = _addressSpace.get32(exceptionTableAddr);
1472     isSingleWordEHT = false;
1473   }
1474 
1475   // Now we know the 3 things:
1476   //   exceptionTableAddr -- exception handler table entry.
1477   //   exceptionTableData -- the data inside the first word of the eht entry.
1478   //   isSingleWordEHT -- whether the entry is in the index.
1479   unw_word_t personalityRoutine = 0xbadf00d;
1480   bool scope32 = false;
1481   uintptr_t lsda;
1482 
1483   // If the high bit in the exception handling table entry is set, the entry is
1484   // in compact form (section 6.3 EHABI).
1485   if (exceptionTableData & 0x80000000) {
1486     // Grab the index of the personality routine from the compact form.
1487     uint32_t choice = (exceptionTableData & 0x0f000000) >> 24;
1488     uint32_t extraWords = 0;
1489     switch (choice) {
1490       case 0:
1491         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr0;
1492         extraWords = 0;
1493         scope32 = false;
1494         lsda = isSingleWordEHT ? 0 : (exceptionTableAddr + 4);
1495         break;
1496       case 1:
1497         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr1;
1498         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1499         scope32 = false;
1500         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1501         break;
1502       case 2:
1503         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr2;
1504         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1505         scope32 = true;
1506         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1507         break;
1508       default:
1509         _LIBUNWIND_ABORT("unknown personality routine");
1510         return false;
1511     }
1512 
1513     if (isSingleWordEHT) {
1514       if (extraWords != 0) {
1515         _LIBUNWIND_ABORT("index inlined table detected but pr function "
1516                          "requires extra words");
1517         return false;
1518       }
1519     }
1520   } else {
1521     pint_t personalityAddr =
1522         exceptionTableAddr + signExtendPrel31(exceptionTableData);
1523     personalityRoutine = personalityAddr;
1524 
1525     // ARM EHABI # 6.2, # 9.2
1526     //
1527     //  +---- ehtp
1528     //  v
1529     // +--------------------------------------+
1530     // | +--------+--------+--------+-------+ |
1531     // | |0| prel31 to personalityRoutine   | |
1532     // | +--------+--------+--------+-------+ |
1533     // | |      N |      unwind opcodes     | |  <-- UnwindData
1534     // | +--------+--------+--------+-------+ |
1535     // | | Word 2        unwind opcodes     | |
1536     // | +--------+--------+--------+-------+ |
1537     // | ...                                  |
1538     // | +--------+--------+--------+-------+ |
1539     // | | Word N        unwind opcodes     | |
1540     // | +--------+--------+--------+-------+ |
1541     // | | LSDA                             | |  <-- lsda
1542     // | | ...                              | |
1543     // | +--------+--------+--------+-------+ |
1544     // +--------------------------------------+
1545 
1546     uint32_t *UnwindData = reinterpret_cast<uint32_t*>(exceptionTableAddr) + 1;
1547     uint32_t FirstDataWord = *UnwindData;
1548     size_t N = ((FirstDataWord >> 24) & 0xff);
1549     size_t NDataWords = N + 1;
1550     lsda = reinterpret_cast<uintptr_t>(UnwindData + NDataWords);
1551   }
1552 
1553   _info.start_ip = thisPC;
1554   _info.end_ip = nextPC;
1555   _info.handler = personalityRoutine;
1556   _info.unwind_info = exceptionTableAddr;
1557   _info.lsda = lsda;
1558   // flags is pr_cache.additional. See EHABI #7.2 for definition of bit 0.
1559   _info.flags = (isSingleWordEHT ? 1 : 0) | (scope32 ? 0x2 : 0);  // Use enum?
1560 
1561   return true;
1562 }
1563 #endif
1564 
1565 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1566 template <typename A, typename R>
1567 bool UnwindCursor<A, R>::getInfoFromFdeCie(
1568     const typename CFI_Parser<A>::FDE_Info &fdeInfo,
1569     const typename CFI_Parser<A>::CIE_Info &cieInfo, pint_t pc,
1570     uintptr_t dso_base) {
1571   typename CFI_Parser<A>::PrologInfo prolog;
1572   if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo, pc,
1573                                           R::getArch(), &prolog)) {
1574     // Save off parsed FDE info
1575     _info.start_ip          = fdeInfo.pcStart;
1576     _info.end_ip            = fdeInfo.pcEnd;
1577     _info.lsda              = fdeInfo.lsda;
1578     _info.handler           = cieInfo.personality;
1579     // Some frameless functions need SP altered when resuming in function, so
1580     // propagate spExtraArgSize.
1581     _info.gp                = prolog.spExtraArgSize;
1582     _info.flags             = 0;
1583     _info.format            = dwarfEncoding();
1584     _info.unwind_info       = fdeInfo.fdeStart;
1585     _info.unwind_info_size  = static_cast<uint32_t>(fdeInfo.fdeLength);
1586     _info.extra             = static_cast<unw_word_t>(dso_base);
1587     return true;
1588   }
1589   return false;
1590 }
1591 
1592 template <typename A, typename R>
1593 bool UnwindCursor<A, R>::getInfoFromDwarfSection(pint_t pc,
1594                                                 const UnwindInfoSections &sects,
1595                                                 uint32_t fdeSectionOffsetHint) {
1596   typename CFI_Parser<A>::FDE_Info fdeInfo;
1597   typename CFI_Parser<A>::CIE_Info cieInfo;
1598   bool foundFDE = false;
1599   bool foundInCache = false;
1600   // If compact encoding table gave offset into dwarf section, go directly there
1601   if (fdeSectionOffsetHint != 0) {
1602     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1603                                     sects.dwarf_section_length,
1604                                     sects.dwarf_section + fdeSectionOffsetHint,
1605                                     &fdeInfo, &cieInfo);
1606   }
1607 #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1608   if (!foundFDE && (sects.dwarf_index_section != 0)) {
1609     foundFDE = EHHeaderParser<A>::findFDE(
1610         _addressSpace, pc, sects.dwarf_index_section,
1611         (uint32_t)sects.dwarf_index_section_length, &fdeInfo, &cieInfo);
1612   }
1613 #endif
1614   if (!foundFDE) {
1615     // otherwise, search cache of previously found FDEs.
1616     pint_t cachedFDE = DwarfFDECache<A>::findFDE(sects.dso_base, pc);
1617     if (cachedFDE != 0) {
1618       foundFDE =
1619           CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1620                                  sects.dwarf_section_length,
1621                                  cachedFDE, &fdeInfo, &cieInfo);
1622       foundInCache = foundFDE;
1623     }
1624   }
1625   if (!foundFDE) {
1626     // Still not found, do full scan of __eh_frame section.
1627     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1628                                       sects.dwarf_section_length, 0,
1629                                       &fdeInfo, &cieInfo);
1630   }
1631   if (foundFDE) {
1632     if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, sects.dso_base)) {
1633       // Add to cache (to make next lookup faster) if we had no hint
1634       // and there was no index.
1635       if (!foundInCache && (fdeSectionOffsetHint == 0)) {
1636   #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1637         if (sects.dwarf_index_section == 0)
1638   #endif
1639         DwarfFDECache<A>::add(sects.dso_base, fdeInfo.pcStart, fdeInfo.pcEnd,
1640                               fdeInfo.fdeStart);
1641       }
1642       return true;
1643     }
1644   }
1645   //_LIBUNWIND_DEBUG_LOG("can't find/use FDE for pc=0x%llX", (uint64_t)pc);
1646   return false;
1647 }
1648 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1649 
1650 
1651 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1652 template <typename A, typename R>
1653 bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
1654                                               const UnwindInfoSections &sects) {
1655   const bool log = false;
1656   if (log)
1657     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX, mh=0x%llX)\n",
1658             (uint64_t)pc, (uint64_t)sects.dso_base);
1659 
1660   const UnwindSectionHeader<A> sectionHeader(_addressSpace,
1661                                                 sects.compact_unwind_section);
1662   if (sectionHeader.version() != UNWIND_SECTION_VERSION)
1663     return false;
1664 
1665   // do a binary search of top level index to find page with unwind info
1666   pint_t targetFunctionOffset = pc - sects.dso_base;
1667   const UnwindSectionIndexArray<A> topIndex(_addressSpace,
1668                                            sects.compact_unwind_section
1669                                          + sectionHeader.indexSectionOffset());
1670   uint32_t low = 0;
1671   uint32_t high = sectionHeader.indexCount();
1672   uint32_t last = high - 1;
1673   while (low < high) {
1674     uint32_t mid = (low + high) / 2;
1675     //if ( log ) fprintf(stderr, "\tmid=%d, low=%d, high=%d, *mid=0x%08X\n",
1676     //mid, low, high, topIndex.functionOffset(mid));
1677     if (topIndex.functionOffset(mid) <= targetFunctionOffset) {
1678       if ((mid == last) ||
1679           (topIndex.functionOffset(mid + 1) > targetFunctionOffset)) {
1680         low = mid;
1681         break;
1682       } else {
1683         low = mid + 1;
1684       }
1685     } else {
1686       high = mid;
1687     }
1688   }
1689   const uint32_t firstLevelFunctionOffset = topIndex.functionOffset(low);
1690   const uint32_t firstLevelNextPageFunctionOffset =
1691       topIndex.functionOffset(low + 1);
1692   const pint_t secondLevelAddr =
1693       sects.compact_unwind_section + topIndex.secondLevelPagesSectionOffset(low);
1694   const pint_t lsdaArrayStartAddr =
1695       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low);
1696   const pint_t lsdaArrayEndAddr =
1697       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low+1);
1698   if (log)
1699     fprintf(stderr, "\tfirst level search for result index=%d "
1700                     "to secondLevelAddr=0x%llX\n",
1701                     low, (uint64_t) secondLevelAddr);
1702   // do a binary search of second level page index
1703   uint32_t encoding = 0;
1704   pint_t funcStart = 0;
1705   pint_t funcEnd = 0;
1706   pint_t lsda = 0;
1707   pint_t personality = 0;
1708   uint32_t pageKind = _addressSpace.get32(secondLevelAddr);
1709   if (pageKind == UNWIND_SECOND_LEVEL_REGULAR) {
1710     // regular page
1711     UnwindSectionRegularPageHeader<A> pageHeader(_addressSpace,
1712                                                  secondLevelAddr);
1713     UnwindSectionRegularArray<A> pageIndex(
1714         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1715     // binary search looks for entry with e where index[e].offset <= pc <
1716     // index[e+1].offset
1717     if (log)
1718       fprintf(stderr, "\tbinary search for targetFunctionOffset=0x%08llX in "
1719                       "regular page starting at secondLevelAddr=0x%llX\n",
1720               (uint64_t) targetFunctionOffset, (uint64_t) secondLevelAddr);
1721     low = 0;
1722     high = pageHeader.entryCount();
1723     while (low < high) {
1724       uint32_t mid = (low + high) / 2;
1725       if (pageIndex.functionOffset(mid) <= targetFunctionOffset) {
1726         if (mid == (uint32_t)(pageHeader.entryCount() - 1)) {
1727           // at end of table
1728           low = mid;
1729           funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1730           break;
1731         } else if (pageIndex.functionOffset(mid + 1) > targetFunctionOffset) {
1732           // next is too big, so we found it
1733           low = mid;
1734           funcEnd = pageIndex.functionOffset(low + 1) + sects.dso_base;
1735           break;
1736         } else {
1737           low = mid + 1;
1738         }
1739       } else {
1740         high = mid;
1741       }
1742     }
1743     encoding = pageIndex.encoding(low);
1744     funcStart = pageIndex.functionOffset(low) + sects.dso_base;
1745     if (pc < funcStart) {
1746       if (log)
1747         fprintf(
1748             stderr,
1749             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1750             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1751       return false;
1752     }
1753     if (pc > funcEnd) {
1754       if (log)
1755         fprintf(
1756             stderr,
1757             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1758             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1759       return false;
1760     }
1761   } else if (pageKind == UNWIND_SECOND_LEVEL_COMPRESSED) {
1762     // compressed page
1763     UnwindSectionCompressedPageHeader<A> pageHeader(_addressSpace,
1764                                                     secondLevelAddr);
1765     UnwindSectionCompressedArray<A> pageIndex(
1766         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1767     const uint32_t targetFunctionPageOffset =
1768         (uint32_t)(targetFunctionOffset - firstLevelFunctionOffset);
1769     // binary search looks for entry with e where index[e].offset <= pc <
1770     // index[e+1].offset
1771     if (log)
1772       fprintf(stderr, "\tbinary search of compressed page starting at "
1773                       "secondLevelAddr=0x%llX\n",
1774               (uint64_t) secondLevelAddr);
1775     low = 0;
1776     last = pageHeader.entryCount() - 1;
1777     high = pageHeader.entryCount();
1778     while (low < high) {
1779       uint32_t mid = (low + high) / 2;
1780       if (pageIndex.functionOffset(mid) <= targetFunctionPageOffset) {
1781         if ((mid == last) ||
1782             (pageIndex.functionOffset(mid + 1) > targetFunctionPageOffset)) {
1783           low = mid;
1784           break;
1785         } else {
1786           low = mid + 1;
1787         }
1788       } else {
1789         high = mid;
1790       }
1791     }
1792     funcStart = pageIndex.functionOffset(low) + firstLevelFunctionOffset
1793                                                               + sects.dso_base;
1794     if (low < last)
1795       funcEnd =
1796           pageIndex.functionOffset(low + 1) + firstLevelFunctionOffset
1797                                                               + sects.dso_base;
1798     else
1799       funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1800     if (pc < funcStart) {
1801       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1802                            "not in second level compressed unwind table. "
1803                            "funcStart=0x%llX",
1804                             (uint64_t) pc, (uint64_t) funcStart);
1805       return false;
1806     }
1807     if (pc > funcEnd) {
1808       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1809                            "not in second level compressed unwind table. "
1810                            "funcEnd=0x%llX",
1811                            (uint64_t) pc, (uint64_t) funcEnd);
1812       return false;
1813     }
1814     uint16_t encodingIndex = pageIndex.encodingIndex(low);
1815     if (encodingIndex < sectionHeader.commonEncodingsArrayCount()) {
1816       // encoding is in common table in section header
1817       encoding = _addressSpace.get32(
1818           sects.compact_unwind_section +
1819           sectionHeader.commonEncodingsArraySectionOffset() +
1820           encodingIndex * sizeof(uint32_t));
1821     } else {
1822       // encoding is in page specific table
1823       uint16_t pageEncodingIndex =
1824           encodingIndex - (uint16_t)sectionHeader.commonEncodingsArrayCount();
1825       encoding = _addressSpace.get32(secondLevelAddr +
1826                                      pageHeader.encodingsPageOffset() +
1827                                      pageEncodingIndex * sizeof(uint32_t));
1828     }
1829   } else {
1830     _LIBUNWIND_DEBUG_LOG(
1831         "malformed __unwind_info at 0x%0llX bad second level page",
1832         (uint64_t)sects.compact_unwind_section);
1833     return false;
1834   }
1835 
1836   // look up LSDA, if encoding says function has one
1837   if (encoding & UNWIND_HAS_LSDA) {
1838     UnwindSectionLsdaArray<A> lsdaIndex(_addressSpace, lsdaArrayStartAddr);
1839     uint32_t funcStartOffset = (uint32_t)(funcStart - sects.dso_base);
1840     low = 0;
1841     high = (uint32_t)(lsdaArrayEndAddr - lsdaArrayStartAddr) /
1842                     sizeof(unwind_info_section_header_lsda_index_entry);
1843     // binary search looks for entry with exact match for functionOffset
1844     if (log)
1845       fprintf(stderr,
1846               "\tbinary search of lsda table for targetFunctionOffset=0x%08X\n",
1847               funcStartOffset);
1848     while (low < high) {
1849       uint32_t mid = (low + high) / 2;
1850       if (lsdaIndex.functionOffset(mid) == funcStartOffset) {
1851         lsda = lsdaIndex.lsdaOffset(mid) + sects.dso_base;
1852         break;
1853       } else if (lsdaIndex.functionOffset(mid) < funcStartOffset) {
1854         low = mid + 1;
1855       } else {
1856         high = mid;
1857       }
1858     }
1859     if (lsda == 0) {
1860       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with HAS_LSDA bit set for "
1861                     "pc=0x%0llX, but lsda table has no entry",
1862                     encoding, (uint64_t) pc);
1863       return false;
1864     }
1865   }
1866 
1867   // extract personality routine, if encoding says function has one
1868   uint32_t personalityIndex = (encoding & UNWIND_PERSONALITY_MASK) >>
1869                               (__builtin_ctz(UNWIND_PERSONALITY_MASK));
1870   if (personalityIndex != 0) {
1871     --personalityIndex; // change 1-based to zero-based index
1872     if (personalityIndex >= sectionHeader.personalityArrayCount()) {
1873       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with personality index %d,  "
1874                             "but personality table has only %d entries",
1875                             encoding, personalityIndex,
1876                             sectionHeader.personalityArrayCount());
1877       return false;
1878     }
1879     int32_t personalityDelta = (int32_t)_addressSpace.get32(
1880         sects.compact_unwind_section +
1881         sectionHeader.personalityArraySectionOffset() +
1882         personalityIndex * sizeof(uint32_t));
1883     pint_t personalityPointer = sects.dso_base + (pint_t)personalityDelta;
1884     personality = _addressSpace.getP(personalityPointer);
1885     if (log)
1886       fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1887                       "personalityDelta=0x%08X, personality=0x%08llX\n",
1888               (uint64_t) pc, personalityDelta, (uint64_t) personality);
1889   }
1890 
1891   if (log)
1892     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1893                     "encoding=0x%08X, lsda=0x%08llX for funcStart=0x%llX\n",
1894             (uint64_t) pc, encoding, (uint64_t) lsda, (uint64_t) funcStart);
1895   _info.start_ip = funcStart;
1896   _info.end_ip = funcEnd;
1897   _info.lsda = lsda;
1898   _info.handler = personality;
1899   _info.gp = 0;
1900   _info.flags = 0;
1901   _info.format = encoding;
1902   _info.unwind_info = 0;
1903   _info.unwind_info_size = 0;
1904   _info.extra = sects.dso_base;
1905   return true;
1906 }
1907 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1908 
1909 
1910 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1911 template <typename A, typename R>
1912 bool UnwindCursor<A, R>::getInfoFromSEH(pint_t pc) {
1913   pint_t base;
1914   RUNTIME_FUNCTION *unwindEntry = lookUpSEHUnwindInfo(pc, &base);
1915   if (!unwindEntry) {
1916     _LIBUNWIND_DEBUG_LOG("\tpc not in table, pc=0x%llX", (uint64_t) pc);
1917     return false;
1918   }
1919   _info.gp = 0;
1920   _info.flags = 0;
1921   _info.format = 0;
1922   _info.unwind_info_size = sizeof(RUNTIME_FUNCTION);
1923   _info.unwind_info = reinterpret_cast<unw_word_t>(unwindEntry);
1924   _info.extra = base;
1925   _info.start_ip = base + unwindEntry->BeginAddress;
1926 #ifdef _LIBUNWIND_TARGET_X86_64
1927   _info.end_ip = base + unwindEntry->EndAddress;
1928   // Only fill in the handler and LSDA if they're stale.
1929   if (pc != getLastPC()) {
1930     UNWIND_INFO *xdata = reinterpret_cast<UNWIND_INFO *>(base + unwindEntry->UnwindData);
1931     if (xdata->Flags & (UNW_FLAG_EHANDLER|UNW_FLAG_UHANDLER)) {
1932       // The personality is given in the UNWIND_INFO itself. The LSDA immediately
1933       // follows the UNWIND_INFO. (This follows how both Clang and MSVC emit
1934       // these structures.)
1935       // N.B. UNWIND_INFO structs are DWORD-aligned.
1936       uint32_t lastcode = (xdata->CountOfCodes + 1) & ~1;
1937       const uint32_t *handler = reinterpret_cast<uint32_t *>(&xdata->UnwindCodes[lastcode]);
1938       _info.lsda = reinterpret_cast<unw_word_t>(handler+1);
1939       if (*handler) {
1940         _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
1941       } else
1942         _info.handler = 0;
1943     } else {
1944       _info.lsda = 0;
1945       _info.handler = 0;
1946     }
1947   }
1948 #elif defined(_LIBUNWIND_TARGET_ARM)
1949   _info.end_ip = _info.start_ip + unwindEntry->FunctionLength;
1950   _info.lsda = 0; // FIXME
1951   _info.handler = 0; // FIXME
1952 #endif
1953   setLastPC(pc);
1954   return true;
1955 }
1956 #endif
1957 
1958 #if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1959 // Masks for traceback table field xtbtable.
1960 enum xTBTableMask : uint8_t {
1961   reservedBit = 0x02, // The traceback table was incorrectly generated if set
1962                       // (see comments in function getInfoFromTBTable().
1963   ehInfoBit = 0x08    // Exception handling info is present if set
1964 };
1965 
1966 enum frameType : unw_word_t {
1967   frameWithXLEHStateTable = 0,
1968   frameWithEHInfo = 1
1969 };
1970 
1971 extern "C" {
1972 typedef _Unwind_Reason_Code __xlcxx_personality_v0_t(int, _Unwind_Action,
1973                                                      uint64_t,
1974                                                      _Unwind_Exception *,
1975                                                      struct _Unwind_Context *);
1976 __attribute__((__weak__)) __xlcxx_personality_v0_t __xlcxx_personality_v0;
1977 }
1978 
1979 static __xlcxx_personality_v0_t *xlcPersonalityV0;
1980 static RWMutex xlcPersonalityV0InitLock;
1981 
1982 template <typename A, typename R>
1983 bool UnwindCursor<A, R>::getInfoFromTBTable(pint_t pc, R &registers) {
1984   uint32_t *p = reinterpret_cast<uint32_t *>(pc);
1985 
1986   // Keep looking forward until a word of 0 is found. The traceback
1987   // table starts at the following word.
1988   while (*p)
1989     ++p;
1990   tbtable *TBTable = reinterpret_cast<tbtable *>(p + 1);
1991 
1992   if (_LIBUNWIND_TRACING_UNWINDING) {
1993     char functionBuf[512];
1994     const char *functionName = functionBuf;
1995     unw_word_t offset;
1996     if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
1997       functionName = ".anonymous.";
1998     }
1999     _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2000                                __func__, functionName,
2001                                reinterpret_cast<void *>(TBTable));
2002   }
2003 
2004   // If the traceback table does not contain necessary info, bypass this frame.
2005   if (!TBTable->tb.has_tboff)
2006     return false;
2007 
2008   // Structure tbtable_ext contains important data we are looking for.
2009   p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2010 
2011   // Skip field parminfo if it exists.
2012   if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2013     ++p;
2014 
2015   // p now points to tb_offset, the offset from start of function to TB table.
2016   unw_word_t start_ip =
2017       reinterpret_cast<unw_word_t>(TBTable) - *p - sizeof(uint32_t);
2018   unw_word_t end_ip = reinterpret_cast<unw_word_t>(TBTable);
2019   ++p;
2020 
2021   _LIBUNWIND_TRACE_UNWINDING("start_ip=%p, end_ip=%p\n",
2022                              reinterpret_cast<void *>(start_ip),
2023                              reinterpret_cast<void *>(end_ip));
2024 
2025   // Skip field hand_mask if it exists.
2026   if (TBTable->tb.int_hndl)
2027     ++p;
2028 
2029   unw_word_t lsda = 0;
2030   unw_word_t handler = 0;
2031   unw_word_t flags = frameType::frameWithXLEHStateTable;
2032 
2033   if (TBTable->tb.lang == TB_CPLUSPLUS && TBTable->tb.has_ctl) {
2034     // State table info is available. The ctl_info field indicates the
2035     // number of CTL anchors. There should be only one entry for the C++
2036     // state table.
2037     assert(*p == 1 && "libunwind: there must be only one ctl_info entry");
2038     ++p;
2039     // p points to the offset of the state table into the stack.
2040     pint_t stateTableOffset = *p++;
2041 
2042     int framePointerReg;
2043 
2044     // Skip fields name_len and name if exist.
2045     if (TBTable->tb.name_present) {
2046       const uint16_t name_len = *(reinterpret_cast<uint16_t *>(p));
2047       p = reinterpret_cast<uint32_t *>(reinterpret_cast<char *>(p) + name_len +
2048                                        sizeof(uint16_t));
2049     }
2050 
2051     if (TBTable->tb.uses_alloca)
2052       framePointerReg = *(reinterpret_cast<char *>(p));
2053     else
2054       framePointerReg = 1; // default frame pointer == SP
2055 
2056     _LIBUNWIND_TRACE_UNWINDING(
2057         "framePointerReg=%d, framePointer=%p, "
2058         "stateTableOffset=%#lx\n",
2059         framePointerReg,
2060         reinterpret_cast<void *>(_registers.getRegister(framePointerReg)),
2061         stateTableOffset);
2062     lsda = _registers.getRegister(framePointerReg) + stateTableOffset;
2063 
2064     // Since the traceback table generated by the legacy XLC++ does not
2065     // provide the location of the personality for the state table,
2066     // function __xlcxx_personality_v0(), which is the personality for the state
2067     // table and is exported from libc++abi, is directly assigned as the
2068     // handler here. When a legacy XLC++ frame is encountered, the symbol
2069     // is resolved dynamically using dlopen() to avoid hard dependency from
2070     // libunwind on libc++abi.
2071 
2072     // Resolve the function pointer to the state table personality if it has
2073     // not already.
2074     if (xlcPersonalityV0 == NULL) {
2075       xlcPersonalityV0InitLock.lock();
2076       if (xlcPersonalityV0 == NULL) {
2077         // If libc++abi is statically linked in, symbol __xlcxx_personality_v0
2078         // has been resolved at the link time.
2079         xlcPersonalityV0 = &__xlcxx_personality_v0;
2080         if (xlcPersonalityV0 == NULL) {
2081           // libc++abi is dynamically linked. Resolve __xlcxx_personality_v0
2082           // using dlopen().
2083           const char libcxxabi[] = "libc++abi.a(libc++abi.so.1)";
2084           void *libHandle;
2085           libHandle = dlopen(libcxxabi, RTLD_MEMBER | RTLD_NOW);
2086           if (libHandle == NULL) {
2087             _LIBUNWIND_TRACE_UNWINDING("dlopen() failed with errno=%d\n",
2088                                        errno);
2089             assert(0 && "dlopen() failed");
2090           }
2091           xlcPersonalityV0 = reinterpret_cast<__xlcxx_personality_v0_t *>(
2092               dlsym(libHandle, "__xlcxx_personality_v0"));
2093           if (xlcPersonalityV0 == NULL) {
2094             _LIBUNWIND_TRACE_UNWINDING("dlsym() failed with errno=%d\n", errno);
2095             assert(0 && "dlsym() failed");
2096           }
2097           dlclose(libHandle);
2098         }
2099       }
2100       xlcPersonalityV0InitLock.unlock();
2101     }
2102     handler = reinterpret_cast<unw_word_t>(xlcPersonalityV0);
2103     _LIBUNWIND_TRACE_UNWINDING("State table: LSDA=%p, Personality=%p\n",
2104                                reinterpret_cast<void *>(lsda),
2105                                reinterpret_cast<void *>(handler));
2106   } else if (TBTable->tb.longtbtable) {
2107     // This frame has the traceback table extension. Possible cases are
2108     // 1) a C++ frame that has the 'eh_info' structure; 2) a C++ frame that
2109     // is not EH aware; or, 3) a frame of other languages. We need to figure out
2110     // if the traceback table extension contains the 'eh_info' structure.
2111     //
2112     // We also need to deal with the complexity arising from some XL compiler
2113     // versions use the wrong ordering of 'longtbtable' and 'has_vec' bits
2114     // where the 'longtbtable' bit is meant to be the 'has_vec' bit and vice
2115     // versa. For frames of code generated by those compilers, the 'longtbtable'
2116     // bit may be set but there isn't really a traceback table extension.
2117     //
2118     // In </usr/include/sys/debug.h>, there is the following definition of
2119     // 'struct tbtable_ext'. It is not really a structure but a dummy to
2120     // collect the description of optional parts of the traceback table.
2121     //
2122     // struct tbtable_ext {
2123     //   ...
2124     //   char alloca_reg;        /* Register for alloca automatic storage */
2125     //   struct vec_ext vec_ext; /* Vector extension (if has_vec is set) */
2126     //   unsigned char xtbtable; /* More tbtable fields, if longtbtable is set*/
2127     // };
2128     //
2129     // Depending on how the 'has_vec'/'longtbtable' bit is interpreted, the data
2130     // following 'alloca_reg' can be treated either as 'struct vec_ext' or
2131     // 'unsigned char xtbtable'. 'xtbtable' bits are defined in
2132     // </usr/include/sys/debug.h> as flags. The 7th bit '0x02' is currently
2133     // unused and should not be set. 'struct vec_ext' is defined in
2134     // </usr/include/sys/debug.h> as follows:
2135     //
2136     // struct vec_ext {
2137     //   unsigned vr_saved:6;      /* Number of non-volatile vector regs saved
2138     //   */
2139     //                             /* first register saved is assumed to be */
2140     //                             /* 32 - vr_saved                         */
2141     //   unsigned saves_vrsave:1;  /* Set if vrsave is saved on the stack */
2142     //   unsigned has_varargs:1;
2143     //   ...
2144     // };
2145     //
2146     // Here, the 7th bit is used as 'saves_vrsave'. To determine whether it
2147     // is 'struct vec_ext' or 'xtbtable' that follows 'alloca_reg',
2148     // we checks if the 7th bit is set or not because 'xtbtable' should
2149     // never have the 7th bit set. The 7th bit of 'xtbtable' will be reserved
2150     // in the future to make sure the mitigation works. This mitigation
2151     // is not 100% bullet proof because 'struct vec_ext' may not always have
2152     // 'saves_vrsave' bit set.
2153     //
2154     // 'reservedBit' is defined in enum 'xTBTableMask' above as the mask for
2155     // checking the 7th bit.
2156 
2157     // p points to field name len.
2158     uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2159 
2160     // Skip fields name_len and name if they exist.
2161     if (TBTable->tb.name_present) {
2162       const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2163       charPtr = charPtr + name_len + sizeof(uint16_t);
2164     }
2165 
2166     // Skip field alloc_reg if it exists.
2167     if (TBTable->tb.uses_alloca)
2168       ++charPtr;
2169 
2170     // Check traceback table bit has_vec. Skip struct vec_ext if it exists.
2171     if (TBTable->tb.has_vec)
2172       // Note struct vec_ext does exist at this point because whether the
2173       // ordering of longtbtable and has_vec bits is correct or not, both
2174       // are set.
2175       charPtr += sizeof(struct vec_ext);
2176 
2177     // charPtr points to field 'xtbtable'. Check if the EH info is available.
2178     // Also check if the reserved bit of the extended traceback table field
2179     // 'xtbtable' is set. If it is, the traceback table was incorrectly
2180     // generated by an XL compiler that uses the wrong ordering of 'longtbtable'
2181     // and 'has_vec' bits and this is in fact 'struct vec_ext'. So skip the
2182     // frame.
2183     if ((*charPtr & xTBTableMask::ehInfoBit) &&
2184         !(*charPtr & xTBTableMask::reservedBit)) {
2185       // Mark this frame has the new EH info.
2186       flags = frameType::frameWithEHInfo;
2187 
2188       // eh_info is available.
2189       charPtr++;
2190       // The pointer is 4-byte aligned.
2191       if (reinterpret_cast<uintptr_t>(charPtr) % 4)
2192         charPtr += 4 - reinterpret_cast<uintptr_t>(charPtr) % 4;
2193       uintptr_t *ehInfo =
2194           reinterpret_cast<uintptr_t *>(*(reinterpret_cast<uintptr_t *>(
2195               registers.getRegister(2) +
2196               *(reinterpret_cast<uintptr_t *>(charPtr)))));
2197 
2198       // ehInfo points to structure en_info. The first member is version.
2199       // Only version 0 is currently supported.
2200       assert(*(reinterpret_cast<uint32_t *>(ehInfo)) == 0 &&
2201              "libunwind: ehInfo version other than 0 is not supported");
2202 
2203       // Increment ehInfo to point to member lsda.
2204       ++ehInfo;
2205       lsda = *ehInfo++;
2206 
2207       // enInfo now points to member personality.
2208       handler = *ehInfo;
2209 
2210       _LIBUNWIND_TRACE_UNWINDING("Range table: LSDA=%#lx, Personality=%#lx\n",
2211                                  lsda, handler);
2212     }
2213   }
2214 
2215   _info.start_ip = start_ip;
2216   _info.end_ip = end_ip;
2217   _info.lsda = lsda;
2218   _info.handler = handler;
2219   _info.gp = 0;
2220   _info.flags = flags;
2221   _info.format = 0;
2222   _info.unwind_info = reinterpret_cast<unw_word_t>(TBTable);
2223   _info.unwind_info_size = 0;
2224   _info.extra = registers.getRegister(2);
2225 
2226   return true;
2227 }
2228 
2229 // Step back up the stack following the frame back link.
2230 template <typename A, typename R>
2231 int UnwindCursor<A, R>::stepWithTBTable(pint_t pc, tbtable *TBTable,
2232                                         R &registers, bool &isSignalFrame) {
2233   if (_LIBUNWIND_TRACING_UNWINDING) {
2234     char functionBuf[512];
2235     const char *functionName = functionBuf;
2236     unw_word_t offset;
2237     if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
2238       functionName = ".anonymous.";
2239     }
2240     _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2241                                __func__, functionName,
2242                                reinterpret_cast<void *>(TBTable));
2243   }
2244 
2245 #if defined(__powerpc64__)
2246   // Instruction to reload TOC register "l r2,40(r1)"
2247   const uint32_t loadTOCRegInst = 0xe8410028;
2248   const int32_t unwPPCF0Index = UNW_PPC64_F0;
2249   const int32_t unwPPCV0Index = UNW_PPC64_V0;
2250 #else
2251   // Instruction to reload TOC register "l r2,20(r1)"
2252   const uint32_t loadTOCRegInst = 0x80410014;
2253   const int32_t unwPPCF0Index = UNW_PPC_F0;
2254   const int32_t unwPPCV0Index = UNW_PPC_V0;
2255 #endif
2256 
2257   R newRegisters = registers;
2258 
2259   // lastStack points to the stack frame of the next routine up.
2260   pint_t lastStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2261 
2262   // Return address is the address after call site instruction.
2263   pint_t returnAddress;
2264 
2265   if (isSignalFrame) {
2266     _LIBUNWIND_TRACE_UNWINDING("Possible signal handler frame: lastStack=%p",
2267                                reinterpret_cast<void *>(lastStack));
2268 
2269     sigcontext *sigContext = reinterpret_cast<sigcontext *>(
2270         reinterpret_cast<char *>(lastStack) + STKMIN);
2271     returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2272 
2273     _LIBUNWIND_TRACE_UNWINDING("From sigContext=%p, returnAddress=%p\n",
2274                                reinterpret_cast<void *>(sigContext),
2275                                reinterpret_cast<void *>(returnAddress));
2276 
2277     if (returnAddress < 0x10000000) {
2278       // Try again using STKMINALIGN
2279       sigContext = reinterpret_cast<sigcontext *>(
2280           reinterpret_cast<char *>(lastStack) + STKMINALIGN);
2281       returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2282       if (returnAddress < 0x10000000) {
2283         _LIBUNWIND_TRACE_UNWINDING("Bad returnAddress=%p\n",
2284                                    reinterpret_cast<void *>(returnAddress));
2285         return UNW_EBADFRAME;
2286       } else {
2287         _LIBUNWIND_TRACE_UNWINDING("Tried again using STKMINALIGN: "
2288                                    "sigContext=%p, returnAddress=%p. "
2289                                    "Seems to be a valid address\n",
2290                                    reinterpret_cast<void *>(sigContext),
2291                                    reinterpret_cast<void *>(returnAddress));
2292       }
2293     }
2294     // Restore the condition register from sigcontext.
2295     newRegisters.setCR(sigContext->sc_jmpbuf.jmp_context.cr);
2296 
2297     // Restore GPRs from sigcontext.
2298     for (int i = 0; i < 32; ++i)
2299       newRegisters.setRegister(i, sigContext->sc_jmpbuf.jmp_context.gpr[i]);
2300 
2301     // Restore FPRs from sigcontext.
2302     for (int i = 0; i < 32; ++i)
2303       newRegisters.setFloatRegister(i + unwPPCF0Index,
2304                                     sigContext->sc_jmpbuf.jmp_context.fpr[i]);
2305 
2306     // Restore vector registers if there is an associated extended context
2307     // structure.
2308     if (sigContext->sc_jmpbuf.jmp_context.msr & __EXTCTX) {
2309       ucontext_t *uContext = reinterpret_cast<ucontext_t *>(sigContext);
2310       if (uContext->__extctx->__extctx_magic == __EXTCTX_MAGIC) {
2311         for (int i = 0; i < 32; ++i)
2312           newRegisters.setVectorRegister(
2313               i + unwPPCV0Index, *(reinterpret_cast<v128 *>(
2314                                      &(uContext->__extctx->__vmx.__vr[i]))));
2315       }
2316     }
2317   } else {
2318     // Step up a normal frame.
2319     returnAddress = reinterpret_cast<pint_t *>(lastStack)[2];
2320 
2321     _LIBUNWIND_TRACE_UNWINDING("Extract info from lastStack=%p, "
2322                                "returnAddress=%p\n",
2323                                reinterpret_cast<void *>(lastStack),
2324                                reinterpret_cast<void *>(returnAddress));
2325     _LIBUNWIND_TRACE_UNWINDING("fpr_regs=%d, gpr_regs=%d, saves_cr=%d\n",
2326                                TBTable->tb.fpr_saved, TBTable->tb.gpr_saved,
2327                                TBTable->tb.saves_cr);
2328 
2329     // Restore FP registers.
2330     char *ptrToRegs = reinterpret_cast<char *>(lastStack);
2331     double *FPRegs = reinterpret_cast<double *>(
2332         ptrToRegs - (TBTable->tb.fpr_saved * sizeof(double)));
2333     for (int i = 0; i < TBTable->tb.fpr_saved; ++i)
2334       newRegisters.setFloatRegister(
2335           32 - TBTable->tb.fpr_saved + i + unwPPCF0Index, FPRegs[i]);
2336 
2337     // Restore GP registers.
2338     ptrToRegs = reinterpret_cast<char *>(FPRegs);
2339     uintptr_t *GPRegs = reinterpret_cast<uintptr_t *>(
2340         ptrToRegs - (TBTable->tb.gpr_saved * sizeof(uintptr_t)));
2341     for (int i = 0; i < TBTable->tb.gpr_saved; ++i)
2342       newRegisters.setRegister(32 - TBTable->tb.gpr_saved + i, GPRegs[i]);
2343 
2344     // Restore Vector registers.
2345     ptrToRegs = reinterpret_cast<char *>(GPRegs);
2346 
2347     // Restore vector registers only if this is a Clang frame. Also
2348     // check if traceback table bit has_vec is set. If it is, structure
2349     // vec_ext is available.
2350     if (_info.flags == frameType::frameWithEHInfo && TBTable->tb.has_vec) {
2351 
2352       // Get to the vec_ext structure to check if vector registers are saved.
2353       uint32_t *p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2354 
2355       // Skip field parminfo if exists.
2356       if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2357         ++p;
2358 
2359       // Skip field tb_offset if exists.
2360       if (TBTable->tb.has_tboff)
2361         ++p;
2362 
2363       // Skip field hand_mask if exists.
2364       if (TBTable->tb.int_hndl)
2365         ++p;
2366 
2367       // Skip fields ctl_info and ctl_info_disp if exist.
2368       if (TBTable->tb.has_ctl) {
2369         // Skip field ctl_info.
2370         ++p;
2371         // Skip field ctl_info_disp.
2372         ++p;
2373       }
2374 
2375       // Skip fields name_len and name if exist.
2376       // p is supposed to point to field name_len now.
2377       uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2378       if (TBTable->tb.name_present) {
2379         const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2380         charPtr = charPtr + name_len + sizeof(uint16_t);
2381       }
2382 
2383       // Skip field alloc_reg if it exists.
2384       if (TBTable->tb.uses_alloca)
2385         ++charPtr;
2386 
2387       struct vec_ext *vec_ext = reinterpret_cast<struct vec_ext *>(charPtr);
2388 
2389       _LIBUNWIND_TRACE_UNWINDING("vr_saved=%d\n", vec_ext->vr_saved);
2390 
2391       // Restore vector register(s) if saved on the stack.
2392       if (vec_ext->vr_saved) {
2393         // Saved vector registers are 16-byte aligned.
2394         if (reinterpret_cast<uintptr_t>(ptrToRegs) % 16)
2395           ptrToRegs -= reinterpret_cast<uintptr_t>(ptrToRegs) % 16;
2396         v128 *VecRegs = reinterpret_cast<v128 *>(ptrToRegs - vec_ext->vr_saved *
2397                                                                  sizeof(v128));
2398         for (int i = 0; i < vec_ext->vr_saved; ++i) {
2399           newRegisters.setVectorRegister(
2400               32 - vec_ext->vr_saved + i + unwPPCV0Index, VecRegs[i]);
2401         }
2402       }
2403     }
2404     if (TBTable->tb.saves_cr) {
2405       // Get the saved condition register. The condition register is only
2406       // a single word.
2407       newRegisters.setCR(
2408           *(reinterpret_cast<uint32_t *>(lastStack + sizeof(uintptr_t))));
2409     }
2410 
2411     // Restore the SP.
2412     newRegisters.setSP(lastStack);
2413 
2414     // The first instruction after return.
2415     uint32_t firstInstruction = *(reinterpret_cast<uint32_t *>(returnAddress));
2416 
2417     // Do we need to set the TOC register?
2418     _LIBUNWIND_TRACE_UNWINDING(
2419         "Current gpr2=%p\n",
2420         reinterpret_cast<void *>(newRegisters.getRegister(2)));
2421     if (firstInstruction == loadTOCRegInst) {
2422       _LIBUNWIND_TRACE_UNWINDING(
2423           "Set gpr2=%p from frame\n",
2424           reinterpret_cast<void *>(reinterpret_cast<pint_t *>(lastStack)[5]));
2425       newRegisters.setRegister(2, reinterpret_cast<pint_t *>(lastStack)[5]);
2426     }
2427   }
2428   _LIBUNWIND_TRACE_UNWINDING("lastStack=%p, returnAddress=%p, pc=%p\n",
2429                              reinterpret_cast<void *>(lastStack),
2430                              reinterpret_cast<void *>(returnAddress),
2431                              reinterpret_cast<void *>(pc));
2432 
2433   // The return address is the address after call site instruction, so
2434   // setting IP to that simualates a return.
2435   newRegisters.setIP(reinterpret_cast<uintptr_t>(returnAddress));
2436 
2437   // Simulate the step by replacing the register set with the new ones.
2438   registers = newRegisters;
2439 
2440   // Check if the next frame is a signal frame.
2441   pint_t nextStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2442 
2443   // Return address is the address after call site instruction.
2444   pint_t nextReturnAddress = reinterpret_cast<pint_t *>(nextStack)[2];
2445 
2446   if (nextReturnAddress > 0x01 && nextReturnAddress < 0x10000) {
2447     _LIBUNWIND_TRACE_UNWINDING("The next is a signal handler frame: "
2448                                "nextStack=%p, next return address=%p\n",
2449                                reinterpret_cast<void *>(nextStack),
2450                                reinterpret_cast<void *>(nextReturnAddress));
2451     isSignalFrame = true;
2452   } else {
2453     isSignalFrame = false;
2454   }
2455 
2456   return UNW_STEP_SUCCESS;
2457 }
2458 #endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2459 
2460 template <typename A, typename R>
2461 void UnwindCursor<A, R>::setInfoBasedOnIPRegister(bool isReturnAddress) {
2462 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2463   _isSigReturn = false;
2464 #endif
2465 
2466   pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2467 #if defined(_LIBUNWIND_ARM_EHABI)
2468   // Remove the thumb bit so the IP represents the actual instruction address.
2469   // This matches the behaviour of _Unwind_GetIP on arm.
2470   pc &= (pint_t)~0x1;
2471 #endif
2472 
2473   // Exit early if at the top of the stack.
2474   if (pc == 0) {
2475     _unwindInfoMissing = true;
2476     return;
2477   }
2478 
2479   // If the last line of a function is a "throw" the compiler sometimes
2480   // emits no instructions after the call to __cxa_throw.  This means
2481   // the return address is actually the start of the next function.
2482   // To disambiguate this, back up the pc when we know it is a return
2483   // address.
2484   if (isReturnAddress)
2485 #if defined(_AIX)
2486     // PC needs to be a 4-byte aligned address to be able to look for a
2487     // word of 0 that indicates the start of the traceback table at the end
2488     // of a function on AIX.
2489     pc -= 4;
2490 #else
2491     --pc;
2492 #endif
2493 
2494   // Ask address space object to find unwind sections for this pc.
2495   UnwindInfoSections sects;
2496   if (_addressSpace.findUnwindSections(pc, sects)) {
2497 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
2498     // If there is a compact unwind encoding table, look there first.
2499     if (sects.compact_unwind_section != 0) {
2500       if (this->getInfoFromCompactEncodingSection(pc, sects)) {
2501   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2502         // Found info in table, done unless encoding says to use dwarf.
2503         uint32_t dwarfOffset;
2504         if ((sects.dwarf_section != 0) && compactSaysUseDwarf(&dwarfOffset)) {
2505           if (this->getInfoFromDwarfSection(pc, sects, dwarfOffset)) {
2506             // found info in dwarf, done
2507             return;
2508           }
2509         }
2510   #endif
2511         // If unwind table has entry, but entry says there is no unwind info,
2512         // record that we have no unwind info.
2513         if (_info.format == 0)
2514           _unwindInfoMissing = true;
2515         return;
2516       }
2517     }
2518 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
2519 
2520 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
2521     // If there is SEH unwind info, look there next.
2522     if (this->getInfoFromSEH(pc))
2523       return;
2524 #endif
2525 
2526 #if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2527     // If there is unwind info in the traceback table, look there next.
2528     if (this->getInfoFromTBTable(pc, _registers))
2529       return;
2530 #endif
2531 
2532 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2533     // If there is dwarf unwind info, look there next.
2534     if (sects.dwarf_section != 0) {
2535       if (this->getInfoFromDwarfSection(pc, sects)) {
2536         // found info in dwarf, done
2537         return;
2538       }
2539     }
2540 #endif
2541 
2542 #if defined(_LIBUNWIND_ARM_EHABI)
2543     // If there is ARM EHABI unwind info, look there next.
2544     if (sects.arm_section != 0 && this->getInfoFromEHABISection(pc, sects))
2545       return;
2546 #endif
2547   }
2548 
2549 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2550   // There is no static unwind info for this pc. Look to see if an FDE was
2551   // dynamically registered for it.
2552   pint_t cachedFDE = DwarfFDECache<A>::findFDE(DwarfFDECache<A>::kSearchAll,
2553                                                pc);
2554   if (cachedFDE != 0) {
2555     typename CFI_Parser<A>::FDE_Info fdeInfo;
2556     typename CFI_Parser<A>::CIE_Info cieInfo;
2557     if (!CFI_Parser<A>::decodeFDE(_addressSpace, cachedFDE, &fdeInfo, &cieInfo))
2558       if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
2559         return;
2560   }
2561 
2562   // Lastly, ask AddressSpace object about platform specific ways to locate
2563   // other FDEs.
2564   pint_t fde;
2565   if (_addressSpace.findOtherFDE(pc, fde)) {
2566     typename CFI_Parser<A>::FDE_Info fdeInfo;
2567     typename CFI_Parser<A>::CIE_Info cieInfo;
2568     if (!CFI_Parser<A>::decodeFDE(_addressSpace, fde, &fdeInfo, &cieInfo)) {
2569       // Double check this FDE is for a function that includes the pc.
2570       if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd))
2571         if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
2572           return;
2573     }
2574   }
2575 #endif // #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2576 
2577 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2578   if (setInfoForSigReturn())
2579     return;
2580 #endif
2581 
2582   // no unwind info, flag that we can't reliably unwind
2583   _unwindInfoMissing = true;
2584 }
2585 
2586 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2587 template <typename A, typename R>
2588 bool UnwindCursor<A, R>::setInfoForSigReturn(Registers_arm64 &) {
2589   // Look for the sigreturn trampoline. The trampoline's body is two
2590   // specific instructions (see below). Typically the trampoline comes from the
2591   // vDSO[1] (i.e. the __kernel_rt_sigreturn function). A libc might provide its
2592   // own restorer function, though, or user-mode QEMU might write a trampoline
2593   // onto the stack.
2594   //
2595   // This special code path is a fallback that is only used if the trampoline
2596   // lacks proper (e.g. DWARF) unwind info. On AArch64, a new DWARF register
2597   // constant for the PC needs to be defined before DWARF can handle a signal
2598   // trampoline. This code may segfault if the target PC is unreadable, e.g.:
2599   //  - The PC points at a function compiled without unwind info, and which is
2600   //    part of an execute-only mapping (e.g. using -Wl,--execute-only).
2601   //  - The PC is invalid and happens to point to unreadable or unmapped memory.
2602   //
2603   // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/vdso/sigreturn.S
2604   const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2605   // Look for instructions: mov x8, #0x8b; svc #0x0
2606   if (_addressSpace.get32(pc) == 0xd2801168 &&
2607       _addressSpace.get32(pc + 4) == 0xd4000001) {
2608     _info = {};
2609     _isSigReturn = true;
2610     return true;
2611   }
2612   return false;
2613 }
2614 
2615 template <typename A, typename R>
2616 int UnwindCursor<A, R>::stepThroughSigReturn(Registers_arm64 &) {
2617   // In the signal trampoline frame, sp points to an rt_sigframe[1], which is:
2618   //  - 128-byte siginfo struct
2619   //  - ucontext struct:
2620   //     - 8-byte long (uc_flags)
2621   //     - 8-byte pointer (uc_link)
2622   //     - 24-byte stack_t
2623   //     - 128-byte signal set
2624   //     - 8 bytes of padding because sigcontext has 16-byte alignment
2625   //     - sigcontext/mcontext_t
2626   // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/signal.c
2627   const pint_t kOffsetSpToSigcontext = (128 + 8 + 8 + 24 + 128 + 8); // 304
2628 
2629   // Offsets from sigcontext to each register.
2630   const pint_t kOffsetGprs = 8; // offset to "__u64 regs[31]" field
2631   const pint_t kOffsetSp = 256; // offset to "__u64 sp" field
2632   const pint_t kOffsetPc = 264; // offset to "__u64 pc" field
2633 
2634   pint_t sigctx = _registers.getSP() + kOffsetSpToSigcontext;
2635 
2636   for (int i = 0; i <= 30; ++i) {
2637     uint64_t value = _addressSpace.get64(sigctx + kOffsetGprs +
2638                                          static_cast<pint_t>(i * 8));
2639     _registers.setRegister(UNW_AARCH64_X0 + i, value);
2640   }
2641   _registers.setSP(_addressSpace.get64(sigctx + kOffsetSp));
2642   _registers.setIP(_addressSpace.get64(sigctx + kOffsetPc));
2643   _isSignalFrame = true;
2644   return UNW_STEP_SUCCESS;
2645 }
2646 #endif // defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2647 
2648 template <typename A, typename R>
2649 int UnwindCursor<A, R>::step() {
2650   // Bottom of stack is defined is when unwind info cannot be found.
2651   if (_unwindInfoMissing)
2652     return UNW_STEP_END;
2653 
2654   // Use unwinding info to modify register set as if function returned.
2655   int result;
2656 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2657   if (_isSigReturn) {
2658     result = this->stepThroughSigReturn();
2659   } else
2660 #endif
2661   {
2662 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
2663     result = this->stepWithCompactEncoding();
2664 #elif defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
2665     result = this->stepWithSEHData();
2666 #elif defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2667     result = this->stepWithTBTableData();
2668 #elif defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2669     result = this->stepWithDwarfFDE();
2670 #elif defined(_LIBUNWIND_ARM_EHABI)
2671     result = this->stepWithEHABI();
2672 #else
2673   #error Need _LIBUNWIND_SUPPORT_COMPACT_UNWIND or \
2674               _LIBUNWIND_SUPPORT_SEH_UNWIND or \
2675               _LIBUNWIND_SUPPORT_DWARF_UNWIND or \
2676               _LIBUNWIND_ARM_EHABI
2677 #endif
2678   }
2679 
2680   // update info based on new PC
2681   if (result == UNW_STEP_SUCCESS) {
2682     this->setInfoBasedOnIPRegister(true);
2683     if (_unwindInfoMissing)
2684       return UNW_STEP_END;
2685   }
2686 
2687   return result;
2688 }
2689 
2690 template <typename A, typename R>
2691 void UnwindCursor<A, R>::getInfo(unw_proc_info_t *info) {
2692   if (_unwindInfoMissing)
2693     memset(info, 0, sizeof(*info));
2694   else
2695     *info = _info;
2696 }
2697 
2698 template <typename A, typename R>
2699 bool UnwindCursor<A, R>::getFunctionName(char *buf, size_t bufLen,
2700                                                            unw_word_t *offset) {
2701   return _addressSpace.findFunctionName((pint_t)this->getReg(UNW_REG_IP),
2702                                          buf, bufLen, offset);
2703 }
2704 
2705 #if defined(_LIBUNWIND_USE_CET)
2706 extern "C" void *__libunwind_cet_get_registers(unw_cursor_t *cursor) {
2707   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
2708   return co->get_registers();
2709 }
2710 #endif
2711 } // namespace libunwind
2712 
2713 #endif // __UNWINDCURSOR_HPP__
2714