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