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) || defined(_LIBUNWIND_TARGET_S390X))
957   bool setInfoForSigReturn() {
958     R dummy;
959     return setInfoForSigReturn(dummy);
960   }
961   int stepThroughSigReturn() {
962     R dummy;
963     return stepThroughSigReturn(dummy);
964   }
965   #if defined(_LIBUNWIND_TARGET_AARCH64)
966   bool setInfoForSigReturn(Registers_arm64 &);
967   int stepThroughSigReturn(Registers_arm64 &);
968   #endif
969   #if defined(_LIBUNWIND_TARGET_S390X)
970   bool setInfoForSigReturn(Registers_s390x &);
971   int stepThroughSigReturn(Registers_s390x &);
972   #endif
973   template <typename Registers> bool setInfoForSigReturn(Registers &) {
974     return false;
975   }
976   template <typename Registers> int stepThroughSigReturn(Registers &) {
977     return UNW_STEP_END;
978   }
979 #endif
980 
981 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
982   bool getInfoFromFdeCie(const typename CFI_Parser<A>::FDE_Info &fdeInfo,
983                          const typename CFI_Parser<A>::CIE_Info &cieInfo,
984                          pint_t pc, uintptr_t dso_base);
985   bool getInfoFromDwarfSection(pint_t pc, const UnwindInfoSections &sects,
986                                             uint32_t fdeSectionOffsetHint=0);
987   int stepWithDwarfFDE() {
988     return DwarfInstructions<A, R>::stepWithDwarf(_addressSpace,
989                                               (pint_t)this->getReg(UNW_REG_IP),
990                                               (pint_t)_info.unwind_info,
991                                               _registers, _isSignalFrame);
992   }
993 #endif
994 
995 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
996   bool getInfoFromCompactEncodingSection(pint_t pc,
997                                             const UnwindInfoSections &sects);
998   int stepWithCompactEncoding() {
999   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1000     if ( compactSaysUseDwarf() )
1001       return stepWithDwarfFDE();
1002   #endif
1003     R dummy;
1004     return stepWithCompactEncoding(dummy);
1005   }
1006 
1007 #if defined(_LIBUNWIND_TARGET_X86_64)
1008   int stepWithCompactEncoding(Registers_x86_64 &) {
1009     return CompactUnwinder_x86_64<A>::stepWithCompactEncoding(
1010         _info.format, _info.start_ip, _addressSpace, _registers);
1011   }
1012 #endif
1013 
1014 #if defined(_LIBUNWIND_TARGET_I386)
1015   int stepWithCompactEncoding(Registers_x86 &) {
1016     return CompactUnwinder_x86<A>::stepWithCompactEncoding(
1017         _info.format, (uint32_t)_info.start_ip, _addressSpace, _registers);
1018   }
1019 #endif
1020 
1021 #if defined(_LIBUNWIND_TARGET_PPC)
1022   int stepWithCompactEncoding(Registers_ppc &) {
1023     return UNW_EINVAL;
1024   }
1025 #endif
1026 
1027 #if defined(_LIBUNWIND_TARGET_PPC64)
1028   int stepWithCompactEncoding(Registers_ppc64 &) {
1029     return UNW_EINVAL;
1030   }
1031 #endif
1032 
1033 
1034 #if defined(_LIBUNWIND_TARGET_AARCH64)
1035   int stepWithCompactEncoding(Registers_arm64 &) {
1036     return CompactUnwinder_arm64<A>::stepWithCompactEncoding(
1037         _info.format, _info.start_ip, _addressSpace, _registers);
1038   }
1039 #endif
1040 
1041 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
1042   int stepWithCompactEncoding(Registers_mips_o32 &) {
1043     return UNW_EINVAL;
1044   }
1045 #endif
1046 
1047 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1048   int stepWithCompactEncoding(Registers_mips_newabi &) {
1049     return UNW_EINVAL;
1050   }
1051 #endif
1052 
1053 #if defined(_LIBUNWIND_TARGET_SPARC)
1054   int stepWithCompactEncoding(Registers_sparc &) { return UNW_EINVAL; }
1055 #endif
1056 
1057 #if defined(_LIBUNWIND_TARGET_SPARC64)
1058   int stepWithCompactEncoding(Registers_sparc64 &) { return UNW_EINVAL; }
1059 #endif
1060 
1061 #if defined (_LIBUNWIND_TARGET_RISCV)
1062   int stepWithCompactEncoding(Registers_riscv &) {
1063     return UNW_EINVAL;
1064   }
1065 #endif
1066 
1067   bool compactSaysUseDwarf(uint32_t *offset=NULL) const {
1068     R dummy;
1069     return compactSaysUseDwarf(dummy, offset);
1070   }
1071 
1072 #if defined(_LIBUNWIND_TARGET_X86_64)
1073   bool compactSaysUseDwarf(Registers_x86_64 &, uint32_t *offset) const {
1074     if ((_info.format & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF) {
1075       if (offset)
1076         *offset = (_info.format & UNWIND_X86_64_DWARF_SECTION_OFFSET);
1077       return true;
1078     }
1079     return false;
1080   }
1081 #endif
1082 
1083 #if defined(_LIBUNWIND_TARGET_I386)
1084   bool compactSaysUseDwarf(Registers_x86 &, uint32_t *offset) const {
1085     if ((_info.format & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF) {
1086       if (offset)
1087         *offset = (_info.format & UNWIND_X86_DWARF_SECTION_OFFSET);
1088       return true;
1089     }
1090     return false;
1091   }
1092 #endif
1093 
1094 #if defined(_LIBUNWIND_TARGET_PPC)
1095   bool compactSaysUseDwarf(Registers_ppc &, uint32_t *) const {
1096     return true;
1097   }
1098 #endif
1099 
1100 #if defined(_LIBUNWIND_TARGET_PPC64)
1101   bool compactSaysUseDwarf(Registers_ppc64 &, uint32_t *) const {
1102     return true;
1103   }
1104 #endif
1105 
1106 #if defined(_LIBUNWIND_TARGET_AARCH64)
1107   bool compactSaysUseDwarf(Registers_arm64 &, uint32_t *offset) const {
1108     if ((_info.format & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF) {
1109       if (offset)
1110         *offset = (_info.format & UNWIND_ARM64_DWARF_SECTION_OFFSET);
1111       return true;
1112     }
1113     return false;
1114   }
1115 #endif
1116 
1117 #if defined(_LIBUNWIND_TARGET_MIPS_O32)
1118   bool compactSaysUseDwarf(Registers_mips_o32 &, uint32_t *) const {
1119     return true;
1120   }
1121 #endif
1122 
1123 #if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1124   bool compactSaysUseDwarf(Registers_mips_newabi &, uint32_t *) const {
1125     return true;
1126   }
1127 #endif
1128 
1129 #if defined(_LIBUNWIND_TARGET_SPARC)
1130   bool compactSaysUseDwarf(Registers_sparc &, uint32_t *) const { return true; }
1131 #endif
1132 
1133 #if defined(_LIBUNWIND_TARGET_SPARC64)
1134   bool compactSaysUseDwarf(Registers_sparc64 &, uint32_t *) const {
1135     return true;
1136   }
1137 #endif
1138 
1139 #if defined (_LIBUNWIND_TARGET_RISCV)
1140   bool compactSaysUseDwarf(Registers_riscv &, uint32_t *) const {
1141     return true;
1142   }
1143 #endif
1144 
1145 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1146 
1147 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1148   compact_unwind_encoding_t dwarfEncoding() const {
1149     R dummy;
1150     return dwarfEncoding(dummy);
1151   }
1152 
1153 #if defined(_LIBUNWIND_TARGET_X86_64)
1154   compact_unwind_encoding_t dwarfEncoding(Registers_x86_64 &) const {
1155     return UNWIND_X86_64_MODE_DWARF;
1156   }
1157 #endif
1158 
1159 #if defined(_LIBUNWIND_TARGET_I386)
1160   compact_unwind_encoding_t dwarfEncoding(Registers_x86 &) const {
1161     return UNWIND_X86_MODE_DWARF;
1162   }
1163 #endif
1164 
1165 #if defined(_LIBUNWIND_TARGET_PPC)
1166   compact_unwind_encoding_t dwarfEncoding(Registers_ppc &) const {
1167     return 0;
1168   }
1169 #endif
1170 
1171 #if defined(_LIBUNWIND_TARGET_PPC64)
1172   compact_unwind_encoding_t dwarfEncoding(Registers_ppc64 &) const {
1173     return 0;
1174   }
1175 #endif
1176 
1177 #if defined(_LIBUNWIND_TARGET_AARCH64)
1178   compact_unwind_encoding_t dwarfEncoding(Registers_arm64 &) const {
1179     return UNWIND_ARM64_MODE_DWARF;
1180   }
1181 #endif
1182 
1183 #if defined(_LIBUNWIND_TARGET_ARM)
1184   compact_unwind_encoding_t dwarfEncoding(Registers_arm &) const {
1185     return 0;
1186   }
1187 #endif
1188 
1189 #if defined (_LIBUNWIND_TARGET_OR1K)
1190   compact_unwind_encoding_t dwarfEncoding(Registers_or1k &) const {
1191     return 0;
1192   }
1193 #endif
1194 
1195 #if defined (_LIBUNWIND_TARGET_HEXAGON)
1196   compact_unwind_encoding_t dwarfEncoding(Registers_hexagon &) const {
1197     return 0;
1198   }
1199 #endif
1200 
1201 #if defined (_LIBUNWIND_TARGET_MIPS_O32)
1202   compact_unwind_encoding_t dwarfEncoding(Registers_mips_o32 &) const {
1203     return 0;
1204   }
1205 #endif
1206 
1207 #if defined (_LIBUNWIND_TARGET_MIPS_NEWABI)
1208   compact_unwind_encoding_t dwarfEncoding(Registers_mips_newabi &) const {
1209     return 0;
1210   }
1211 #endif
1212 
1213 #if defined(_LIBUNWIND_TARGET_SPARC)
1214   compact_unwind_encoding_t dwarfEncoding(Registers_sparc &) const { return 0; }
1215 #endif
1216 
1217 #if defined(_LIBUNWIND_TARGET_SPARC64)
1218   compact_unwind_encoding_t dwarfEncoding(Registers_sparc64 &) const {
1219     return 0;
1220   }
1221 #endif
1222 
1223 #if defined (_LIBUNWIND_TARGET_RISCV)
1224   compact_unwind_encoding_t dwarfEncoding(Registers_riscv &) const {
1225     return 0;
1226   }
1227 #endif
1228 
1229 #if defined (_LIBUNWIND_TARGET_S390X)
1230   compact_unwind_encoding_t dwarfEncoding(Registers_s390x &) const {
1231     return 0;
1232   }
1233 #endif
1234 
1235 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1236 
1237 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1238   // For runtime environments using SEH unwind data without Windows runtime
1239   // support.
1240   pint_t getLastPC() const { /* FIXME: Implement */ return 0; }
1241   void setLastPC(pint_t pc) { /* FIXME: Implement */ }
1242   RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
1243     /* FIXME: Implement */
1244     *base = 0;
1245     return nullptr;
1246   }
1247   bool getInfoFromSEH(pint_t pc);
1248   int stepWithSEHData() { /* FIXME: Implement */ return 0; }
1249 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1250 
1251 #if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1252   bool getInfoFromTBTable(pint_t pc, R &registers);
1253   int stepWithTBTable(pint_t pc, tbtable *TBTable, R &registers,
1254                       bool &isSignalFrame);
1255   int stepWithTBTableData() {
1256     return stepWithTBTable(reinterpret_cast<pint_t>(this->getReg(UNW_REG_IP)),
1257                            reinterpret_cast<tbtable *>(_info.unwind_info),
1258                            _registers, _isSignalFrame);
1259   }
1260 #endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1261 
1262   A               &_addressSpace;
1263   R                _registers;
1264   unw_proc_info_t  _info;
1265   bool             _unwindInfoMissing;
1266   bool             _isSignalFrame;
1267 #if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_S390X))
1268   bool             _isSigReturn = false;
1269 #endif
1270 };
1271 
1272 
1273 template <typename A, typename R>
1274 UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
1275     : _addressSpace(as), _registers(context), _unwindInfoMissing(false),
1276       _isSignalFrame(false) {
1277   static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
1278                 "UnwindCursor<> does not fit in unw_cursor_t");
1279   static_assert((alignof(UnwindCursor<A, R>) <= alignof(unw_cursor_t)),
1280                 "UnwindCursor<> requires more alignment than unw_cursor_t");
1281   memset(&_info, 0, sizeof(_info));
1282 }
1283 
1284 template <typename A, typename R>
1285 UnwindCursor<A, R>::UnwindCursor(A &as, void *)
1286     : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) {
1287   memset(&_info, 0, sizeof(_info));
1288   // FIXME
1289   // fill in _registers from thread arg
1290 }
1291 
1292 
1293 template <typename A, typename R>
1294 bool UnwindCursor<A, R>::validReg(int regNum) {
1295   return _registers.validRegister(regNum);
1296 }
1297 
1298 template <typename A, typename R>
1299 unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
1300   return _registers.getRegister(regNum);
1301 }
1302 
1303 template <typename A, typename R>
1304 void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
1305   _registers.setRegister(regNum, (typename A::pint_t)value);
1306 }
1307 
1308 template <typename A, typename R>
1309 bool UnwindCursor<A, R>::validFloatReg(int regNum) {
1310   return _registers.validFloatRegister(regNum);
1311 }
1312 
1313 template <typename A, typename R>
1314 unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
1315   return _registers.getFloatRegister(regNum);
1316 }
1317 
1318 template <typename A, typename R>
1319 void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
1320   _registers.setFloatRegister(regNum, value);
1321 }
1322 
1323 template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
1324   _registers.jumpto();
1325 }
1326 
1327 #ifdef __arm__
1328 template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {
1329   _registers.saveVFPAsX();
1330 }
1331 #endif
1332 
1333 #ifdef _AIX
1334 template <typename A, typename R>
1335 uintptr_t UnwindCursor<A, R>::getDataRelBase() {
1336   return reinterpret_cast<uintptr_t>(_info.extra);
1337 }
1338 #endif
1339 
1340 template <typename A, typename R>
1341 const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
1342   return _registers.getRegisterName(regNum);
1343 }
1344 
1345 template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
1346   return _isSignalFrame;
1347 }
1348 
1349 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1350 
1351 #if defined(_LIBUNWIND_ARM_EHABI)
1352 template<typename A>
1353 struct EHABISectionIterator {
1354   typedef EHABISectionIterator _Self;
1355 
1356   typedef typename A::pint_t value_type;
1357   typedef typename A::pint_t* pointer;
1358   typedef typename A::pint_t& reference;
1359   typedef size_t size_type;
1360   typedef size_t difference_type;
1361 
1362   static _Self begin(A& addressSpace, const UnwindInfoSections& sects) {
1363     return _Self(addressSpace, sects, 0);
1364   }
1365   static _Self end(A& addressSpace, const UnwindInfoSections& sects) {
1366     return _Self(addressSpace, sects,
1367                  sects.arm_section_length / sizeof(EHABIIndexEntry));
1368   }
1369 
1370   EHABISectionIterator(A& addressSpace, const UnwindInfoSections& sects, size_t i)
1371       : _i(i), _addressSpace(&addressSpace), _sects(&sects) {}
1372 
1373   _Self& operator++() { ++_i; return *this; }
1374   _Self& operator+=(size_t a) { _i += a; return *this; }
1375   _Self& operator--() { assert(_i > 0); --_i; return *this; }
1376   _Self& operator-=(size_t a) { assert(_i >= a); _i -= a; return *this; }
1377 
1378   _Self operator+(size_t a) { _Self out = *this; out._i += a; return out; }
1379   _Self operator-(size_t a) { assert(_i >= a); _Self out = *this; out._i -= a; return out; }
1380 
1381   size_t operator-(const _Self& other) const { return _i - other._i; }
1382 
1383   bool operator==(const _Self& other) const {
1384     assert(_addressSpace == other._addressSpace);
1385     assert(_sects == other._sects);
1386     return _i == other._i;
1387   }
1388 
1389   bool operator!=(const _Self& other) const {
1390     assert(_addressSpace == other._addressSpace);
1391     assert(_sects == other._sects);
1392     return _i != other._i;
1393   }
1394 
1395   typename A::pint_t operator*() const { return functionAddress(); }
1396 
1397   typename A::pint_t functionAddress() const {
1398     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1399         EHABIIndexEntry, _i, functionOffset);
1400     return indexAddr + signExtendPrel31(_addressSpace->get32(indexAddr));
1401   }
1402 
1403   typename A::pint_t dataAddress() {
1404     typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1405         EHABIIndexEntry, _i, data);
1406     return indexAddr;
1407   }
1408 
1409  private:
1410   size_t _i;
1411   A* _addressSpace;
1412   const UnwindInfoSections* _sects;
1413 };
1414 
1415 namespace {
1416 
1417 template <typename A>
1418 EHABISectionIterator<A> EHABISectionUpperBound(
1419     EHABISectionIterator<A> first,
1420     EHABISectionIterator<A> last,
1421     typename A::pint_t value) {
1422   size_t len = last - first;
1423   while (len > 0) {
1424     size_t l2 = len / 2;
1425     EHABISectionIterator<A> m = first + l2;
1426     if (value < *m) {
1427         len = l2;
1428     } else {
1429         first = ++m;
1430         len -= l2 + 1;
1431     }
1432   }
1433   return first;
1434 }
1435 
1436 }
1437 
1438 template <typename A, typename R>
1439 bool UnwindCursor<A, R>::getInfoFromEHABISection(
1440     pint_t pc,
1441     const UnwindInfoSections &sects) {
1442   EHABISectionIterator<A> begin =
1443       EHABISectionIterator<A>::begin(_addressSpace, sects);
1444   EHABISectionIterator<A> end =
1445       EHABISectionIterator<A>::end(_addressSpace, sects);
1446   if (begin == end)
1447     return false;
1448 
1449   EHABISectionIterator<A> itNextPC = EHABISectionUpperBound(begin, end, pc);
1450   if (itNextPC == begin)
1451     return false;
1452   EHABISectionIterator<A> itThisPC = itNextPC - 1;
1453 
1454   pint_t thisPC = itThisPC.functionAddress();
1455   // If an exception is thrown from a function, corresponding to the last entry
1456   // in the table, we don't really know the function extent and have to choose a
1457   // value for nextPC. Choosing max() will allow the range check during trace to
1458   // succeed.
1459   pint_t nextPC = (itNextPC == end) ? UINTPTR_MAX : itNextPC.functionAddress();
1460   pint_t indexDataAddr = itThisPC.dataAddress();
1461 
1462   if (indexDataAddr == 0)
1463     return false;
1464 
1465   uint32_t indexData = _addressSpace.get32(indexDataAddr);
1466   if (indexData == UNW_EXIDX_CANTUNWIND)
1467     return false;
1468 
1469   // If the high bit is set, the exception handling table entry is inline inside
1470   // the index table entry on the second word (aka |indexDataAddr|). Otherwise,
1471   // the table points at an offset in the exception handling table (section 5
1472   // EHABI).
1473   pint_t exceptionTableAddr;
1474   uint32_t exceptionTableData;
1475   bool isSingleWordEHT;
1476   if (indexData & 0x80000000) {
1477     exceptionTableAddr = indexDataAddr;
1478     // TODO(ajwong): Should this data be 0?
1479     exceptionTableData = indexData;
1480     isSingleWordEHT = true;
1481   } else {
1482     exceptionTableAddr = indexDataAddr + signExtendPrel31(indexData);
1483     exceptionTableData = _addressSpace.get32(exceptionTableAddr);
1484     isSingleWordEHT = false;
1485   }
1486 
1487   // Now we know the 3 things:
1488   //   exceptionTableAddr -- exception handler table entry.
1489   //   exceptionTableData -- the data inside the first word of the eht entry.
1490   //   isSingleWordEHT -- whether the entry is in the index.
1491   unw_word_t personalityRoutine = 0xbadf00d;
1492   bool scope32 = false;
1493   uintptr_t lsda;
1494 
1495   // If the high bit in the exception handling table entry is set, the entry is
1496   // in compact form (section 6.3 EHABI).
1497   if (exceptionTableData & 0x80000000) {
1498     // Grab the index of the personality routine from the compact form.
1499     uint32_t choice = (exceptionTableData & 0x0f000000) >> 24;
1500     uint32_t extraWords = 0;
1501     switch (choice) {
1502       case 0:
1503         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr0;
1504         extraWords = 0;
1505         scope32 = false;
1506         lsda = isSingleWordEHT ? 0 : (exceptionTableAddr + 4);
1507         break;
1508       case 1:
1509         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr1;
1510         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1511         scope32 = false;
1512         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1513         break;
1514       case 2:
1515         personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr2;
1516         extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1517         scope32 = true;
1518         lsda = exceptionTableAddr + (extraWords + 1) * 4;
1519         break;
1520       default:
1521         _LIBUNWIND_ABORT("unknown personality routine");
1522         return false;
1523     }
1524 
1525     if (isSingleWordEHT) {
1526       if (extraWords != 0) {
1527         _LIBUNWIND_ABORT("index inlined table detected but pr function "
1528                          "requires extra words");
1529         return false;
1530       }
1531     }
1532   } else {
1533     pint_t personalityAddr =
1534         exceptionTableAddr + signExtendPrel31(exceptionTableData);
1535     personalityRoutine = personalityAddr;
1536 
1537     // ARM EHABI # 6.2, # 9.2
1538     //
1539     //  +---- ehtp
1540     //  v
1541     // +--------------------------------------+
1542     // | +--------+--------+--------+-------+ |
1543     // | |0| prel31 to personalityRoutine   | |
1544     // | +--------+--------+--------+-------+ |
1545     // | |      N |      unwind opcodes     | |  <-- UnwindData
1546     // | +--------+--------+--------+-------+ |
1547     // | | Word 2        unwind opcodes     | |
1548     // | +--------+--------+--------+-------+ |
1549     // | ...                                  |
1550     // | +--------+--------+--------+-------+ |
1551     // | | Word N        unwind opcodes     | |
1552     // | +--------+--------+--------+-------+ |
1553     // | | LSDA                             | |  <-- lsda
1554     // | | ...                              | |
1555     // | +--------+--------+--------+-------+ |
1556     // +--------------------------------------+
1557 
1558     uint32_t *UnwindData = reinterpret_cast<uint32_t*>(exceptionTableAddr) + 1;
1559     uint32_t FirstDataWord = *UnwindData;
1560     size_t N = ((FirstDataWord >> 24) & 0xff);
1561     size_t NDataWords = N + 1;
1562     lsda = reinterpret_cast<uintptr_t>(UnwindData + NDataWords);
1563   }
1564 
1565   _info.start_ip = thisPC;
1566   _info.end_ip = nextPC;
1567   _info.handler = personalityRoutine;
1568   _info.unwind_info = exceptionTableAddr;
1569   _info.lsda = lsda;
1570   // flags is pr_cache.additional. See EHABI #7.2 for definition of bit 0.
1571   _info.flags = (isSingleWordEHT ? 1 : 0) | (scope32 ? 0x2 : 0);  // Use enum?
1572 
1573   return true;
1574 }
1575 #endif
1576 
1577 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1578 template <typename A, typename R>
1579 bool UnwindCursor<A, R>::getInfoFromFdeCie(
1580     const typename CFI_Parser<A>::FDE_Info &fdeInfo,
1581     const typename CFI_Parser<A>::CIE_Info &cieInfo, pint_t pc,
1582     uintptr_t dso_base) {
1583   typename CFI_Parser<A>::PrologInfo prolog;
1584   if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo, pc,
1585                                           R::getArch(), &prolog)) {
1586     // Save off parsed FDE info
1587     _info.start_ip          = fdeInfo.pcStart;
1588     _info.end_ip            = fdeInfo.pcEnd;
1589     _info.lsda              = fdeInfo.lsda;
1590     _info.handler           = cieInfo.personality;
1591     // Some frameless functions need SP altered when resuming in function, so
1592     // propagate spExtraArgSize.
1593     _info.gp                = prolog.spExtraArgSize;
1594     _info.flags             = 0;
1595     _info.format            = dwarfEncoding();
1596     _info.unwind_info       = fdeInfo.fdeStart;
1597     _info.unwind_info_size  = static_cast<uint32_t>(fdeInfo.fdeLength);
1598     _info.extra             = static_cast<unw_word_t>(dso_base);
1599     return true;
1600   }
1601   return false;
1602 }
1603 
1604 template <typename A, typename R>
1605 bool UnwindCursor<A, R>::getInfoFromDwarfSection(pint_t pc,
1606                                                 const UnwindInfoSections &sects,
1607                                                 uint32_t fdeSectionOffsetHint) {
1608   typename CFI_Parser<A>::FDE_Info fdeInfo;
1609   typename CFI_Parser<A>::CIE_Info cieInfo;
1610   bool foundFDE = false;
1611   bool foundInCache = false;
1612   // If compact encoding table gave offset into dwarf section, go directly there
1613   if (fdeSectionOffsetHint != 0) {
1614     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1615                                     sects.dwarf_section_length,
1616                                     sects.dwarf_section + fdeSectionOffsetHint,
1617                                     &fdeInfo, &cieInfo);
1618   }
1619 #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1620   if (!foundFDE && (sects.dwarf_index_section != 0)) {
1621     foundFDE = EHHeaderParser<A>::findFDE(
1622         _addressSpace, pc, sects.dwarf_index_section,
1623         (uint32_t)sects.dwarf_index_section_length, &fdeInfo, &cieInfo);
1624   }
1625 #endif
1626   if (!foundFDE) {
1627     // otherwise, search cache of previously found FDEs.
1628     pint_t cachedFDE = DwarfFDECache<A>::findFDE(sects.dso_base, pc);
1629     if (cachedFDE != 0) {
1630       foundFDE =
1631           CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1632                                  sects.dwarf_section_length,
1633                                  cachedFDE, &fdeInfo, &cieInfo);
1634       foundInCache = foundFDE;
1635     }
1636   }
1637   if (!foundFDE) {
1638     // Still not found, do full scan of __eh_frame section.
1639     foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
1640                                       sects.dwarf_section_length, 0,
1641                                       &fdeInfo, &cieInfo);
1642   }
1643   if (foundFDE) {
1644     if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, sects.dso_base)) {
1645       // Add to cache (to make next lookup faster) if we had no hint
1646       // and there was no index.
1647       if (!foundInCache && (fdeSectionOffsetHint == 0)) {
1648   #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
1649         if (sects.dwarf_index_section == 0)
1650   #endif
1651         DwarfFDECache<A>::add(sects.dso_base, fdeInfo.pcStart, fdeInfo.pcEnd,
1652                               fdeInfo.fdeStart);
1653       }
1654       return true;
1655     }
1656   }
1657   //_LIBUNWIND_DEBUG_LOG("can't find/use FDE for pc=0x%llX", (uint64_t)pc);
1658   return false;
1659 }
1660 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
1661 
1662 
1663 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1664 template <typename A, typename R>
1665 bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
1666                                               const UnwindInfoSections &sects) {
1667   const bool log = false;
1668   if (log)
1669     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX, mh=0x%llX)\n",
1670             (uint64_t)pc, (uint64_t)sects.dso_base);
1671 
1672   const UnwindSectionHeader<A> sectionHeader(_addressSpace,
1673                                                 sects.compact_unwind_section);
1674   if (sectionHeader.version() != UNWIND_SECTION_VERSION)
1675     return false;
1676 
1677   // do a binary search of top level index to find page with unwind info
1678   pint_t targetFunctionOffset = pc - sects.dso_base;
1679   const UnwindSectionIndexArray<A> topIndex(_addressSpace,
1680                                            sects.compact_unwind_section
1681                                          + sectionHeader.indexSectionOffset());
1682   uint32_t low = 0;
1683   uint32_t high = sectionHeader.indexCount();
1684   uint32_t last = high - 1;
1685   while (low < high) {
1686     uint32_t mid = (low + high) / 2;
1687     //if ( log ) fprintf(stderr, "\tmid=%d, low=%d, high=%d, *mid=0x%08X\n",
1688     //mid, low, high, topIndex.functionOffset(mid));
1689     if (topIndex.functionOffset(mid) <= targetFunctionOffset) {
1690       if ((mid == last) ||
1691           (topIndex.functionOffset(mid + 1) > targetFunctionOffset)) {
1692         low = mid;
1693         break;
1694       } else {
1695         low = mid + 1;
1696       }
1697     } else {
1698       high = mid;
1699     }
1700   }
1701   const uint32_t firstLevelFunctionOffset = topIndex.functionOffset(low);
1702   const uint32_t firstLevelNextPageFunctionOffset =
1703       topIndex.functionOffset(low + 1);
1704   const pint_t secondLevelAddr =
1705       sects.compact_unwind_section + topIndex.secondLevelPagesSectionOffset(low);
1706   const pint_t lsdaArrayStartAddr =
1707       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low);
1708   const pint_t lsdaArrayEndAddr =
1709       sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low+1);
1710   if (log)
1711     fprintf(stderr, "\tfirst level search for result index=%d "
1712                     "to secondLevelAddr=0x%llX\n",
1713                     low, (uint64_t) secondLevelAddr);
1714   // do a binary search of second level page index
1715   uint32_t encoding = 0;
1716   pint_t funcStart = 0;
1717   pint_t funcEnd = 0;
1718   pint_t lsda = 0;
1719   pint_t personality = 0;
1720   uint32_t pageKind = _addressSpace.get32(secondLevelAddr);
1721   if (pageKind == UNWIND_SECOND_LEVEL_REGULAR) {
1722     // regular page
1723     UnwindSectionRegularPageHeader<A> pageHeader(_addressSpace,
1724                                                  secondLevelAddr);
1725     UnwindSectionRegularArray<A> pageIndex(
1726         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1727     // binary search looks for entry with e where index[e].offset <= pc <
1728     // index[e+1].offset
1729     if (log)
1730       fprintf(stderr, "\tbinary search for targetFunctionOffset=0x%08llX in "
1731                       "regular page starting at secondLevelAddr=0x%llX\n",
1732               (uint64_t) targetFunctionOffset, (uint64_t) secondLevelAddr);
1733     low = 0;
1734     high = pageHeader.entryCount();
1735     while (low < high) {
1736       uint32_t mid = (low + high) / 2;
1737       if (pageIndex.functionOffset(mid) <= targetFunctionOffset) {
1738         if (mid == (uint32_t)(pageHeader.entryCount() - 1)) {
1739           // at end of table
1740           low = mid;
1741           funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1742           break;
1743         } else if (pageIndex.functionOffset(mid + 1) > targetFunctionOffset) {
1744           // next is too big, so we found it
1745           low = mid;
1746           funcEnd = pageIndex.functionOffset(low + 1) + sects.dso_base;
1747           break;
1748         } else {
1749           low = mid + 1;
1750         }
1751       } else {
1752         high = mid;
1753       }
1754     }
1755     encoding = pageIndex.encoding(low);
1756     funcStart = pageIndex.functionOffset(low) + sects.dso_base;
1757     if (pc < funcStart) {
1758       if (log)
1759         fprintf(
1760             stderr,
1761             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1762             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1763       return false;
1764     }
1765     if (pc > funcEnd) {
1766       if (log)
1767         fprintf(
1768             stderr,
1769             "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1770             (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1771       return false;
1772     }
1773   } else if (pageKind == UNWIND_SECOND_LEVEL_COMPRESSED) {
1774     // compressed page
1775     UnwindSectionCompressedPageHeader<A> pageHeader(_addressSpace,
1776                                                     secondLevelAddr);
1777     UnwindSectionCompressedArray<A> pageIndex(
1778         _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1779     const uint32_t targetFunctionPageOffset =
1780         (uint32_t)(targetFunctionOffset - firstLevelFunctionOffset);
1781     // binary search looks for entry with e where index[e].offset <= pc <
1782     // index[e+1].offset
1783     if (log)
1784       fprintf(stderr, "\tbinary search of compressed page starting at "
1785                       "secondLevelAddr=0x%llX\n",
1786               (uint64_t) secondLevelAddr);
1787     low = 0;
1788     last = pageHeader.entryCount() - 1;
1789     high = pageHeader.entryCount();
1790     while (low < high) {
1791       uint32_t mid = (low + high) / 2;
1792       if (pageIndex.functionOffset(mid) <= targetFunctionPageOffset) {
1793         if ((mid == last) ||
1794             (pageIndex.functionOffset(mid + 1) > targetFunctionPageOffset)) {
1795           low = mid;
1796           break;
1797         } else {
1798           low = mid + 1;
1799         }
1800       } else {
1801         high = mid;
1802       }
1803     }
1804     funcStart = pageIndex.functionOffset(low) + firstLevelFunctionOffset
1805                                                               + sects.dso_base;
1806     if (low < last)
1807       funcEnd =
1808           pageIndex.functionOffset(low + 1) + firstLevelFunctionOffset
1809                                                               + sects.dso_base;
1810     else
1811       funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1812     if (pc < funcStart) {
1813       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1814                            "not in second level compressed unwind table. "
1815                            "funcStart=0x%llX",
1816                             (uint64_t) pc, (uint64_t) funcStart);
1817       return false;
1818     }
1819     if (pc > funcEnd) {
1820       _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1821                            "not in second level compressed unwind table. "
1822                            "funcEnd=0x%llX",
1823                            (uint64_t) pc, (uint64_t) funcEnd);
1824       return false;
1825     }
1826     uint16_t encodingIndex = pageIndex.encodingIndex(low);
1827     if (encodingIndex < sectionHeader.commonEncodingsArrayCount()) {
1828       // encoding is in common table in section header
1829       encoding = _addressSpace.get32(
1830           sects.compact_unwind_section +
1831           sectionHeader.commonEncodingsArraySectionOffset() +
1832           encodingIndex * sizeof(uint32_t));
1833     } else {
1834       // encoding is in page specific table
1835       uint16_t pageEncodingIndex =
1836           encodingIndex - (uint16_t)sectionHeader.commonEncodingsArrayCount();
1837       encoding = _addressSpace.get32(secondLevelAddr +
1838                                      pageHeader.encodingsPageOffset() +
1839                                      pageEncodingIndex * sizeof(uint32_t));
1840     }
1841   } else {
1842     _LIBUNWIND_DEBUG_LOG(
1843         "malformed __unwind_info at 0x%0llX bad second level page",
1844         (uint64_t)sects.compact_unwind_section);
1845     return false;
1846   }
1847 
1848   // look up LSDA, if encoding says function has one
1849   if (encoding & UNWIND_HAS_LSDA) {
1850     UnwindSectionLsdaArray<A> lsdaIndex(_addressSpace, lsdaArrayStartAddr);
1851     uint32_t funcStartOffset = (uint32_t)(funcStart - sects.dso_base);
1852     low = 0;
1853     high = (uint32_t)(lsdaArrayEndAddr - lsdaArrayStartAddr) /
1854                     sizeof(unwind_info_section_header_lsda_index_entry);
1855     // binary search looks for entry with exact match for functionOffset
1856     if (log)
1857       fprintf(stderr,
1858               "\tbinary search of lsda table for targetFunctionOffset=0x%08X\n",
1859               funcStartOffset);
1860     while (low < high) {
1861       uint32_t mid = (low + high) / 2;
1862       if (lsdaIndex.functionOffset(mid) == funcStartOffset) {
1863         lsda = lsdaIndex.lsdaOffset(mid) + sects.dso_base;
1864         break;
1865       } else if (lsdaIndex.functionOffset(mid) < funcStartOffset) {
1866         low = mid + 1;
1867       } else {
1868         high = mid;
1869       }
1870     }
1871     if (lsda == 0) {
1872       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with HAS_LSDA bit set for "
1873                     "pc=0x%0llX, but lsda table has no entry",
1874                     encoding, (uint64_t) pc);
1875       return false;
1876     }
1877   }
1878 
1879   // extract personality routine, if encoding says function has one
1880   uint32_t personalityIndex = (encoding & UNWIND_PERSONALITY_MASK) >>
1881                               (__builtin_ctz(UNWIND_PERSONALITY_MASK));
1882   if (personalityIndex != 0) {
1883     --personalityIndex; // change 1-based to zero-based index
1884     if (personalityIndex >= sectionHeader.personalityArrayCount()) {
1885       _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with personality index %d,  "
1886                             "but personality table has only %d entries",
1887                             encoding, personalityIndex,
1888                             sectionHeader.personalityArrayCount());
1889       return false;
1890     }
1891     int32_t personalityDelta = (int32_t)_addressSpace.get32(
1892         sects.compact_unwind_section +
1893         sectionHeader.personalityArraySectionOffset() +
1894         personalityIndex * sizeof(uint32_t));
1895     pint_t personalityPointer = sects.dso_base + (pint_t)personalityDelta;
1896     personality = _addressSpace.getP(personalityPointer);
1897     if (log)
1898       fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1899                       "personalityDelta=0x%08X, personality=0x%08llX\n",
1900               (uint64_t) pc, personalityDelta, (uint64_t) personality);
1901   }
1902 
1903   if (log)
1904     fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1905                     "encoding=0x%08X, lsda=0x%08llX for funcStart=0x%llX\n",
1906             (uint64_t) pc, encoding, (uint64_t) lsda, (uint64_t) funcStart);
1907   _info.start_ip = funcStart;
1908   _info.end_ip = funcEnd;
1909   _info.lsda = lsda;
1910   _info.handler = personality;
1911   _info.gp = 0;
1912   _info.flags = 0;
1913   _info.format = encoding;
1914   _info.unwind_info = 0;
1915   _info.unwind_info_size = 0;
1916   _info.extra = sects.dso_base;
1917   return true;
1918 }
1919 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
1920 
1921 
1922 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1923 template <typename A, typename R>
1924 bool UnwindCursor<A, R>::getInfoFromSEH(pint_t pc) {
1925   pint_t base;
1926   RUNTIME_FUNCTION *unwindEntry = lookUpSEHUnwindInfo(pc, &base);
1927   if (!unwindEntry) {
1928     _LIBUNWIND_DEBUG_LOG("\tpc not in table, pc=0x%llX", (uint64_t) pc);
1929     return false;
1930   }
1931   _info.gp = 0;
1932   _info.flags = 0;
1933   _info.format = 0;
1934   _info.unwind_info_size = sizeof(RUNTIME_FUNCTION);
1935   _info.unwind_info = reinterpret_cast<unw_word_t>(unwindEntry);
1936   _info.extra = base;
1937   _info.start_ip = base + unwindEntry->BeginAddress;
1938 #ifdef _LIBUNWIND_TARGET_X86_64
1939   _info.end_ip = base + unwindEntry->EndAddress;
1940   // Only fill in the handler and LSDA if they're stale.
1941   if (pc != getLastPC()) {
1942     UNWIND_INFO *xdata = reinterpret_cast<UNWIND_INFO *>(base + unwindEntry->UnwindData);
1943     if (xdata->Flags & (UNW_FLAG_EHANDLER|UNW_FLAG_UHANDLER)) {
1944       // The personality is given in the UNWIND_INFO itself. The LSDA immediately
1945       // follows the UNWIND_INFO. (This follows how both Clang and MSVC emit
1946       // these structures.)
1947       // N.B. UNWIND_INFO structs are DWORD-aligned.
1948       uint32_t lastcode = (xdata->CountOfCodes + 1) & ~1;
1949       const uint32_t *handler = reinterpret_cast<uint32_t *>(&xdata->UnwindCodes[lastcode]);
1950       _info.lsda = reinterpret_cast<unw_word_t>(handler+1);
1951       if (*handler) {
1952         _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
1953       } else
1954         _info.handler = 0;
1955     } else {
1956       _info.lsda = 0;
1957       _info.handler = 0;
1958     }
1959   }
1960 #elif defined(_LIBUNWIND_TARGET_ARM)
1961   _info.end_ip = _info.start_ip + unwindEntry->FunctionLength;
1962   _info.lsda = 0; // FIXME
1963   _info.handler = 0; // FIXME
1964 #endif
1965   setLastPC(pc);
1966   return true;
1967 }
1968 #endif
1969 
1970 #if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1971 // Masks for traceback table field xtbtable.
1972 enum xTBTableMask : uint8_t {
1973   reservedBit = 0x02, // The traceback table was incorrectly generated if set
1974                       // (see comments in function getInfoFromTBTable().
1975   ehInfoBit = 0x08    // Exception handling info is present if set
1976 };
1977 
1978 enum frameType : unw_word_t {
1979   frameWithXLEHStateTable = 0,
1980   frameWithEHInfo = 1
1981 };
1982 
1983 extern "C" {
1984 typedef _Unwind_Reason_Code __xlcxx_personality_v0_t(int, _Unwind_Action,
1985                                                      uint64_t,
1986                                                      _Unwind_Exception *,
1987                                                      struct _Unwind_Context *);
1988 __attribute__((__weak__)) __xlcxx_personality_v0_t __xlcxx_personality_v0;
1989 }
1990 
1991 static __xlcxx_personality_v0_t *xlcPersonalityV0;
1992 static RWMutex xlcPersonalityV0InitLock;
1993 
1994 template <typename A, typename R>
1995 bool UnwindCursor<A, R>::getInfoFromTBTable(pint_t pc, R &registers) {
1996   uint32_t *p = reinterpret_cast<uint32_t *>(pc);
1997 
1998   // Keep looking forward until a word of 0 is found. The traceback
1999   // table starts at the following word.
2000   while (*p)
2001     ++p;
2002   tbtable *TBTable = reinterpret_cast<tbtable *>(p + 1);
2003 
2004   if (_LIBUNWIND_TRACING_UNWINDING) {
2005     char functionBuf[512];
2006     const char *functionName = functionBuf;
2007     unw_word_t offset;
2008     if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
2009       functionName = ".anonymous.";
2010     }
2011     _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2012                                __func__, functionName,
2013                                reinterpret_cast<void *>(TBTable));
2014   }
2015 
2016   // If the traceback table does not contain necessary info, bypass this frame.
2017   if (!TBTable->tb.has_tboff)
2018     return false;
2019 
2020   // Structure tbtable_ext contains important data we are looking for.
2021   p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2022 
2023   // Skip field parminfo if it exists.
2024   if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2025     ++p;
2026 
2027   // p now points to tb_offset, the offset from start of function to TB table.
2028   unw_word_t start_ip =
2029       reinterpret_cast<unw_word_t>(TBTable) - *p - sizeof(uint32_t);
2030   unw_word_t end_ip = reinterpret_cast<unw_word_t>(TBTable);
2031   ++p;
2032 
2033   _LIBUNWIND_TRACE_UNWINDING("start_ip=%p, end_ip=%p\n",
2034                              reinterpret_cast<void *>(start_ip),
2035                              reinterpret_cast<void *>(end_ip));
2036 
2037   // Skip field hand_mask if it exists.
2038   if (TBTable->tb.int_hndl)
2039     ++p;
2040 
2041   unw_word_t lsda = 0;
2042   unw_word_t handler = 0;
2043   unw_word_t flags = frameType::frameWithXLEHStateTable;
2044 
2045   if (TBTable->tb.lang == TB_CPLUSPLUS && TBTable->tb.has_ctl) {
2046     // State table info is available. The ctl_info field indicates the
2047     // number of CTL anchors. There should be only one entry for the C++
2048     // state table.
2049     assert(*p == 1 && "libunwind: there must be only one ctl_info entry");
2050     ++p;
2051     // p points to the offset of the state table into the stack.
2052     pint_t stateTableOffset = *p++;
2053 
2054     int framePointerReg;
2055 
2056     // Skip fields name_len and name if exist.
2057     if (TBTable->tb.name_present) {
2058       const uint16_t name_len = *(reinterpret_cast<uint16_t *>(p));
2059       p = reinterpret_cast<uint32_t *>(reinterpret_cast<char *>(p) + name_len +
2060                                        sizeof(uint16_t));
2061     }
2062 
2063     if (TBTable->tb.uses_alloca)
2064       framePointerReg = *(reinterpret_cast<char *>(p));
2065     else
2066       framePointerReg = 1; // default frame pointer == SP
2067 
2068     _LIBUNWIND_TRACE_UNWINDING(
2069         "framePointerReg=%d, framePointer=%p, "
2070         "stateTableOffset=%#lx\n",
2071         framePointerReg,
2072         reinterpret_cast<void *>(_registers.getRegister(framePointerReg)),
2073         stateTableOffset);
2074     lsda = _registers.getRegister(framePointerReg) + stateTableOffset;
2075 
2076     // Since the traceback table generated by the legacy XLC++ does not
2077     // provide the location of the personality for the state table,
2078     // function __xlcxx_personality_v0(), which is the personality for the state
2079     // table and is exported from libc++abi, is directly assigned as the
2080     // handler here. When a legacy XLC++ frame is encountered, the symbol
2081     // is resolved dynamically using dlopen() to avoid hard dependency from
2082     // libunwind on libc++abi.
2083 
2084     // Resolve the function pointer to the state table personality if it has
2085     // not already.
2086     if (xlcPersonalityV0 == NULL) {
2087       xlcPersonalityV0InitLock.lock();
2088       if (xlcPersonalityV0 == NULL) {
2089         // If libc++abi is statically linked in, symbol __xlcxx_personality_v0
2090         // has been resolved at the link time.
2091         xlcPersonalityV0 = &__xlcxx_personality_v0;
2092         if (xlcPersonalityV0 == NULL) {
2093           // libc++abi is dynamically linked. Resolve __xlcxx_personality_v0
2094           // using dlopen().
2095           const char libcxxabi[] = "libc++abi.a(libc++abi.so.1)";
2096           void *libHandle;
2097           libHandle = dlopen(libcxxabi, RTLD_MEMBER | RTLD_NOW);
2098           if (libHandle == NULL) {
2099             _LIBUNWIND_TRACE_UNWINDING("dlopen() failed with errno=%d\n",
2100                                        errno);
2101             assert(0 && "dlopen() failed");
2102           }
2103           xlcPersonalityV0 = reinterpret_cast<__xlcxx_personality_v0_t *>(
2104               dlsym(libHandle, "__xlcxx_personality_v0"));
2105           if (xlcPersonalityV0 == NULL) {
2106             _LIBUNWIND_TRACE_UNWINDING("dlsym() failed with errno=%d\n", errno);
2107             assert(0 && "dlsym() failed");
2108           }
2109           dlclose(libHandle);
2110         }
2111       }
2112       xlcPersonalityV0InitLock.unlock();
2113     }
2114     handler = reinterpret_cast<unw_word_t>(xlcPersonalityV0);
2115     _LIBUNWIND_TRACE_UNWINDING("State table: LSDA=%p, Personality=%p\n",
2116                                reinterpret_cast<void *>(lsda),
2117                                reinterpret_cast<void *>(handler));
2118   } else if (TBTable->tb.longtbtable) {
2119     // This frame has the traceback table extension. Possible cases are
2120     // 1) a C++ frame that has the 'eh_info' structure; 2) a C++ frame that
2121     // is not EH aware; or, 3) a frame of other languages. We need to figure out
2122     // if the traceback table extension contains the 'eh_info' structure.
2123     //
2124     // We also need to deal with the complexity arising from some XL compiler
2125     // versions use the wrong ordering of 'longtbtable' and 'has_vec' bits
2126     // where the 'longtbtable' bit is meant to be the 'has_vec' bit and vice
2127     // versa. For frames of code generated by those compilers, the 'longtbtable'
2128     // bit may be set but there isn't really a traceback table extension.
2129     //
2130     // In </usr/include/sys/debug.h>, there is the following definition of
2131     // 'struct tbtable_ext'. It is not really a structure but a dummy to
2132     // collect the description of optional parts of the traceback table.
2133     //
2134     // struct tbtable_ext {
2135     //   ...
2136     //   char alloca_reg;        /* Register for alloca automatic storage */
2137     //   struct vec_ext vec_ext; /* Vector extension (if has_vec is set) */
2138     //   unsigned char xtbtable; /* More tbtable fields, if longtbtable is set*/
2139     // };
2140     //
2141     // Depending on how the 'has_vec'/'longtbtable' bit is interpreted, the data
2142     // following 'alloca_reg' can be treated either as 'struct vec_ext' or
2143     // 'unsigned char xtbtable'. 'xtbtable' bits are defined in
2144     // </usr/include/sys/debug.h> as flags. The 7th bit '0x02' is currently
2145     // unused and should not be set. 'struct vec_ext' is defined in
2146     // </usr/include/sys/debug.h> as follows:
2147     //
2148     // struct vec_ext {
2149     //   unsigned vr_saved:6;      /* Number of non-volatile vector regs saved
2150     //   */
2151     //                             /* first register saved is assumed to be */
2152     //                             /* 32 - vr_saved                         */
2153     //   unsigned saves_vrsave:1;  /* Set if vrsave is saved on the stack */
2154     //   unsigned has_varargs:1;
2155     //   ...
2156     // };
2157     //
2158     // Here, the 7th bit is used as 'saves_vrsave'. To determine whether it
2159     // is 'struct vec_ext' or 'xtbtable' that follows 'alloca_reg',
2160     // we checks if the 7th bit is set or not because 'xtbtable' should
2161     // never have the 7th bit set. The 7th bit of 'xtbtable' will be reserved
2162     // in the future to make sure the mitigation works. This mitigation
2163     // is not 100% bullet proof because 'struct vec_ext' may not always have
2164     // 'saves_vrsave' bit set.
2165     //
2166     // 'reservedBit' is defined in enum 'xTBTableMask' above as the mask for
2167     // checking the 7th bit.
2168 
2169     // p points to field name len.
2170     uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2171 
2172     // Skip fields name_len and name if they exist.
2173     if (TBTable->tb.name_present) {
2174       const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2175       charPtr = charPtr + name_len + sizeof(uint16_t);
2176     }
2177 
2178     // Skip field alloc_reg if it exists.
2179     if (TBTable->tb.uses_alloca)
2180       ++charPtr;
2181 
2182     // Check traceback table bit has_vec. Skip struct vec_ext if it exists.
2183     if (TBTable->tb.has_vec)
2184       // Note struct vec_ext does exist at this point because whether the
2185       // ordering of longtbtable and has_vec bits is correct or not, both
2186       // are set.
2187       charPtr += sizeof(struct vec_ext);
2188 
2189     // charPtr points to field 'xtbtable'. Check if the EH info is available.
2190     // Also check if the reserved bit of the extended traceback table field
2191     // 'xtbtable' is set. If it is, the traceback table was incorrectly
2192     // generated by an XL compiler that uses the wrong ordering of 'longtbtable'
2193     // and 'has_vec' bits and this is in fact 'struct vec_ext'. So skip the
2194     // frame.
2195     if ((*charPtr & xTBTableMask::ehInfoBit) &&
2196         !(*charPtr & xTBTableMask::reservedBit)) {
2197       // Mark this frame has the new EH info.
2198       flags = frameType::frameWithEHInfo;
2199 
2200       // eh_info is available.
2201       charPtr++;
2202       // The pointer is 4-byte aligned.
2203       if (reinterpret_cast<uintptr_t>(charPtr) % 4)
2204         charPtr += 4 - reinterpret_cast<uintptr_t>(charPtr) % 4;
2205       uintptr_t *ehInfo =
2206           reinterpret_cast<uintptr_t *>(*(reinterpret_cast<uintptr_t *>(
2207               registers.getRegister(2) +
2208               *(reinterpret_cast<uintptr_t *>(charPtr)))));
2209 
2210       // ehInfo points to structure en_info. The first member is version.
2211       // Only version 0 is currently supported.
2212       assert(*(reinterpret_cast<uint32_t *>(ehInfo)) == 0 &&
2213              "libunwind: ehInfo version other than 0 is not supported");
2214 
2215       // Increment ehInfo to point to member lsda.
2216       ++ehInfo;
2217       lsda = *ehInfo++;
2218 
2219       // enInfo now points to member personality.
2220       handler = *ehInfo;
2221 
2222       _LIBUNWIND_TRACE_UNWINDING("Range table: LSDA=%#lx, Personality=%#lx\n",
2223                                  lsda, handler);
2224     }
2225   }
2226 
2227   _info.start_ip = start_ip;
2228   _info.end_ip = end_ip;
2229   _info.lsda = lsda;
2230   _info.handler = handler;
2231   _info.gp = 0;
2232   _info.flags = flags;
2233   _info.format = 0;
2234   _info.unwind_info = reinterpret_cast<unw_word_t>(TBTable);
2235   _info.unwind_info_size = 0;
2236   _info.extra = registers.getRegister(2);
2237 
2238   return true;
2239 }
2240 
2241 // Step back up the stack following the frame back link.
2242 template <typename A, typename R>
2243 int UnwindCursor<A, R>::stepWithTBTable(pint_t pc, tbtable *TBTable,
2244                                         R &registers, bool &isSignalFrame) {
2245   if (_LIBUNWIND_TRACING_UNWINDING) {
2246     char functionBuf[512];
2247     const char *functionName = functionBuf;
2248     unw_word_t offset;
2249     if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
2250       functionName = ".anonymous.";
2251     }
2252     _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2253                                __func__, functionName,
2254                                reinterpret_cast<void *>(TBTable));
2255   }
2256 
2257 #if defined(__powerpc64__)
2258   // Instruction to reload TOC register "l r2,40(r1)"
2259   const uint32_t loadTOCRegInst = 0xe8410028;
2260   const int32_t unwPPCF0Index = UNW_PPC64_F0;
2261   const int32_t unwPPCV0Index = UNW_PPC64_V0;
2262 #else
2263   // Instruction to reload TOC register "l r2,20(r1)"
2264   const uint32_t loadTOCRegInst = 0x80410014;
2265   const int32_t unwPPCF0Index = UNW_PPC_F0;
2266   const int32_t unwPPCV0Index = UNW_PPC_V0;
2267 #endif
2268 
2269   R newRegisters = registers;
2270 
2271   // lastStack points to the stack frame of the next routine up.
2272   pint_t lastStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2273 
2274   // Return address is the address after call site instruction.
2275   pint_t returnAddress;
2276 
2277   if (isSignalFrame) {
2278     _LIBUNWIND_TRACE_UNWINDING("Possible signal handler frame: lastStack=%p",
2279                                reinterpret_cast<void *>(lastStack));
2280 
2281     sigcontext *sigContext = reinterpret_cast<sigcontext *>(
2282         reinterpret_cast<char *>(lastStack) + STKMIN);
2283     returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2284 
2285     _LIBUNWIND_TRACE_UNWINDING("From sigContext=%p, returnAddress=%p\n",
2286                                reinterpret_cast<void *>(sigContext),
2287                                reinterpret_cast<void *>(returnAddress));
2288 
2289     if (returnAddress < 0x10000000) {
2290       // Try again using STKMINALIGN
2291       sigContext = reinterpret_cast<sigcontext *>(
2292           reinterpret_cast<char *>(lastStack) + STKMINALIGN);
2293       returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2294       if (returnAddress < 0x10000000) {
2295         _LIBUNWIND_TRACE_UNWINDING("Bad returnAddress=%p\n",
2296                                    reinterpret_cast<void *>(returnAddress));
2297         return UNW_EBADFRAME;
2298       } else {
2299         _LIBUNWIND_TRACE_UNWINDING("Tried again using STKMINALIGN: "
2300                                    "sigContext=%p, returnAddress=%p. "
2301                                    "Seems to be a valid address\n",
2302                                    reinterpret_cast<void *>(sigContext),
2303                                    reinterpret_cast<void *>(returnAddress));
2304       }
2305     }
2306     // Restore the condition register from sigcontext.
2307     newRegisters.setCR(sigContext->sc_jmpbuf.jmp_context.cr);
2308 
2309     // Restore GPRs from sigcontext.
2310     for (int i = 0; i < 32; ++i)
2311       newRegisters.setRegister(i, sigContext->sc_jmpbuf.jmp_context.gpr[i]);
2312 
2313     // Restore FPRs from sigcontext.
2314     for (int i = 0; i < 32; ++i)
2315       newRegisters.setFloatRegister(i + unwPPCF0Index,
2316                                     sigContext->sc_jmpbuf.jmp_context.fpr[i]);
2317 
2318     // Restore vector registers if there is an associated extended context
2319     // structure.
2320     if (sigContext->sc_jmpbuf.jmp_context.msr & __EXTCTX) {
2321       ucontext_t *uContext = reinterpret_cast<ucontext_t *>(sigContext);
2322       if (uContext->__extctx->__extctx_magic == __EXTCTX_MAGIC) {
2323         for (int i = 0; i < 32; ++i)
2324           newRegisters.setVectorRegister(
2325               i + unwPPCV0Index, *(reinterpret_cast<v128 *>(
2326                                      &(uContext->__extctx->__vmx.__vr[i]))));
2327       }
2328     }
2329   } else {
2330     // Step up a normal frame.
2331     returnAddress = reinterpret_cast<pint_t *>(lastStack)[2];
2332 
2333     _LIBUNWIND_TRACE_UNWINDING("Extract info from lastStack=%p, "
2334                                "returnAddress=%p\n",
2335                                reinterpret_cast<void *>(lastStack),
2336                                reinterpret_cast<void *>(returnAddress));
2337     _LIBUNWIND_TRACE_UNWINDING("fpr_regs=%d, gpr_regs=%d, saves_cr=%d\n",
2338                                TBTable->tb.fpr_saved, TBTable->tb.gpr_saved,
2339                                TBTable->tb.saves_cr);
2340 
2341     // Restore FP registers.
2342     char *ptrToRegs = reinterpret_cast<char *>(lastStack);
2343     double *FPRegs = reinterpret_cast<double *>(
2344         ptrToRegs - (TBTable->tb.fpr_saved * sizeof(double)));
2345     for (int i = 0; i < TBTable->tb.fpr_saved; ++i)
2346       newRegisters.setFloatRegister(
2347           32 - TBTable->tb.fpr_saved + i + unwPPCF0Index, FPRegs[i]);
2348 
2349     // Restore GP registers.
2350     ptrToRegs = reinterpret_cast<char *>(FPRegs);
2351     uintptr_t *GPRegs = reinterpret_cast<uintptr_t *>(
2352         ptrToRegs - (TBTable->tb.gpr_saved * sizeof(uintptr_t)));
2353     for (int i = 0; i < TBTable->tb.gpr_saved; ++i)
2354       newRegisters.setRegister(32 - TBTable->tb.gpr_saved + i, GPRegs[i]);
2355 
2356     // Restore Vector registers.
2357     ptrToRegs = reinterpret_cast<char *>(GPRegs);
2358 
2359     // Restore vector registers only if this is a Clang frame. Also
2360     // check if traceback table bit has_vec is set. If it is, structure
2361     // vec_ext is available.
2362     if (_info.flags == frameType::frameWithEHInfo && TBTable->tb.has_vec) {
2363 
2364       // Get to the vec_ext structure to check if vector registers are saved.
2365       uint32_t *p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2366 
2367       // Skip field parminfo if exists.
2368       if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2369         ++p;
2370 
2371       // Skip field tb_offset if exists.
2372       if (TBTable->tb.has_tboff)
2373         ++p;
2374 
2375       // Skip field hand_mask if exists.
2376       if (TBTable->tb.int_hndl)
2377         ++p;
2378 
2379       // Skip fields ctl_info and ctl_info_disp if exist.
2380       if (TBTable->tb.has_ctl) {
2381         // Skip field ctl_info.
2382         ++p;
2383         // Skip field ctl_info_disp.
2384         ++p;
2385       }
2386 
2387       // Skip fields name_len and name if exist.
2388       // p is supposed to point to field name_len now.
2389       uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2390       if (TBTable->tb.name_present) {
2391         const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2392         charPtr = charPtr + name_len + sizeof(uint16_t);
2393       }
2394 
2395       // Skip field alloc_reg if it exists.
2396       if (TBTable->tb.uses_alloca)
2397         ++charPtr;
2398 
2399       struct vec_ext *vec_ext = reinterpret_cast<struct vec_ext *>(charPtr);
2400 
2401       _LIBUNWIND_TRACE_UNWINDING("vr_saved=%d\n", vec_ext->vr_saved);
2402 
2403       // Restore vector register(s) if saved on the stack.
2404       if (vec_ext->vr_saved) {
2405         // Saved vector registers are 16-byte aligned.
2406         if (reinterpret_cast<uintptr_t>(ptrToRegs) % 16)
2407           ptrToRegs -= reinterpret_cast<uintptr_t>(ptrToRegs) % 16;
2408         v128 *VecRegs = reinterpret_cast<v128 *>(ptrToRegs - vec_ext->vr_saved *
2409                                                                  sizeof(v128));
2410         for (int i = 0; i < vec_ext->vr_saved; ++i) {
2411           newRegisters.setVectorRegister(
2412               32 - vec_ext->vr_saved + i + unwPPCV0Index, VecRegs[i]);
2413         }
2414       }
2415     }
2416     if (TBTable->tb.saves_cr) {
2417       // Get the saved condition register. The condition register is only
2418       // a single word.
2419       newRegisters.setCR(
2420           *(reinterpret_cast<uint32_t *>(lastStack + sizeof(uintptr_t))));
2421     }
2422 
2423     // Restore the SP.
2424     newRegisters.setSP(lastStack);
2425 
2426     // The first instruction after return.
2427     uint32_t firstInstruction = *(reinterpret_cast<uint32_t *>(returnAddress));
2428 
2429     // Do we need to set the TOC register?
2430     _LIBUNWIND_TRACE_UNWINDING(
2431         "Current gpr2=%p\n",
2432         reinterpret_cast<void *>(newRegisters.getRegister(2)));
2433     if (firstInstruction == loadTOCRegInst) {
2434       _LIBUNWIND_TRACE_UNWINDING(
2435           "Set gpr2=%p from frame\n",
2436           reinterpret_cast<void *>(reinterpret_cast<pint_t *>(lastStack)[5]));
2437       newRegisters.setRegister(2, reinterpret_cast<pint_t *>(lastStack)[5]);
2438     }
2439   }
2440   _LIBUNWIND_TRACE_UNWINDING("lastStack=%p, returnAddress=%p, pc=%p\n",
2441                              reinterpret_cast<void *>(lastStack),
2442                              reinterpret_cast<void *>(returnAddress),
2443                              reinterpret_cast<void *>(pc));
2444 
2445   // The return address is the address after call site instruction, so
2446   // setting IP to that simualates a return.
2447   newRegisters.setIP(reinterpret_cast<uintptr_t>(returnAddress));
2448 
2449   // Simulate the step by replacing the register set with the new ones.
2450   registers = newRegisters;
2451 
2452   // Check if the next frame is a signal frame.
2453   pint_t nextStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2454 
2455   // Return address is the address after call site instruction.
2456   pint_t nextReturnAddress = reinterpret_cast<pint_t *>(nextStack)[2];
2457 
2458   if (nextReturnAddress > 0x01 && nextReturnAddress < 0x10000) {
2459     _LIBUNWIND_TRACE_UNWINDING("The next is a signal handler frame: "
2460                                "nextStack=%p, next return address=%p\n",
2461                                reinterpret_cast<void *>(nextStack),
2462                                reinterpret_cast<void *>(nextReturnAddress));
2463     isSignalFrame = true;
2464   } else {
2465     isSignalFrame = false;
2466   }
2467 
2468   return UNW_STEP_SUCCESS;
2469 }
2470 #endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2471 
2472 template <typename A, typename R>
2473 void UnwindCursor<A, R>::setInfoBasedOnIPRegister(bool isReturnAddress) {
2474 #if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_S390X))
2475   _isSigReturn = false;
2476 #endif
2477 
2478   pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2479 #if defined(_LIBUNWIND_ARM_EHABI)
2480   // Remove the thumb bit so the IP represents the actual instruction address.
2481   // This matches the behaviour of _Unwind_GetIP on arm.
2482   pc &= (pint_t)~0x1;
2483 #endif
2484 
2485   // Exit early if at the top of the stack.
2486   if (pc == 0) {
2487     _unwindInfoMissing = true;
2488     return;
2489   }
2490 
2491   // If the last line of a function is a "throw" the compiler sometimes
2492   // emits no instructions after the call to __cxa_throw.  This means
2493   // the return address is actually the start of the next function.
2494   // To disambiguate this, back up the pc when we know it is a return
2495   // address.
2496   if (isReturnAddress)
2497 #if defined(_AIX)
2498     // PC needs to be a 4-byte aligned address to be able to look for a
2499     // word of 0 that indicates the start of the traceback table at the end
2500     // of a function on AIX.
2501     pc -= 4;
2502 #else
2503     --pc;
2504 #endif
2505 
2506   // Ask address space object to find unwind sections for this pc.
2507   UnwindInfoSections sects;
2508   if (_addressSpace.findUnwindSections(pc, sects)) {
2509 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
2510     // If there is a compact unwind encoding table, look there first.
2511     if (sects.compact_unwind_section != 0) {
2512       if (this->getInfoFromCompactEncodingSection(pc, sects)) {
2513   #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2514         // Found info in table, done unless encoding says to use dwarf.
2515         uint32_t dwarfOffset;
2516         if ((sects.dwarf_section != 0) && compactSaysUseDwarf(&dwarfOffset)) {
2517           if (this->getInfoFromDwarfSection(pc, sects, dwarfOffset)) {
2518             // found info in dwarf, done
2519             return;
2520           }
2521         }
2522   #endif
2523         // If unwind table has entry, but entry says there is no unwind info,
2524         // record that we have no unwind info.
2525         if (_info.format == 0)
2526           _unwindInfoMissing = true;
2527         return;
2528       }
2529     }
2530 #endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
2531 
2532 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
2533     // If there is SEH unwind info, look there next.
2534     if (this->getInfoFromSEH(pc))
2535       return;
2536 #endif
2537 
2538 #if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2539     // If there is unwind info in the traceback table, look there next.
2540     if (this->getInfoFromTBTable(pc, _registers))
2541       return;
2542 #endif
2543 
2544 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2545     // If there is dwarf unwind info, look there next.
2546     if (sects.dwarf_section != 0) {
2547       if (this->getInfoFromDwarfSection(pc, sects)) {
2548         // found info in dwarf, done
2549         return;
2550       }
2551     }
2552 #endif
2553 
2554 #if defined(_LIBUNWIND_ARM_EHABI)
2555     // If there is ARM EHABI unwind info, look there next.
2556     if (sects.arm_section != 0 && this->getInfoFromEHABISection(pc, sects))
2557       return;
2558 #endif
2559   }
2560 
2561 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2562   // There is no static unwind info for this pc. Look to see if an FDE was
2563   // dynamically registered for it.
2564   pint_t cachedFDE = DwarfFDECache<A>::findFDE(DwarfFDECache<A>::kSearchAll,
2565                                                pc);
2566   if (cachedFDE != 0) {
2567     typename CFI_Parser<A>::FDE_Info fdeInfo;
2568     typename CFI_Parser<A>::CIE_Info cieInfo;
2569     if (!CFI_Parser<A>::decodeFDE(_addressSpace, cachedFDE, &fdeInfo, &cieInfo))
2570       if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
2571         return;
2572   }
2573 
2574   // Lastly, ask AddressSpace object about platform specific ways to locate
2575   // other FDEs.
2576   pint_t fde;
2577   if (_addressSpace.findOtherFDE(pc, fde)) {
2578     typename CFI_Parser<A>::FDE_Info fdeInfo;
2579     typename CFI_Parser<A>::CIE_Info cieInfo;
2580     if (!CFI_Parser<A>::decodeFDE(_addressSpace, fde, &fdeInfo, &cieInfo)) {
2581       // Double check this FDE is for a function that includes the pc.
2582       if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd))
2583         if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
2584           return;
2585     }
2586   }
2587 #endif // #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2588 
2589 #if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_S390X))
2590   if (setInfoForSigReturn())
2591     return;
2592 #endif
2593 
2594   // no unwind info, flag that we can't reliably unwind
2595   _unwindInfoMissing = true;
2596 }
2597 
2598 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2599 template <typename A, typename R>
2600 bool UnwindCursor<A, R>::setInfoForSigReturn(Registers_arm64 &) {
2601   // Look for the sigreturn trampoline. The trampoline's body is two
2602   // specific instructions (see below). Typically the trampoline comes from the
2603   // vDSO[1] (i.e. the __kernel_rt_sigreturn function). A libc might provide its
2604   // own restorer function, though, or user-mode QEMU might write a trampoline
2605   // onto the stack.
2606   //
2607   // This special code path is a fallback that is only used if the trampoline
2608   // lacks proper (e.g. DWARF) unwind info. On AArch64, a new DWARF register
2609   // constant for the PC needs to be defined before DWARF can handle a signal
2610   // trampoline. This code may segfault if the target PC is unreadable, e.g.:
2611   //  - The PC points at a function compiled without unwind info, and which is
2612   //    part of an execute-only mapping (e.g. using -Wl,--execute-only).
2613   //  - The PC is invalid and happens to point to unreadable or unmapped memory.
2614   //
2615   // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/vdso/sigreturn.S
2616   const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2617   // Look for instructions: mov x8, #0x8b; svc #0x0
2618   if (_addressSpace.get32(pc) == 0xd2801168 &&
2619       _addressSpace.get32(pc + 4) == 0xd4000001) {
2620     _info = {};
2621     _info.start_ip = pc;
2622     _info.end_ip = pc + 4;
2623     _isSigReturn = true;
2624     return true;
2625   }
2626   return false;
2627 }
2628 
2629 template <typename A, typename R>
2630 int UnwindCursor<A, R>::stepThroughSigReturn(Registers_arm64 &) {
2631   // In the signal trampoline frame, sp points to an rt_sigframe[1], which is:
2632   //  - 128-byte siginfo struct
2633   //  - ucontext struct:
2634   //     - 8-byte long (uc_flags)
2635   //     - 8-byte pointer (uc_link)
2636   //     - 24-byte stack_t
2637   //     - 128-byte signal set
2638   //     - 8 bytes of padding because sigcontext has 16-byte alignment
2639   //     - sigcontext/mcontext_t
2640   // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/signal.c
2641   const pint_t kOffsetSpToSigcontext = (128 + 8 + 8 + 24 + 128 + 8); // 304
2642 
2643   // Offsets from sigcontext to each register.
2644   const pint_t kOffsetGprs = 8; // offset to "__u64 regs[31]" field
2645   const pint_t kOffsetSp = 256; // offset to "__u64 sp" field
2646   const pint_t kOffsetPc = 264; // offset to "__u64 pc" field
2647 
2648   pint_t sigctx = _registers.getSP() + kOffsetSpToSigcontext;
2649 
2650   for (int i = 0; i <= 30; ++i) {
2651     uint64_t value = _addressSpace.get64(sigctx + kOffsetGprs +
2652                                          static_cast<pint_t>(i * 8));
2653     _registers.setRegister(UNW_AARCH64_X0 + i, value);
2654   }
2655   _registers.setSP(_addressSpace.get64(sigctx + kOffsetSp));
2656   _registers.setIP(_addressSpace.get64(sigctx + kOffsetPc));
2657   _isSignalFrame = true;
2658   return UNW_STEP_SUCCESS;
2659 }
2660 #endif // defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2661 
2662 #if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_S390X)
2663 template <typename A, typename R>
2664 bool UnwindCursor<A, R>::setInfoForSigReturn(Registers_s390x &) {
2665   // Look for the sigreturn trampoline. The trampoline's body is a
2666   // specific instruction (see below). Typically the trampoline comes from the
2667   // vDSO (i.e. the __kernel_[rt_]sigreturn function). A libc might provide its
2668   // own restorer function, though, or user-mode QEMU might write a trampoline
2669   // onto the stack.
2670   const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2671   const uint16_t inst = _addressSpace.get16(pc);
2672   if (inst == 0x0a77 || inst == 0x0aad) {
2673     _info = {};
2674     _info.start_ip = pc;
2675     _info.end_ip = pc + 2;
2676     _isSigReturn = true;
2677     return true;
2678   }
2679   return false;
2680 }
2681 
2682 template <typename A, typename R>
2683 int UnwindCursor<A, R>::stepThroughSigReturn(Registers_s390x &) {
2684   // Determine current SP.
2685   const pint_t sp = static_cast<pint_t>(this->getReg(UNW_REG_SP));
2686   // According to the s390x ABI, the CFA is at (incoming) SP + 160.
2687   const pint_t cfa = sp + 160;
2688 
2689   // Determine current PC and instruction there (this must be either
2690   // a "svc __NR_sigreturn" or "svc __NR_rt_sigreturn").
2691   const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2692   const uint16_t inst = _addressSpace.get16(pc);
2693 
2694   // Find the addresses of the signo and sigcontext in the frame.
2695   pint_t pSigctx = 0;
2696   pint_t pSigno = 0;
2697 
2698   // "svc __NR_sigreturn" uses a non-RT signal trampoline frame.
2699   if (inst == 0x0a77) {
2700     // Layout of a non-RT signal trampoline frame, starting at the CFA:
2701     //  - 8-byte signal mask
2702     //  - 8-byte pointer to sigcontext, followed by signo
2703     //  - 4-byte signo
2704     pSigctx = _addressSpace.get64(cfa + 8);
2705     pSigno = pSigctx + 344;
2706   }
2707 
2708   // "svc __NR_rt_sigreturn" uses a RT signal trampoline frame.
2709   if (inst == 0x0aad) {
2710     // Layout of a RT signal trampoline frame, starting at the CFA:
2711     //  - 8-byte retcode (+ alignment)
2712     //  - 128-byte siginfo struct (starts with signo)
2713     //  - ucontext struct:
2714     //     - 8-byte long (uc_flags)
2715     //     - 8-byte pointer (uc_link)
2716     //     - 24-byte stack_t
2717     //     - 8 bytes of padding because sigcontext has 16-byte alignment
2718     //     - sigcontext/mcontext_t
2719     pSigctx = cfa + 8 + 128 + 8 + 8 + 24 + 8;
2720     pSigno = cfa + 8;
2721   }
2722 
2723   assert(pSigctx != 0);
2724   assert(pSigno != 0);
2725 
2726   // Offsets from sigcontext to each register.
2727   const pint_t kOffsetPc = 8;
2728   const pint_t kOffsetGprs = 16;
2729   const pint_t kOffsetFprs = 216;
2730 
2731   // Restore all registers.
2732   for (int i = 0; i < 16; ++i) {
2733     uint64_t value = _addressSpace.get64(pSigctx + kOffsetGprs +
2734                                          static_cast<pint_t>(i * 8));
2735     _registers.setRegister(UNW_S390X_R0 + i, value);
2736   }
2737   for (int i = 0; i < 16; ++i) {
2738     static const int fpr[16] = {
2739       UNW_S390X_F0, UNW_S390X_F1, UNW_S390X_F2, UNW_S390X_F3,
2740       UNW_S390X_F4, UNW_S390X_F5, UNW_S390X_F6, UNW_S390X_F7,
2741       UNW_S390X_F8, UNW_S390X_F9, UNW_S390X_F10, UNW_S390X_F11,
2742       UNW_S390X_F12, UNW_S390X_F13, UNW_S390X_F14, UNW_S390X_F15
2743     };
2744     double value = _addressSpace.getDouble(pSigctx + kOffsetFprs +
2745                                            static_cast<pint_t>(i * 8));
2746     _registers.setFloatRegister(fpr[i], value);
2747   }
2748   _registers.setIP(_addressSpace.get64(pSigctx + kOffsetPc));
2749 
2750   // SIGILL, SIGFPE and SIGTRAP are delivered with psw_addr
2751   // after the faulting instruction rather than before it.
2752   // Do not set _isSignalFrame in that case.
2753   uint32_t signo = _addressSpace.get32(pSigno);
2754   _isSignalFrame = (signo != 4 && signo != 5 && signo != 8);
2755 
2756   return UNW_STEP_SUCCESS;
2757 }
2758 #endif // defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_S390X)
2759 
2760 template <typename A, typename R>
2761 int UnwindCursor<A, R>::step() {
2762   // Bottom of stack is defined is when unwind info cannot be found.
2763   if (_unwindInfoMissing)
2764     return UNW_STEP_END;
2765 
2766   // Use unwinding info to modify register set as if function returned.
2767   int result;
2768 #if defined(_LIBUNWIND_TARGET_LINUX) && (defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_S390X))
2769   if (_isSigReturn) {
2770     result = this->stepThroughSigReturn();
2771   } else
2772 #endif
2773   {
2774 #if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
2775     result = this->stepWithCompactEncoding();
2776 #elif defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
2777     result = this->stepWithSEHData();
2778 #elif defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2779     result = this->stepWithTBTableData();
2780 #elif defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
2781     result = this->stepWithDwarfFDE();
2782 #elif defined(_LIBUNWIND_ARM_EHABI)
2783     result = this->stepWithEHABI();
2784 #else
2785   #error Need _LIBUNWIND_SUPPORT_COMPACT_UNWIND or \
2786               _LIBUNWIND_SUPPORT_SEH_UNWIND or \
2787               _LIBUNWIND_SUPPORT_DWARF_UNWIND or \
2788               _LIBUNWIND_ARM_EHABI
2789 #endif
2790   }
2791 
2792   // update info based on new PC
2793   if (result == UNW_STEP_SUCCESS) {
2794     this->setInfoBasedOnIPRegister(true);
2795     if (_unwindInfoMissing)
2796       return UNW_STEP_END;
2797   }
2798 
2799   return result;
2800 }
2801 
2802 template <typename A, typename R>
2803 void UnwindCursor<A, R>::getInfo(unw_proc_info_t *info) {
2804   if (_unwindInfoMissing)
2805     memset(info, 0, sizeof(*info));
2806   else
2807     *info = _info;
2808 }
2809 
2810 template <typename A, typename R>
2811 bool UnwindCursor<A, R>::getFunctionName(char *buf, size_t bufLen,
2812                                                            unw_word_t *offset) {
2813   return _addressSpace.findFunctionName((pint_t)this->getReg(UNW_REG_IP),
2814                                          buf, bufLen, offset);
2815 }
2816 
2817 #if defined(_LIBUNWIND_USE_CET)
2818 extern "C" void *__libunwind_cet_get_registers(unw_cursor_t *cursor) {
2819   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
2820   return co->get_registers();
2821 }
2822 #endif
2823 } // namespace libunwind
2824 
2825 #endif // __UNWINDCURSOR_HPP__
2826