blob: dd849b781753e169b08f4397638e52a5262730c6 [file] [log] [blame]
Louis Dionne7f068e52021-11-17 16:25:01 -05001//===----------------------------------------------------------------------===//
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002//
Chandler Carruth61860a52019-01-19 10:56:40 +00003// 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
Saleem Abdulrasool17552662015-04-24 19:39:17 +00006//
7//
Ed Maste6f723382016-08-30 13:08:21 +00008// C++ interface to lower levels of libunwind
Saleem Abdulrasool17552662015-04-24 19:39:17 +00009//===----------------------------------------------------------------------===//
10
11#ifndef __UNWINDCURSOR_HPP__
12#define __UNWINDCURSOR_HPP__
13
gejin7f493162021-08-26 16:20:38 +080014#include "cet_unwind.h"
Saleem Abdulrasool17552662015-04-24 19:39:17 +000015#include <stdint.h>
16#include <stdio.h>
17#include <stdlib.h>
Saleem Abdulrasool17552662015-04-24 19:39:17 +000018#include <unwind.h>
19
Charles Davisfa2e6202018-08-30 21:29:00 +000020#ifdef _WIN32
21 #include <windows.h>
22 #include <ntverp.h>
23#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +000024#ifdef __APPLE__
25 #include <mach-o/dyld.h>
26#endif
Xing Xuebbcbce92022-04-13 11:01:59 -040027#ifdef _AIX
28#include <dlfcn.h>
29#include <sys/debug.h>
30#include <sys/pseg.h>
31#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +000032
Charles Davisfa2e6202018-08-30 21:29:00 +000033#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
39struct _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
54struct 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
64extern "C" _Unwind_Reason_Code __libunwind_seh_personality(
65 int, _Unwind_Action, uint64_t, _Unwind_Exception *,
66 struct _Unwind_Context *);
67
68#endif
69
Saleem Abdulrasool17552662015-04-24 19:39:17 +000070#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"
Martin Storsjo590ffef2017-10-23 19:29:36 +000079#include "RWMutex.hpp"
Saleem Abdulrasool17552662015-04-24 19:39:17 +000080#include "Unwind-EHABI.h"
81
82namespace libunwind {
83
Ranjeet Singh421231a2017-03-31 15:28:06 +000084#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +000085/// Cache of recently found FDEs.
86template <typename A>
87class _LIBUNWIND_HIDDEN DwarfFDECache {
88 typedef typename A::pint_t pint_t;
89public:
Ryan Prichard2cfcb8c2020-09-09 15:43:35 -070090 static constexpr pint_t kSearchAll = static_cast<pint_t>(-1);
Saleem Abdulrasool17552662015-04-24 19:39:17 +000091 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
98private:
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.
Martin Storsjo590ffef2017-10-23 19:29:36 +0000109 static RWMutex _lock;
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000110#ifdef __APPLE__
111 static void dyldUnloadHook(const struct mach_header *mh, intptr_t slide);
112 static bool _registeredForDyldUnloads;
113#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000114 static entry *_buffer;
115 static entry *_bufferUsed;
116 static entry *_bufferEnd;
117 static entry _initialBuffer[64];
118};
119
120template <typename A>
121typename DwarfFDECache<A>::entry *
122DwarfFDECache<A>::_buffer = _initialBuffer;
123
124template <typename A>
125typename DwarfFDECache<A>::entry *
126DwarfFDECache<A>::_bufferUsed = _initialBuffer;
127
128template <typename A>
129typename DwarfFDECache<A>::entry *
130DwarfFDECache<A>::_bufferEnd = &_initialBuffer[64];
131
132template <typename A>
133typename DwarfFDECache<A>::entry DwarfFDECache<A>::_initialBuffer[64];
134
135template <typename A>
Martin Storsjo590ffef2017-10-23 19:29:36 +0000136RWMutex DwarfFDECache<A>::_lock;
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000137
138#ifdef __APPLE__
139template <typename A>
140bool DwarfFDECache<A>::_registeredForDyldUnloads = false;
141#endif
142
143template <typename A>
144typename A::pint_t DwarfFDECache<A>::findFDE(pint_t mh, pint_t pc) {
145 pint_t result = 0;
Martin Storsjo590ffef2017-10-23 19:29:36 +0000146 _LIBUNWIND_LOG_IF_FALSE(_lock.lock_shared());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000147 for (entry *p = _buffer; p < _bufferUsed; ++p) {
Ryan Prichard2cfcb8c2020-09-09 15:43:35 -0700148 if ((mh == p->mh) || (mh == kSearchAll)) {
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000149 if ((p->ip_start <= pc) && (pc < p->ip_end)) {
150 result = p->fde;
151 break;
152 }
153 }
154 }
Martin Storsjo590ffef2017-10-23 19:29:36 +0000155 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock_shared());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000156 return result;
157}
158
159template <typename A>
160void DwarfFDECache<A>::add(pint_t mh, pint_t ip_start, pint_t ip_end,
161 pint_t fde) {
Peter Zotov0717a2e2015-11-09 06:57:29 +0000162#if !defined(_LIBUNWIND_NO_HEAP)
Martin Storsjo590ffef2017-10-23 19:29:36 +0000163 _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000164 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
Martin Storsjo590ffef2017-10-23 19:29:36 +0000187 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
Peter Zotov0717a2e2015-11-09 06:57:29 +0000188#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000189}
190
191template <typename A>
192void DwarfFDECache<A>::removeAllIn(pint_t mh) {
Martin Storsjo590ffef2017-10-23 19:29:36 +0000193 _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000194 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;
Martin Storsjo590ffef2017-10-23 19:29:36 +0000203 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000204}
205
206#ifdef __APPLE__
207template <typename A>
208void DwarfFDECache<A>::dyldUnloadHook(const struct mach_header *mh, intptr_t ) {
209 removeAllIn((pint_t) mh);
210}
211#endif
212
213template <typename A>
214void DwarfFDECache<A>::iterateCacheEntries(void (*func)(
215 unw_word_t ip_start, unw_word_t ip_end, unw_word_t fde, unw_word_t mh)) {
Martin Storsjo590ffef2017-10-23 19:29:36 +0000216 _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000217 for (entry *p = _buffer; p < _bufferUsed; ++p) {
218 (*func)(p->ip_start, p->ip_end, p->fde, p->mh);
219 }
Martin Storsjo590ffef2017-10-23 19:29:36 +0000220 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000221}
Ranjeet Singh421231a2017-03-31 15:28:06 +0000222#endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000223
224
225#define arrayoffsetof(type, index, field) ((size_t)(&((type *)0)[index].field))
226
Ranjeet Singh421231a2017-03-31 15:28:06 +0000227#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000228template <typename A> class UnwindSectionHeader {
229public:
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
263private:
264 A &_addressSpace;
265 typename A::pint_t _addr;
266};
267
268template <typename A> class UnwindSectionIndexArray {
269public:
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
289private:
290 A &_addressSpace;
291 typename A::pint_t _addr;
292};
293
294template <typename A> class UnwindSectionRegularPageHeader {
295public:
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
314private:
315 A &_addressSpace;
316 typename A::pint_t _addr;
317};
318
319template <typename A> class UnwindSectionRegularArray {
320public:
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
335private:
336 A &_addressSpace;
337 typename A::pint_t _addr;
338};
339
340template <typename A> class UnwindSectionCompressedPageHeader {
341public:
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
371private:
372 A &_addressSpace;
373 typename A::pint_t _addr;
374};
375
376template <typename A> class UnwindSectionCompressedArray {
377public:
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
390private:
391 A &_addressSpace;
392 typename A::pint_t _addr;
393};
394
395template <typename A> class UnwindSectionLsdaArray {
396public:
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
411private:
412 A &_addressSpace;
413 typename A::pint_t _addr;
414};
Ranjeet Singh421231a2017-03-31 15:28:06 +0000415#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000416
417class _LIBUNWIND_HIDDEN AbstractUnwindCursor {
418public:
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
gejin7f493162021-08-26 16:20:38 +0800458
Xing Xuebbcbce92022-04-13 11:01:59 -0400459#ifdef _AIX
460 virtual uintptr_t getDataRelBase() {
461 _LIBUNWIND_ABORT("getDataRelBase not implemented");
462 }
463#endif
464
gejin7f493162021-08-26 16:20:38 +0800465#if defined(_LIBUNWIND_USE_CET)
466 virtual void *get_registers() {
467 _LIBUNWIND_ABORT("get_registers not implemented");
468 }
469#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000470};
471
Charles Davisfa2e6202018-08-30 21:29:00 +0000472#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.
476template <typename A, typename R>
477class UnwindCursor : public AbstractUnwindCursor {
478 typedef typename A::pint_t pint_t;
479public:
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
Martin Storsjo5f5036e2019-02-03 22:16:53 +0000504 // 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
Charles Davisfa2e6202018-08-30 21:29:00 +0000508private:
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
547template <typename A, typename R>
548UnwindCursor<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");
Martin Storsjö1c0575e2020-08-17 22:41:58 +0300552 static_assert((alignof(UnwindCursor<A, R>) <= alignof(unw_cursor_t)),
553 "UnwindCursor<> requires more alignment than unw_cursor_t");
Charles Davisfa2e6202018-08-30 21:29:00 +0000554 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);
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000631 _msContext.Pc = r.getRegister(UNW_ARM_IP);
632 for (int i = UNW_ARM_D0; i <= UNW_ARM_D31; ++i) {
Charles Davisfa2e6202018-08-30 21:29:00 +0000633 union {
634 uint64_t w;
635 double d;
636 } d;
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000637 d.d = r.getFloatRegister(i);
638 _msContext.D[i - UNW_ARM_D0] = d.w;
Charles Davisfa2e6202018-08-30 21:29:00 +0000639 }
Martin Storsjoce150112018-12-18 20:05:59 +0000640#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700641 for (int i = UNW_AARCH64_X0; i <= UNW_ARM64_X30; ++i)
642 _msContext.X[i - UNW_AARCH64_X0] = r.getRegister(i);
Martin Storsjoce150112018-12-18 20:05:59 +0000643 _msContext.Sp = r.getRegister(UNW_REG_SP);
644 _msContext.Pc = r.getRegister(UNW_REG_IP);
Fangrui Song5f263002021-08-20 14:26:27 -0700645 for (int i = UNW_AARCH64_V0; i <= UNW_ARM64_D31; ++i)
646 _msContext.V[i - UNW_AARCH64_V0].D[0] = r.getFloatRegister(i);
Charles Davisfa2e6202018-08-30 21:29:00 +0000647#endif
648}
649
650template <typename A, typename R>
651UnwindCursor<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
663template <typename A, typename R>
664bool 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)
Ties Stuijc8c0ec92021-12-08 09:44:45 +0000669 if ((regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) ||
670 regNum == UNW_ARM_RA_AUTH_CODE)
671 return true;
Martin Storsjoce150112018-12-18 20:05:59 +0000672#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700673 if (regNum >= UNW_AARCH64_X0 && regNum <= UNW_ARM64_X30) return true;
Charles Davisfa2e6202018-08-30 21:29:00 +0000674#endif
675 return false;
676}
677
678template <typename A, typename R>
679unw_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:
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000718 case UNW_ARM_IP: return _msContext.Pc;
Martin Storsjoce150112018-12-18 20:05:59 +0000719#elif defined(_LIBUNWIND_TARGET_AARCH64)
720 case UNW_REG_SP: return _msContext.Sp;
721 case UNW_REG_IP: return _msContext.Pc;
Fangrui Song5f263002021-08-20 14:26:27 -0700722 default: return _msContext.X[regNum - UNW_AARCH64_X0];
Charles Davisfa2e6202018-08-30 21:29:00 +0000723#endif
724 }
725 _LIBUNWIND_ABORT("unsupported register");
726}
727
728template <typename A, typename R>
729void 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:
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000768 case UNW_ARM_IP: _msContext.Pc = value; break;
Martin Storsjoce150112018-12-18 20:05:59 +0000769#elif defined(_LIBUNWIND_TARGET_AARCH64)
770 case UNW_REG_SP: _msContext.Sp = value; break;
771 case UNW_REG_IP: _msContext.Pc = value; break;
Fangrui Song5f263002021-08-20 14:26:27 -0700772 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;
Charles Davisfa2e6202018-08-30 21:29:00 +0000803#endif
804 default:
805 _LIBUNWIND_ABORT("unsupported register");
806 }
807}
808
809template <typename A, typename R>
810bool 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;
Martin Storsjoce150112018-12-18 20:05:59 +0000814#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700815 if (regNum >= UNW_AARCH64_V0 && regNum <= UNW_ARM64_D31) return true;
Martin Storsjo059a1632019-01-22 22:12:23 +0000816#else
817 (void)regNum;
Charles Davisfa2e6202018-08-30 21:29:00 +0000818#endif
819 return false;
820}
821
822template <typename A, typename R>
823unw_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");
Martin Storsjoce150112018-12-18 20:05:59 +0000842#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700843 return _msContext.V[regNum - UNW_AARCH64_V0].D[0];
Charles Davisfa2e6202018-08-30 21:29:00 +0000844#else
Martin Storsjo059a1632019-01-22 22:12:23 +0000845 (void)regNum;
Charles Davisfa2e6202018-08-30 21:29:00 +0000846 _LIBUNWIND_ABORT("float registers unimplemented");
847#endif
848}
849
850template <typename A, typename R>
851void 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");
Martin Storsjoce150112018-12-18 20:05:59 +0000870#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700871 _msContext.V[regNum - UNW_AARCH64_V0].D[0] = value;
Charles Davisfa2e6202018-08-30 21:29:00 +0000872#else
Martin Storsjo059a1632019-01-22 22:12:23 +0000873 (void)regNum;
874 (void)value;
Charles Davisfa2e6202018-08-30 21:29:00 +0000875 _LIBUNWIND_ABORT("float registers unimplemented");
876#endif
877}
878
879template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
880 RtlRestoreContext(&_msContext, nullptr);
881}
882
883#ifdef __arm__
884template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {}
885#endif
886
887template <typename A, typename R>
888const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
Martin Storsjo43bb9f82018-12-12 22:24:42 +0000889 return R::getRegisterName(regNum);
Charles Davisfa2e6202018-08-30 21:29:00 +0000890}
891
892template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
893 return false;
894}
895
896#else // !defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) || !defined(_WIN32)
897
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000898/// UnwindCursor contains all state (including all register values) during
899/// an unwind. This is normally stack allocated inside a unw_cursor_t.
900template <typename A, typename R>
901class UnwindCursor : public AbstractUnwindCursor{
902 typedef typename A::pint_t pint_t;
903public:
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
Xing Xuebbcbce92022-04-13 11:01:59 -0400924#ifdef _AIX
925 virtual uintptr_t getDataRelBase();
926#endif
927
gejin7f493162021-08-26 16:20:38 +0800928#if defined(_LIBUNWIND_USE_CET)
929 virtual void *get_registers() { return &_registers; }
930#endif
Xing Xuebbcbce92022-04-13 11:01:59 -0400931
Petr Hosek36f61542019-02-02 21:15:49 +0000932 // 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
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000936private:
937
Ranjeet Singh421231a2017-03-31 15:28:06 +0000938#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000939 bool getInfoFromEHABISection(pint_t pc, const UnwindInfoSections &sects);
Logan Chiena54f0962015-05-29 15:33:38 +0000940
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 }
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000954#endif
955
Ryan Pricharda684bed2021-01-13 16:38:36 -0800956#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
957 bool setInfoForSigReturn() {
958 R dummy;
959 return setInfoForSigReturn(dummy);
960 }
961 int stepThroughSigReturn() {
962 R dummy;
963 return stepThroughSigReturn(dummy);
964 }
965 bool setInfoForSigReturn(Registers_arm64 &);
966 int stepThroughSigReturn(Registers_arm64 &);
967 template <typename Registers> bool setInfoForSigReturn(Registers &) {
968 return false;
969 }
970 template <typename Registers> int stepThroughSigReturn(Registers &) {
971 return UNW_STEP_END;
972 }
973#endif
974
Ranjeet Singh421231a2017-03-31 15:28:06 +0000975#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Ryan Prichard1ae2b942020-08-18 02:31:38 -0700976 bool getInfoFromFdeCie(const typename CFI_Parser<A>::FDE_Info &fdeInfo,
977 const typename CFI_Parser<A>::CIE_Info &cieInfo,
978 pint_t pc, uintptr_t dso_base);
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000979 bool getInfoFromDwarfSection(pint_t pc, const UnwindInfoSections &sects,
980 uint32_t fdeSectionOffsetHint=0);
981 int stepWithDwarfFDE() {
982 return DwarfInstructions<A, R>::stepWithDwarf(_addressSpace,
983 (pint_t)this->getReg(UNW_REG_IP),
984 (pint_t)_info.unwind_info,
Sterling Augustineb6a66392019-10-31 12:45:20 -0700985 _registers, _isSignalFrame);
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000986 }
987#endif
988
Ranjeet Singh421231a2017-03-31 15:28:06 +0000989#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000990 bool getInfoFromCompactEncodingSection(pint_t pc,
991 const UnwindInfoSections &sects);
992 int stepWithCompactEncoding() {
Ranjeet Singh421231a2017-03-31 15:28:06 +0000993 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000994 if ( compactSaysUseDwarf() )
995 return stepWithDwarfFDE();
996 #endif
997 R dummy;
998 return stepWithCompactEncoding(dummy);
999 }
1000
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001001#if defined(_LIBUNWIND_TARGET_X86_64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001002 int stepWithCompactEncoding(Registers_x86_64 &) {
1003 return CompactUnwinder_x86_64<A>::stepWithCompactEncoding(
1004 _info.format, _info.start_ip, _addressSpace, _registers);
1005 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001006#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001007
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001008#if defined(_LIBUNWIND_TARGET_I386)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001009 int stepWithCompactEncoding(Registers_x86 &) {
1010 return CompactUnwinder_x86<A>::stepWithCompactEncoding(
1011 _info.format, (uint32_t)_info.start_ip, _addressSpace, _registers);
1012 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001013#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001014
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001015#if defined(_LIBUNWIND_TARGET_PPC)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001016 int stepWithCompactEncoding(Registers_ppc &) {
1017 return UNW_EINVAL;
1018 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001019#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001020
Martin Storsjo8338b0a2018-01-02 22:11:30 +00001021#if defined(_LIBUNWIND_TARGET_PPC64)
1022 int stepWithCompactEncoding(Registers_ppc64 &) {
1023 return UNW_EINVAL;
1024 }
1025#endif
1026
1027
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001028#if defined(_LIBUNWIND_TARGET_AARCH64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001029 int stepWithCompactEncoding(Registers_arm64 &) {
1030 return CompactUnwinder_arm64<A>::stepWithCompactEncoding(
1031 _info.format, _info.start_ip, _addressSpace, _registers);
1032 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001033#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001034
John Baldwin56441d42017-12-12 21:43:36 +00001035#if defined(_LIBUNWIND_TARGET_MIPS_O32)
1036 int stepWithCompactEncoding(Registers_mips_o32 &) {
1037 return UNW_EINVAL;
1038 }
1039#endif
1040
John Baldwin541a4352018-01-09 17:07:18 +00001041#if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1042 int stepWithCompactEncoding(Registers_mips_newabi &) {
John Baldwin56441d42017-12-12 21:43:36 +00001043 return UNW_EINVAL;
1044 }
1045#endif
1046
Daniel Cederman9f2f07a2019-01-14 10:15:20 +00001047#if defined(_LIBUNWIND_TARGET_SPARC)
1048 int stepWithCompactEncoding(Registers_sparc &) { return UNW_EINVAL; }
1049#endif
1050
Koakumaf2ef96e2022-02-05 13:08:26 -08001051#if defined(_LIBUNWIND_TARGET_SPARC64)
1052 int stepWithCompactEncoding(Registers_sparc64 &) { return UNW_EINVAL; }
1053#endif
1054
Sam Elliott81f7e172019-12-16 16:35:17 +00001055#if defined (_LIBUNWIND_TARGET_RISCV)
1056 int stepWithCompactEncoding(Registers_riscv &) {
1057 return UNW_EINVAL;
1058 }
1059#endif
1060
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001061 bool compactSaysUseDwarf(uint32_t *offset=NULL) const {
1062 R dummy;
1063 return compactSaysUseDwarf(dummy, offset);
1064 }
1065
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001066#if defined(_LIBUNWIND_TARGET_X86_64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001067 bool compactSaysUseDwarf(Registers_x86_64 &, uint32_t *offset) const {
1068 if ((_info.format & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF) {
1069 if (offset)
1070 *offset = (_info.format & UNWIND_X86_64_DWARF_SECTION_OFFSET);
1071 return true;
1072 }
1073 return false;
1074 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001075#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001076
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001077#if defined(_LIBUNWIND_TARGET_I386)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001078 bool compactSaysUseDwarf(Registers_x86 &, uint32_t *offset) const {
1079 if ((_info.format & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF) {
1080 if (offset)
1081 *offset = (_info.format & UNWIND_X86_DWARF_SECTION_OFFSET);
1082 return true;
1083 }
1084 return false;
1085 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001086#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001087
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001088#if defined(_LIBUNWIND_TARGET_PPC)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001089 bool compactSaysUseDwarf(Registers_ppc &, uint32_t *) const {
1090 return true;
1091 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001092#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001093
Martin Storsjo8338b0a2018-01-02 22:11:30 +00001094#if defined(_LIBUNWIND_TARGET_PPC64)
1095 bool compactSaysUseDwarf(Registers_ppc64 &, uint32_t *) const {
1096 return true;
1097 }
1098#endif
1099
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001100#if defined(_LIBUNWIND_TARGET_AARCH64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001101 bool compactSaysUseDwarf(Registers_arm64 &, uint32_t *offset) const {
1102 if ((_info.format & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF) {
1103 if (offset)
1104 *offset = (_info.format & UNWIND_ARM64_DWARF_SECTION_OFFSET);
1105 return true;
1106 }
1107 return false;
1108 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001109#endif
John Baldwin56441d42017-12-12 21:43:36 +00001110
1111#if defined(_LIBUNWIND_TARGET_MIPS_O32)
1112 bool compactSaysUseDwarf(Registers_mips_o32 &, uint32_t *) const {
1113 return true;
1114 }
1115#endif
1116
John Baldwin541a4352018-01-09 17:07:18 +00001117#if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1118 bool compactSaysUseDwarf(Registers_mips_newabi &, uint32_t *) const {
John Baldwin56441d42017-12-12 21:43:36 +00001119 return true;
1120 }
1121#endif
Daniel Cederman9f2f07a2019-01-14 10:15:20 +00001122
1123#if defined(_LIBUNWIND_TARGET_SPARC)
1124 bool compactSaysUseDwarf(Registers_sparc &, uint32_t *) const { return true; }
1125#endif
1126
Koakumaf2ef96e2022-02-05 13:08:26 -08001127#if defined(_LIBUNWIND_TARGET_SPARC64)
1128 bool compactSaysUseDwarf(Registers_sparc64 &, uint32_t *) const {
1129 return true;
1130 }
1131#endif
1132
Sam Elliott81f7e172019-12-16 16:35:17 +00001133#if defined (_LIBUNWIND_TARGET_RISCV)
1134 bool compactSaysUseDwarf(Registers_riscv &, uint32_t *) const {
1135 return true;
1136 }
1137#endif
1138
Ranjeet Singh421231a2017-03-31 15:28:06 +00001139#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001140
Ranjeet Singh421231a2017-03-31 15:28:06 +00001141#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001142 compact_unwind_encoding_t dwarfEncoding() const {
1143 R dummy;
1144 return dwarfEncoding(dummy);
1145 }
1146
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001147#if defined(_LIBUNWIND_TARGET_X86_64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001148 compact_unwind_encoding_t dwarfEncoding(Registers_x86_64 &) const {
1149 return UNWIND_X86_64_MODE_DWARF;
1150 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001151#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001152
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001153#if defined(_LIBUNWIND_TARGET_I386)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001154 compact_unwind_encoding_t dwarfEncoding(Registers_x86 &) const {
1155 return UNWIND_X86_MODE_DWARF;
1156 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001157#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001158
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001159#if defined(_LIBUNWIND_TARGET_PPC)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001160 compact_unwind_encoding_t dwarfEncoding(Registers_ppc &) const {
1161 return 0;
1162 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001163#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001164
Martin Storsjo8338b0a2018-01-02 22:11:30 +00001165#if defined(_LIBUNWIND_TARGET_PPC64)
1166 compact_unwind_encoding_t dwarfEncoding(Registers_ppc64 &) const {
1167 return 0;
1168 }
1169#endif
1170
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001171#if defined(_LIBUNWIND_TARGET_AARCH64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001172 compact_unwind_encoding_t dwarfEncoding(Registers_arm64 &) const {
1173 return UNWIND_ARM64_MODE_DWARF;
1174 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001175#endif
Peter Zotov8d639992015-08-31 05:26:37 +00001176
Martin Storsjoa72285f2017-11-02 08:16:16 +00001177#if defined(_LIBUNWIND_TARGET_ARM)
1178 compact_unwind_encoding_t dwarfEncoding(Registers_arm &) const {
1179 return 0;
1180 }
1181#endif
1182
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001183#if defined (_LIBUNWIND_TARGET_OR1K)
Peter Zotov8d639992015-08-31 05:26:37 +00001184 compact_unwind_encoding_t dwarfEncoding(Registers_or1k &) const {
1185 return 0;
1186 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001187#endif
John Baldwin56441d42017-12-12 21:43:36 +00001188
Brian Cainb432c472020-04-09 00:14:02 -05001189#if defined (_LIBUNWIND_TARGET_HEXAGON)
1190 compact_unwind_encoding_t dwarfEncoding(Registers_hexagon &) const {
1191 return 0;
1192 }
1193#endif
1194
John Baldwin56441d42017-12-12 21:43:36 +00001195#if defined (_LIBUNWIND_TARGET_MIPS_O32)
1196 compact_unwind_encoding_t dwarfEncoding(Registers_mips_o32 &) const {
1197 return 0;
1198 }
1199#endif
1200
John Baldwin541a4352018-01-09 17:07:18 +00001201#if defined (_LIBUNWIND_TARGET_MIPS_NEWABI)
1202 compact_unwind_encoding_t dwarfEncoding(Registers_mips_newabi &) const {
John Baldwin56441d42017-12-12 21:43:36 +00001203 return 0;
1204 }
1205#endif
Daniel Cederman9f2f07a2019-01-14 10:15:20 +00001206
1207#if defined(_LIBUNWIND_TARGET_SPARC)
1208 compact_unwind_encoding_t dwarfEncoding(Registers_sparc &) const { return 0; }
1209#endif
1210
Koakumaf2ef96e2022-02-05 13:08:26 -08001211#if defined(_LIBUNWIND_TARGET_SPARC64)
1212 compact_unwind_encoding_t dwarfEncoding(Registers_sparc64 &) const {
1213 return 0;
1214 }
1215#endif
1216
Sam Elliott81f7e172019-12-16 16:35:17 +00001217#if defined (_LIBUNWIND_TARGET_RISCV)
1218 compact_unwind_encoding_t dwarfEncoding(Registers_riscv &) const {
1219 return 0;
1220 }
1221#endif
1222
Ranjeet Singh421231a2017-03-31 15:28:06 +00001223#endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001224
Charles Davisfa2e6202018-08-30 21:29:00 +00001225#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1226 // For runtime environments using SEH unwind data without Windows runtime
1227 // support.
1228 pint_t getLastPC() const { /* FIXME: Implement */ return 0; }
1229 void setLastPC(pint_t pc) { /* FIXME: Implement */ }
1230 RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
1231 /* FIXME: Implement */
1232 *base = 0;
1233 return nullptr;
1234 }
1235 bool getInfoFromSEH(pint_t pc);
1236 int stepWithSEHData() { /* FIXME: Implement */ return 0; }
1237#endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1238
Xing Xuebbcbce92022-04-13 11:01:59 -04001239#if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1240 bool getInfoFromTBTable(pint_t pc, R &registers);
1241 int stepWithTBTable(pint_t pc, tbtable *TBTable, R &registers,
1242 bool &isSignalFrame);
1243 int stepWithTBTableData() {
1244 return stepWithTBTable(reinterpret_cast<pint_t>(this->getReg(UNW_REG_IP)),
1245 reinterpret_cast<tbtable *>(_info.unwind_info),
1246 _registers, _isSignalFrame);
1247 }
1248#endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001249
1250 A &_addressSpace;
1251 R _registers;
1252 unw_proc_info_t _info;
1253 bool _unwindInfoMissing;
1254 bool _isSignalFrame;
Ryan Pricharda684bed2021-01-13 16:38:36 -08001255#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
1256 bool _isSigReturn = false;
1257#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001258};
1259
1260
1261template <typename A, typename R>
1262UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
1263 : _addressSpace(as), _registers(context), _unwindInfoMissing(false),
1264 _isSignalFrame(false) {
Asiri Rathnayake74d35252016-05-26 21:45:54 +00001265 static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001266 "UnwindCursor<> does not fit in unw_cursor_t");
Martin Storsjö1c0575e2020-08-17 22:41:58 +03001267 static_assert((alignof(UnwindCursor<A, R>) <= alignof(unw_cursor_t)),
1268 "UnwindCursor<> requires more alignment than unw_cursor_t");
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001269 memset(&_info, 0, sizeof(_info));
1270}
1271
1272template <typename A, typename R>
1273UnwindCursor<A, R>::UnwindCursor(A &as, void *)
1274 : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) {
1275 memset(&_info, 0, sizeof(_info));
1276 // FIXME
1277 // fill in _registers from thread arg
1278}
1279
1280
1281template <typename A, typename R>
1282bool UnwindCursor<A, R>::validReg(int regNum) {
1283 return _registers.validRegister(regNum);
1284}
1285
1286template <typename A, typename R>
1287unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
1288 return _registers.getRegister(regNum);
1289}
1290
1291template <typename A, typename R>
1292void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
1293 _registers.setRegister(regNum, (typename A::pint_t)value);
1294}
1295
1296template <typename A, typename R>
1297bool UnwindCursor<A, R>::validFloatReg(int regNum) {
1298 return _registers.validFloatRegister(regNum);
1299}
1300
1301template <typename A, typename R>
1302unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
1303 return _registers.getFloatRegister(regNum);
1304}
1305
1306template <typename A, typename R>
1307void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
1308 _registers.setFloatRegister(regNum, value);
1309}
1310
1311template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
1312 _registers.jumpto();
1313}
1314
1315#ifdef __arm__
1316template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {
1317 _registers.saveVFPAsX();
1318}
1319#endif
1320
Xing Xuebbcbce92022-04-13 11:01:59 -04001321#ifdef _AIX
1322template <typename A, typename R>
1323uintptr_t UnwindCursor<A, R>::getDataRelBase() {
1324 return reinterpret_cast<uintptr_t>(_info.extra);
1325}
1326#endif
1327
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001328template <typename A, typename R>
1329const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
1330 return _registers.getRegisterName(regNum);
1331}
1332
1333template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
1334 return _isSignalFrame;
1335}
1336
Charles Davisfa2e6202018-08-30 21:29:00 +00001337#endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1338
Ranjeet Singh421231a2017-03-31 15:28:06 +00001339#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001340template<typename A>
1341struct EHABISectionIterator {
1342 typedef EHABISectionIterator _Self;
1343
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001344 typedef typename A::pint_t value_type;
1345 typedef typename A::pint_t* pointer;
1346 typedef typename A::pint_t& reference;
1347 typedef size_t size_type;
1348 typedef size_t difference_type;
1349
1350 static _Self begin(A& addressSpace, const UnwindInfoSections& sects) {
1351 return _Self(addressSpace, sects, 0);
1352 }
1353 static _Self end(A& addressSpace, const UnwindInfoSections& sects) {
Ed Schouten5d3f35b2017-03-07 15:21:57 +00001354 return _Self(addressSpace, sects,
1355 sects.arm_section_length / sizeof(EHABIIndexEntry));
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001356 }
1357
1358 EHABISectionIterator(A& addressSpace, const UnwindInfoSections& sects, size_t i)
1359 : _i(i), _addressSpace(&addressSpace), _sects(&sects) {}
1360
1361 _Self& operator++() { ++_i; return *this; }
1362 _Self& operator+=(size_t a) { _i += a; return *this; }
1363 _Self& operator--() { assert(_i > 0); --_i; return *this; }
1364 _Self& operator-=(size_t a) { assert(_i >= a); _i -= a; return *this; }
1365
1366 _Self operator+(size_t a) { _Self out = *this; out._i += a; return out; }
1367 _Self operator-(size_t a) { assert(_i >= a); _Self out = *this; out._i -= a; return out; }
1368
Saleem Abdulrasoolfbff6b12020-06-18 08:51:44 -07001369 size_t operator-(const _Self& other) const { return _i - other._i; }
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001370
1371 bool operator==(const _Self& other) const {
1372 assert(_addressSpace == other._addressSpace);
1373 assert(_sects == other._sects);
1374 return _i == other._i;
1375 }
1376
Saleem Abdulrasoolfbff6b12020-06-18 08:51:44 -07001377 bool operator!=(const _Self& other) const {
1378 assert(_addressSpace == other._addressSpace);
1379 assert(_sects == other._sects);
1380 return _i != other._i;
1381 }
1382
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001383 typename A::pint_t operator*() const { return functionAddress(); }
1384
1385 typename A::pint_t functionAddress() const {
1386 typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1387 EHABIIndexEntry, _i, functionOffset);
1388 return indexAddr + signExtendPrel31(_addressSpace->get32(indexAddr));
1389 }
1390
1391 typename A::pint_t dataAddress() {
1392 typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1393 EHABIIndexEntry, _i, data);
1394 return indexAddr;
1395 }
1396
1397 private:
1398 size_t _i;
1399 A* _addressSpace;
1400 const UnwindInfoSections* _sects;
1401};
1402
Petr Hosekac0d9e02019-01-29 22:26:18 +00001403namespace {
1404
1405template <typename A>
1406EHABISectionIterator<A> EHABISectionUpperBound(
1407 EHABISectionIterator<A> first,
1408 EHABISectionIterator<A> last,
1409 typename A::pint_t value) {
1410 size_t len = last - first;
1411 while (len > 0) {
1412 size_t l2 = len / 2;
1413 EHABISectionIterator<A> m = first + l2;
1414 if (value < *m) {
1415 len = l2;
1416 } else {
1417 first = ++m;
1418 len -= l2 + 1;
1419 }
1420 }
1421 return first;
1422}
1423
1424}
1425
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001426template <typename A, typename R>
1427bool UnwindCursor<A, R>::getInfoFromEHABISection(
1428 pint_t pc,
1429 const UnwindInfoSections &sects) {
1430 EHABISectionIterator<A> begin =
1431 EHABISectionIterator<A>::begin(_addressSpace, sects);
1432 EHABISectionIterator<A> end =
1433 EHABISectionIterator<A>::end(_addressSpace, sects);
Momchil Velikov064d69a2017-07-24 09:19:32 +00001434 if (begin == end)
1435 return false;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001436
Petr Hosekac0d9e02019-01-29 22:26:18 +00001437 EHABISectionIterator<A> itNextPC = EHABISectionUpperBound(begin, end, pc);
Momchil Velikov064d69a2017-07-24 09:19:32 +00001438 if (itNextPC == begin)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001439 return false;
1440 EHABISectionIterator<A> itThisPC = itNextPC - 1;
1441
1442 pint_t thisPC = itThisPC.functionAddress();
Momchil Velikov064d69a2017-07-24 09:19:32 +00001443 // If an exception is thrown from a function, corresponding to the last entry
1444 // in the table, we don't really know the function extent and have to choose a
1445 // value for nextPC. Choosing max() will allow the range check during trace to
1446 // succeed.
Petr Hosekac0d9e02019-01-29 22:26:18 +00001447 pint_t nextPC = (itNextPC == end) ? UINTPTR_MAX : itNextPC.functionAddress();
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001448 pint_t indexDataAddr = itThisPC.dataAddress();
1449
1450 if (indexDataAddr == 0)
1451 return false;
1452
1453 uint32_t indexData = _addressSpace.get32(indexDataAddr);
1454 if (indexData == UNW_EXIDX_CANTUNWIND)
1455 return false;
1456
1457 // If the high bit is set, the exception handling table entry is inline inside
1458 // the index table entry on the second word (aka |indexDataAddr|). Otherwise,
Nico Weberd999d542020-02-03 14:16:52 -05001459 // the table points at an offset in the exception handling table (section 5
1460 // EHABI).
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001461 pint_t exceptionTableAddr;
1462 uint32_t exceptionTableData;
1463 bool isSingleWordEHT;
1464 if (indexData & 0x80000000) {
1465 exceptionTableAddr = indexDataAddr;
1466 // TODO(ajwong): Should this data be 0?
1467 exceptionTableData = indexData;
1468 isSingleWordEHT = true;
1469 } else {
1470 exceptionTableAddr = indexDataAddr + signExtendPrel31(indexData);
1471 exceptionTableData = _addressSpace.get32(exceptionTableAddr);
1472 isSingleWordEHT = false;
1473 }
1474
1475 // Now we know the 3 things:
1476 // exceptionTableAddr -- exception handler table entry.
1477 // exceptionTableData -- the data inside the first word of the eht entry.
1478 // isSingleWordEHT -- whether the entry is in the index.
1479 unw_word_t personalityRoutine = 0xbadf00d;
1480 bool scope32 = false;
Logan Chiena54f0962015-05-29 15:33:38 +00001481 uintptr_t lsda;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001482
1483 // If the high bit in the exception handling table entry is set, the entry is
1484 // in compact form (section 6.3 EHABI).
1485 if (exceptionTableData & 0x80000000) {
1486 // Grab the index of the personality routine from the compact form.
1487 uint32_t choice = (exceptionTableData & 0x0f000000) >> 24;
1488 uint32_t extraWords = 0;
1489 switch (choice) {
1490 case 0:
1491 personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr0;
1492 extraWords = 0;
1493 scope32 = false;
Logan Chiena54f0962015-05-29 15:33:38 +00001494 lsda = isSingleWordEHT ? 0 : (exceptionTableAddr + 4);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001495 break;
1496 case 1:
1497 personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr1;
1498 extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1499 scope32 = false;
Logan Chiena54f0962015-05-29 15:33:38 +00001500 lsda = exceptionTableAddr + (extraWords + 1) * 4;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001501 break;
1502 case 2:
1503 personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr2;
1504 extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1505 scope32 = true;
Logan Chiena54f0962015-05-29 15:33:38 +00001506 lsda = exceptionTableAddr + (extraWords + 1) * 4;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001507 break;
1508 default:
1509 _LIBUNWIND_ABORT("unknown personality routine");
1510 return false;
1511 }
1512
1513 if (isSingleWordEHT) {
1514 if (extraWords != 0) {
1515 _LIBUNWIND_ABORT("index inlined table detected but pr function "
1516 "requires extra words");
1517 return false;
1518 }
1519 }
1520 } else {
1521 pint_t personalityAddr =
1522 exceptionTableAddr + signExtendPrel31(exceptionTableData);
1523 personalityRoutine = personalityAddr;
1524
1525 // ARM EHABI # 6.2, # 9.2
1526 //
1527 // +---- ehtp
1528 // v
1529 // +--------------------------------------+
1530 // | +--------+--------+--------+-------+ |
1531 // | |0| prel31 to personalityRoutine | |
1532 // | +--------+--------+--------+-------+ |
1533 // | | N | unwind opcodes | | <-- UnwindData
1534 // | +--------+--------+--------+-------+ |
1535 // | | Word 2 unwind opcodes | |
1536 // | +--------+--------+--------+-------+ |
1537 // | ... |
1538 // | +--------+--------+--------+-------+ |
1539 // | | Word N unwind opcodes | |
1540 // | +--------+--------+--------+-------+ |
1541 // | | LSDA | | <-- lsda
1542 // | | ... | |
1543 // | +--------+--------+--------+-------+ |
1544 // +--------------------------------------+
1545
1546 uint32_t *UnwindData = reinterpret_cast<uint32_t*>(exceptionTableAddr) + 1;
1547 uint32_t FirstDataWord = *UnwindData;
1548 size_t N = ((FirstDataWord >> 24) & 0xff);
1549 size_t NDataWords = N + 1;
1550 lsda = reinterpret_cast<uintptr_t>(UnwindData + NDataWords);
1551 }
1552
1553 _info.start_ip = thisPC;
1554 _info.end_ip = nextPC;
1555 _info.handler = personalityRoutine;
1556 _info.unwind_info = exceptionTableAddr;
1557 _info.lsda = lsda;
1558 // flags is pr_cache.additional. See EHABI #7.2 for definition of bit 0.
Nico Weberd999d542020-02-03 14:16:52 -05001559 _info.flags = (isSingleWordEHT ? 1 : 0) | (scope32 ? 0x2 : 0); // Use enum?
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001560
1561 return true;
1562}
1563#endif
1564
Ranjeet Singh421231a2017-03-31 15:28:06 +00001565#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001566template <typename A, typename R>
Ryan Prichard1ae2b942020-08-18 02:31:38 -07001567bool UnwindCursor<A, R>::getInfoFromFdeCie(
1568 const typename CFI_Parser<A>::FDE_Info &fdeInfo,
1569 const typename CFI_Parser<A>::CIE_Info &cieInfo, pint_t pc,
1570 uintptr_t dso_base) {
1571 typename CFI_Parser<A>::PrologInfo prolog;
1572 if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo, pc,
1573 R::getArch(), &prolog)) {
1574 // Save off parsed FDE info
1575 _info.start_ip = fdeInfo.pcStart;
1576 _info.end_ip = fdeInfo.pcEnd;
1577 _info.lsda = fdeInfo.lsda;
1578 _info.handler = cieInfo.personality;
1579 // Some frameless functions need SP altered when resuming in function, so
1580 // propagate spExtraArgSize.
1581 _info.gp = prolog.spExtraArgSize;
1582 _info.flags = 0;
1583 _info.format = dwarfEncoding();
1584 _info.unwind_info = fdeInfo.fdeStart;
1585 _info.unwind_info_size = static_cast<uint32_t>(fdeInfo.fdeLength);
1586 _info.extra = static_cast<unw_word_t>(dso_base);
1587 return true;
1588 }
1589 return false;
1590}
1591
1592template <typename A, typename R>
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001593bool UnwindCursor<A, R>::getInfoFromDwarfSection(pint_t pc,
1594 const UnwindInfoSections &sects,
1595 uint32_t fdeSectionOffsetHint) {
1596 typename CFI_Parser<A>::FDE_Info fdeInfo;
1597 typename CFI_Parser<A>::CIE_Info cieInfo;
1598 bool foundFDE = false;
1599 bool foundInCache = false;
1600 // If compact encoding table gave offset into dwarf section, go directly there
1601 if (fdeSectionOffsetHint != 0) {
1602 foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
Ryan Prichard0cff8572020-09-16 01:22:55 -07001603 sects.dwarf_section_length,
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001604 sects.dwarf_section + fdeSectionOffsetHint,
1605 &fdeInfo, &cieInfo);
1606 }
Ranjeet Singh421231a2017-03-31 15:28:06 +00001607#if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001608 if (!foundFDE && (sects.dwarf_index_section != 0)) {
1609 foundFDE = EHHeaderParser<A>::findFDE(
1610 _addressSpace, pc, sects.dwarf_index_section,
1611 (uint32_t)sects.dwarf_index_section_length, &fdeInfo, &cieInfo);
1612 }
1613#endif
1614 if (!foundFDE) {
1615 // otherwise, search cache of previously found FDEs.
1616 pint_t cachedFDE = DwarfFDECache<A>::findFDE(sects.dso_base, pc);
1617 if (cachedFDE != 0) {
1618 foundFDE =
1619 CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
Ryan Prichard0cff8572020-09-16 01:22:55 -07001620 sects.dwarf_section_length,
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001621 cachedFDE, &fdeInfo, &cieInfo);
1622 foundInCache = foundFDE;
1623 }
1624 }
1625 if (!foundFDE) {
1626 // Still not found, do full scan of __eh_frame section.
1627 foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
Ryan Prichard0cff8572020-09-16 01:22:55 -07001628 sects.dwarf_section_length, 0,
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001629 &fdeInfo, &cieInfo);
1630 }
1631 if (foundFDE) {
Ryan Prichard1ae2b942020-08-18 02:31:38 -07001632 if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, sects.dso_base)) {
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001633 // Add to cache (to make next lookup faster) if we had no hint
1634 // and there was no index.
1635 if (!foundInCache && (fdeSectionOffsetHint == 0)) {
Ranjeet Singh421231a2017-03-31 15:28:06 +00001636 #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001637 if (sects.dwarf_index_section == 0)
1638 #endif
1639 DwarfFDECache<A>::add(sects.dso_base, fdeInfo.pcStart, fdeInfo.pcEnd,
1640 fdeInfo.fdeStart);
1641 }
1642 return true;
1643 }
1644 }
Ed Maste41bc5a72016-08-30 15:38:10 +00001645 //_LIBUNWIND_DEBUG_LOG("can't find/use FDE for pc=0x%llX", (uint64_t)pc);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001646 return false;
1647}
Ranjeet Singh421231a2017-03-31 15:28:06 +00001648#endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001649
1650
Ranjeet Singh421231a2017-03-31 15:28:06 +00001651#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001652template <typename A, typename R>
1653bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
1654 const UnwindInfoSections &sects) {
1655 const bool log = false;
1656 if (log)
1657 fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX, mh=0x%llX)\n",
1658 (uint64_t)pc, (uint64_t)sects.dso_base);
1659
1660 const UnwindSectionHeader<A> sectionHeader(_addressSpace,
1661 sects.compact_unwind_section);
1662 if (sectionHeader.version() != UNWIND_SECTION_VERSION)
1663 return false;
1664
1665 // do a binary search of top level index to find page with unwind info
1666 pint_t targetFunctionOffset = pc - sects.dso_base;
1667 const UnwindSectionIndexArray<A> topIndex(_addressSpace,
1668 sects.compact_unwind_section
1669 + sectionHeader.indexSectionOffset());
1670 uint32_t low = 0;
1671 uint32_t high = sectionHeader.indexCount();
1672 uint32_t last = high - 1;
1673 while (low < high) {
1674 uint32_t mid = (low + high) / 2;
1675 //if ( log ) fprintf(stderr, "\tmid=%d, low=%d, high=%d, *mid=0x%08X\n",
1676 //mid, low, high, topIndex.functionOffset(mid));
1677 if (topIndex.functionOffset(mid) <= targetFunctionOffset) {
1678 if ((mid == last) ||
1679 (topIndex.functionOffset(mid + 1) > targetFunctionOffset)) {
1680 low = mid;
1681 break;
1682 } else {
1683 low = mid + 1;
1684 }
1685 } else {
1686 high = mid;
1687 }
1688 }
1689 const uint32_t firstLevelFunctionOffset = topIndex.functionOffset(low);
1690 const uint32_t firstLevelNextPageFunctionOffset =
1691 topIndex.functionOffset(low + 1);
1692 const pint_t secondLevelAddr =
1693 sects.compact_unwind_section + topIndex.secondLevelPagesSectionOffset(low);
1694 const pint_t lsdaArrayStartAddr =
1695 sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low);
1696 const pint_t lsdaArrayEndAddr =
1697 sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low+1);
1698 if (log)
1699 fprintf(stderr, "\tfirst level search for result index=%d "
1700 "to secondLevelAddr=0x%llX\n",
1701 low, (uint64_t) secondLevelAddr);
1702 // do a binary search of second level page index
1703 uint32_t encoding = 0;
1704 pint_t funcStart = 0;
1705 pint_t funcEnd = 0;
1706 pint_t lsda = 0;
1707 pint_t personality = 0;
1708 uint32_t pageKind = _addressSpace.get32(secondLevelAddr);
1709 if (pageKind == UNWIND_SECOND_LEVEL_REGULAR) {
1710 // regular page
1711 UnwindSectionRegularPageHeader<A> pageHeader(_addressSpace,
1712 secondLevelAddr);
1713 UnwindSectionRegularArray<A> pageIndex(
1714 _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1715 // binary search looks for entry with e where index[e].offset <= pc <
1716 // index[e+1].offset
1717 if (log)
1718 fprintf(stderr, "\tbinary search for targetFunctionOffset=0x%08llX in "
1719 "regular page starting at secondLevelAddr=0x%llX\n",
1720 (uint64_t) targetFunctionOffset, (uint64_t) secondLevelAddr);
1721 low = 0;
1722 high = pageHeader.entryCount();
1723 while (low < high) {
1724 uint32_t mid = (low + high) / 2;
1725 if (pageIndex.functionOffset(mid) <= targetFunctionOffset) {
1726 if (mid == (uint32_t)(pageHeader.entryCount() - 1)) {
1727 // at end of table
1728 low = mid;
1729 funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1730 break;
1731 } else if (pageIndex.functionOffset(mid + 1) > targetFunctionOffset) {
1732 // next is too big, so we found it
1733 low = mid;
1734 funcEnd = pageIndex.functionOffset(low + 1) + sects.dso_base;
1735 break;
1736 } else {
1737 low = mid + 1;
1738 }
1739 } else {
1740 high = mid;
1741 }
1742 }
1743 encoding = pageIndex.encoding(low);
1744 funcStart = pageIndex.functionOffset(low) + sects.dso_base;
1745 if (pc < funcStart) {
1746 if (log)
1747 fprintf(
1748 stderr,
1749 "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1750 (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1751 return false;
1752 }
1753 if (pc > funcEnd) {
1754 if (log)
1755 fprintf(
1756 stderr,
1757 "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1758 (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1759 return false;
1760 }
1761 } else if (pageKind == UNWIND_SECOND_LEVEL_COMPRESSED) {
1762 // compressed page
1763 UnwindSectionCompressedPageHeader<A> pageHeader(_addressSpace,
1764 secondLevelAddr);
1765 UnwindSectionCompressedArray<A> pageIndex(
1766 _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1767 const uint32_t targetFunctionPageOffset =
1768 (uint32_t)(targetFunctionOffset - firstLevelFunctionOffset);
1769 // binary search looks for entry with e where index[e].offset <= pc <
1770 // index[e+1].offset
1771 if (log)
1772 fprintf(stderr, "\tbinary search of compressed page starting at "
1773 "secondLevelAddr=0x%llX\n",
1774 (uint64_t) secondLevelAddr);
1775 low = 0;
1776 last = pageHeader.entryCount() - 1;
1777 high = pageHeader.entryCount();
1778 while (low < high) {
1779 uint32_t mid = (low + high) / 2;
1780 if (pageIndex.functionOffset(mid) <= targetFunctionPageOffset) {
1781 if ((mid == last) ||
1782 (pageIndex.functionOffset(mid + 1) > targetFunctionPageOffset)) {
1783 low = mid;
1784 break;
1785 } else {
1786 low = mid + 1;
1787 }
1788 } else {
1789 high = mid;
1790 }
1791 }
1792 funcStart = pageIndex.functionOffset(low) + firstLevelFunctionOffset
1793 + sects.dso_base;
1794 if (low < last)
1795 funcEnd =
1796 pageIndex.functionOffset(low + 1) + firstLevelFunctionOffset
1797 + sects.dso_base;
1798 else
1799 funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1800 if (pc < funcStart) {
Nico Weber5f424e32021-07-02 10:03:32 -04001801 _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1802 "not in second level compressed unwind table. "
1803 "funcStart=0x%llX",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001804 (uint64_t) pc, (uint64_t) funcStart);
1805 return false;
1806 }
1807 if (pc > funcEnd) {
Nico Weber5f424e32021-07-02 10:03:32 -04001808 _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1809 "not in second level compressed unwind table. "
1810 "funcEnd=0x%llX",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001811 (uint64_t) pc, (uint64_t) funcEnd);
1812 return false;
1813 }
1814 uint16_t encodingIndex = pageIndex.encodingIndex(low);
1815 if (encodingIndex < sectionHeader.commonEncodingsArrayCount()) {
1816 // encoding is in common table in section header
1817 encoding = _addressSpace.get32(
1818 sects.compact_unwind_section +
1819 sectionHeader.commonEncodingsArraySectionOffset() +
1820 encodingIndex * sizeof(uint32_t));
1821 } else {
1822 // encoding is in page specific table
1823 uint16_t pageEncodingIndex =
1824 encodingIndex - (uint16_t)sectionHeader.commonEncodingsArrayCount();
1825 encoding = _addressSpace.get32(secondLevelAddr +
1826 pageHeader.encodingsPageOffset() +
1827 pageEncodingIndex * sizeof(uint32_t));
1828 }
1829 } else {
Nico Weber5f424e32021-07-02 10:03:32 -04001830 _LIBUNWIND_DEBUG_LOG(
1831 "malformed __unwind_info at 0x%0llX bad second level page",
1832 (uint64_t)sects.compact_unwind_section);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001833 return false;
1834 }
1835
1836 // look up LSDA, if encoding says function has one
1837 if (encoding & UNWIND_HAS_LSDA) {
1838 UnwindSectionLsdaArray<A> lsdaIndex(_addressSpace, lsdaArrayStartAddr);
1839 uint32_t funcStartOffset = (uint32_t)(funcStart - sects.dso_base);
1840 low = 0;
1841 high = (uint32_t)(lsdaArrayEndAddr - lsdaArrayStartAddr) /
1842 sizeof(unwind_info_section_header_lsda_index_entry);
1843 // binary search looks for entry with exact match for functionOffset
1844 if (log)
1845 fprintf(stderr,
1846 "\tbinary search of lsda table for targetFunctionOffset=0x%08X\n",
1847 funcStartOffset);
1848 while (low < high) {
1849 uint32_t mid = (low + high) / 2;
1850 if (lsdaIndex.functionOffset(mid) == funcStartOffset) {
1851 lsda = lsdaIndex.lsdaOffset(mid) + sects.dso_base;
1852 break;
1853 } else if (lsdaIndex.functionOffset(mid) < funcStartOffset) {
1854 low = mid + 1;
1855 } else {
1856 high = mid;
1857 }
1858 }
1859 if (lsda == 0) {
1860 _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with HAS_LSDA bit set for "
Ed Maste41bc5a72016-08-30 15:38:10 +00001861 "pc=0x%0llX, but lsda table has no entry",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001862 encoding, (uint64_t) pc);
1863 return false;
1864 }
1865 }
1866
Louis Dionned3bbbc32020-08-11 15:24:21 -04001867 // extract personality routine, if encoding says function has one
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001868 uint32_t personalityIndex = (encoding & UNWIND_PERSONALITY_MASK) >>
1869 (__builtin_ctz(UNWIND_PERSONALITY_MASK));
1870 if (personalityIndex != 0) {
1871 --personalityIndex; // change 1-based to zero-based index
Louis Dionne8c360cb2020-08-11 15:29:00 -04001872 if (personalityIndex >= sectionHeader.personalityArrayCount()) {
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001873 _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with personality index %d, "
Louis Dionne103afa42019-04-22 15:40:50 +00001874 "but personality table has only %d entries",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001875 encoding, personalityIndex,
1876 sectionHeader.personalityArrayCount());
1877 return false;
1878 }
1879 int32_t personalityDelta = (int32_t)_addressSpace.get32(
1880 sects.compact_unwind_section +
1881 sectionHeader.personalityArraySectionOffset() +
1882 personalityIndex * sizeof(uint32_t));
1883 pint_t personalityPointer = sects.dso_base + (pint_t)personalityDelta;
1884 personality = _addressSpace.getP(personalityPointer);
1885 if (log)
1886 fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1887 "personalityDelta=0x%08X, personality=0x%08llX\n",
1888 (uint64_t) pc, personalityDelta, (uint64_t) personality);
1889 }
1890
1891 if (log)
1892 fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1893 "encoding=0x%08X, lsda=0x%08llX for funcStart=0x%llX\n",
1894 (uint64_t) pc, encoding, (uint64_t) lsda, (uint64_t) funcStart);
1895 _info.start_ip = funcStart;
1896 _info.end_ip = funcEnd;
1897 _info.lsda = lsda;
1898 _info.handler = personality;
1899 _info.gp = 0;
1900 _info.flags = 0;
1901 _info.format = encoding;
1902 _info.unwind_info = 0;
1903 _info.unwind_info_size = 0;
1904 _info.extra = sects.dso_base;
1905 return true;
1906}
Ranjeet Singh421231a2017-03-31 15:28:06 +00001907#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001908
1909
Charles Davisfa2e6202018-08-30 21:29:00 +00001910#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1911template <typename A, typename R>
1912bool UnwindCursor<A, R>::getInfoFromSEH(pint_t pc) {
1913 pint_t base;
1914 RUNTIME_FUNCTION *unwindEntry = lookUpSEHUnwindInfo(pc, &base);
1915 if (!unwindEntry) {
1916 _LIBUNWIND_DEBUG_LOG("\tpc not in table, pc=0x%llX", (uint64_t) pc);
1917 return false;
1918 }
1919 _info.gp = 0;
1920 _info.flags = 0;
1921 _info.format = 0;
1922 _info.unwind_info_size = sizeof(RUNTIME_FUNCTION);
1923 _info.unwind_info = reinterpret_cast<unw_word_t>(unwindEntry);
1924 _info.extra = base;
1925 _info.start_ip = base + unwindEntry->BeginAddress;
1926#ifdef _LIBUNWIND_TARGET_X86_64
1927 _info.end_ip = base + unwindEntry->EndAddress;
1928 // Only fill in the handler and LSDA if they're stale.
1929 if (pc != getLastPC()) {
1930 UNWIND_INFO *xdata = reinterpret_cast<UNWIND_INFO *>(base + unwindEntry->UnwindData);
1931 if (xdata->Flags & (UNW_FLAG_EHANDLER|UNW_FLAG_UHANDLER)) {
1932 // The personality is given in the UNWIND_INFO itself. The LSDA immediately
1933 // follows the UNWIND_INFO. (This follows how both Clang and MSVC emit
1934 // these structures.)
1935 // N.B. UNWIND_INFO structs are DWORD-aligned.
1936 uint32_t lastcode = (xdata->CountOfCodes + 1) & ~1;
1937 const uint32_t *handler = reinterpret_cast<uint32_t *>(&xdata->UnwindCodes[lastcode]);
1938 _info.lsda = reinterpret_cast<unw_word_t>(handler+1);
1939 if (*handler) {
1940 _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
1941 } else
1942 _info.handler = 0;
1943 } else {
1944 _info.lsda = 0;
1945 _info.handler = 0;
1946 }
1947 }
1948#elif defined(_LIBUNWIND_TARGET_ARM)
1949 _info.end_ip = _info.start_ip + unwindEntry->FunctionLength;
1950 _info.lsda = 0; // FIXME
1951 _info.handler = 0; // FIXME
1952#endif
1953 setLastPC(pc);
1954 return true;
1955}
1956#endif
1957
Xing Xuebbcbce92022-04-13 11:01:59 -04001958#if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1959// Masks for traceback table field xtbtable.
1960enum xTBTableMask : uint8_t {
1961 reservedBit = 0x02, // The traceback table was incorrectly generated if set
1962 // (see comments in function getInfoFromTBTable().
1963 ehInfoBit = 0x08 // Exception handling info is present if set
1964};
1965
1966enum frameType : unw_word_t {
1967 frameWithXLEHStateTable = 0,
1968 frameWithEHInfo = 1
1969};
1970
1971extern "C" {
1972typedef _Unwind_Reason_Code __xlcxx_personality_v0_t(int, _Unwind_Action,
1973 uint64_t,
1974 _Unwind_Exception *,
1975 struct _Unwind_Context *);
1976__attribute__((__weak__)) __xlcxx_personality_v0_t __xlcxx_personality_v0;
1977}
1978
1979static __xlcxx_personality_v0_t *xlcPersonalityV0;
1980static RWMutex xlcPersonalityV0InitLock;
1981
1982template <typename A, typename R>
1983bool UnwindCursor<A, R>::getInfoFromTBTable(pint_t pc, R &registers) {
1984 uint32_t *p = reinterpret_cast<uint32_t *>(pc);
1985
1986 // Keep looking forward until a word of 0 is found. The traceback
1987 // table starts at the following word.
1988 while (*p)
1989 ++p;
1990 tbtable *TBTable = reinterpret_cast<tbtable *>(p + 1);
1991
1992 if (_LIBUNWIND_TRACING_UNWINDING) {
1993 char functionBuf[512];
1994 const char *functionName = functionBuf;
1995 unw_word_t offset;
1996 if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
1997 functionName = ".anonymous.";
1998 }
1999 _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2000 __func__, functionName,
2001 reinterpret_cast<void *>(TBTable));
2002 }
2003
2004 // If the traceback table does not contain necessary info, bypass this frame.
2005 if (!TBTable->tb.has_tboff)
2006 return false;
2007
2008 // Structure tbtable_ext contains important data we are looking for.
2009 p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2010
2011 // Skip field parminfo if it exists.
2012 if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2013 ++p;
2014
2015 // p now points to tb_offset, the offset from start of function to TB table.
2016 unw_word_t start_ip =
2017 reinterpret_cast<unw_word_t>(TBTable) - *p - sizeof(uint32_t);
2018 unw_word_t end_ip = reinterpret_cast<unw_word_t>(TBTable);
2019 ++p;
2020
2021 _LIBUNWIND_TRACE_UNWINDING("start_ip=%p, end_ip=%p\n",
2022 reinterpret_cast<void *>(start_ip),
2023 reinterpret_cast<void *>(end_ip));
2024
2025 // Skip field hand_mask if it exists.
2026 if (TBTable->tb.int_hndl)
2027 ++p;
2028
2029 unw_word_t lsda = 0;
2030 unw_word_t handler = 0;
2031 unw_word_t flags = frameType::frameWithXLEHStateTable;
2032
2033 if (TBTable->tb.lang == TB_CPLUSPLUS && TBTable->tb.has_ctl) {
2034 // State table info is available. The ctl_info field indicates the
2035 // number of CTL anchors. There should be only one entry for the C++
2036 // state table.
2037 assert(*p == 1 && "libunwind: there must be only one ctl_info entry");
2038 ++p;
2039 // p points to the offset of the state table into the stack.
2040 pint_t stateTableOffset = *p++;
2041
2042 int framePointerReg;
2043
2044 // Skip fields name_len and name if exist.
2045 if (TBTable->tb.name_present) {
2046 const uint16_t name_len = *(reinterpret_cast<uint16_t *>(p));
2047 p = reinterpret_cast<uint32_t *>(reinterpret_cast<char *>(p) + name_len +
2048 sizeof(uint16_t));
2049 }
2050
2051 if (TBTable->tb.uses_alloca)
2052 framePointerReg = *(reinterpret_cast<char *>(p));
2053 else
2054 framePointerReg = 1; // default frame pointer == SP
2055
2056 _LIBUNWIND_TRACE_UNWINDING(
2057 "framePointerReg=%d, framePointer=%p, "
2058 "stateTableOffset=%#lx\n",
2059 framePointerReg,
2060 reinterpret_cast<void *>(_registers.getRegister(framePointerReg)),
2061 stateTableOffset);
2062 lsda = _registers.getRegister(framePointerReg) + stateTableOffset;
2063
2064 // Since the traceback table generated by the legacy XLC++ does not
2065 // provide the location of the personality for the state table,
2066 // function __xlcxx_personality_v0(), which is the personality for the state
2067 // table and is exported from libc++abi, is directly assigned as the
2068 // handler here. When a legacy XLC++ frame is encountered, the symbol
2069 // is resolved dynamically using dlopen() to avoid hard dependency from
2070 // libunwind on libc++abi.
2071
2072 // Resolve the function pointer to the state table personality if it has
2073 // not already.
2074 if (xlcPersonalityV0 == NULL) {
2075 xlcPersonalityV0InitLock.lock();
2076 if (xlcPersonalityV0 == NULL) {
2077 // If libc++abi is statically linked in, symbol __xlcxx_personality_v0
2078 // has been resolved at the link time.
2079 xlcPersonalityV0 = &__xlcxx_personality_v0;
2080 if (xlcPersonalityV0 == NULL) {
2081 // libc++abi is dynamically linked. Resolve __xlcxx_personality_v0
2082 // using dlopen().
2083 const char libcxxabi[] = "libc++abi.a(libc++abi.so.1)";
2084 void *libHandle;
2085 libHandle = dlopen(libcxxabi, RTLD_MEMBER | RTLD_NOW);
2086 if (libHandle == NULL) {
2087 _LIBUNWIND_TRACE_UNWINDING("dlopen() failed with errno=%d\n",
2088 errno);
2089 assert(0 && "dlopen() failed");
2090 }
2091 xlcPersonalityV0 = reinterpret_cast<__xlcxx_personality_v0_t *>(
2092 dlsym(libHandle, "__xlcxx_personality_v0"));
2093 if (xlcPersonalityV0 == NULL) {
2094 _LIBUNWIND_TRACE_UNWINDING("dlsym() failed with errno=%d\n", errno);
2095 assert(0 && "dlsym() failed");
2096 }
2097 dlclose(libHandle);
2098 }
2099 }
2100 xlcPersonalityV0InitLock.unlock();
2101 }
2102 handler = reinterpret_cast<unw_word_t>(xlcPersonalityV0);
2103 _LIBUNWIND_TRACE_UNWINDING("State table: LSDA=%p, Personality=%p\n",
2104 reinterpret_cast<void *>(lsda),
2105 reinterpret_cast<void *>(handler));
2106 } else if (TBTable->tb.longtbtable) {
2107 // This frame has the traceback table extension. Possible cases are
2108 // 1) a C++ frame that has the 'eh_info' structure; 2) a C++ frame that
2109 // is not EH aware; or, 3) a frame of other languages. We need to figure out
2110 // if the traceback table extension contains the 'eh_info' structure.
2111 //
2112 // We also need to deal with the complexity arising from some XL compiler
2113 // versions use the wrong ordering of 'longtbtable' and 'has_vec' bits
2114 // where the 'longtbtable' bit is meant to be the 'has_vec' bit and vice
2115 // versa. For frames of code generated by those compilers, the 'longtbtable'
2116 // bit may be set but there isn't really a traceback table extension.
2117 //
2118 // In </usr/include/sys/debug.h>, there is the following definition of
2119 // 'struct tbtable_ext'. It is not really a structure but a dummy to
2120 // collect the description of optional parts of the traceback table.
2121 //
2122 // struct tbtable_ext {
2123 // ...
2124 // char alloca_reg; /* Register for alloca automatic storage */
2125 // struct vec_ext vec_ext; /* Vector extension (if has_vec is set) */
2126 // unsigned char xtbtable; /* More tbtable fields, if longtbtable is set*/
2127 // };
2128 //
2129 // Depending on how the 'has_vec'/'longtbtable' bit is interpreted, the data
2130 // following 'alloca_reg' can be treated either as 'struct vec_ext' or
2131 // 'unsigned char xtbtable'. 'xtbtable' bits are defined in
2132 // </usr/include/sys/debug.h> as flags. The 7th bit '0x02' is currently
2133 // unused and should not be set. 'struct vec_ext' is defined in
2134 // </usr/include/sys/debug.h> as follows:
2135 //
2136 // struct vec_ext {
2137 // unsigned vr_saved:6; /* Number of non-volatile vector regs saved
2138 // */
2139 // /* first register saved is assumed to be */
2140 // /* 32 - vr_saved */
2141 // unsigned saves_vrsave:1; /* Set if vrsave is saved on the stack */
2142 // unsigned has_varargs:1;
2143 // ...
2144 // };
2145 //
2146 // Here, the 7th bit is used as 'saves_vrsave'. To determine whether it
2147 // is 'struct vec_ext' or 'xtbtable' that follows 'alloca_reg',
2148 // we checks if the 7th bit is set or not because 'xtbtable' should
2149 // never have the 7th bit set. The 7th bit of 'xtbtable' will be reserved
2150 // in the future to make sure the mitigation works. This mitigation
2151 // is not 100% bullet proof because 'struct vec_ext' may not always have
2152 // 'saves_vrsave' bit set.
2153 //
2154 // 'reservedBit' is defined in enum 'xTBTableMask' above as the mask for
2155 // checking the 7th bit.
2156
2157 // p points to field name len.
2158 uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2159
2160 // Skip fields name_len and name if they exist.
2161 if (TBTable->tb.name_present) {
2162 const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2163 charPtr = charPtr + name_len + sizeof(uint16_t);
2164 }
2165
2166 // Skip field alloc_reg if it exists.
2167 if (TBTable->tb.uses_alloca)
2168 ++charPtr;
2169
2170 // Check traceback table bit has_vec. Skip struct vec_ext if it exists.
2171 if (TBTable->tb.has_vec)
2172 // Note struct vec_ext does exist at this point because whether the
2173 // ordering of longtbtable and has_vec bits is correct or not, both
2174 // are set.
2175 charPtr += sizeof(struct vec_ext);
2176
2177 // charPtr points to field 'xtbtable'. Check if the EH info is available.
2178 // Also check if the reserved bit of the extended traceback table field
2179 // 'xtbtable' is set. If it is, the traceback table was incorrectly
2180 // generated by an XL compiler that uses the wrong ordering of 'longtbtable'
2181 // and 'has_vec' bits and this is in fact 'struct vec_ext'. So skip the
2182 // frame.
2183 if ((*charPtr & xTBTableMask::ehInfoBit) &&
2184 !(*charPtr & xTBTableMask::reservedBit)) {
2185 // Mark this frame has the new EH info.
2186 flags = frameType::frameWithEHInfo;
2187
2188 // eh_info is available.
2189 charPtr++;
2190 // The pointer is 4-byte aligned.
2191 if (reinterpret_cast<uintptr_t>(charPtr) % 4)
2192 charPtr += 4 - reinterpret_cast<uintptr_t>(charPtr) % 4;
2193 uintptr_t *ehInfo =
2194 reinterpret_cast<uintptr_t *>(*(reinterpret_cast<uintptr_t *>(
2195 registers.getRegister(2) +
2196 *(reinterpret_cast<uintptr_t *>(charPtr)))));
2197
2198 // ehInfo points to structure en_info. The first member is version.
2199 // Only version 0 is currently supported.
2200 assert(*(reinterpret_cast<uint32_t *>(ehInfo)) == 0 &&
2201 "libunwind: ehInfo version other than 0 is not supported");
2202
2203 // Increment ehInfo to point to member lsda.
2204 ++ehInfo;
2205 lsda = *ehInfo++;
2206
2207 // enInfo now points to member personality.
2208 handler = *ehInfo;
2209
2210 _LIBUNWIND_TRACE_UNWINDING("Range table: LSDA=%#lx, Personality=%#lx\n",
2211 lsda, handler);
2212 }
2213 }
2214
2215 _info.start_ip = start_ip;
2216 _info.end_ip = end_ip;
2217 _info.lsda = lsda;
2218 _info.handler = handler;
2219 _info.gp = 0;
2220 _info.flags = flags;
2221 _info.format = 0;
2222 _info.unwind_info = reinterpret_cast<unw_word_t>(TBTable);
2223 _info.unwind_info_size = 0;
2224 _info.extra = registers.getRegister(2);
2225
2226 return true;
2227}
2228
2229// Step back up the stack following the frame back link.
2230template <typename A, typename R>
2231int UnwindCursor<A, R>::stepWithTBTable(pint_t pc, tbtable *TBTable,
2232 R &registers, bool &isSignalFrame) {
2233 if (_LIBUNWIND_TRACING_UNWINDING) {
2234 char functionBuf[512];
2235 const char *functionName = functionBuf;
2236 unw_word_t offset;
2237 if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
2238 functionName = ".anonymous.";
2239 }
2240 _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2241 __func__, functionName,
2242 reinterpret_cast<void *>(TBTable));
2243 }
2244
2245#if defined(__powerpc64__)
2246 // Instruction to reload TOC register "l r2,40(r1)"
2247 const uint32_t loadTOCRegInst = 0xe8410028;
2248 const int32_t unwPPCF0Index = UNW_PPC64_F0;
2249 const int32_t unwPPCV0Index = UNW_PPC64_V0;
2250#else
2251 // Instruction to reload TOC register "l r2,20(r1)"
2252 const uint32_t loadTOCRegInst = 0x80410014;
2253 const int32_t unwPPCF0Index = UNW_PPC_F0;
2254 const int32_t unwPPCV0Index = UNW_PPC_V0;
2255#endif
2256
2257 R newRegisters = registers;
2258
2259 // lastStack points to the stack frame of the next routine up.
2260 pint_t lastStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2261
2262 // Return address is the address after call site instruction.
2263 pint_t returnAddress;
2264
2265 if (isSignalFrame) {
2266 _LIBUNWIND_TRACE_UNWINDING("Possible signal handler frame: lastStack=%p",
2267 reinterpret_cast<void *>(lastStack));
2268
2269 sigcontext *sigContext = reinterpret_cast<sigcontext *>(
2270 reinterpret_cast<char *>(lastStack) + STKMIN);
2271 returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2272
2273 _LIBUNWIND_TRACE_UNWINDING("From sigContext=%p, returnAddress=%p\n",
2274 reinterpret_cast<void *>(sigContext),
2275 reinterpret_cast<void *>(returnAddress));
2276
2277 if (returnAddress < 0x10000000) {
2278 // Try again using STKMINALIGN
2279 sigContext = reinterpret_cast<sigcontext *>(
2280 reinterpret_cast<char *>(lastStack) + STKMINALIGN);
2281 returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2282 if (returnAddress < 0x10000000) {
2283 _LIBUNWIND_TRACE_UNWINDING("Bad returnAddress=%p\n",
2284 reinterpret_cast<void *>(returnAddress));
2285 return UNW_EBADFRAME;
2286 } else {
2287 _LIBUNWIND_TRACE_UNWINDING("Tried again using STKMINALIGN: "
2288 "sigContext=%p, returnAddress=%p. "
2289 "Seems to be a valid address\n",
2290 reinterpret_cast<void *>(sigContext),
2291 reinterpret_cast<void *>(returnAddress));
2292 }
2293 }
2294 // Restore the condition register from sigcontext.
2295 newRegisters.setCR(sigContext->sc_jmpbuf.jmp_context.cr);
2296
2297 // Restore GPRs from sigcontext.
2298 for (int i = 0; i < 32; ++i)
2299 newRegisters.setRegister(i, sigContext->sc_jmpbuf.jmp_context.gpr[i]);
2300
2301 // Restore FPRs from sigcontext.
2302 for (int i = 0; i < 32; ++i)
2303 newRegisters.setFloatRegister(i + unwPPCF0Index,
2304 sigContext->sc_jmpbuf.jmp_context.fpr[i]);
2305
2306 // Restore vector registers if there is an associated extended context
2307 // structure.
2308 if (sigContext->sc_jmpbuf.jmp_context.msr & __EXTCTX) {
2309 ucontext_t *uContext = reinterpret_cast<ucontext_t *>(sigContext);
2310 if (uContext->__extctx->__extctx_magic == __EXTCTX_MAGIC) {
2311 for (int i = 0; i < 32; ++i)
2312 newRegisters.setVectorRegister(
2313 i + unwPPCV0Index, *(reinterpret_cast<v128 *>(
2314 &(uContext->__extctx->__vmx.__vr[i]))));
2315 }
2316 }
2317 } else {
2318 // Step up a normal frame.
2319 returnAddress = reinterpret_cast<pint_t *>(lastStack)[2];
2320
2321 _LIBUNWIND_TRACE_UNWINDING("Extract info from lastStack=%p, "
2322 "returnAddress=%p\n",
2323 reinterpret_cast<void *>(lastStack),
2324 reinterpret_cast<void *>(returnAddress));
2325 _LIBUNWIND_TRACE_UNWINDING("fpr_regs=%d, gpr_regs=%d, saves_cr=%d\n",
2326 TBTable->tb.fpr_saved, TBTable->tb.gpr_saved,
2327 TBTable->tb.saves_cr);
2328
2329 // Restore FP registers.
2330 char *ptrToRegs = reinterpret_cast<char *>(lastStack);
2331 double *FPRegs = reinterpret_cast<double *>(
2332 ptrToRegs - (TBTable->tb.fpr_saved * sizeof(double)));
2333 for (int i = 0; i < TBTable->tb.fpr_saved; ++i)
2334 newRegisters.setFloatRegister(
2335 32 - TBTable->tb.fpr_saved + i + unwPPCF0Index, FPRegs[i]);
2336
2337 // Restore GP registers.
2338 ptrToRegs = reinterpret_cast<char *>(FPRegs);
2339 uintptr_t *GPRegs = reinterpret_cast<uintptr_t *>(
2340 ptrToRegs - (TBTable->tb.gpr_saved * sizeof(uintptr_t)));
2341 for (int i = 0; i < TBTable->tb.gpr_saved; ++i)
2342 newRegisters.setRegister(32 - TBTable->tb.gpr_saved + i, GPRegs[i]);
2343
2344 // Restore Vector registers.
2345 ptrToRegs = reinterpret_cast<char *>(GPRegs);
2346
2347 // Restore vector registers only if this is a Clang frame. Also
2348 // check if traceback table bit has_vec is set. If it is, structure
2349 // vec_ext is available.
2350 if (_info.flags == frameType::frameWithEHInfo && TBTable->tb.has_vec) {
2351
2352 // Get to the vec_ext structure to check if vector registers are saved.
2353 uint32_t *p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2354
2355 // Skip field parminfo if exists.
2356 if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2357 ++p;
2358
2359 // Skip field tb_offset if exists.
2360 if (TBTable->tb.has_tboff)
2361 ++p;
2362
2363 // Skip field hand_mask if exists.
2364 if (TBTable->tb.int_hndl)
2365 ++p;
2366
2367 // Skip fields ctl_info and ctl_info_disp if exist.
2368 if (TBTable->tb.has_ctl) {
2369 // Skip field ctl_info.
2370 ++p;
2371 // Skip field ctl_info_disp.
2372 ++p;
2373 }
2374
2375 // Skip fields name_len and name if exist.
2376 // p is supposed to point to field name_len now.
2377 uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2378 if (TBTable->tb.name_present) {
2379 const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2380 charPtr = charPtr + name_len + sizeof(uint16_t);
2381 }
2382
2383 // Skip field alloc_reg if it exists.
2384 if (TBTable->tb.uses_alloca)
2385 ++charPtr;
2386
2387 struct vec_ext *vec_ext = reinterpret_cast<struct vec_ext *>(charPtr);
2388
2389 _LIBUNWIND_TRACE_UNWINDING("vr_saved=%d\n", vec_ext->vr_saved);
2390
2391 // Restore vector register(s) if saved on the stack.
2392 if (vec_ext->vr_saved) {
2393 // Saved vector registers are 16-byte aligned.
2394 if (reinterpret_cast<uintptr_t>(ptrToRegs) % 16)
2395 ptrToRegs -= reinterpret_cast<uintptr_t>(ptrToRegs) % 16;
2396 v128 *VecRegs = reinterpret_cast<v128 *>(ptrToRegs - vec_ext->vr_saved *
2397 sizeof(v128));
2398 for (int i = 0; i < vec_ext->vr_saved; ++i) {
2399 newRegisters.setVectorRegister(
2400 32 - vec_ext->vr_saved + i + unwPPCV0Index, VecRegs[i]);
2401 }
2402 }
2403 }
2404 if (TBTable->tb.saves_cr) {
2405 // Get the saved condition register. The condition register is only
2406 // a single word.
2407 newRegisters.setCR(
2408 *(reinterpret_cast<uint32_t *>(lastStack + sizeof(uintptr_t))));
2409 }
2410
2411 // Restore the SP.
2412 newRegisters.setSP(lastStack);
2413
2414 // The first instruction after return.
2415 uint32_t firstInstruction = *(reinterpret_cast<uint32_t *>(returnAddress));
2416
2417 // Do we need to set the TOC register?
2418 _LIBUNWIND_TRACE_UNWINDING(
2419 "Current gpr2=%p\n",
2420 reinterpret_cast<void *>(newRegisters.getRegister(2)));
2421 if (firstInstruction == loadTOCRegInst) {
2422 _LIBUNWIND_TRACE_UNWINDING(
2423 "Set gpr2=%p from frame\n",
2424 reinterpret_cast<void *>(reinterpret_cast<pint_t *>(lastStack)[5]));
2425 newRegisters.setRegister(2, reinterpret_cast<pint_t *>(lastStack)[5]);
2426 }
2427 }
2428 _LIBUNWIND_TRACE_UNWINDING("lastStack=%p, returnAddress=%p, pc=%p\n",
2429 reinterpret_cast<void *>(lastStack),
2430 reinterpret_cast<void *>(returnAddress),
2431 reinterpret_cast<void *>(pc));
2432
2433 // The return address is the address after call site instruction, so
2434 // setting IP to that simualates a return.
2435 newRegisters.setIP(reinterpret_cast<uintptr_t>(returnAddress));
2436
2437 // Simulate the step by replacing the register set with the new ones.
2438 registers = newRegisters;
2439
2440 // Check if the next frame is a signal frame.
2441 pint_t nextStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2442
2443 // Return address is the address after call site instruction.
2444 pint_t nextReturnAddress = reinterpret_cast<pint_t *>(nextStack)[2];
2445
2446 if (nextReturnAddress > 0x01 && nextReturnAddress < 0x10000) {
2447 _LIBUNWIND_TRACE_UNWINDING("The next is a signal handler frame: "
2448 "nextStack=%p, next return address=%p\n",
2449 reinterpret_cast<void *>(nextStack),
2450 reinterpret_cast<void *>(nextReturnAddress));
2451 isSignalFrame = true;
2452 } else {
2453 isSignalFrame = false;
2454 }
2455
2456 return UNW_STEP_SUCCESS;
2457}
2458#endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
Charles Davisfa2e6202018-08-30 21:29:00 +00002459
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002460template <typename A, typename R>
2461void UnwindCursor<A, R>::setInfoBasedOnIPRegister(bool isReturnAddress) {
Ryan Pricharda684bed2021-01-13 16:38:36 -08002462#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2463 _isSigReturn = false;
2464#endif
2465
2466 pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
Ranjeet Singh421231a2017-03-31 15:28:06 +00002467#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002468 // Remove the thumb bit so the IP represents the actual instruction address.
2469 // This matches the behaviour of _Unwind_GetIP on arm.
2470 pc &= (pint_t)~0x1;
2471#endif
2472
Sterling Augustinec100c4d2020-03-30 15:20:26 -07002473 // Exit early if at the top of the stack.
2474 if (pc == 0) {
2475 _unwindInfoMissing = true;
2476 return;
2477 }
2478
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002479 // If the last line of a function is a "throw" the compiler sometimes
2480 // emits no instructions after the call to __cxa_throw. This means
2481 // the return address is actually the start of the next function.
2482 // To disambiguate this, back up the pc when we know it is a return
2483 // address.
2484 if (isReturnAddress)
Xing Xuebbcbce92022-04-13 11:01:59 -04002485#if defined(_AIX)
2486 // PC needs to be a 4-byte aligned address to be able to look for a
2487 // word of 0 that indicates the start of the traceback table at the end
2488 // of a function on AIX.
2489 pc -= 4;
2490#else
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002491 --pc;
Xing Xuebbcbce92022-04-13 11:01:59 -04002492#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002493
2494 // Ask address space object to find unwind sections for this pc.
2495 UnwindInfoSections sects;
2496 if (_addressSpace.findUnwindSections(pc, sects)) {
Ranjeet Singh421231a2017-03-31 15:28:06 +00002497#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002498 // If there is a compact unwind encoding table, look there first.
2499 if (sects.compact_unwind_section != 0) {
2500 if (this->getInfoFromCompactEncodingSection(pc, sects)) {
Ranjeet Singh421231a2017-03-31 15:28:06 +00002501 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002502 // Found info in table, done unless encoding says to use dwarf.
2503 uint32_t dwarfOffset;
2504 if ((sects.dwarf_section != 0) && compactSaysUseDwarf(&dwarfOffset)) {
2505 if (this->getInfoFromDwarfSection(pc, sects, dwarfOffset)) {
2506 // found info in dwarf, done
2507 return;
2508 }
2509 }
2510 #endif
2511 // If unwind table has entry, but entry says there is no unwind info,
2512 // record that we have no unwind info.
2513 if (_info.format == 0)
2514 _unwindInfoMissing = true;
2515 return;
2516 }
2517 }
Ranjeet Singh421231a2017-03-31 15:28:06 +00002518#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002519
Charles Davisfa2e6202018-08-30 21:29:00 +00002520#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
2521 // If there is SEH unwind info, look there next.
2522 if (this->getInfoFromSEH(pc))
2523 return;
2524#endif
2525
Xing Xuebbcbce92022-04-13 11:01:59 -04002526#if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2527 // If there is unwind info in the traceback table, look there next.
2528 if (this->getInfoFromTBTable(pc, _registers))
2529 return;
2530#endif
2531
Ranjeet Singh421231a2017-03-31 15:28:06 +00002532#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002533 // If there is dwarf unwind info, look there next.
2534 if (sects.dwarf_section != 0) {
2535 if (this->getInfoFromDwarfSection(pc, sects)) {
2536 // found info in dwarf, done
2537 return;
2538 }
2539 }
2540#endif
2541
Ranjeet Singh421231a2017-03-31 15:28:06 +00002542#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002543 // If there is ARM EHABI unwind info, look there next.
2544 if (sects.arm_section != 0 && this->getInfoFromEHABISection(pc, sects))
2545 return;
2546#endif
2547 }
2548
Ranjeet Singh421231a2017-03-31 15:28:06 +00002549#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002550 // There is no static unwind info for this pc. Look to see if an FDE was
2551 // dynamically registered for it.
Ryan Prichard2cfcb8c2020-09-09 15:43:35 -07002552 pint_t cachedFDE = DwarfFDECache<A>::findFDE(DwarfFDECache<A>::kSearchAll,
2553 pc);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002554 if (cachedFDE != 0) {
Ryan Prichard1ae2b942020-08-18 02:31:38 -07002555 typename CFI_Parser<A>::FDE_Info fdeInfo;
2556 typename CFI_Parser<A>::CIE_Info cieInfo;
2557 if (!CFI_Parser<A>::decodeFDE(_addressSpace, cachedFDE, &fdeInfo, &cieInfo))
2558 if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002559 return;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002560 }
2561
2562 // Lastly, ask AddressSpace object about platform specific ways to locate
2563 // other FDEs.
2564 pint_t fde;
2565 if (_addressSpace.findOtherFDE(pc, fde)) {
Ryan Prichard1ae2b942020-08-18 02:31:38 -07002566 typename CFI_Parser<A>::FDE_Info fdeInfo;
2567 typename CFI_Parser<A>::CIE_Info cieInfo;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002568 if (!CFI_Parser<A>::decodeFDE(_addressSpace, fde, &fdeInfo, &cieInfo)) {
2569 // Double check this FDE is for a function that includes the pc.
Ryan Prichard1ae2b942020-08-18 02:31:38 -07002570 if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd))
2571 if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002572 return;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002573 }
2574 }
Ranjeet Singh421231a2017-03-31 15:28:06 +00002575#endif // #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002576
Ryan Pricharda684bed2021-01-13 16:38:36 -08002577#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2578 if (setInfoForSigReturn())
2579 return;
2580#endif
2581
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002582 // no unwind info, flag that we can't reliably unwind
2583 _unwindInfoMissing = true;
2584}
2585
Ryan Pricharda684bed2021-01-13 16:38:36 -08002586#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2587template <typename A, typename R>
2588bool UnwindCursor<A, R>::setInfoForSigReturn(Registers_arm64 &) {
2589 // Look for the sigreturn trampoline. The trampoline's body is two
2590 // specific instructions (see below). Typically the trampoline comes from the
2591 // vDSO[1] (i.e. the __kernel_rt_sigreturn function). A libc might provide its
2592 // own restorer function, though, or user-mode QEMU might write a trampoline
2593 // onto the stack.
2594 //
2595 // This special code path is a fallback that is only used if the trampoline
2596 // lacks proper (e.g. DWARF) unwind info. On AArch64, a new DWARF register
2597 // constant for the PC needs to be defined before DWARF can handle a signal
2598 // trampoline. This code may segfault if the target PC is unreadable, e.g.:
2599 // - The PC points at a function compiled without unwind info, and which is
2600 // part of an execute-only mapping (e.g. using -Wl,--execute-only).
2601 // - The PC is invalid and happens to point to unreadable or unmapped memory.
2602 //
2603 // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/vdso/sigreturn.S
2604 const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2605 // Look for instructions: mov x8, #0x8b; svc #0x0
2606 if (_addressSpace.get32(pc) == 0xd2801168 &&
2607 _addressSpace.get32(pc + 4) == 0xd4000001) {
2608 _info = {};
2609 _isSigReturn = true;
2610 return true;
2611 }
2612 return false;
2613}
2614
2615template <typename A, typename R>
2616int UnwindCursor<A, R>::stepThroughSigReturn(Registers_arm64 &) {
2617 // In the signal trampoline frame, sp points to an rt_sigframe[1], which is:
2618 // - 128-byte siginfo struct
2619 // - ucontext struct:
2620 // - 8-byte long (uc_flags)
2621 // - 8-byte pointer (uc_link)
2622 // - 24-byte stack_t
2623 // - 128-byte signal set
2624 // - 8 bytes of padding because sigcontext has 16-byte alignment
2625 // - sigcontext/mcontext_t
2626 // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/signal.c
2627 const pint_t kOffsetSpToSigcontext = (128 + 8 + 8 + 24 + 128 + 8); // 304
2628
2629 // Offsets from sigcontext to each register.
2630 const pint_t kOffsetGprs = 8; // offset to "__u64 regs[31]" field
2631 const pint_t kOffsetSp = 256; // offset to "__u64 sp" field
2632 const pint_t kOffsetPc = 264; // offset to "__u64 pc" field
2633
2634 pint_t sigctx = _registers.getSP() + kOffsetSpToSigcontext;
2635
2636 for (int i = 0; i <= 30; ++i) {
2637 uint64_t value = _addressSpace.get64(sigctx + kOffsetGprs +
2638 static_cast<pint_t>(i * 8));
Fangrui Song5f263002021-08-20 14:26:27 -07002639 _registers.setRegister(UNW_AARCH64_X0 + i, value);
Ryan Pricharda684bed2021-01-13 16:38:36 -08002640 }
2641 _registers.setSP(_addressSpace.get64(sigctx + kOffsetSp));
2642 _registers.setIP(_addressSpace.get64(sigctx + kOffsetPc));
2643 _isSignalFrame = true;
2644 return UNW_STEP_SUCCESS;
2645}
2646#endif // defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2647
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002648template <typename A, typename R>
2649int UnwindCursor<A, R>::step() {
2650 // Bottom of stack is defined is when unwind info cannot be found.
2651 if (_unwindInfoMissing)
2652 return UNW_STEP_END;
2653
2654 // Use unwinding info to modify register set as if function returned.
2655 int result;
Ryan Pricharda684bed2021-01-13 16:38:36 -08002656#if defined(_LIBUNWIND_TARGET_LINUX) && defined(_LIBUNWIND_TARGET_AARCH64)
2657 if (_isSigReturn) {
2658 result = this->stepThroughSigReturn();
2659 } else
2660#endif
2661 {
Ranjeet Singh421231a2017-03-31 15:28:06 +00002662#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002663 result = this->stepWithCompactEncoding();
Charles Davisfa2e6202018-08-30 21:29:00 +00002664#elif defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002665 result = this->stepWithSEHData();
Xing Xuebbcbce92022-04-13 11:01:59 -04002666#elif defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2667 result = this->stepWithTBTableData();
Ranjeet Singh421231a2017-03-31 15:28:06 +00002668#elif defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002669 result = this->stepWithDwarfFDE();
Ranjeet Singh421231a2017-03-31 15:28:06 +00002670#elif defined(_LIBUNWIND_ARM_EHABI)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002671 result = this->stepWithEHABI();
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002672#else
2673 #error Need _LIBUNWIND_SUPPORT_COMPACT_UNWIND or \
Charles Davisfa2e6202018-08-30 21:29:00 +00002674 _LIBUNWIND_SUPPORT_SEH_UNWIND or \
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002675 _LIBUNWIND_SUPPORT_DWARF_UNWIND or \
Logan Chien06b0c7a2015-07-19 15:23:10 +00002676 _LIBUNWIND_ARM_EHABI
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002677#endif
Ryan Pricharda684bed2021-01-13 16:38:36 -08002678 }
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002679
2680 // update info based on new PC
2681 if (result == UNW_STEP_SUCCESS) {
2682 this->setInfoBasedOnIPRegister(true);
2683 if (_unwindInfoMissing)
2684 return UNW_STEP_END;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002685 }
2686
2687 return result;
2688}
2689
2690template <typename A, typename R>
2691void UnwindCursor<A, R>::getInfo(unw_proc_info_t *info) {
Saleem Abdulrasool78b42cc2019-09-20 15:53:42 +00002692 if (_unwindInfoMissing)
2693 memset(info, 0, sizeof(*info));
2694 else
2695 *info = _info;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002696}
2697
2698template <typename A, typename R>
2699bool UnwindCursor<A, R>::getFunctionName(char *buf, size_t bufLen,
2700 unw_word_t *offset) {
2701 return _addressSpace.findFunctionName((pint_t)this->getReg(UNW_REG_IP),
2702 buf, bufLen, offset);
2703}
2704
gejin7f493162021-08-26 16:20:38 +08002705#if defined(_LIBUNWIND_USE_CET)
2706extern "C" void *__libunwind_cet_get_registers(unw_cursor_t *cursor) {
2707 AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
2708 return co->get_registers();
2709}
2710#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002711} // namespace libunwind
2712
2713#endif // __UNWINDCURSOR_HPP__