blob: f1184970f3ce9531a448b40eec5743b93802b916 [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
Shoaib Meenai67bace72022-05-23 22:11:34 -070033#if defined(_LIBUNWIND_TARGET_LINUX) && \
34 (defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_S390X))
Shoaib Meenai8c606b02022-05-25 21:39:12 -070035#include <sys/syscall.h>
36#include <sys/uio.h>
37#include <unistd.h>
Shoaib Meenai67bace72022-05-23 22:11:34 -070038#define _LIBUNWIND_CHECK_LINUX_SIGRETURN 1
39#endif
40
Ryan Prichard60a480e2022-09-07 17:27:57 -040041#include "AddressSpace.hpp"
42#include "CompactUnwinder.hpp"
43#include "config.h"
44#include "DwarfInstructions.hpp"
45#include "EHHeaderParser.hpp"
46#include "libunwind.h"
47#include "libunwind_ext.h"
48#include "Registers.hpp"
49#include "RWMutex.hpp"
50#include "Unwind-EHABI.h"
51
Charles Davisfa2e6202018-08-30 21:29:00 +000052#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
53// Provide a definition for the DISPATCHER_CONTEXT struct for old (Win7 and
54// earlier) SDKs.
55// MinGW-w64 has always provided this struct.
56 #if defined(_WIN32) && defined(_LIBUNWIND_TARGET_X86_64) && \
57 !defined(__MINGW32__) && VER_PRODUCTBUILD < 8000
58struct _DISPATCHER_CONTEXT {
59 ULONG64 ControlPc;
60 ULONG64 ImageBase;
61 PRUNTIME_FUNCTION FunctionEntry;
62 ULONG64 EstablisherFrame;
63 ULONG64 TargetIp;
64 PCONTEXT ContextRecord;
65 PEXCEPTION_ROUTINE LanguageHandler;
66 PVOID HandlerData;
67 PUNWIND_HISTORY_TABLE HistoryTable;
68 ULONG ScopeIndex;
69 ULONG Fill0;
70};
71 #endif
72
73struct UNWIND_INFO {
74 uint8_t Version : 3;
75 uint8_t Flags : 5;
76 uint8_t SizeOfProlog;
77 uint8_t CountOfCodes;
78 uint8_t FrameRegister : 4;
79 uint8_t FrameOffset : 4;
80 uint16_t UnwindCodes[2];
81};
82
83extern "C" _Unwind_Reason_Code __libunwind_seh_personality(
84 int, _Unwind_Action, uint64_t, _Unwind_Exception *,
85 struct _Unwind_Context *);
86
87#endif
88
Saleem Abdulrasool17552662015-04-24 19:39:17 +000089namespace libunwind {
90
Ranjeet Singh421231a2017-03-31 15:28:06 +000091#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +000092/// Cache of recently found FDEs.
93template <typename A>
94class _LIBUNWIND_HIDDEN DwarfFDECache {
95 typedef typename A::pint_t pint_t;
96public:
Ryan Prichard2cfcb8c2020-09-09 15:43:35 -070097 static constexpr pint_t kSearchAll = static_cast<pint_t>(-1);
Saleem Abdulrasool17552662015-04-24 19:39:17 +000098 static pint_t findFDE(pint_t mh, pint_t pc);
99 static void add(pint_t mh, pint_t ip_start, pint_t ip_end, pint_t fde);
100 static void removeAllIn(pint_t mh);
101 static void iterateCacheEntries(void (*func)(unw_word_t ip_start,
102 unw_word_t ip_end,
103 unw_word_t fde, unw_word_t mh));
104
105private:
106
107 struct entry {
108 pint_t mh;
109 pint_t ip_start;
110 pint_t ip_end;
111 pint_t fde;
112 };
113
114 // These fields are all static to avoid needing an initializer.
115 // There is only one instance of this class per process.
Martin Storsjo590ffef2017-10-23 19:29:36 +0000116 static RWMutex _lock;
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000117#ifdef __APPLE__
118 static void dyldUnloadHook(const struct mach_header *mh, intptr_t slide);
119 static bool _registeredForDyldUnloads;
120#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000121 static entry *_buffer;
122 static entry *_bufferUsed;
123 static entry *_bufferEnd;
124 static entry _initialBuffer[64];
125};
126
127template <typename A>
128typename DwarfFDECache<A>::entry *
129DwarfFDECache<A>::_buffer = _initialBuffer;
130
131template <typename A>
132typename DwarfFDECache<A>::entry *
133DwarfFDECache<A>::_bufferUsed = _initialBuffer;
134
135template <typename A>
136typename DwarfFDECache<A>::entry *
137DwarfFDECache<A>::_bufferEnd = &_initialBuffer[64];
138
139template <typename A>
140typename DwarfFDECache<A>::entry DwarfFDECache<A>::_initialBuffer[64];
141
142template <typename A>
Martin Storsjo590ffef2017-10-23 19:29:36 +0000143RWMutex DwarfFDECache<A>::_lock;
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000144
145#ifdef __APPLE__
146template <typename A>
147bool DwarfFDECache<A>::_registeredForDyldUnloads = false;
148#endif
149
150template <typename A>
151typename A::pint_t DwarfFDECache<A>::findFDE(pint_t mh, pint_t pc) {
152 pint_t result = 0;
Martin Storsjo590ffef2017-10-23 19:29:36 +0000153 _LIBUNWIND_LOG_IF_FALSE(_lock.lock_shared());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000154 for (entry *p = _buffer; p < _bufferUsed; ++p) {
Ryan Prichard2cfcb8c2020-09-09 15:43:35 -0700155 if ((mh == p->mh) || (mh == kSearchAll)) {
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000156 if ((p->ip_start <= pc) && (pc < p->ip_end)) {
157 result = p->fde;
158 break;
159 }
160 }
161 }
Martin Storsjo590ffef2017-10-23 19:29:36 +0000162 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock_shared());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000163 return result;
164}
165
166template <typename A>
167void DwarfFDECache<A>::add(pint_t mh, pint_t ip_start, pint_t ip_end,
168 pint_t fde) {
Peter Zotov0717a2e2015-11-09 06:57:29 +0000169#if !defined(_LIBUNWIND_NO_HEAP)
Martin Storsjo590ffef2017-10-23 19:29:36 +0000170 _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000171 if (_bufferUsed >= _bufferEnd) {
172 size_t oldSize = (size_t)(_bufferEnd - _buffer);
173 size_t newSize = oldSize * 4;
174 // Can't use operator new (we are below it).
175 entry *newBuffer = (entry *)malloc(newSize * sizeof(entry));
176 memcpy(newBuffer, _buffer, oldSize * sizeof(entry));
177 if (_buffer != _initialBuffer)
178 free(_buffer);
179 _buffer = newBuffer;
180 _bufferUsed = &newBuffer[oldSize];
181 _bufferEnd = &newBuffer[newSize];
182 }
183 _bufferUsed->mh = mh;
184 _bufferUsed->ip_start = ip_start;
185 _bufferUsed->ip_end = ip_end;
186 _bufferUsed->fde = fde;
187 ++_bufferUsed;
188#ifdef __APPLE__
189 if (!_registeredForDyldUnloads) {
190 _dyld_register_func_for_remove_image(&dyldUnloadHook);
191 _registeredForDyldUnloads = true;
192 }
193#endif
Martin Storsjo590ffef2017-10-23 19:29:36 +0000194 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
Peter Zotov0717a2e2015-11-09 06:57:29 +0000195#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000196}
197
198template <typename A>
199void DwarfFDECache<A>::removeAllIn(pint_t mh) {
Martin Storsjo590ffef2017-10-23 19:29:36 +0000200 _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000201 entry *d = _buffer;
202 for (const entry *s = _buffer; s < _bufferUsed; ++s) {
203 if (s->mh != mh) {
204 if (d != s)
205 *d = *s;
206 ++d;
207 }
208 }
209 _bufferUsed = d;
Martin Storsjo590ffef2017-10-23 19:29:36 +0000210 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000211}
212
213#ifdef __APPLE__
214template <typename A>
215void DwarfFDECache<A>::dyldUnloadHook(const struct mach_header *mh, intptr_t ) {
216 removeAllIn((pint_t) mh);
217}
218#endif
219
220template <typename A>
221void DwarfFDECache<A>::iterateCacheEntries(void (*func)(
222 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 +0000223 _LIBUNWIND_LOG_IF_FALSE(_lock.lock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000224 for (entry *p = _buffer; p < _bufferUsed; ++p) {
225 (*func)(p->ip_start, p->ip_end, p->fde, p->mh);
226 }
Martin Storsjo590ffef2017-10-23 19:29:36 +0000227 _LIBUNWIND_LOG_IF_FALSE(_lock.unlock());
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000228}
Ranjeet Singh421231a2017-03-31 15:28:06 +0000229#endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000230
231
232#define arrayoffsetof(type, index, field) ((size_t)(&((type *)0)[index].field))
233
Ranjeet Singh421231a2017-03-31 15:28:06 +0000234#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000235template <typename A> class UnwindSectionHeader {
236public:
237 UnwindSectionHeader(A &addressSpace, typename A::pint_t addr)
238 : _addressSpace(addressSpace), _addr(addr) {}
239
240 uint32_t version() const {
241 return _addressSpace.get32(_addr +
242 offsetof(unwind_info_section_header, version));
243 }
244 uint32_t commonEncodingsArraySectionOffset() const {
245 return _addressSpace.get32(_addr +
246 offsetof(unwind_info_section_header,
247 commonEncodingsArraySectionOffset));
248 }
249 uint32_t commonEncodingsArrayCount() const {
250 return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
251 commonEncodingsArrayCount));
252 }
253 uint32_t personalityArraySectionOffset() const {
254 return _addressSpace.get32(_addr + offsetof(unwind_info_section_header,
255 personalityArraySectionOffset));
256 }
257 uint32_t personalityArrayCount() const {
258 return _addressSpace.get32(
259 _addr + offsetof(unwind_info_section_header, personalityArrayCount));
260 }
261 uint32_t indexSectionOffset() const {
262 return _addressSpace.get32(
263 _addr + offsetof(unwind_info_section_header, indexSectionOffset));
264 }
265 uint32_t indexCount() const {
266 return _addressSpace.get32(
267 _addr + offsetof(unwind_info_section_header, indexCount));
268 }
269
270private:
271 A &_addressSpace;
272 typename A::pint_t _addr;
273};
274
275template <typename A> class UnwindSectionIndexArray {
276public:
277 UnwindSectionIndexArray(A &addressSpace, typename A::pint_t addr)
278 : _addressSpace(addressSpace), _addr(addr) {}
279
280 uint32_t functionOffset(uint32_t index) const {
281 return _addressSpace.get32(
282 _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
283 functionOffset));
284 }
285 uint32_t secondLevelPagesSectionOffset(uint32_t index) const {
286 return _addressSpace.get32(
287 _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
288 secondLevelPagesSectionOffset));
289 }
290 uint32_t lsdaIndexArraySectionOffset(uint32_t index) const {
291 return _addressSpace.get32(
292 _addr + arrayoffsetof(unwind_info_section_header_index_entry, index,
293 lsdaIndexArraySectionOffset));
294 }
295
296private:
297 A &_addressSpace;
298 typename A::pint_t _addr;
299};
300
301template <typename A> class UnwindSectionRegularPageHeader {
302public:
303 UnwindSectionRegularPageHeader(A &addressSpace, typename A::pint_t addr)
304 : _addressSpace(addressSpace), _addr(addr) {}
305
306 uint32_t kind() const {
307 return _addressSpace.get32(
308 _addr + offsetof(unwind_info_regular_second_level_page_header, kind));
309 }
310 uint16_t entryPageOffset() const {
311 return _addressSpace.get16(
312 _addr + offsetof(unwind_info_regular_second_level_page_header,
313 entryPageOffset));
314 }
315 uint16_t entryCount() const {
316 return _addressSpace.get16(
317 _addr +
318 offsetof(unwind_info_regular_second_level_page_header, entryCount));
319 }
320
321private:
322 A &_addressSpace;
323 typename A::pint_t _addr;
324};
325
326template <typename A> class UnwindSectionRegularArray {
327public:
328 UnwindSectionRegularArray(A &addressSpace, typename A::pint_t addr)
329 : _addressSpace(addressSpace), _addr(addr) {}
330
331 uint32_t functionOffset(uint32_t index) const {
332 return _addressSpace.get32(
333 _addr + arrayoffsetof(unwind_info_regular_second_level_entry, index,
334 functionOffset));
335 }
336 uint32_t encoding(uint32_t index) const {
337 return _addressSpace.get32(
338 _addr +
339 arrayoffsetof(unwind_info_regular_second_level_entry, index, encoding));
340 }
341
342private:
343 A &_addressSpace;
344 typename A::pint_t _addr;
345};
346
347template <typename A> class UnwindSectionCompressedPageHeader {
348public:
349 UnwindSectionCompressedPageHeader(A &addressSpace, typename A::pint_t addr)
350 : _addressSpace(addressSpace), _addr(addr) {}
351
352 uint32_t kind() const {
353 return _addressSpace.get32(
354 _addr +
355 offsetof(unwind_info_compressed_second_level_page_header, kind));
356 }
357 uint16_t entryPageOffset() const {
358 return _addressSpace.get16(
359 _addr + offsetof(unwind_info_compressed_second_level_page_header,
360 entryPageOffset));
361 }
362 uint16_t entryCount() const {
363 return _addressSpace.get16(
364 _addr +
365 offsetof(unwind_info_compressed_second_level_page_header, entryCount));
366 }
367 uint16_t encodingsPageOffset() const {
368 return _addressSpace.get16(
369 _addr + offsetof(unwind_info_compressed_second_level_page_header,
370 encodingsPageOffset));
371 }
372 uint16_t encodingsCount() const {
373 return _addressSpace.get16(
374 _addr + offsetof(unwind_info_compressed_second_level_page_header,
375 encodingsCount));
376 }
377
378private:
379 A &_addressSpace;
380 typename A::pint_t _addr;
381};
382
383template <typename A> class UnwindSectionCompressedArray {
384public:
385 UnwindSectionCompressedArray(A &addressSpace, typename A::pint_t addr)
386 : _addressSpace(addressSpace), _addr(addr) {}
387
388 uint32_t functionOffset(uint32_t index) const {
389 return UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(
390 _addressSpace.get32(_addr + index * sizeof(uint32_t)));
391 }
392 uint16_t encodingIndex(uint32_t index) const {
393 return UNWIND_INFO_COMPRESSED_ENTRY_ENCODING_INDEX(
394 _addressSpace.get32(_addr + index * sizeof(uint32_t)));
395 }
396
397private:
398 A &_addressSpace;
399 typename A::pint_t _addr;
400};
401
402template <typename A> class UnwindSectionLsdaArray {
403public:
404 UnwindSectionLsdaArray(A &addressSpace, typename A::pint_t addr)
405 : _addressSpace(addressSpace), _addr(addr) {}
406
407 uint32_t functionOffset(uint32_t index) const {
408 return _addressSpace.get32(
409 _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
410 index, functionOffset));
411 }
412 uint32_t lsdaOffset(uint32_t index) const {
413 return _addressSpace.get32(
414 _addr + arrayoffsetof(unwind_info_section_header_lsda_index_entry,
415 index, lsdaOffset));
416 }
417
418private:
419 A &_addressSpace;
420 typename A::pint_t _addr;
421};
Ranjeet Singh421231a2017-03-31 15:28:06 +0000422#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000423
424class _LIBUNWIND_HIDDEN AbstractUnwindCursor {
425public:
426 // NOTE: provide a class specific placement deallocation function (S5.3.4 p20)
427 // This avoids an unnecessary dependency to libc++abi.
428 void operator delete(void *, size_t) {}
429
430 virtual ~AbstractUnwindCursor() {}
431 virtual bool validReg(int) { _LIBUNWIND_ABORT("validReg not implemented"); }
432 virtual unw_word_t getReg(int) { _LIBUNWIND_ABORT("getReg not implemented"); }
433 virtual void setReg(int, unw_word_t) {
434 _LIBUNWIND_ABORT("setReg not implemented");
435 }
436 virtual bool validFloatReg(int) {
437 _LIBUNWIND_ABORT("validFloatReg not implemented");
438 }
439 virtual unw_fpreg_t getFloatReg(int) {
440 _LIBUNWIND_ABORT("getFloatReg not implemented");
441 }
442 virtual void setFloatReg(int, unw_fpreg_t) {
443 _LIBUNWIND_ABORT("setFloatReg not implemented");
444 }
Florian Mayer7ff728a2022-06-03 14:33:08 -0700445 virtual int step(bool = false) { _LIBUNWIND_ABORT("step not implemented"); }
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000446 virtual void getInfo(unw_proc_info_t *) {
447 _LIBUNWIND_ABORT("getInfo not implemented");
448 }
449 virtual void jumpto() { _LIBUNWIND_ABORT("jumpto not implemented"); }
450 virtual bool isSignalFrame() {
451 _LIBUNWIND_ABORT("isSignalFrame not implemented");
452 }
453 virtual bool getFunctionName(char *, size_t, unw_word_t *) {
454 _LIBUNWIND_ABORT("getFunctionName not implemented");
455 }
456 virtual void setInfoBasedOnIPRegister(bool = false) {
457 _LIBUNWIND_ABORT("setInfoBasedOnIPRegister not implemented");
458 }
459 virtual const char *getRegisterName(int) {
460 _LIBUNWIND_ABORT("getRegisterName not implemented");
461 }
462#ifdef __arm__
463 virtual void saveVFPAsX() { _LIBUNWIND_ABORT("saveVFPAsX not implemented"); }
464#endif
gejin7f493162021-08-26 16:20:38 +0800465
Xing Xuebbcbce92022-04-13 11:01:59 -0400466#ifdef _AIX
467 virtual uintptr_t getDataRelBase() {
468 _LIBUNWIND_ABORT("getDataRelBase not implemented");
469 }
470#endif
471
gejin7f493162021-08-26 16:20:38 +0800472#if defined(_LIBUNWIND_USE_CET)
473 virtual void *get_registers() {
474 _LIBUNWIND_ABORT("get_registers not implemented");
475 }
476#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000477};
478
Charles Davisfa2e6202018-08-30 21:29:00 +0000479#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) && defined(_WIN32)
480
481/// \c UnwindCursor contains all state (including all register values) during
482/// an unwind. This is normally stack-allocated inside a unw_cursor_t.
483template <typename A, typename R>
484class UnwindCursor : public AbstractUnwindCursor {
485 typedef typename A::pint_t pint_t;
486public:
487 UnwindCursor(unw_context_t *context, A &as);
488 UnwindCursor(CONTEXT *context, A &as);
489 UnwindCursor(A &as, void *threadArg);
490 virtual ~UnwindCursor() {}
491 virtual bool validReg(int);
492 virtual unw_word_t getReg(int);
493 virtual void setReg(int, unw_word_t);
494 virtual bool validFloatReg(int);
495 virtual unw_fpreg_t getFloatReg(int);
496 virtual void setFloatReg(int, unw_fpreg_t);
Florian Mayer7ff728a2022-06-03 14:33:08 -0700497 virtual int step(bool = false);
Charles Davisfa2e6202018-08-30 21:29:00 +0000498 virtual void getInfo(unw_proc_info_t *);
499 virtual void jumpto();
500 virtual bool isSignalFrame();
501 virtual bool getFunctionName(char *buf, size_t len, unw_word_t *off);
502 virtual void setInfoBasedOnIPRegister(bool isReturnAddress = false);
503 virtual const char *getRegisterName(int num);
504#ifdef __arm__
505 virtual void saveVFPAsX();
506#endif
507
508 DISPATCHER_CONTEXT *getDispatcherContext() { return &_dispContext; }
509 void setDispatcherContext(DISPATCHER_CONTEXT *disp) { _dispContext = *disp; }
510
Martin Storsjo5f5036e2019-02-03 22:16:53 +0000511 // libunwind does not and should not depend on C++ library which means that we
Gabriel Ravier42aa6de2022-08-20 18:09:03 -0700512 // need our own definition of inline placement new.
Martin Storsjo5f5036e2019-02-03 22:16:53 +0000513 static void *operator new(size_t, UnwindCursor<A, R> *p) { return p; }
514
Charles Davisfa2e6202018-08-30 21:29:00 +0000515private:
516
517 pint_t getLastPC() const { return _dispContext.ControlPc; }
518 void setLastPC(pint_t pc) { _dispContext.ControlPc = pc; }
519 RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
Martin Storsjö1644d072022-05-11 11:20:38 +0300520#ifdef __arm__
521 // Remove the thumb bit; FunctionEntry ranges don't include the thumb bit.
522 pc &= ~1U;
523#endif
524 // If pc points exactly at the end of the range, we might resolve the
525 // next function instead. Decrement pc by 1 to fit inside the current
526 // function.
527 pc -= 1;
Charles Davisfa2e6202018-08-30 21:29:00 +0000528 _dispContext.FunctionEntry = RtlLookupFunctionEntry(pc,
529 &_dispContext.ImageBase,
530 _dispContext.HistoryTable);
531 *base = _dispContext.ImageBase;
532 return _dispContext.FunctionEntry;
533 }
534 bool getInfoFromSEH(pint_t pc);
535 int stepWithSEHData() {
536 _dispContext.LanguageHandler = RtlVirtualUnwind(UNW_FLAG_UHANDLER,
537 _dispContext.ImageBase,
538 _dispContext.ControlPc,
539 _dispContext.FunctionEntry,
540 _dispContext.ContextRecord,
541 &_dispContext.HandlerData,
542 &_dispContext.EstablisherFrame,
543 NULL);
544 // Update some fields of the unwind info now, since we have them.
545 _info.lsda = reinterpret_cast<unw_word_t>(_dispContext.HandlerData);
546 if (_dispContext.LanguageHandler) {
547 _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
548 } else
549 _info.handler = 0;
550 return UNW_STEP_SUCCESS;
551 }
552
553 A &_addressSpace;
554 unw_proc_info_t _info;
555 DISPATCHER_CONTEXT _dispContext;
556 CONTEXT _msContext;
557 UNWIND_HISTORY_TABLE _histTable;
558 bool _unwindInfoMissing;
559};
560
561
562template <typename A, typename R>
563UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
564 : _addressSpace(as), _unwindInfoMissing(false) {
565 static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
566 "UnwindCursor<> does not fit in unw_cursor_t");
Martin Storsjö1c0575e2020-08-17 22:41:58 +0300567 static_assert((alignof(UnwindCursor<A, R>) <= alignof(unw_cursor_t)),
568 "UnwindCursor<> requires more alignment than unw_cursor_t");
Charles Davisfa2e6202018-08-30 21:29:00 +0000569 memset(&_info, 0, sizeof(_info));
570 memset(&_histTable, 0, sizeof(_histTable));
571 _dispContext.ContextRecord = &_msContext;
572 _dispContext.HistoryTable = &_histTable;
573 // Initialize MS context from ours.
574 R r(context);
575 _msContext.ContextFlags = CONTEXT_CONTROL|CONTEXT_INTEGER|CONTEXT_FLOATING_POINT;
576#if defined(_LIBUNWIND_TARGET_X86_64)
577 _msContext.Rax = r.getRegister(UNW_X86_64_RAX);
578 _msContext.Rcx = r.getRegister(UNW_X86_64_RCX);
579 _msContext.Rdx = r.getRegister(UNW_X86_64_RDX);
580 _msContext.Rbx = r.getRegister(UNW_X86_64_RBX);
581 _msContext.Rsp = r.getRegister(UNW_X86_64_RSP);
582 _msContext.Rbp = r.getRegister(UNW_X86_64_RBP);
583 _msContext.Rsi = r.getRegister(UNW_X86_64_RSI);
584 _msContext.Rdi = r.getRegister(UNW_X86_64_RDI);
585 _msContext.R8 = r.getRegister(UNW_X86_64_R8);
586 _msContext.R9 = r.getRegister(UNW_X86_64_R9);
587 _msContext.R10 = r.getRegister(UNW_X86_64_R10);
588 _msContext.R11 = r.getRegister(UNW_X86_64_R11);
589 _msContext.R12 = r.getRegister(UNW_X86_64_R12);
590 _msContext.R13 = r.getRegister(UNW_X86_64_R13);
591 _msContext.R14 = r.getRegister(UNW_X86_64_R14);
592 _msContext.R15 = r.getRegister(UNW_X86_64_R15);
593 _msContext.Rip = r.getRegister(UNW_REG_IP);
594 union {
595 v128 v;
596 M128A m;
597 } t;
598 t.v = r.getVectorRegister(UNW_X86_64_XMM0);
599 _msContext.Xmm0 = t.m;
600 t.v = r.getVectorRegister(UNW_X86_64_XMM1);
601 _msContext.Xmm1 = t.m;
602 t.v = r.getVectorRegister(UNW_X86_64_XMM2);
603 _msContext.Xmm2 = t.m;
604 t.v = r.getVectorRegister(UNW_X86_64_XMM3);
605 _msContext.Xmm3 = t.m;
606 t.v = r.getVectorRegister(UNW_X86_64_XMM4);
607 _msContext.Xmm4 = t.m;
608 t.v = r.getVectorRegister(UNW_X86_64_XMM5);
609 _msContext.Xmm5 = t.m;
610 t.v = r.getVectorRegister(UNW_X86_64_XMM6);
611 _msContext.Xmm6 = t.m;
612 t.v = r.getVectorRegister(UNW_X86_64_XMM7);
613 _msContext.Xmm7 = t.m;
614 t.v = r.getVectorRegister(UNW_X86_64_XMM8);
615 _msContext.Xmm8 = t.m;
616 t.v = r.getVectorRegister(UNW_X86_64_XMM9);
617 _msContext.Xmm9 = t.m;
618 t.v = r.getVectorRegister(UNW_X86_64_XMM10);
619 _msContext.Xmm10 = t.m;
620 t.v = r.getVectorRegister(UNW_X86_64_XMM11);
621 _msContext.Xmm11 = t.m;
622 t.v = r.getVectorRegister(UNW_X86_64_XMM12);
623 _msContext.Xmm12 = t.m;
624 t.v = r.getVectorRegister(UNW_X86_64_XMM13);
625 _msContext.Xmm13 = t.m;
626 t.v = r.getVectorRegister(UNW_X86_64_XMM14);
627 _msContext.Xmm14 = t.m;
628 t.v = r.getVectorRegister(UNW_X86_64_XMM15);
629 _msContext.Xmm15 = t.m;
630#elif defined(_LIBUNWIND_TARGET_ARM)
631 _msContext.R0 = r.getRegister(UNW_ARM_R0);
632 _msContext.R1 = r.getRegister(UNW_ARM_R1);
633 _msContext.R2 = r.getRegister(UNW_ARM_R2);
634 _msContext.R3 = r.getRegister(UNW_ARM_R3);
635 _msContext.R4 = r.getRegister(UNW_ARM_R4);
636 _msContext.R5 = r.getRegister(UNW_ARM_R5);
637 _msContext.R6 = r.getRegister(UNW_ARM_R6);
638 _msContext.R7 = r.getRegister(UNW_ARM_R7);
639 _msContext.R8 = r.getRegister(UNW_ARM_R8);
640 _msContext.R9 = r.getRegister(UNW_ARM_R9);
641 _msContext.R10 = r.getRegister(UNW_ARM_R10);
642 _msContext.R11 = r.getRegister(UNW_ARM_R11);
643 _msContext.R12 = r.getRegister(UNW_ARM_R12);
644 _msContext.Sp = r.getRegister(UNW_ARM_SP);
645 _msContext.Lr = r.getRegister(UNW_ARM_LR);
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000646 _msContext.Pc = r.getRegister(UNW_ARM_IP);
647 for (int i = UNW_ARM_D0; i <= UNW_ARM_D31; ++i) {
Charles Davisfa2e6202018-08-30 21:29:00 +0000648 union {
649 uint64_t w;
650 double d;
651 } d;
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000652 d.d = r.getFloatRegister(i);
653 _msContext.D[i - UNW_ARM_D0] = d.w;
Charles Davisfa2e6202018-08-30 21:29:00 +0000654 }
Martin Storsjoce150112018-12-18 20:05:59 +0000655#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700656 for (int i = UNW_AARCH64_X0; i <= UNW_ARM64_X30; ++i)
657 _msContext.X[i - UNW_AARCH64_X0] = r.getRegister(i);
Martin Storsjoce150112018-12-18 20:05:59 +0000658 _msContext.Sp = r.getRegister(UNW_REG_SP);
659 _msContext.Pc = r.getRegister(UNW_REG_IP);
Fangrui Song5f263002021-08-20 14:26:27 -0700660 for (int i = UNW_AARCH64_V0; i <= UNW_ARM64_D31; ++i)
661 _msContext.V[i - UNW_AARCH64_V0].D[0] = r.getFloatRegister(i);
Charles Davisfa2e6202018-08-30 21:29:00 +0000662#endif
663}
664
665template <typename A, typename R>
666UnwindCursor<A, R>::UnwindCursor(CONTEXT *context, A &as)
667 : _addressSpace(as), _unwindInfoMissing(false) {
668 static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
669 "UnwindCursor<> does not fit in unw_cursor_t");
670 memset(&_info, 0, sizeof(_info));
671 memset(&_histTable, 0, sizeof(_histTable));
672 _dispContext.ContextRecord = &_msContext;
673 _dispContext.HistoryTable = &_histTable;
674 _msContext = *context;
675}
676
677
678template <typename A, typename R>
679bool UnwindCursor<A, R>::validReg(int regNum) {
680 if (regNum == UNW_REG_IP || regNum == UNW_REG_SP) return true;
681#if defined(_LIBUNWIND_TARGET_X86_64)
682 if (regNum >= UNW_X86_64_RAX && regNum <= UNW_X86_64_R15) return true;
683#elif defined(_LIBUNWIND_TARGET_ARM)
Ties Stuijc8c0ec92021-12-08 09:44:45 +0000684 if ((regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) ||
685 regNum == UNW_ARM_RA_AUTH_CODE)
686 return true;
Martin Storsjoce150112018-12-18 20:05:59 +0000687#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700688 if (regNum >= UNW_AARCH64_X0 && regNum <= UNW_ARM64_X30) return true;
Charles Davisfa2e6202018-08-30 21:29:00 +0000689#endif
690 return false;
691}
692
693template <typename A, typename R>
694unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
695 switch (regNum) {
696#if defined(_LIBUNWIND_TARGET_X86_64)
697 case UNW_REG_IP: return _msContext.Rip;
698 case UNW_X86_64_RAX: return _msContext.Rax;
699 case UNW_X86_64_RDX: return _msContext.Rdx;
700 case UNW_X86_64_RCX: return _msContext.Rcx;
701 case UNW_X86_64_RBX: return _msContext.Rbx;
702 case UNW_REG_SP:
703 case UNW_X86_64_RSP: return _msContext.Rsp;
704 case UNW_X86_64_RBP: return _msContext.Rbp;
705 case UNW_X86_64_RSI: return _msContext.Rsi;
706 case UNW_X86_64_RDI: return _msContext.Rdi;
707 case UNW_X86_64_R8: return _msContext.R8;
708 case UNW_X86_64_R9: return _msContext.R9;
709 case UNW_X86_64_R10: return _msContext.R10;
710 case UNW_X86_64_R11: return _msContext.R11;
711 case UNW_X86_64_R12: return _msContext.R12;
712 case UNW_X86_64_R13: return _msContext.R13;
713 case UNW_X86_64_R14: return _msContext.R14;
714 case UNW_X86_64_R15: return _msContext.R15;
715#elif defined(_LIBUNWIND_TARGET_ARM)
716 case UNW_ARM_R0: return _msContext.R0;
717 case UNW_ARM_R1: return _msContext.R1;
718 case UNW_ARM_R2: return _msContext.R2;
719 case UNW_ARM_R3: return _msContext.R3;
720 case UNW_ARM_R4: return _msContext.R4;
721 case UNW_ARM_R5: return _msContext.R5;
722 case UNW_ARM_R6: return _msContext.R6;
723 case UNW_ARM_R7: return _msContext.R7;
724 case UNW_ARM_R8: return _msContext.R8;
725 case UNW_ARM_R9: return _msContext.R9;
726 case UNW_ARM_R10: return _msContext.R10;
727 case UNW_ARM_R11: return _msContext.R11;
728 case UNW_ARM_R12: return _msContext.R12;
729 case UNW_REG_SP:
730 case UNW_ARM_SP: return _msContext.Sp;
731 case UNW_ARM_LR: return _msContext.Lr;
732 case UNW_REG_IP:
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000733 case UNW_ARM_IP: return _msContext.Pc;
Martin Storsjoce150112018-12-18 20:05:59 +0000734#elif defined(_LIBUNWIND_TARGET_AARCH64)
735 case UNW_REG_SP: return _msContext.Sp;
736 case UNW_REG_IP: return _msContext.Pc;
Fangrui Song5f263002021-08-20 14:26:27 -0700737 default: return _msContext.X[regNum - UNW_AARCH64_X0];
Charles Davisfa2e6202018-08-30 21:29:00 +0000738#endif
739 }
740 _LIBUNWIND_ABORT("unsupported register");
741}
742
743template <typename A, typename R>
744void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
745 switch (regNum) {
746#if defined(_LIBUNWIND_TARGET_X86_64)
747 case UNW_REG_IP: _msContext.Rip = value; break;
748 case UNW_X86_64_RAX: _msContext.Rax = value; break;
749 case UNW_X86_64_RDX: _msContext.Rdx = value; break;
750 case UNW_X86_64_RCX: _msContext.Rcx = value; break;
751 case UNW_X86_64_RBX: _msContext.Rbx = value; break;
752 case UNW_REG_SP:
753 case UNW_X86_64_RSP: _msContext.Rsp = value; break;
754 case UNW_X86_64_RBP: _msContext.Rbp = value; break;
755 case UNW_X86_64_RSI: _msContext.Rsi = value; break;
756 case UNW_X86_64_RDI: _msContext.Rdi = value; break;
757 case UNW_X86_64_R8: _msContext.R8 = value; break;
758 case UNW_X86_64_R9: _msContext.R9 = value; break;
759 case UNW_X86_64_R10: _msContext.R10 = value; break;
760 case UNW_X86_64_R11: _msContext.R11 = value; break;
761 case UNW_X86_64_R12: _msContext.R12 = value; break;
762 case UNW_X86_64_R13: _msContext.R13 = value; break;
763 case UNW_X86_64_R14: _msContext.R14 = value; break;
764 case UNW_X86_64_R15: _msContext.R15 = value; break;
765#elif defined(_LIBUNWIND_TARGET_ARM)
766 case UNW_ARM_R0: _msContext.R0 = value; break;
767 case UNW_ARM_R1: _msContext.R1 = value; break;
768 case UNW_ARM_R2: _msContext.R2 = value; break;
769 case UNW_ARM_R3: _msContext.R3 = value; break;
770 case UNW_ARM_R4: _msContext.R4 = value; break;
771 case UNW_ARM_R5: _msContext.R5 = value; break;
772 case UNW_ARM_R6: _msContext.R6 = value; break;
773 case UNW_ARM_R7: _msContext.R7 = value; break;
774 case UNW_ARM_R8: _msContext.R8 = value; break;
775 case UNW_ARM_R9: _msContext.R9 = value; break;
776 case UNW_ARM_R10: _msContext.R10 = value; break;
777 case UNW_ARM_R11: _msContext.R11 = value; break;
778 case UNW_ARM_R12: _msContext.R12 = value; break;
779 case UNW_REG_SP:
780 case UNW_ARM_SP: _msContext.Sp = value; break;
781 case UNW_ARM_LR: _msContext.Lr = value; break;
782 case UNW_REG_IP:
Martin Storsjoe5dbce22018-08-31 14:56:55 +0000783 case UNW_ARM_IP: _msContext.Pc = value; break;
Martin Storsjoce150112018-12-18 20:05:59 +0000784#elif defined(_LIBUNWIND_TARGET_AARCH64)
785 case UNW_REG_SP: _msContext.Sp = value; break;
786 case UNW_REG_IP: _msContext.Pc = value; break;
Fangrui Song5f263002021-08-20 14:26:27 -0700787 case UNW_AARCH64_X0:
788 case UNW_AARCH64_X1:
789 case UNW_AARCH64_X2:
790 case UNW_AARCH64_X3:
791 case UNW_AARCH64_X4:
792 case UNW_AARCH64_X5:
793 case UNW_AARCH64_X6:
794 case UNW_AARCH64_X7:
795 case UNW_AARCH64_X8:
796 case UNW_AARCH64_X9:
797 case UNW_AARCH64_X10:
798 case UNW_AARCH64_X11:
799 case UNW_AARCH64_X12:
800 case UNW_AARCH64_X13:
801 case UNW_AARCH64_X14:
802 case UNW_AARCH64_X15:
803 case UNW_AARCH64_X16:
804 case UNW_AARCH64_X17:
805 case UNW_AARCH64_X18:
806 case UNW_AARCH64_X19:
807 case UNW_AARCH64_X20:
808 case UNW_AARCH64_X21:
809 case UNW_AARCH64_X22:
810 case UNW_AARCH64_X23:
811 case UNW_AARCH64_X24:
812 case UNW_AARCH64_X25:
813 case UNW_AARCH64_X26:
814 case UNW_AARCH64_X27:
815 case UNW_AARCH64_X28:
816 case UNW_AARCH64_FP:
817 case UNW_AARCH64_LR: _msContext.X[regNum - UNW_ARM64_X0] = value; break;
Charles Davisfa2e6202018-08-30 21:29:00 +0000818#endif
819 default:
820 _LIBUNWIND_ABORT("unsupported register");
821 }
822}
823
824template <typename A, typename R>
825bool UnwindCursor<A, R>::validFloatReg(int regNum) {
826#if defined(_LIBUNWIND_TARGET_ARM)
827 if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) return true;
828 if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) return true;
Martin Storsjoce150112018-12-18 20:05:59 +0000829#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700830 if (regNum >= UNW_AARCH64_V0 && regNum <= UNW_ARM64_D31) return true;
Martin Storsjo059a1632019-01-22 22:12:23 +0000831#else
832 (void)regNum;
Charles Davisfa2e6202018-08-30 21:29:00 +0000833#endif
834 return false;
835}
836
837template <typename A, typename R>
838unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
839#if defined(_LIBUNWIND_TARGET_ARM)
840 if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
841 union {
842 uint32_t w;
843 float f;
844 } d;
845 d.w = _msContext.S[regNum - UNW_ARM_S0];
846 return d.f;
847 }
848 if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
849 union {
850 uint64_t w;
851 double d;
852 } d;
853 d.w = _msContext.D[regNum - UNW_ARM_D0];
854 return d.d;
855 }
856 _LIBUNWIND_ABORT("unsupported float register");
Martin Storsjoce150112018-12-18 20:05:59 +0000857#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700858 return _msContext.V[regNum - UNW_AARCH64_V0].D[0];
Charles Davisfa2e6202018-08-30 21:29:00 +0000859#else
Martin Storsjo059a1632019-01-22 22:12:23 +0000860 (void)regNum;
Charles Davisfa2e6202018-08-30 21:29:00 +0000861 _LIBUNWIND_ABORT("float registers unimplemented");
862#endif
863}
864
865template <typename A, typename R>
866void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
867#if defined(_LIBUNWIND_TARGET_ARM)
868 if (regNum >= UNW_ARM_S0 && regNum <= UNW_ARM_S31) {
869 union {
870 uint32_t w;
871 float f;
872 } d;
Martin Storsjö1c11cfe2022-05-07 00:26:45 +0300873 d.f = (float)value;
Charles Davisfa2e6202018-08-30 21:29:00 +0000874 _msContext.S[regNum - UNW_ARM_S0] = d.w;
875 }
876 if (regNum >= UNW_ARM_D0 && regNum <= UNW_ARM_D31) {
877 union {
878 uint64_t w;
879 double d;
880 } d;
881 d.d = value;
882 _msContext.D[regNum - UNW_ARM_D0] = d.w;
883 }
884 _LIBUNWIND_ABORT("unsupported float register");
Martin Storsjoce150112018-12-18 20:05:59 +0000885#elif defined(_LIBUNWIND_TARGET_AARCH64)
Fangrui Song5f263002021-08-20 14:26:27 -0700886 _msContext.V[regNum - UNW_AARCH64_V0].D[0] = value;
Charles Davisfa2e6202018-08-30 21:29:00 +0000887#else
Martin Storsjo059a1632019-01-22 22:12:23 +0000888 (void)regNum;
889 (void)value;
Charles Davisfa2e6202018-08-30 21:29:00 +0000890 _LIBUNWIND_ABORT("float registers unimplemented");
891#endif
892}
893
894template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
895 RtlRestoreContext(&_msContext, nullptr);
896}
897
898#ifdef __arm__
899template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {}
900#endif
901
902template <typename A, typename R>
903const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
Martin Storsjo43bb9f82018-12-12 22:24:42 +0000904 return R::getRegisterName(regNum);
Charles Davisfa2e6202018-08-30 21:29:00 +0000905}
906
907template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
908 return false;
909}
910
911#else // !defined(_LIBUNWIND_SUPPORT_SEH_UNWIND) || !defined(_WIN32)
912
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000913/// UnwindCursor contains all state (including all register values) during
914/// an unwind. This is normally stack allocated inside a unw_cursor_t.
915template <typename A, typename R>
916class UnwindCursor : public AbstractUnwindCursor{
917 typedef typename A::pint_t pint_t;
918public:
919 UnwindCursor(unw_context_t *context, A &as);
920 UnwindCursor(A &as, void *threadArg);
921 virtual ~UnwindCursor() {}
922 virtual bool validReg(int);
923 virtual unw_word_t getReg(int);
924 virtual void setReg(int, unw_word_t);
925 virtual bool validFloatReg(int);
926 virtual unw_fpreg_t getFloatReg(int);
927 virtual void setFloatReg(int, unw_fpreg_t);
Florian Mayer7ff728a2022-06-03 14:33:08 -0700928 virtual int step(bool stage2 = false);
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000929 virtual void getInfo(unw_proc_info_t *);
930 virtual void jumpto();
931 virtual bool isSignalFrame();
932 virtual bool getFunctionName(char *buf, size_t len, unw_word_t *off);
933 virtual void setInfoBasedOnIPRegister(bool isReturnAddress = false);
934 virtual const char *getRegisterName(int num);
935#ifdef __arm__
936 virtual void saveVFPAsX();
937#endif
938
Xing Xuebbcbce92022-04-13 11:01:59 -0400939#ifdef _AIX
940 virtual uintptr_t getDataRelBase();
941#endif
942
gejin7f493162021-08-26 16:20:38 +0800943#if defined(_LIBUNWIND_USE_CET)
944 virtual void *get_registers() { return &_registers; }
945#endif
Xing Xuebbcbce92022-04-13 11:01:59 -0400946
Petr Hosek36f61542019-02-02 21:15:49 +0000947 // libunwind does not and should not depend on C++ library which means that we
Gabriel Ravier42aa6de2022-08-20 18:09:03 -0700948 // need our own definition of inline placement new.
Petr Hosek36f61542019-02-02 21:15:49 +0000949 static void *operator new(size_t, UnwindCursor<A, R> *p) { return p; }
950
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000951private:
952
Ranjeet Singh421231a2017-03-31 15:28:06 +0000953#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000954 bool getInfoFromEHABISection(pint_t pc, const UnwindInfoSections &sects);
Logan Chiena54f0962015-05-29 15:33:38 +0000955
956 int stepWithEHABI() {
957 size_t len = 0;
958 size_t off = 0;
959 // FIXME: Calling decode_eht_entry() here is violating the libunwind
960 // abstraction layer.
961 const uint32_t *ehtp =
962 decode_eht_entry(reinterpret_cast<const uint32_t *>(_info.unwind_info),
963 &off, &len);
964 if (_Unwind_VRS_Interpret((_Unwind_Context *)this, ehtp, off, len) !=
965 _URC_CONTINUE_UNWIND)
966 return UNW_STEP_END;
967 return UNW_STEP_SUCCESS;
968 }
Saleem Abdulrasool17552662015-04-24 19:39:17 +0000969#endif
970
Shoaib Meenai67bace72022-05-23 22:11:34 -0700971#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
Ryan Pricharda684bed2021-01-13 16:38:36 -0800972 bool setInfoForSigReturn() {
973 R dummy;
974 return setInfoForSigReturn(dummy);
975 }
976 int stepThroughSigReturn() {
977 R dummy;
978 return stepThroughSigReturn(dummy);
979 }
Shoaib Meenai67bace72022-05-23 22:11:34 -0700980#if defined(_LIBUNWIND_TARGET_AARCH64)
Ryan Pricharda684bed2021-01-13 16:38:36 -0800981 bool setInfoForSigReturn(Registers_arm64 &);
982 int stepThroughSigReturn(Registers_arm64 &);
Shoaib Meenai67bace72022-05-23 22:11:34 -0700983#endif
984#if defined(_LIBUNWIND_TARGET_S390X)
Ulrich Weigandf1108b62022-05-04 10:43:11 +0200985 bool setInfoForSigReturn(Registers_s390x &);
986 int stepThroughSigReturn(Registers_s390x &);
Shoaib Meenai67bace72022-05-23 22:11:34 -0700987#endif
Ryan Pricharda684bed2021-01-13 16:38:36 -0800988 template <typename Registers> bool setInfoForSigReturn(Registers &) {
989 return false;
990 }
991 template <typename Registers> int stepThroughSigReturn(Registers &) {
992 return UNW_STEP_END;
993 }
994#endif
995
Ranjeet Singh421231a2017-03-31 15:28:06 +0000996#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Ryan Prichard1ae2b942020-08-18 02:31:38 -0700997 bool getInfoFromFdeCie(const typename CFI_Parser<A>::FDE_Info &fdeInfo,
998 const typename CFI_Parser<A>::CIE_Info &cieInfo,
999 pint_t pc, uintptr_t dso_base);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001000 bool getInfoFromDwarfSection(pint_t pc, const UnwindInfoSections &sects,
1001 uint32_t fdeSectionOffsetHint=0);
Florian Mayer7ff728a2022-06-03 14:33:08 -07001002 int stepWithDwarfFDE(bool stage2) {
1003 return DwarfInstructions<A, R>::stepWithDwarf(
1004 _addressSpace, (pint_t)this->getReg(UNW_REG_IP),
1005 (pint_t)_info.unwind_info, _registers, _isSignalFrame, stage2);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001006 }
1007#endif
1008
Ranjeet Singh421231a2017-03-31 15:28:06 +00001009#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001010 bool getInfoFromCompactEncodingSection(pint_t pc,
1011 const UnwindInfoSections &sects);
Florian Mayer7ff728a2022-06-03 14:33:08 -07001012 int stepWithCompactEncoding(bool stage2 = false) {
1013#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001014 if ( compactSaysUseDwarf() )
Florian Mayer7ff728a2022-06-03 14:33:08 -07001015 return stepWithDwarfFDE(stage2);
1016#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001017 R dummy;
1018 return stepWithCompactEncoding(dummy);
1019 }
1020
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001021#if defined(_LIBUNWIND_TARGET_X86_64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001022 int stepWithCompactEncoding(Registers_x86_64 &) {
1023 return CompactUnwinder_x86_64<A>::stepWithCompactEncoding(
1024 _info.format, _info.start_ip, _addressSpace, _registers);
1025 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001026#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001027
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001028#if defined(_LIBUNWIND_TARGET_I386)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001029 int stepWithCompactEncoding(Registers_x86 &) {
1030 return CompactUnwinder_x86<A>::stepWithCompactEncoding(
1031 _info.format, (uint32_t)_info.start_ip, _addressSpace, _registers);
1032 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001033#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001034
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001035#if defined(_LIBUNWIND_TARGET_PPC)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001036 int stepWithCompactEncoding(Registers_ppc &) {
1037 return UNW_EINVAL;
1038 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001039#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001040
Martin Storsjo8338b0a2018-01-02 22:11:30 +00001041#if defined(_LIBUNWIND_TARGET_PPC64)
1042 int stepWithCompactEncoding(Registers_ppc64 &) {
1043 return UNW_EINVAL;
1044 }
1045#endif
1046
1047
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001048#if defined(_LIBUNWIND_TARGET_AARCH64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001049 int stepWithCompactEncoding(Registers_arm64 &) {
1050 return CompactUnwinder_arm64<A>::stepWithCompactEncoding(
1051 _info.format, _info.start_ip, _addressSpace, _registers);
1052 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001053#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001054
John Baldwin56441d42017-12-12 21:43:36 +00001055#if defined(_LIBUNWIND_TARGET_MIPS_O32)
1056 int stepWithCompactEncoding(Registers_mips_o32 &) {
1057 return UNW_EINVAL;
1058 }
1059#endif
1060
John Baldwin541a4352018-01-09 17:07:18 +00001061#if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1062 int stepWithCompactEncoding(Registers_mips_newabi &) {
John Baldwin56441d42017-12-12 21:43:36 +00001063 return UNW_EINVAL;
1064 }
1065#endif
1066
Daniel Cederman9f2f07a2019-01-14 10:15:20 +00001067#if defined(_LIBUNWIND_TARGET_SPARC)
1068 int stepWithCompactEncoding(Registers_sparc &) { return UNW_EINVAL; }
1069#endif
1070
Koakumaf2ef96e2022-02-05 13:08:26 -08001071#if defined(_LIBUNWIND_TARGET_SPARC64)
1072 int stepWithCompactEncoding(Registers_sparc64 &) { return UNW_EINVAL; }
1073#endif
1074
Sam Elliott81f7e172019-12-16 16:35:17 +00001075#if defined (_LIBUNWIND_TARGET_RISCV)
1076 int stepWithCompactEncoding(Registers_riscv &) {
1077 return UNW_EINVAL;
1078 }
1079#endif
1080
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001081 bool compactSaysUseDwarf(uint32_t *offset=NULL) const {
1082 R dummy;
1083 return compactSaysUseDwarf(dummy, offset);
1084 }
1085
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001086#if defined(_LIBUNWIND_TARGET_X86_64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001087 bool compactSaysUseDwarf(Registers_x86_64 &, uint32_t *offset) const {
1088 if ((_info.format & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF) {
1089 if (offset)
1090 *offset = (_info.format & UNWIND_X86_64_DWARF_SECTION_OFFSET);
1091 return true;
1092 }
1093 return false;
1094 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001095#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001096
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001097#if defined(_LIBUNWIND_TARGET_I386)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001098 bool compactSaysUseDwarf(Registers_x86 &, uint32_t *offset) const {
1099 if ((_info.format & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF) {
1100 if (offset)
1101 *offset = (_info.format & UNWIND_X86_DWARF_SECTION_OFFSET);
1102 return true;
1103 }
1104 return false;
1105 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001106#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001107
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001108#if defined(_LIBUNWIND_TARGET_PPC)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001109 bool compactSaysUseDwarf(Registers_ppc &, uint32_t *) const {
1110 return true;
1111 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001112#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001113
Martin Storsjo8338b0a2018-01-02 22:11:30 +00001114#if defined(_LIBUNWIND_TARGET_PPC64)
1115 bool compactSaysUseDwarf(Registers_ppc64 &, uint32_t *) const {
1116 return true;
1117 }
1118#endif
1119
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001120#if defined(_LIBUNWIND_TARGET_AARCH64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001121 bool compactSaysUseDwarf(Registers_arm64 &, uint32_t *offset) const {
1122 if ((_info.format & UNWIND_ARM64_MODE_MASK) == UNWIND_ARM64_MODE_DWARF) {
1123 if (offset)
1124 *offset = (_info.format & UNWIND_ARM64_DWARF_SECTION_OFFSET);
1125 return true;
1126 }
1127 return false;
1128 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001129#endif
John Baldwin56441d42017-12-12 21:43:36 +00001130
1131#if defined(_LIBUNWIND_TARGET_MIPS_O32)
1132 bool compactSaysUseDwarf(Registers_mips_o32 &, uint32_t *) const {
1133 return true;
1134 }
1135#endif
1136
John Baldwin541a4352018-01-09 17:07:18 +00001137#if defined(_LIBUNWIND_TARGET_MIPS_NEWABI)
1138 bool compactSaysUseDwarf(Registers_mips_newabi &, uint32_t *) const {
John Baldwin56441d42017-12-12 21:43:36 +00001139 return true;
1140 }
1141#endif
Daniel Cederman9f2f07a2019-01-14 10:15:20 +00001142
1143#if defined(_LIBUNWIND_TARGET_SPARC)
1144 bool compactSaysUseDwarf(Registers_sparc &, uint32_t *) const { return true; }
1145#endif
1146
Koakumaf2ef96e2022-02-05 13:08:26 -08001147#if defined(_LIBUNWIND_TARGET_SPARC64)
1148 bool compactSaysUseDwarf(Registers_sparc64 &, uint32_t *) const {
1149 return true;
1150 }
1151#endif
1152
Sam Elliott81f7e172019-12-16 16:35:17 +00001153#if defined (_LIBUNWIND_TARGET_RISCV)
1154 bool compactSaysUseDwarf(Registers_riscv &, uint32_t *) const {
1155 return true;
1156 }
1157#endif
1158
Ranjeet Singh421231a2017-03-31 15:28:06 +00001159#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001160
Ranjeet Singh421231a2017-03-31 15:28:06 +00001161#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001162 compact_unwind_encoding_t dwarfEncoding() const {
1163 R dummy;
1164 return dwarfEncoding(dummy);
1165 }
1166
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001167#if defined(_LIBUNWIND_TARGET_X86_64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001168 compact_unwind_encoding_t dwarfEncoding(Registers_x86_64 &) const {
1169 return UNWIND_X86_64_MODE_DWARF;
1170 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001171#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001172
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001173#if defined(_LIBUNWIND_TARGET_I386)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001174 compact_unwind_encoding_t dwarfEncoding(Registers_x86 &) const {
1175 return UNWIND_X86_MODE_DWARF;
1176 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001177#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001178
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001179#if defined(_LIBUNWIND_TARGET_PPC)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001180 compact_unwind_encoding_t dwarfEncoding(Registers_ppc &) const {
1181 return 0;
1182 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001183#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001184
Martin Storsjo8338b0a2018-01-02 22:11:30 +00001185#if defined(_LIBUNWIND_TARGET_PPC64)
1186 compact_unwind_encoding_t dwarfEncoding(Registers_ppc64 &) const {
1187 return 0;
1188 }
1189#endif
1190
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001191#if defined(_LIBUNWIND_TARGET_AARCH64)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001192 compact_unwind_encoding_t dwarfEncoding(Registers_arm64 &) const {
1193 return UNWIND_ARM64_MODE_DWARF;
1194 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001195#endif
Peter Zotov8d639992015-08-31 05:26:37 +00001196
Martin Storsjoa72285f2017-11-02 08:16:16 +00001197#if defined(_LIBUNWIND_TARGET_ARM)
1198 compact_unwind_encoding_t dwarfEncoding(Registers_arm &) const {
1199 return 0;
1200 }
1201#endif
1202
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001203#if defined (_LIBUNWIND_TARGET_OR1K)
Peter Zotov8d639992015-08-31 05:26:37 +00001204 compact_unwind_encoding_t dwarfEncoding(Registers_or1k &) const {
1205 return 0;
1206 }
Asiri Rathnayakec00dcef2016-05-25 12:36:34 +00001207#endif
John Baldwin56441d42017-12-12 21:43:36 +00001208
Brian Cainb432c472020-04-09 00:14:02 -05001209#if defined (_LIBUNWIND_TARGET_HEXAGON)
1210 compact_unwind_encoding_t dwarfEncoding(Registers_hexagon &) const {
1211 return 0;
1212 }
1213#endif
1214
John Baldwin56441d42017-12-12 21:43:36 +00001215#if defined (_LIBUNWIND_TARGET_MIPS_O32)
1216 compact_unwind_encoding_t dwarfEncoding(Registers_mips_o32 &) const {
1217 return 0;
1218 }
1219#endif
1220
John Baldwin541a4352018-01-09 17:07:18 +00001221#if defined (_LIBUNWIND_TARGET_MIPS_NEWABI)
1222 compact_unwind_encoding_t dwarfEncoding(Registers_mips_newabi &) const {
John Baldwin56441d42017-12-12 21:43:36 +00001223 return 0;
1224 }
1225#endif
Daniel Cederman9f2f07a2019-01-14 10:15:20 +00001226
1227#if defined(_LIBUNWIND_TARGET_SPARC)
1228 compact_unwind_encoding_t dwarfEncoding(Registers_sparc &) const { return 0; }
1229#endif
1230
Koakumaf2ef96e2022-02-05 13:08:26 -08001231#if defined(_LIBUNWIND_TARGET_SPARC64)
1232 compact_unwind_encoding_t dwarfEncoding(Registers_sparc64 &) const {
1233 return 0;
1234 }
1235#endif
1236
Sam Elliott81f7e172019-12-16 16:35:17 +00001237#if defined (_LIBUNWIND_TARGET_RISCV)
1238 compact_unwind_encoding_t dwarfEncoding(Registers_riscv &) const {
1239 return 0;
1240 }
1241#endif
1242
Ulrich Weigand393e3ee2022-05-02 14:35:29 +02001243#if defined (_LIBUNWIND_TARGET_S390X)
1244 compact_unwind_encoding_t dwarfEncoding(Registers_s390x &) const {
1245 return 0;
1246 }
1247#endif
1248
Ranjeet Singh421231a2017-03-31 15:28:06 +00001249#endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001250
Charles Davisfa2e6202018-08-30 21:29:00 +00001251#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1252 // For runtime environments using SEH unwind data without Windows runtime
1253 // support.
1254 pint_t getLastPC() const { /* FIXME: Implement */ return 0; }
1255 void setLastPC(pint_t pc) { /* FIXME: Implement */ }
1256 RUNTIME_FUNCTION *lookUpSEHUnwindInfo(pint_t pc, pint_t *base) {
1257 /* FIXME: Implement */
1258 *base = 0;
1259 return nullptr;
1260 }
1261 bool getInfoFromSEH(pint_t pc);
1262 int stepWithSEHData() { /* FIXME: Implement */ return 0; }
1263#endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1264
Xing Xuebbcbce92022-04-13 11:01:59 -04001265#if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1266 bool getInfoFromTBTable(pint_t pc, R &registers);
1267 int stepWithTBTable(pint_t pc, tbtable *TBTable, R &registers,
1268 bool &isSignalFrame);
1269 int stepWithTBTableData() {
1270 return stepWithTBTable(reinterpret_cast<pint_t>(this->getReg(UNW_REG_IP)),
1271 reinterpret_cast<tbtable *>(_info.unwind_info),
1272 _registers, _isSignalFrame);
1273 }
1274#endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001275
1276 A &_addressSpace;
1277 R _registers;
1278 unw_proc_info_t _info;
1279 bool _unwindInfoMissing;
1280 bool _isSignalFrame;
Shoaib Meenai67bace72022-05-23 22:11:34 -07001281#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
Ryan Pricharda684bed2021-01-13 16:38:36 -08001282 bool _isSigReturn = false;
1283#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001284};
1285
1286
1287template <typename A, typename R>
1288UnwindCursor<A, R>::UnwindCursor(unw_context_t *context, A &as)
1289 : _addressSpace(as), _registers(context), _unwindInfoMissing(false),
1290 _isSignalFrame(false) {
Asiri Rathnayake74d35252016-05-26 21:45:54 +00001291 static_assert((check_fit<UnwindCursor<A, R>, unw_cursor_t>::does_fit),
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001292 "UnwindCursor<> does not fit in unw_cursor_t");
Martin Storsjö1c0575e2020-08-17 22:41:58 +03001293 static_assert((alignof(UnwindCursor<A, R>) <= alignof(unw_cursor_t)),
1294 "UnwindCursor<> requires more alignment than unw_cursor_t");
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001295 memset(&_info, 0, sizeof(_info));
1296}
1297
1298template <typename A, typename R>
1299UnwindCursor<A, R>::UnwindCursor(A &as, void *)
1300 : _addressSpace(as), _unwindInfoMissing(false), _isSignalFrame(false) {
1301 memset(&_info, 0, sizeof(_info));
1302 // FIXME
1303 // fill in _registers from thread arg
1304}
1305
1306
1307template <typename A, typename R>
1308bool UnwindCursor<A, R>::validReg(int regNum) {
1309 return _registers.validRegister(regNum);
1310}
1311
1312template <typename A, typename R>
1313unw_word_t UnwindCursor<A, R>::getReg(int regNum) {
1314 return _registers.getRegister(regNum);
1315}
1316
1317template <typename A, typename R>
1318void UnwindCursor<A, R>::setReg(int regNum, unw_word_t value) {
1319 _registers.setRegister(regNum, (typename A::pint_t)value);
1320}
1321
1322template <typename A, typename R>
1323bool UnwindCursor<A, R>::validFloatReg(int regNum) {
1324 return _registers.validFloatRegister(regNum);
1325}
1326
1327template <typename A, typename R>
1328unw_fpreg_t UnwindCursor<A, R>::getFloatReg(int regNum) {
1329 return _registers.getFloatRegister(regNum);
1330}
1331
1332template <typename A, typename R>
1333void UnwindCursor<A, R>::setFloatReg(int regNum, unw_fpreg_t value) {
1334 _registers.setFloatRegister(regNum, value);
1335}
1336
1337template <typename A, typename R> void UnwindCursor<A, R>::jumpto() {
1338 _registers.jumpto();
1339}
1340
1341#ifdef __arm__
1342template <typename A, typename R> void UnwindCursor<A, R>::saveVFPAsX() {
1343 _registers.saveVFPAsX();
1344}
1345#endif
1346
Xing Xuebbcbce92022-04-13 11:01:59 -04001347#ifdef _AIX
1348template <typename A, typename R>
1349uintptr_t UnwindCursor<A, R>::getDataRelBase() {
1350 return reinterpret_cast<uintptr_t>(_info.extra);
1351}
1352#endif
1353
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001354template <typename A, typename R>
1355const char *UnwindCursor<A, R>::getRegisterName(int regNum) {
1356 return _registers.getRegisterName(regNum);
1357}
1358
1359template <typename A, typename R> bool UnwindCursor<A, R>::isSignalFrame() {
1360 return _isSignalFrame;
1361}
1362
Charles Davisfa2e6202018-08-30 21:29:00 +00001363#endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1364
Ranjeet Singh421231a2017-03-31 15:28:06 +00001365#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001366template<typename A>
1367struct EHABISectionIterator {
1368 typedef EHABISectionIterator _Self;
1369
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001370 typedef typename A::pint_t value_type;
1371 typedef typename A::pint_t* pointer;
1372 typedef typename A::pint_t& reference;
1373 typedef size_t size_type;
1374 typedef size_t difference_type;
1375
1376 static _Self begin(A& addressSpace, const UnwindInfoSections& sects) {
1377 return _Self(addressSpace, sects, 0);
1378 }
1379 static _Self end(A& addressSpace, const UnwindInfoSections& sects) {
Ed Schouten5d3f35b2017-03-07 15:21:57 +00001380 return _Self(addressSpace, sects,
1381 sects.arm_section_length / sizeof(EHABIIndexEntry));
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001382 }
1383
1384 EHABISectionIterator(A& addressSpace, const UnwindInfoSections& sects, size_t i)
1385 : _i(i), _addressSpace(&addressSpace), _sects(&sects) {}
1386
1387 _Self& operator++() { ++_i; return *this; }
1388 _Self& operator+=(size_t a) { _i += a; return *this; }
1389 _Self& operator--() { assert(_i > 0); --_i; return *this; }
1390 _Self& operator-=(size_t a) { assert(_i >= a); _i -= a; return *this; }
1391
1392 _Self operator+(size_t a) { _Self out = *this; out._i += a; return out; }
1393 _Self operator-(size_t a) { assert(_i >= a); _Self out = *this; out._i -= a; return out; }
1394
Saleem Abdulrasoolfbff6b12020-06-18 08:51:44 -07001395 size_t operator-(const _Self& other) const { return _i - other._i; }
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001396
1397 bool operator==(const _Self& other) const {
1398 assert(_addressSpace == other._addressSpace);
1399 assert(_sects == other._sects);
1400 return _i == other._i;
1401 }
1402
Saleem Abdulrasoolfbff6b12020-06-18 08:51:44 -07001403 bool operator!=(const _Self& other) const {
1404 assert(_addressSpace == other._addressSpace);
1405 assert(_sects == other._sects);
1406 return _i != other._i;
1407 }
1408
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001409 typename A::pint_t operator*() const { return functionAddress(); }
1410
1411 typename A::pint_t functionAddress() const {
1412 typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1413 EHABIIndexEntry, _i, functionOffset);
1414 return indexAddr + signExtendPrel31(_addressSpace->get32(indexAddr));
1415 }
1416
1417 typename A::pint_t dataAddress() {
1418 typename A::pint_t indexAddr = _sects->arm_section + arrayoffsetof(
1419 EHABIIndexEntry, _i, data);
1420 return indexAddr;
1421 }
1422
1423 private:
1424 size_t _i;
1425 A* _addressSpace;
1426 const UnwindInfoSections* _sects;
1427};
1428
Petr Hosekac0d9e02019-01-29 22:26:18 +00001429namespace {
1430
1431template <typename A>
1432EHABISectionIterator<A> EHABISectionUpperBound(
1433 EHABISectionIterator<A> first,
1434 EHABISectionIterator<A> last,
1435 typename A::pint_t value) {
1436 size_t len = last - first;
1437 while (len > 0) {
1438 size_t l2 = len / 2;
1439 EHABISectionIterator<A> m = first + l2;
1440 if (value < *m) {
1441 len = l2;
1442 } else {
1443 first = ++m;
1444 len -= l2 + 1;
1445 }
1446 }
1447 return first;
1448}
1449
1450}
1451
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001452template <typename A, typename R>
1453bool UnwindCursor<A, R>::getInfoFromEHABISection(
1454 pint_t pc,
1455 const UnwindInfoSections &sects) {
1456 EHABISectionIterator<A> begin =
1457 EHABISectionIterator<A>::begin(_addressSpace, sects);
1458 EHABISectionIterator<A> end =
1459 EHABISectionIterator<A>::end(_addressSpace, sects);
Momchil Velikov064d69a2017-07-24 09:19:32 +00001460 if (begin == end)
1461 return false;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001462
Petr Hosekac0d9e02019-01-29 22:26:18 +00001463 EHABISectionIterator<A> itNextPC = EHABISectionUpperBound(begin, end, pc);
Momchil Velikov064d69a2017-07-24 09:19:32 +00001464 if (itNextPC == begin)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001465 return false;
1466 EHABISectionIterator<A> itThisPC = itNextPC - 1;
1467
1468 pint_t thisPC = itThisPC.functionAddress();
Momchil Velikov064d69a2017-07-24 09:19:32 +00001469 // If an exception is thrown from a function, corresponding to the last entry
1470 // in the table, we don't really know the function extent and have to choose a
1471 // value for nextPC. Choosing max() will allow the range check during trace to
1472 // succeed.
Petr Hosekac0d9e02019-01-29 22:26:18 +00001473 pint_t nextPC = (itNextPC == end) ? UINTPTR_MAX : itNextPC.functionAddress();
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001474 pint_t indexDataAddr = itThisPC.dataAddress();
1475
1476 if (indexDataAddr == 0)
1477 return false;
1478
1479 uint32_t indexData = _addressSpace.get32(indexDataAddr);
1480 if (indexData == UNW_EXIDX_CANTUNWIND)
1481 return false;
1482
1483 // If the high bit is set, the exception handling table entry is inline inside
1484 // the index table entry on the second word (aka |indexDataAddr|). Otherwise,
Nico Weberd999d542020-02-03 14:16:52 -05001485 // the table points at an offset in the exception handling table (section 5
1486 // EHABI).
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001487 pint_t exceptionTableAddr;
1488 uint32_t exceptionTableData;
1489 bool isSingleWordEHT;
1490 if (indexData & 0x80000000) {
1491 exceptionTableAddr = indexDataAddr;
1492 // TODO(ajwong): Should this data be 0?
1493 exceptionTableData = indexData;
1494 isSingleWordEHT = true;
1495 } else {
1496 exceptionTableAddr = indexDataAddr + signExtendPrel31(indexData);
1497 exceptionTableData = _addressSpace.get32(exceptionTableAddr);
1498 isSingleWordEHT = false;
1499 }
1500
1501 // Now we know the 3 things:
1502 // exceptionTableAddr -- exception handler table entry.
1503 // exceptionTableData -- the data inside the first word of the eht entry.
1504 // isSingleWordEHT -- whether the entry is in the index.
1505 unw_word_t personalityRoutine = 0xbadf00d;
1506 bool scope32 = false;
Logan Chiena54f0962015-05-29 15:33:38 +00001507 uintptr_t lsda;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001508
1509 // If the high bit in the exception handling table entry is set, the entry is
1510 // in compact form (section 6.3 EHABI).
1511 if (exceptionTableData & 0x80000000) {
1512 // Grab the index of the personality routine from the compact form.
1513 uint32_t choice = (exceptionTableData & 0x0f000000) >> 24;
1514 uint32_t extraWords = 0;
1515 switch (choice) {
1516 case 0:
1517 personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr0;
1518 extraWords = 0;
1519 scope32 = false;
Logan Chiena54f0962015-05-29 15:33:38 +00001520 lsda = isSingleWordEHT ? 0 : (exceptionTableAddr + 4);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001521 break;
1522 case 1:
1523 personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr1;
1524 extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1525 scope32 = false;
Logan Chiena54f0962015-05-29 15:33:38 +00001526 lsda = exceptionTableAddr + (extraWords + 1) * 4;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001527 break;
1528 case 2:
1529 personalityRoutine = (unw_word_t) &__aeabi_unwind_cpp_pr2;
1530 extraWords = (exceptionTableData & 0x00ff0000) >> 16;
1531 scope32 = true;
Logan Chiena54f0962015-05-29 15:33:38 +00001532 lsda = exceptionTableAddr + (extraWords + 1) * 4;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001533 break;
1534 default:
1535 _LIBUNWIND_ABORT("unknown personality routine");
1536 return false;
1537 }
1538
1539 if (isSingleWordEHT) {
1540 if (extraWords != 0) {
1541 _LIBUNWIND_ABORT("index inlined table detected but pr function "
1542 "requires extra words");
1543 return false;
1544 }
1545 }
1546 } else {
1547 pint_t personalityAddr =
1548 exceptionTableAddr + signExtendPrel31(exceptionTableData);
1549 personalityRoutine = personalityAddr;
1550
1551 // ARM EHABI # 6.2, # 9.2
1552 //
1553 // +---- ehtp
1554 // v
1555 // +--------------------------------------+
1556 // | +--------+--------+--------+-------+ |
1557 // | |0| prel31 to personalityRoutine | |
1558 // | +--------+--------+--------+-------+ |
1559 // | | N | unwind opcodes | | <-- UnwindData
1560 // | +--------+--------+--------+-------+ |
1561 // | | Word 2 unwind opcodes | |
1562 // | +--------+--------+--------+-------+ |
1563 // | ... |
1564 // | +--------+--------+--------+-------+ |
1565 // | | Word N unwind opcodes | |
1566 // | +--------+--------+--------+-------+ |
1567 // | | LSDA | | <-- lsda
1568 // | | ... | |
1569 // | +--------+--------+--------+-------+ |
1570 // +--------------------------------------+
1571
1572 uint32_t *UnwindData = reinterpret_cast<uint32_t*>(exceptionTableAddr) + 1;
1573 uint32_t FirstDataWord = *UnwindData;
1574 size_t N = ((FirstDataWord >> 24) & 0xff);
1575 size_t NDataWords = N + 1;
1576 lsda = reinterpret_cast<uintptr_t>(UnwindData + NDataWords);
1577 }
1578
1579 _info.start_ip = thisPC;
1580 _info.end_ip = nextPC;
1581 _info.handler = personalityRoutine;
1582 _info.unwind_info = exceptionTableAddr;
1583 _info.lsda = lsda;
1584 // flags is pr_cache.additional. See EHABI #7.2 for definition of bit 0.
Nico Weberd999d542020-02-03 14:16:52 -05001585 _info.flags = (isSingleWordEHT ? 1 : 0) | (scope32 ? 0x2 : 0); // Use enum?
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001586
1587 return true;
1588}
1589#endif
1590
Ranjeet Singh421231a2017-03-31 15:28:06 +00001591#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001592template <typename A, typename R>
Ryan Prichard1ae2b942020-08-18 02:31:38 -07001593bool UnwindCursor<A, R>::getInfoFromFdeCie(
1594 const typename CFI_Parser<A>::FDE_Info &fdeInfo,
1595 const typename CFI_Parser<A>::CIE_Info &cieInfo, pint_t pc,
1596 uintptr_t dso_base) {
1597 typename CFI_Parser<A>::PrologInfo prolog;
1598 if (CFI_Parser<A>::parseFDEInstructions(_addressSpace, fdeInfo, cieInfo, pc,
1599 R::getArch(), &prolog)) {
1600 // Save off parsed FDE info
1601 _info.start_ip = fdeInfo.pcStart;
1602 _info.end_ip = fdeInfo.pcEnd;
1603 _info.lsda = fdeInfo.lsda;
1604 _info.handler = cieInfo.personality;
1605 // Some frameless functions need SP altered when resuming in function, so
1606 // propagate spExtraArgSize.
1607 _info.gp = prolog.spExtraArgSize;
1608 _info.flags = 0;
1609 _info.format = dwarfEncoding();
1610 _info.unwind_info = fdeInfo.fdeStart;
1611 _info.unwind_info_size = static_cast<uint32_t>(fdeInfo.fdeLength);
1612 _info.extra = static_cast<unw_word_t>(dso_base);
1613 return true;
1614 }
1615 return false;
1616}
1617
1618template <typename A, typename R>
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001619bool UnwindCursor<A, R>::getInfoFromDwarfSection(pint_t pc,
1620 const UnwindInfoSections &sects,
1621 uint32_t fdeSectionOffsetHint) {
1622 typename CFI_Parser<A>::FDE_Info fdeInfo;
1623 typename CFI_Parser<A>::CIE_Info cieInfo;
1624 bool foundFDE = false;
1625 bool foundInCache = false;
1626 // If compact encoding table gave offset into dwarf section, go directly there
1627 if (fdeSectionOffsetHint != 0) {
1628 foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
Ryan Prichard0cff8572020-09-16 01:22:55 -07001629 sects.dwarf_section_length,
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001630 sects.dwarf_section + fdeSectionOffsetHint,
1631 &fdeInfo, &cieInfo);
1632 }
Ranjeet Singh421231a2017-03-31 15:28:06 +00001633#if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001634 if (!foundFDE && (sects.dwarf_index_section != 0)) {
1635 foundFDE = EHHeaderParser<A>::findFDE(
1636 _addressSpace, pc, sects.dwarf_index_section,
1637 (uint32_t)sects.dwarf_index_section_length, &fdeInfo, &cieInfo);
1638 }
1639#endif
1640 if (!foundFDE) {
1641 // otherwise, search cache of previously found FDEs.
1642 pint_t cachedFDE = DwarfFDECache<A>::findFDE(sects.dso_base, pc);
1643 if (cachedFDE != 0) {
1644 foundFDE =
1645 CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
Ryan Prichard0cff8572020-09-16 01:22:55 -07001646 sects.dwarf_section_length,
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001647 cachedFDE, &fdeInfo, &cieInfo);
1648 foundInCache = foundFDE;
1649 }
1650 }
1651 if (!foundFDE) {
1652 // Still not found, do full scan of __eh_frame section.
1653 foundFDE = CFI_Parser<A>::findFDE(_addressSpace, pc, sects.dwarf_section,
Ryan Prichard0cff8572020-09-16 01:22:55 -07001654 sects.dwarf_section_length, 0,
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001655 &fdeInfo, &cieInfo);
1656 }
1657 if (foundFDE) {
Ryan Prichard1ae2b942020-08-18 02:31:38 -07001658 if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, sects.dso_base)) {
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001659 // Add to cache (to make next lookup faster) if we had no hint
1660 // and there was no index.
1661 if (!foundInCache && (fdeSectionOffsetHint == 0)) {
Ranjeet Singh421231a2017-03-31 15:28:06 +00001662 #if defined(_LIBUNWIND_SUPPORT_DWARF_INDEX)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001663 if (sects.dwarf_index_section == 0)
1664 #endif
1665 DwarfFDECache<A>::add(sects.dso_base, fdeInfo.pcStart, fdeInfo.pcEnd,
1666 fdeInfo.fdeStart);
1667 }
1668 return true;
1669 }
1670 }
Ed Maste41bc5a72016-08-30 15:38:10 +00001671 //_LIBUNWIND_DEBUG_LOG("can't find/use FDE for pc=0x%llX", (uint64_t)pc);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001672 return false;
1673}
Ranjeet Singh421231a2017-03-31 15:28:06 +00001674#endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001675
1676
Ranjeet Singh421231a2017-03-31 15:28:06 +00001677#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001678template <typename A, typename R>
1679bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
1680 const UnwindInfoSections &sects) {
1681 const bool log = false;
1682 if (log)
1683 fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX, mh=0x%llX)\n",
1684 (uint64_t)pc, (uint64_t)sects.dso_base);
1685
1686 const UnwindSectionHeader<A> sectionHeader(_addressSpace,
1687 sects.compact_unwind_section);
1688 if (sectionHeader.version() != UNWIND_SECTION_VERSION)
1689 return false;
1690
1691 // do a binary search of top level index to find page with unwind info
1692 pint_t targetFunctionOffset = pc - sects.dso_base;
1693 const UnwindSectionIndexArray<A> topIndex(_addressSpace,
1694 sects.compact_unwind_section
1695 + sectionHeader.indexSectionOffset());
1696 uint32_t low = 0;
1697 uint32_t high = sectionHeader.indexCount();
1698 uint32_t last = high - 1;
1699 while (low < high) {
1700 uint32_t mid = (low + high) / 2;
1701 //if ( log ) fprintf(stderr, "\tmid=%d, low=%d, high=%d, *mid=0x%08X\n",
1702 //mid, low, high, topIndex.functionOffset(mid));
1703 if (topIndex.functionOffset(mid) <= targetFunctionOffset) {
1704 if ((mid == last) ||
1705 (topIndex.functionOffset(mid + 1) > targetFunctionOffset)) {
1706 low = mid;
1707 break;
1708 } else {
1709 low = mid + 1;
1710 }
1711 } else {
1712 high = mid;
1713 }
1714 }
1715 const uint32_t firstLevelFunctionOffset = topIndex.functionOffset(low);
1716 const uint32_t firstLevelNextPageFunctionOffset =
1717 topIndex.functionOffset(low + 1);
1718 const pint_t secondLevelAddr =
1719 sects.compact_unwind_section + topIndex.secondLevelPagesSectionOffset(low);
1720 const pint_t lsdaArrayStartAddr =
1721 sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low);
1722 const pint_t lsdaArrayEndAddr =
1723 sects.compact_unwind_section + topIndex.lsdaIndexArraySectionOffset(low+1);
1724 if (log)
1725 fprintf(stderr, "\tfirst level search for result index=%d "
1726 "to secondLevelAddr=0x%llX\n",
1727 low, (uint64_t) secondLevelAddr);
1728 // do a binary search of second level page index
1729 uint32_t encoding = 0;
1730 pint_t funcStart = 0;
1731 pint_t funcEnd = 0;
1732 pint_t lsda = 0;
1733 pint_t personality = 0;
1734 uint32_t pageKind = _addressSpace.get32(secondLevelAddr);
1735 if (pageKind == UNWIND_SECOND_LEVEL_REGULAR) {
1736 // regular page
1737 UnwindSectionRegularPageHeader<A> pageHeader(_addressSpace,
1738 secondLevelAddr);
1739 UnwindSectionRegularArray<A> pageIndex(
1740 _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1741 // binary search looks for entry with e where index[e].offset <= pc <
1742 // index[e+1].offset
1743 if (log)
1744 fprintf(stderr, "\tbinary search for targetFunctionOffset=0x%08llX in "
1745 "regular page starting at secondLevelAddr=0x%llX\n",
1746 (uint64_t) targetFunctionOffset, (uint64_t) secondLevelAddr);
1747 low = 0;
1748 high = pageHeader.entryCount();
1749 while (low < high) {
1750 uint32_t mid = (low + high) / 2;
1751 if (pageIndex.functionOffset(mid) <= targetFunctionOffset) {
1752 if (mid == (uint32_t)(pageHeader.entryCount() - 1)) {
1753 // at end of table
1754 low = mid;
1755 funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1756 break;
1757 } else if (pageIndex.functionOffset(mid + 1) > targetFunctionOffset) {
1758 // next is too big, so we found it
1759 low = mid;
1760 funcEnd = pageIndex.functionOffset(low + 1) + sects.dso_base;
1761 break;
1762 } else {
1763 low = mid + 1;
1764 }
1765 } else {
1766 high = mid;
1767 }
1768 }
1769 encoding = pageIndex.encoding(low);
1770 funcStart = pageIndex.functionOffset(low) + sects.dso_base;
1771 if (pc < funcStart) {
1772 if (log)
1773 fprintf(
1774 stderr,
1775 "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1776 (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1777 return false;
1778 }
1779 if (pc > funcEnd) {
1780 if (log)
1781 fprintf(
1782 stderr,
1783 "\tpc not in table, pc=0x%llX, funcStart=0x%llX, funcEnd=0x%llX\n",
1784 (uint64_t) pc, (uint64_t) funcStart, (uint64_t) funcEnd);
1785 return false;
1786 }
1787 } else if (pageKind == UNWIND_SECOND_LEVEL_COMPRESSED) {
1788 // compressed page
1789 UnwindSectionCompressedPageHeader<A> pageHeader(_addressSpace,
1790 secondLevelAddr);
1791 UnwindSectionCompressedArray<A> pageIndex(
1792 _addressSpace, secondLevelAddr + pageHeader.entryPageOffset());
1793 const uint32_t targetFunctionPageOffset =
1794 (uint32_t)(targetFunctionOffset - firstLevelFunctionOffset);
1795 // binary search looks for entry with e where index[e].offset <= pc <
1796 // index[e+1].offset
1797 if (log)
1798 fprintf(stderr, "\tbinary search of compressed page starting at "
1799 "secondLevelAddr=0x%llX\n",
1800 (uint64_t) secondLevelAddr);
1801 low = 0;
1802 last = pageHeader.entryCount() - 1;
1803 high = pageHeader.entryCount();
1804 while (low < high) {
1805 uint32_t mid = (low + high) / 2;
1806 if (pageIndex.functionOffset(mid) <= targetFunctionPageOffset) {
1807 if ((mid == last) ||
1808 (pageIndex.functionOffset(mid + 1) > targetFunctionPageOffset)) {
1809 low = mid;
1810 break;
1811 } else {
1812 low = mid + 1;
1813 }
1814 } else {
1815 high = mid;
1816 }
1817 }
1818 funcStart = pageIndex.functionOffset(low) + firstLevelFunctionOffset
1819 + sects.dso_base;
1820 if (low < last)
1821 funcEnd =
1822 pageIndex.functionOffset(low + 1) + firstLevelFunctionOffset
1823 + sects.dso_base;
1824 else
1825 funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
1826 if (pc < funcStart) {
Nico Weber5f424e32021-07-02 10:03:32 -04001827 _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1828 "not in second level compressed unwind table. "
1829 "funcStart=0x%llX",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001830 (uint64_t) pc, (uint64_t) funcStart);
1831 return false;
1832 }
1833 if (pc > funcEnd) {
Nico Weber5f424e32021-07-02 10:03:32 -04001834 _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
1835 "not in second level compressed unwind table. "
1836 "funcEnd=0x%llX",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001837 (uint64_t) pc, (uint64_t) funcEnd);
1838 return false;
1839 }
1840 uint16_t encodingIndex = pageIndex.encodingIndex(low);
1841 if (encodingIndex < sectionHeader.commonEncodingsArrayCount()) {
1842 // encoding is in common table in section header
1843 encoding = _addressSpace.get32(
1844 sects.compact_unwind_section +
1845 sectionHeader.commonEncodingsArraySectionOffset() +
1846 encodingIndex * sizeof(uint32_t));
1847 } else {
1848 // encoding is in page specific table
1849 uint16_t pageEncodingIndex =
1850 encodingIndex - (uint16_t)sectionHeader.commonEncodingsArrayCount();
1851 encoding = _addressSpace.get32(secondLevelAddr +
1852 pageHeader.encodingsPageOffset() +
1853 pageEncodingIndex * sizeof(uint32_t));
1854 }
1855 } else {
Nico Weber5f424e32021-07-02 10:03:32 -04001856 _LIBUNWIND_DEBUG_LOG(
1857 "malformed __unwind_info at 0x%0llX bad second level page",
1858 (uint64_t)sects.compact_unwind_section);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001859 return false;
1860 }
1861
1862 // look up LSDA, if encoding says function has one
1863 if (encoding & UNWIND_HAS_LSDA) {
1864 UnwindSectionLsdaArray<A> lsdaIndex(_addressSpace, lsdaArrayStartAddr);
1865 uint32_t funcStartOffset = (uint32_t)(funcStart - sects.dso_base);
1866 low = 0;
1867 high = (uint32_t)(lsdaArrayEndAddr - lsdaArrayStartAddr) /
1868 sizeof(unwind_info_section_header_lsda_index_entry);
1869 // binary search looks for entry with exact match for functionOffset
1870 if (log)
1871 fprintf(stderr,
1872 "\tbinary search of lsda table for targetFunctionOffset=0x%08X\n",
1873 funcStartOffset);
1874 while (low < high) {
1875 uint32_t mid = (low + high) / 2;
1876 if (lsdaIndex.functionOffset(mid) == funcStartOffset) {
1877 lsda = lsdaIndex.lsdaOffset(mid) + sects.dso_base;
1878 break;
1879 } else if (lsdaIndex.functionOffset(mid) < funcStartOffset) {
1880 low = mid + 1;
1881 } else {
1882 high = mid;
1883 }
1884 }
1885 if (lsda == 0) {
1886 _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with HAS_LSDA bit set for "
Ed Maste41bc5a72016-08-30 15:38:10 +00001887 "pc=0x%0llX, but lsda table has no entry",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001888 encoding, (uint64_t) pc);
1889 return false;
1890 }
1891 }
1892
Louis Dionned3bbbc32020-08-11 15:24:21 -04001893 // extract personality routine, if encoding says function has one
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001894 uint32_t personalityIndex = (encoding & UNWIND_PERSONALITY_MASK) >>
1895 (__builtin_ctz(UNWIND_PERSONALITY_MASK));
1896 if (personalityIndex != 0) {
1897 --personalityIndex; // change 1-based to zero-based index
Louis Dionne8c360cb2020-08-11 15:29:00 -04001898 if (personalityIndex >= sectionHeader.personalityArrayCount()) {
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001899 _LIBUNWIND_DEBUG_LOG("found encoding 0x%08X with personality index %d, "
Louis Dionne103afa42019-04-22 15:40:50 +00001900 "but personality table has only %d entries",
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001901 encoding, personalityIndex,
1902 sectionHeader.personalityArrayCount());
1903 return false;
1904 }
1905 int32_t personalityDelta = (int32_t)_addressSpace.get32(
1906 sects.compact_unwind_section +
1907 sectionHeader.personalityArraySectionOffset() +
1908 personalityIndex * sizeof(uint32_t));
1909 pint_t personalityPointer = sects.dso_base + (pint_t)personalityDelta;
1910 personality = _addressSpace.getP(personalityPointer);
1911 if (log)
1912 fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1913 "personalityDelta=0x%08X, personality=0x%08llX\n",
1914 (uint64_t) pc, personalityDelta, (uint64_t) personality);
1915 }
1916
1917 if (log)
1918 fprintf(stderr, "getInfoFromCompactEncodingSection(pc=0x%llX), "
1919 "encoding=0x%08X, lsda=0x%08llX for funcStart=0x%llX\n",
1920 (uint64_t) pc, encoding, (uint64_t) lsda, (uint64_t) funcStart);
1921 _info.start_ip = funcStart;
1922 _info.end_ip = funcEnd;
1923 _info.lsda = lsda;
1924 _info.handler = personality;
1925 _info.gp = 0;
1926 _info.flags = 0;
1927 _info.format = encoding;
1928 _info.unwind_info = 0;
1929 _info.unwind_info_size = 0;
1930 _info.extra = sects.dso_base;
1931 return true;
1932}
Ranjeet Singh421231a2017-03-31 15:28:06 +00001933#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00001934
1935
Charles Davisfa2e6202018-08-30 21:29:00 +00001936#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
1937template <typename A, typename R>
1938bool UnwindCursor<A, R>::getInfoFromSEH(pint_t pc) {
1939 pint_t base;
1940 RUNTIME_FUNCTION *unwindEntry = lookUpSEHUnwindInfo(pc, &base);
1941 if (!unwindEntry) {
1942 _LIBUNWIND_DEBUG_LOG("\tpc not in table, pc=0x%llX", (uint64_t) pc);
1943 return false;
1944 }
1945 _info.gp = 0;
1946 _info.flags = 0;
1947 _info.format = 0;
1948 _info.unwind_info_size = sizeof(RUNTIME_FUNCTION);
1949 _info.unwind_info = reinterpret_cast<unw_word_t>(unwindEntry);
1950 _info.extra = base;
1951 _info.start_ip = base + unwindEntry->BeginAddress;
1952#ifdef _LIBUNWIND_TARGET_X86_64
1953 _info.end_ip = base + unwindEntry->EndAddress;
1954 // Only fill in the handler and LSDA if they're stale.
1955 if (pc != getLastPC()) {
1956 UNWIND_INFO *xdata = reinterpret_cast<UNWIND_INFO *>(base + unwindEntry->UnwindData);
1957 if (xdata->Flags & (UNW_FLAG_EHANDLER|UNW_FLAG_UHANDLER)) {
1958 // The personality is given in the UNWIND_INFO itself. The LSDA immediately
1959 // follows the UNWIND_INFO. (This follows how both Clang and MSVC emit
1960 // these structures.)
1961 // N.B. UNWIND_INFO structs are DWORD-aligned.
1962 uint32_t lastcode = (xdata->CountOfCodes + 1) & ~1;
1963 const uint32_t *handler = reinterpret_cast<uint32_t *>(&xdata->UnwindCodes[lastcode]);
1964 _info.lsda = reinterpret_cast<unw_word_t>(handler+1);
1965 if (*handler) {
1966 _info.handler = reinterpret_cast<unw_word_t>(__libunwind_seh_personality);
1967 } else
1968 _info.handler = 0;
1969 } else {
1970 _info.lsda = 0;
1971 _info.handler = 0;
1972 }
1973 }
Charles Davisfa2e6202018-08-30 21:29:00 +00001974#endif
1975 setLastPC(pc);
1976 return true;
1977}
1978#endif
1979
Xing Xuebbcbce92022-04-13 11:01:59 -04001980#if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
1981// Masks for traceback table field xtbtable.
1982enum xTBTableMask : uint8_t {
1983 reservedBit = 0x02, // The traceback table was incorrectly generated if set
1984 // (see comments in function getInfoFromTBTable().
1985 ehInfoBit = 0x08 // Exception handling info is present if set
1986};
1987
1988enum frameType : unw_word_t {
1989 frameWithXLEHStateTable = 0,
1990 frameWithEHInfo = 1
1991};
1992
1993extern "C" {
1994typedef _Unwind_Reason_Code __xlcxx_personality_v0_t(int, _Unwind_Action,
1995 uint64_t,
1996 _Unwind_Exception *,
1997 struct _Unwind_Context *);
1998__attribute__((__weak__)) __xlcxx_personality_v0_t __xlcxx_personality_v0;
1999}
2000
2001static __xlcxx_personality_v0_t *xlcPersonalityV0;
2002static RWMutex xlcPersonalityV0InitLock;
2003
2004template <typename A, typename R>
2005bool UnwindCursor<A, R>::getInfoFromTBTable(pint_t pc, R &registers) {
2006 uint32_t *p = reinterpret_cast<uint32_t *>(pc);
2007
2008 // Keep looking forward until a word of 0 is found. The traceback
2009 // table starts at the following word.
2010 while (*p)
2011 ++p;
2012 tbtable *TBTable = reinterpret_cast<tbtable *>(p + 1);
2013
2014 if (_LIBUNWIND_TRACING_UNWINDING) {
2015 char functionBuf[512];
2016 const char *functionName = functionBuf;
2017 unw_word_t offset;
2018 if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
2019 functionName = ".anonymous.";
2020 }
2021 _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2022 __func__, functionName,
2023 reinterpret_cast<void *>(TBTable));
2024 }
2025
2026 // If the traceback table does not contain necessary info, bypass this frame.
2027 if (!TBTable->tb.has_tboff)
2028 return false;
2029
2030 // Structure tbtable_ext contains important data we are looking for.
2031 p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2032
2033 // Skip field parminfo if it exists.
2034 if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2035 ++p;
2036
2037 // p now points to tb_offset, the offset from start of function to TB table.
2038 unw_word_t start_ip =
2039 reinterpret_cast<unw_word_t>(TBTable) - *p - sizeof(uint32_t);
2040 unw_word_t end_ip = reinterpret_cast<unw_word_t>(TBTable);
2041 ++p;
2042
2043 _LIBUNWIND_TRACE_UNWINDING("start_ip=%p, end_ip=%p\n",
2044 reinterpret_cast<void *>(start_ip),
2045 reinterpret_cast<void *>(end_ip));
2046
2047 // Skip field hand_mask if it exists.
2048 if (TBTable->tb.int_hndl)
2049 ++p;
2050
2051 unw_word_t lsda = 0;
2052 unw_word_t handler = 0;
2053 unw_word_t flags = frameType::frameWithXLEHStateTable;
2054
2055 if (TBTable->tb.lang == TB_CPLUSPLUS && TBTable->tb.has_ctl) {
2056 // State table info is available. The ctl_info field indicates the
2057 // number of CTL anchors. There should be only one entry for the C++
2058 // state table.
2059 assert(*p == 1 && "libunwind: there must be only one ctl_info entry");
2060 ++p;
2061 // p points to the offset of the state table into the stack.
2062 pint_t stateTableOffset = *p++;
2063
2064 int framePointerReg;
2065
2066 // Skip fields name_len and name if exist.
2067 if (TBTable->tb.name_present) {
2068 const uint16_t name_len = *(reinterpret_cast<uint16_t *>(p));
2069 p = reinterpret_cast<uint32_t *>(reinterpret_cast<char *>(p) + name_len +
2070 sizeof(uint16_t));
2071 }
2072
2073 if (TBTable->tb.uses_alloca)
2074 framePointerReg = *(reinterpret_cast<char *>(p));
2075 else
2076 framePointerReg = 1; // default frame pointer == SP
2077
2078 _LIBUNWIND_TRACE_UNWINDING(
2079 "framePointerReg=%d, framePointer=%p, "
2080 "stateTableOffset=%#lx\n",
2081 framePointerReg,
2082 reinterpret_cast<void *>(_registers.getRegister(framePointerReg)),
2083 stateTableOffset);
2084 lsda = _registers.getRegister(framePointerReg) + stateTableOffset;
2085
2086 // Since the traceback table generated by the legacy XLC++ does not
2087 // provide the location of the personality for the state table,
2088 // function __xlcxx_personality_v0(), which is the personality for the state
2089 // table and is exported from libc++abi, is directly assigned as the
2090 // handler here. When a legacy XLC++ frame is encountered, the symbol
2091 // is resolved dynamically using dlopen() to avoid hard dependency from
2092 // libunwind on libc++abi.
2093
2094 // Resolve the function pointer to the state table personality if it has
2095 // not already.
2096 if (xlcPersonalityV0 == NULL) {
2097 xlcPersonalityV0InitLock.lock();
2098 if (xlcPersonalityV0 == NULL) {
2099 // If libc++abi is statically linked in, symbol __xlcxx_personality_v0
2100 // has been resolved at the link time.
2101 xlcPersonalityV0 = &__xlcxx_personality_v0;
2102 if (xlcPersonalityV0 == NULL) {
2103 // libc++abi is dynamically linked. Resolve __xlcxx_personality_v0
2104 // using dlopen().
2105 const char libcxxabi[] = "libc++abi.a(libc++abi.so.1)";
2106 void *libHandle;
Xing Xuec38cbd42022-08-08 17:21:30 -04002107 // The AIX dlopen() sets errno to 0 when it is successful, which
2108 // clobbers the value of errno from the user code. This is an AIX
2109 // bug because according to POSIX it should not set errno to 0. To
2110 // workaround before AIX fixes the bug, errno is saved and restored.
2111 int saveErrno = errno;
Xing Xuebbcbce92022-04-13 11:01:59 -04002112 libHandle = dlopen(libcxxabi, RTLD_MEMBER | RTLD_NOW);
2113 if (libHandle == NULL) {
2114 _LIBUNWIND_TRACE_UNWINDING("dlopen() failed with errno=%d\n",
2115 errno);
2116 assert(0 && "dlopen() failed");
2117 }
2118 xlcPersonalityV0 = reinterpret_cast<__xlcxx_personality_v0_t *>(
2119 dlsym(libHandle, "__xlcxx_personality_v0"));
2120 if (xlcPersonalityV0 == NULL) {
2121 _LIBUNWIND_TRACE_UNWINDING("dlsym() failed with errno=%d\n", errno);
2122 assert(0 && "dlsym() failed");
2123 }
2124 dlclose(libHandle);
Xing Xuec38cbd42022-08-08 17:21:30 -04002125 errno = saveErrno;
Xing Xuebbcbce92022-04-13 11:01:59 -04002126 }
2127 }
2128 xlcPersonalityV0InitLock.unlock();
2129 }
2130 handler = reinterpret_cast<unw_word_t>(xlcPersonalityV0);
2131 _LIBUNWIND_TRACE_UNWINDING("State table: LSDA=%p, Personality=%p\n",
2132 reinterpret_cast<void *>(lsda),
2133 reinterpret_cast<void *>(handler));
2134 } else if (TBTable->tb.longtbtable) {
2135 // This frame has the traceback table extension. Possible cases are
2136 // 1) a C++ frame that has the 'eh_info' structure; 2) a C++ frame that
2137 // is not EH aware; or, 3) a frame of other languages. We need to figure out
2138 // if the traceback table extension contains the 'eh_info' structure.
2139 //
2140 // We also need to deal with the complexity arising from some XL compiler
2141 // versions use the wrong ordering of 'longtbtable' and 'has_vec' bits
2142 // where the 'longtbtable' bit is meant to be the 'has_vec' bit and vice
2143 // versa. For frames of code generated by those compilers, the 'longtbtable'
2144 // bit may be set but there isn't really a traceback table extension.
2145 //
2146 // In </usr/include/sys/debug.h>, there is the following definition of
2147 // 'struct tbtable_ext'. It is not really a structure but a dummy to
2148 // collect the description of optional parts of the traceback table.
2149 //
2150 // struct tbtable_ext {
2151 // ...
2152 // char alloca_reg; /* Register for alloca automatic storage */
2153 // struct vec_ext vec_ext; /* Vector extension (if has_vec is set) */
2154 // unsigned char xtbtable; /* More tbtable fields, if longtbtable is set*/
2155 // };
2156 //
2157 // Depending on how the 'has_vec'/'longtbtable' bit is interpreted, the data
2158 // following 'alloca_reg' can be treated either as 'struct vec_ext' or
2159 // 'unsigned char xtbtable'. 'xtbtable' bits are defined in
2160 // </usr/include/sys/debug.h> as flags. The 7th bit '0x02' is currently
2161 // unused and should not be set. 'struct vec_ext' is defined in
2162 // </usr/include/sys/debug.h> as follows:
2163 //
2164 // struct vec_ext {
2165 // unsigned vr_saved:6; /* Number of non-volatile vector regs saved
2166 // */
2167 // /* first register saved is assumed to be */
2168 // /* 32 - vr_saved */
2169 // unsigned saves_vrsave:1; /* Set if vrsave is saved on the stack */
2170 // unsigned has_varargs:1;
2171 // ...
2172 // };
2173 //
2174 // Here, the 7th bit is used as 'saves_vrsave'. To determine whether it
2175 // is 'struct vec_ext' or 'xtbtable' that follows 'alloca_reg',
2176 // we checks if the 7th bit is set or not because 'xtbtable' should
2177 // never have the 7th bit set. The 7th bit of 'xtbtable' will be reserved
2178 // in the future to make sure the mitigation works. This mitigation
2179 // is not 100% bullet proof because 'struct vec_ext' may not always have
2180 // 'saves_vrsave' bit set.
2181 //
2182 // 'reservedBit' is defined in enum 'xTBTableMask' above as the mask for
2183 // checking the 7th bit.
2184
2185 // p points to field name len.
2186 uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2187
2188 // Skip fields name_len and name if they exist.
2189 if (TBTable->tb.name_present) {
2190 const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2191 charPtr = charPtr + name_len + sizeof(uint16_t);
2192 }
2193
2194 // Skip field alloc_reg if it exists.
2195 if (TBTable->tb.uses_alloca)
2196 ++charPtr;
2197
2198 // Check traceback table bit has_vec. Skip struct vec_ext if it exists.
2199 if (TBTable->tb.has_vec)
2200 // Note struct vec_ext does exist at this point because whether the
2201 // ordering of longtbtable and has_vec bits is correct or not, both
2202 // are set.
2203 charPtr += sizeof(struct vec_ext);
2204
2205 // charPtr points to field 'xtbtable'. Check if the EH info is available.
2206 // Also check if the reserved bit of the extended traceback table field
2207 // 'xtbtable' is set. If it is, the traceback table was incorrectly
2208 // generated by an XL compiler that uses the wrong ordering of 'longtbtable'
2209 // and 'has_vec' bits and this is in fact 'struct vec_ext'. So skip the
2210 // frame.
2211 if ((*charPtr & xTBTableMask::ehInfoBit) &&
2212 !(*charPtr & xTBTableMask::reservedBit)) {
2213 // Mark this frame has the new EH info.
2214 flags = frameType::frameWithEHInfo;
2215
2216 // eh_info is available.
2217 charPtr++;
2218 // The pointer is 4-byte aligned.
2219 if (reinterpret_cast<uintptr_t>(charPtr) % 4)
2220 charPtr += 4 - reinterpret_cast<uintptr_t>(charPtr) % 4;
2221 uintptr_t *ehInfo =
2222 reinterpret_cast<uintptr_t *>(*(reinterpret_cast<uintptr_t *>(
2223 registers.getRegister(2) +
2224 *(reinterpret_cast<uintptr_t *>(charPtr)))));
2225
2226 // ehInfo points to structure en_info. The first member is version.
2227 // Only version 0 is currently supported.
2228 assert(*(reinterpret_cast<uint32_t *>(ehInfo)) == 0 &&
2229 "libunwind: ehInfo version other than 0 is not supported");
2230
2231 // Increment ehInfo to point to member lsda.
2232 ++ehInfo;
2233 lsda = *ehInfo++;
2234
2235 // enInfo now points to member personality.
2236 handler = *ehInfo;
2237
2238 _LIBUNWIND_TRACE_UNWINDING("Range table: LSDA=%#lx, Personality=%#lx\n",
2239 lsda, handler);
2240 }
2241 }
2242
2243 _info.start_ip = start_ip;
2244 _info.end_ip = end_ip;
2245 _info.lsda = lsda;
2246 _info.handler = handler;
2247 _info.gp = 0;
2248 _info.flags = flags;
2249 _info.format = 0;
2250 _info.unwind_info = reinterpret_cast<unw_word_t>(TBTable);
2251 _info.unwind_info_size = 0;
2252 _info.extra = registers.getRegister(2);
2253
2254 return true;
2255}
2256
2257// Step back up the stack following the frame back link.
2258template <typename A, typename R>
2259int UnwindCursor<A, R>::stepWithTBTable(pint_t pc, tbtable *TBTable,
2260 R &registers, bool &isSignalFrame) {
2261 if (_LIBUNWIND_TRACING_UNWINDING) {
2262 char functionBuf[512];
2263 const char *functionName = functionBuf;
2264 unw_word_t offset;
2265 if (!getFunctionName(functionBuf, sizeof(functionBuf), &offset)) {
2266 functionName = ".anonymous.";
2267 }
2268 _LIBUNWIND_TRACE_UNWINDING("%s: Look up traceback table of func=%s at %p",
2269 __func__, functionName,
2270 reinterpret_cast<void *>(TBTable));
2271 }
2272
2273#if defined(__powerpc64__)
2274 // Instruction to reload TOC register "l r2,40(r1)"
2275 const uint32_t loadTOCRegInst = 0xe8410028;
2276 const int32_t unwPPCF0Index = UNW_PPC64_F0;
2277 const int32_t unwPPCV0Index = UNW_PPC64_V0;
2278#else
2279 // Instruction to reload TOC register "l r2,20(r1)"
2280 const uint32_t loadTOCRegInst = 0x80410014;
2281 const int32_t unwPPCF0Index = UNW_PPC_F0;
2282 const int32_t unwPPCV0Index = UNW_PPC_V0;
2283#endif
2284
2285 R newRegisters = registers;
2286
2287 // lastStack points to the stack frame of the next routine up.
2288 pint_t lastStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2289
2290 // Return address is the address after call site instruction.
2291 pint_t returnAddress;
2292
2293 if (isSignalFrame) {
2294 _LIBUNWIND_TRACE_UNWINDING("Possible signal handler frame: lastStack=%p",
2295 reinterpret_cast<void *>(lastStack));
2296
2297 sigcontext *sigContext = reinterpret_cast<sigcontext *>(
2298 reinterpret_cast<char *>(lastStack) + STKMIN);
2299 returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2300
2301 _LIBUNWIND_TRACE_UNWINDING("From sigContext=%p, returnAddress=%p\n",
2302 reinterpret_cast<void *>(sigContext),
2303 reinterpret_cast<void *>(returnAddress));
2304
2305 if (returnAddress < 0x10000000) {
2306 // Try again using STKMINALIGN
2307 sigContext = reinterpret_cast<sigcontext *>(
2308 reinterpret_cast<char *>(lastStack) + STKMINALIGN);
2309 returnAddress = sigContext->sc_jmpbuf.jmp_context.iar;
2310 if (returnAddress < 0x10000000) {
2311 _LIBUNWIND_TRACE_UNWINDING("Bad returnAddress=%p\n",
2312 reinterpret_cast<void *>(returnAddress));
2313 return UNW_EBADFRAME;
2314 } else {
2315 _LIBUNWIND_TRACE_UNWINDING("Tried again using STKMINALIGN: "
2316 "sigContext=%p, returnAddress=%p. "
2317 "Seems to be a valid address\n",
2318 reinterpret_cast<void *>(sigContext),
2319 reinterpret_cast<void *>(returnAddress));
2320 }
2321 }
2322 // Restore the condition register from sigcontext.
2323 newRegisters.setCR(sigContext->sc_jmpbuf.jmp_context.cr);
2324
2325 // Restore GPRs from sigcontext.
2326 for (int i = 0; i < 32; ++i)
2327 newRegisters.setRegister(i, sigContext->sc_jmpbuf.jmp_context.gpr[i]);
2328
2329 // Restore FPRs from sigcontext.
2330 for (int i = 0; i < 32; ++i)
2331 newRegisters.setFloatRegister(i + unwPPCF0Index,
2332 sigContext->sc_jmpbuf.jmp_context.fpr[i]);
2333
2334 // Restore vector registers if there is an associated extended context
2335 // structure.
2336 if (sigContext->sc_jmpbuf.jmp_context.msr & __EXTCTX) {
2337 ucontext_t *uContext = reinterpret_cast<ucontext_t *>(sigContext);
2338 if (uContext->__extctx->__extctx_magic == __EXTCTX_MAGIC) {
2339 for (int i = 0; i < 32; ++i)
2340 newRegisters.setVectorRegister(
2341 i + unwPPCV0Index, *(reinterpret_cast<v128 *>(
2342 &(uContext->__extctx->__vmx.__vr[i]))));
2343 }
2344 }
2345 } else {
2346 // Step up a normal frame.
2347 returnAddress = reinterpret_cast<pint_t *>(lastStack)[2];
2348
2349 _LIBUNWIND_TRACE_UNWINDING("Extract info from lastStack=%p, "
2350 "returnAddress=%p\n",
2351 reinterpret_cast<void *>(lastStack),
2352 reinterpret_cast<void *>(returnAddress));
2353 _LIBUNWIND_TRACE_UNWINDING("fpr_regs=%d, gpr_regs=%d, saves_cr=%d\n",
2354 TBTable->tb.fpr_saved, TBTable->tb.gpr_saved,
2355 TBTable->tb.saves_cr);
2356
2357 // Restore FP registers.
2358 char *ptrToRegs = reinterpret_cast<char *>(lastStack);
2359 double *FPRegs = reinterpret_cast<double *>(
2360 ptrToRegs - (TBTable->tb.fpr_saved * sizeof(double)));
2361 for (int i = 0; i < TBTable->tb.fpr_saved; ++i)
2362 newRegisters.setFloatRegister(
2363 32 - TBTable->tb.fpr_saved + i + unwPPCF0Index, FPRegs[i]);
2364
2365 // Restore GP registers.
2366 ptrToRegs = reinterpret_cast<char *>(FPRegs);
2367 uintptr_t *GPRegs = reinterpret_cast<uintptr_t *>(
2368 ptrToRegs - (TBTable->tb.gpr_saved * sizeof(uintptr_t)));
2369 for (int i = 0; i < TBTable->tb.gpr_saved; ++i)
2370 newRegisters.setRegister(32 - TBTable->tb.gpr_saved + i, GPRegs[i]);
2371
2372 // Restore Vector registers.
2373 ptrToRegs = reinterpret_cast<char *>(GPRegs);
2374
2375 // Restore vector registers only if this is a Clang frame. Also
2376 // check if traceback table bit has_vec is set. If it is, structure
2377 // vec_ext is available.
2378 if (_info.flags == frameType::frameWithEHInfo && TBTable->tb.has_vec) {
2379
2380 // Get to the vec_ext structure to check if vector registers are saved.
2381 uint32_t *p = reinterpret_cast<uint32_t *>(&TBTable->tb_ext);
2382
2383 // Skip field parminfo if exists.
2384 if (TBTable->tb.fixedparms || TBTable->tb.floatparms)
2385 ++p;
2386
2387 // Skip field tb_offset if exists.
2388 if (TBTable->tb.has_tboff)
2389 ++p;
2390
2391 // Skip field hand_mask if exists.
2392 if (TBTable->tb.int_hndl)
2393 ++p;
2394
2395 // Skip fields ctl_info and ctl_info_disp if exist.
2396 if (TBTable->tb.has_ctl) {
2397 // Skip field ctl_info.
2398 ++p;
2399 // Skip field ctl_info_disp.
2400 ++p;
2401 }
2402
2403 // Skip fields name_len and name if exist.
2404 // p is supposed to point to field name_len now.
2405 uint8_t *charPtr = reinterpret_cast<uint8_t *>(p);
2406 if (TBTable->tb.name_present) {
2407 const uint16_t name_len = *(reinterpret_cast<uint16_t *>(charPtr));
2408 charPtr = charPtr + name_len + sizeof(uint16_t);
2409 }
2410
2411 // Skip field alloc_reg if it exists.
2412 if (TBTable->tb.uses_alloca)
2413 ++charPtr;
2414
2415 struct vec_ext *vec_ext = reinterpret_cast<struct vec_ext *>(charPtr);
2416
2417 _LIBUNWIND_TRACE_UNWINDING("vr_saved=%d\n", vec_ext->vr_saved);
2418
2419 // Restore vector register(s) if saved on the stack.
2420 if (vec_ext->vr_saved) {
2421 // Saved vector registers are 16-byte aligned.
2422 if (reinterpret_cast<uintptr_t>(ptrToRegs) % 16)
2423 ptrToRegs -= reinterpret_cast<uintptr_t>(ptrToRegs) % 16;
2424 v128 *VecRegs = reinterpret_cast<v128 *>(ptrToRegs - vec_ext->vr_saved *
2425 sizeof(v128));
2426 for (int i = 0; i < vec_ext->vr_saved; ++i) {
2427 newRegisters.setVectorRegister(
2428 32 - vec_ext->vr_saved + i + unwPPCV0Index, VecRegs[i]);
2429 }
2430 }
2431 }
2432 if (TBTable->tb.saves_cr) {
2433 // Get the saved condition register. The condition register is only
2434 // a single word.
2435 newRegisters.setCR(
2436 *(reinterpret_cast<uint32_t *>(lastStack + sizeof(uintptr_t))));
2437 }
2438
2439 // Restore the SP.
2440 newRegisters.setSP(lastStack);
2441
2442 // The first instruction after return.
2443 uint32_t firstInstruction = *(reinterpret_cast<uint32_t *>(returnAddress));
2444
2445 // Do we need to set the TOC register?
2446 _LIBUNWIND_TRACE_UNWINDING(
2447 "Current gpr2=%p\n",
2448 reinterpret_cast<void *>(newRegisters.getRegister(2)));
2449 if (firstInstruction == loadTOCRegInst) {
2450 _LIBUNWIND_TRACE_UNWINDING(
2451 "Set gpr2=%p from frame\n",
2452 reinterpret_cast<void *>(reinterpret_cast<pint_t *>(lastStack)[5]));
2453 newRegisters.setRegister(2, reinterpret_cast<pint_t *>(lastStack)[5]);
2454 }
2455 }
2456 _LIBUNWIND_TRACE_UNWINDING("lastStack=%p, returnAddress=%p, pc=%p\n",
2457 reinterpret_cast<void *>(lastStack),
2458 reinterpret_cast<void *>(returnAddress),
2459 reinterpret_cast<void *>(pc));
2460
2461 // The return address is the address after call site instruction, so
Gabriel Ravier42aa6de2022-08-20 18:09:03 -07002462 // setting IP to that simulates a return.
Xing Xuebbcbce92022-04-13 11:01:59 -04002463 newRegisters.setIP(reinterpret_cast<uintptr_t>(returnAddress));
2464
2465 // Simulate the step by replacing the register set with the new ones.
2466 registers = newRegisters;
2467
2468 // Check if the next frame is a signal frame.
2469 pint_t nextStack = *(reinterpret_cast<pint_t *>(registers.getSP()));
2470
2471 // Return address is the address after call site instruction.
2472 pint_t nextReturnAddress = reinterpret_cast<pint_t *>(nextStack)[2];
2473
2474 if (nextReturnAddress > 0x01 && nextReturnAddress < 0x10000) {
2475 _LIBUNWIND_TRACE_UNWINDING("The next is a signal handler frame: "
2476 "nextStack=%p, next return address=%p\n",
2477 reinterpret_cast<void *>(nextStack),
2478 reinterpret_cast<void *>(nextReturnAddress));
2479 isSignalFrame = true;
2480 } else {
2481 isSignalFrame = false;
2482 }
2483
2484 return UNW_STEP_SUCCESS;
2485}
2486#endif // defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
Charles Davisfa2e6202018-08-30 21:29:00 +00002487
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002488template <typename A, typename R>
2489void UnwindCursor<A, R>::setInfoBasedOnIPRegister(bool isReturnAddress) {
Shoaib Meenai67bace72022-05-23 22:11:34 -07002490#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002491 _isSigReturn = false;
2492#endif
2493
2494 pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
Ranjeet Singh421231a2017-03-31 15:28:06 +00002495#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002496 // Remove the thumb bit so the IP represents the actual instruction address.
2497 // This matches the behaviour of _Unwind_GetIP on arm.
2498 pc &= (pint_t)~0x1;
2499#endif
2500
Sterling Augustinec100c4d2020-03-30 15:20:26 -07002501 // Exit early if at the top of the stack.
2502 if (pc == 0) {
2503 _unwindInfoMissing = true;
2504 return;
2505 }
2506
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002507 // If the last line of a function is a "throw" the compiler sometimes
2508 // emits no instructions after the call to __cxa_throw. This means
2509 // the return address is actually the start of the next function.
2510 // To disambiguate this, back up the pc when we know it is a return
2511 // address.
2512 if (isReturnAddress)
Xing Xuebbcbce92022-04-13 11:01:59 -04002513#if defined(_AIX)
2514 // PC needs to be a 4-byte aligned address to be able to look for a
2515 // word of 0 that indicates the start of the traceback table at the end
2516 // of a function on AIX.
2517 pc -= 4;
2518#else
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002519 --pc;
Xing Xuebbcbce92022-04-13 11:01:59 -04002520#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002521
2522 // Ask address space object to find unwind sections for this pc.
2523 UnwindInfoSections sects;
2524 if (_addressSpace.findUnwindSections(pc, sects)) {
Ranjeet Singh421231a2017-03-31 15:28:06 +00002525#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002526 // If there is a compact unwind encoding table, look there first.
2527 if (sects.compact_unwind_section != 0) {
2528 if (this->getInfoFromCompactEncodingSection(pc, sects)) {
Ranjeet Singh421231a2017-03-31 15:28:06 +00002529 #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002530 // Found info in table, done unless encoding says to use dwarf.
2531 uint32_t dwarfOffset;
2532 if ((sects.dwarf_section != 0) && compactSaysUseDwarf(&dwarfOffset)) {
2533 if (this->getInfoFromDwarfSection(pc, sects, dwarfOffset)) {
2534 // found info in dwarf, done
2535 return;
2536 }
2537 }
2538 #endif
2539 // If unwind table has entry, but entry says there is no unwind info,
2540 // record that we have no unwind info.
2541 if (_info.format == 0)
2542 _unwindInfoMissing = true;
2543 return;
2544 }
2545 }
Ranjeet Singh421231a2017-03-31 15:28:06 +00002546#endif // defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002547
Charles Davisfa2e6202018-08-30 21:29:00 +00002548#if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
2549 // If there is SEH unwind info, look there next.
2550 if (this->getInfoFromSEH(pc))
2551 return;
2552#endif
2553
Xing Xuebbcbce92022-04-13 11:01:59 -04002554#if defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2555 // If there is unwind info in the traceback table, look there next.
2556 if (this->getInfoFromTBTable(pc, _registers))
2557 return;
2558#endif
2559
Ranjeet Singh421231a2017-03-31 15:28:06 +00002560#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002561 // If there is dwarf unwind info, look there next.
2562 if (sects.dwarf_section != 0) {
2563 if (this->getInfoFromDwarfSection(pc, sects)) {
2564 // found info in dwarf, done
2565 return;
2566 }
2567 }
2568#endif
2569
Ranjeet Singh421231a2017-03-31 15:28:06 +00002570#if defined(_LIBUNWIND_ARM_EHABI)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002571 // If there is ARM EHABI unwind info, look there next.
2572 if (sects.arm_section != 0 && this->getInfoFromEHABISection(pc, sects))
2573 return;
2574#endif
2575 }
2576
Ranjeet Singh421231a2017-03-31 15:28:06 +00002577#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002578 // There is no static unwind info for this pc. Look to see if an FDE was
2579 // dynamically registered for it.
Ryan Prichard2cfcb8c2020-09-09 15:43:35 -07002580 pint_t cachedFDE = DwarfFDECache<A>::findFDE(DwarfFDECache<A>::kSearchAll,
2581 pc);
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002582 if (cachedFDE != 0) {
Ryan Prichard1ae2b942020-08-18 02:31:38 -07002583 typename CFI_Parser<A>::FDE_Info fdeInfo;
2584 typename CFI_Parser<A>::CIE_Info cieInfo;
2585 if (!CFI_Parser<A>::decodeFDE(_addressSpace, cachedFDE, &fdeInfo, &cieInfo))
2586 if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002587 return;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002588 }
2589
2590 // Lastly, ask AddressSpace object about platform specific ways to locate
2591 // other FDEs.
2592 pint_t fde;
2593 if (_addressSpace.findOtherFDE(pc, fde)) {
Ryan Prichard1ae2b942020-08-18 02:31:38 -07002594 typename CFI_Parser<A>::FDE_Info fdeInfo;
2595 typename CFI_Parser<A>::CIE_Info cieInfo;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002596 if (!CFI_Parser<A>::decodeFDE(_addressSpace, fde, &fdeInfo, &cieInfo)) {
2597 // Double check this FDE is for a function that includes the pc.
Ryan Prichard1ae2b942020-08-18 02:31:38 -07002598 if ((fdeInfo.pcStart <= pc) && (pc < fdeInfo.pcEnd))
2599 if (getInfoFromFdeCie(fdeInfo, cieInfo, pc, 0))
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002600 return;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002601 }
2602 }
Ranjeet Singh421231a2017-03-31 15:28:06 +00002603#endif // #if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002604
Shoaib Meenai67bace72022-05-23 22:11:34 -07002605#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002606 if (setInfoForSigReturn())
2607 return;
2608#endif
2609
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002610 // no unwind info, flag that we can't reliably unwind
2611 _unwindInfoMissing = true;
2612}
2613
Shoaib Meenai67bace72022-05-23 22:11:34 -07002614#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) && \
2615 defined(_LIBUNWIND_TARGET_AARCH64)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002616template <typename A, typename R>
2617bool UnwindCursor<A, R>::setInfoForSigReturn(Registers_arm64 &) {
2618 // Look for the sigreturn trampoline. The trampoline's body is two
2619 // specific instructions (see below). Typically the trampoline comes from the
2620 // vDSO[1] (i.e. the __kernel_rt_sigreturn function). A libc might provide its
2621 // own restorer function, though, or user-mode QEMU might write a trampoline
2622 // onto the stack.
2623 //
2624 // This special code path is a fallback that is only used if the trampoline
2625 // lacks proper (e.g. DWARF) unwind info. On AArch64, a new DWARF register
2626 // constant for the PC needs to be defined before DWARF can handle a signal
2627 // trampoline. This code may segfault if the target PC is unreadable, e.g.:
2628 // - The PC points at a function compiled without unwind info, and which is
2629 // part of an execute-only mapping (e.g. using -Wl,--execute-only).
2630 // - The PC is invalid and happens to point to unreadable or unmapped memory.
2631 //
2632 // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/vdso/sigreturn.S
2633 const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
Shoaib Meenai8c606b02022-05-25 21:39:12 -07002634 // The PC might contain an invalid address if the unwind info is bad, so
2635 // directly accessing it could cause a segfault. Use process_vm_readv to read
2636 // the memory safely instead. process_vm_readv was added in Linux 3.2, and
2637 // AArch64 supported was added in Linux 3.7, so the syscall is guaranteed to
2638 // be present. Unfortunately, there are Linux AArch64 environments where the
2639 // libc wrapper for the syscall might not be present (e.g. Android 5), so call
2640 // the syscall directly instead.
2641 uint32_t instructions[2];
2642 struct iovec local_iov = {&instructions, sizeof instructions};
2643 struct iovec remote_iov = {reinterpret_cast<void *>(pc), sizeof instructions};
2644 long bytesRead =
2645 syscall(SYS_process_vm_readv, getpid(), &local_iov, 1, &remote_iov, 1, 0);
Ryan Pricharda684bed2021-01-13 16:38:36 -08002646 // Look for instructions: mov x8, #0x8b; svc #0x0
Shoaib Meenai8c606b02022-05-25 21:39:12 -07002647 if (bytesRead != sizeof instructions || instructions[0] != 0xd2801168 ||
2648 instructions[1] != 0xd4000001)
2649 return false;
2650
2651 _info = {};
2652 _info.start_ip = pc;
2653 _info.end_ip = pc + 4;
2654 _isSigReturn = true;
2655 return true;
Ryan Pricharda684bed2021-01-13 16:38:36 -08002656}
2657
2658template <typename A, typename R>
2659int UnwindCursor<A, R>::stepThroughSigReturn(Registers_arm64 &) {
2660 // In the signal trampoline frame, sp points to an rt_sigframe[1], which is:
2661 // - 128-byte siginfo struct
2662 // - ucontext struct:
2663 // - 8-byte long (uc_flags)
2664 // - 8-byte pointer (uc_link)
2665 // - 24-byte stack_t
2666 // - 128-byte signal set
2667 // - 8 bytes of padding because sigcontext has 16-byte alignment
2668 // - sigcontext/mcontext_t
2669 // [1] https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/signal.c
2670 const pint_t kOffsetSpToSigcontext = (128 + 8 + 8 + 24 + 128 + 8); // 304
2671
2672 // Offsets from sigcontext to each register.
2673 const pint_t kOffsetGprs = 8; // offset to "__u64 regs[31]" field
2674 const pint_t kOffsetSp = 256; // offset to "__u64 sp" field
2675 const pint_t kOffsetPc = 264; // offset to "__u64 pc" field
2676
2677 pint_t sigctx = _registers.getSP() + kOffsetSpToSigcontext;
2678
2679 for (int i = 0; i <= 30; ++i) {
2680 uint64_t value = _addressSpace.get64(sigctx + kOffsetGprs +
2681 static_cast<pint_t>(i * 8));
Fangrui Song5f263002021-08-20 14:26:27 -07002682 _registers.setRegister(UNW_AARCH64_X0 + i, value);
Ryan Pricharda684bed2021-01-13 16:38:36 -08002683 }
2684 _registers.setSP(_addressSpace.get64(sigctx + kOffsetSp));
2685 _registers.setIP(_addressSpace.get64(sigctx + kOffsetPc));
2686 _isSignalFrame = true;
2687 return UNW_STEP_SUCCESS;
2688}
Shoaib Meenai67bace72022-05-23 22:11:34 -07002689#endif // defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) &&
2690 // defined(_LIBUNWIND_TARGET_AARCH64)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002691
Shoaib Meenai67bace72022-05-23 22:11:34 -07002692#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) && \
2693 defined(_LIBUNWIND_TARGET_S390X)
Ulrich Weigandf1108b62022-05-04 10:43:11 +02002694template <typename A, typename R>
2695bool UnwindCursor<A, R>::setInfoForSigReturn(Registers_s390x &) {
2696 // Look for the sigreturn trampoline. The trampoline's body is a
2697 // specific instruction (see below). Typically the trampoline comes from the
2698 // vDSO (i.e. the __kernel_[rt_]sigreturn function). A libc might provide its
2699 // own restorer function, though, or user-mode QEMU might write a trampoline
2700 // onto the stack.
2701 const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
Ulrich Weigand955e2ff2022-07-18 16:54:48 +02002702 // The PC might contain an invalid address if the unwind info is bad, so
2703 // directly accessing it could cause a segfault. Use process_vm_readv to
2704 // read the memory safely instead.
2705 uint16_t inst;
2706 struct iovec local_iov = {&inst, sizeof inst};
2707 struct iovec remote_iov = {reinterpret_cast<void *>(pc), sizeof inst};
2708 long bytesRead = process_vm_readv(getpid(), &local_iov, 1, &remote_iov, 1, 0);
2709 if (bytesRead == sizeof inst && (inst == 0x0a77 || inst == 0x0aad)) {
Ulrich Weigandf1108b62022-05-04 10:43:11 +02002710 _info = {};
2711 _info.start_ip = pc;
2712 _info.end_ip = pc + 2;
2713 _isSigReturn = true;
2714 return true;
2715 }
2716 return false;
2717}
2718
2719template <typename A, typename R>
2720int UnwindCursor<A, R>::stepThroughSigReturn(Registers_s390x &) {
2721 // Determine current SP.
2722 const pint_t sp = static_cast<pint_t>(this->getReg(UNW_REG_SP));
2723 // According to the s390x ABI, the CFA is at (incoming) SP + 160.
2724 const pint_t cfa = sp + 160;
2725
2726 // Determine current PC and instruction there (this must be either
2727 // a "svc __NR_sigreturn" or "svc __NR_rt_sigreturn").
2728 const pint_t pc = static_cast<pint_t>(this->getReg(UNW_REG_IP));
2729 const uint16_t inst = _addressSpace.get16(pc);
2730
2731 // Find the addresses of the signo and sigcontext in the frame.
2732 pint_t pSigctx = 0;
2733 pint_t pSigno = 0;
2734
2735 // "svc __NR_sigreturn" uses a non-RT signal trampoline frame.
2736 if (inst == 0x0a77) {
2737 // Layout of a non-RT signal trampoline frame, starting at the CFA:
2738 // - 8-byte signal mask
2739 // - 8-byte pointer to sigcontext, followed by signo
2740 // - 4-byte signo
2741 pSigctx = _addressSpace.get64(cfa + 8);
2742 pSigno = pSigctx + 344;
2743 }
2744
2745 // "svc __NR_rt_sigreturn" uses a RT signal trampoline frame.
2746 if (inst == 0x0aad) {
2747 // Layout of a RT signal trampoline frame, starting at the CFA:
2748 // - 8-byte retcode (+ alignment)
2749 // - 128-byte siginfo struct (starts with signo)
2750 // - ucontext struct:
2751 // - 8-byte long (uc_flags)
2752 // - 8-byte pointer (uc_link)
2753 // - 24-byte stack_t
2754 // - 8 bytes of padding because sigcontext has 16-byte alignment
2755 // - sigcontext/mcontext_t
2756 pSigctx = cfa + 8 + 128 + 8 + 8 + 24 + 8;
2757 pSigno = cfa + 8;
2758 }
2759
2760 assert(pSigctx != 0);
2761 assert(pSigno != 0);
2762
2763 // Offsets from sigcontext to each register.
2764 const pint_t kOffsetPc = 8;
2765 const pint_t kOffsetGprs = 16;
2766 const pint_t kOffsetFprs = 216;
2767
2768 // Restore all registers.
2769 for (int i = 0; i < 16; ++i) {
2770 uint64_t value = _addressSpace.get64(pSigctx + kOffsetGprs +
2771 static_cast<pint_t>(i * 8));
2772 _registers.setRegister(UNW_S390X_R0 + i, value);
2773 }
2774 for (int i = 0; i < 16; ++i) {
2775 static const int fpr[16] = {
2776 UNW_S390X_F0, UNW_S390X_F1, UNW_S390X_F2, UNW_S390X_F3,
2777 UNW_S390X_F4, UNW_S390X_F5, UNW_S390X_F6, UNW_S390X_F7,
2778 UNW_S390X_F8, UNW_S390X_F9, UNW_S390X_F10, UNW_S390X_F11,
2779 UNW_S390X_F12, UNW_S390X_F13, UNW_S390X_F14, UNW_S390X_F15
2780 };
2781 double value = _addressSpace.getDouble(pSigctx + kOffsetFprs +
2782 static_cast<pint_t>(i * 8));
2783 _registers.setFloatRegister(fpr[i], value);
2784 }
2785 _registers.setIP(_addressSpace.get64(pSigctx + kOffsetPc));
2786
2787 // SIGILL, SIGFPE and SIGTRAP are delivered with psw_addr
2788 // after the faulting instruction rather than before it.
2789 // Do not set _isSignalFrame in that case.
2790 uint32_t signo = _addressSpace.get32(pSigno);
2791 _isSignalFrame = (signo != 4 && signo != 5 && signo != 8);
2792
2793 return UNW_STEP_SUCCESS;
2794}
Shoaib Meenai67bace72022-05-23 22:11:34 -07002795#endif // defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) &&
2796 // defined(_LIBUNWIND_TARGET_S390X)
Ulrich Weigandf1108b62022-05-04 10:43:11 +02002797
Florian Mayer7ff728a2022-06-03 14:33:08 -07002798template <typename A, typename R> int UnwindCursor<A, R>::step(bool stage2) {
2799 (void)stage2;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002800 // Bottom of stack is defined is when unwind info cannot be found.
2801 if (_unwindInfoMissing)
2802 return UNW_STEP_END;
2803
2804 // Use unwinding info to modify register set as if function returned.
2805 int result;
Shoaib Meenai67bace72022-05-23 22:11:34 -07002806#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002807 if (_isSigReturn) {
2808 result = this->stepThroughSigReturn();
2809 } else
2810#endif
2811 {
Ranjeet Singh421231a2017-03-31 15:28:06 +00002812#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
Florian Mayer7ff728a2022-06-03 14:33:08 -07002813 result = this->stepWithCompactEncoding(stage2);
Charles Davisfa2e6202018-08-30 21:29:00 +00002814#elif defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002815 result = this->stepWithSEHData();
Xing Xuebbcbce92022-04-13 11:01:59 -04002816#elif defined(_LIBUNWIND_SUPPORT_TBTAB_UNWIND)
2817 result = this->stepWithTBTableData();
Ranjeet Singh421231a2017-03-31 15:28:06 +00002818#elif defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
Florian Mayer7ff728a2022-06-03 14:33:08 -07002819 result = this->stepWithDwarfFDE(stage2);
Ranjeet Singh421231a2017-03-31 15:28:06 +00002820#elif defined(_LIBUNWIND_ARM_EHABI)
Ryan Pricharda684bed2021-01-13 16:38:36 -08002821 result = this->stepWithEHABI();
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002822#else
2823 #error Need _LIBUNWIND_SUPPORT_COMPACT_UNWIND or \
Charles Davisfa2e6202018-08-30 21:29:00 +00002824 _LIBUNWIND_SUPPORT_SEH_UNWIND or \
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002825 _LIBUNWIND_SUPPORT_DWARF_UNWIND or \
Logan Chien06b0c7a2015-07-19 15:23:10 +00002826 _LIBUNWIND_ARM_EHABI
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002827#endif
Ryan Pricharda684bed2021-01-13 16:38:36 -08002828 }
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002829
2830 // update info based on new PC
2831 if (result == UNW_STEP_SUCCESS) {
2832 this->setInfoBasedOnIPRegister(true);
2833 if (_unwindInfoMissing)
2834 return UNW_STEP_END;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002835 }
2836
2837 return result;
2838}
2839
2840template <typename A, typename R>
2841void UnwindCursor<A, R>::getInfo(unw_proc_info_t *info) {
Saleem Abdulrasool78b42cc2019-09-20 15:53:42 +00002842 if (_unwindInfoMissing)
2843 memset(info, 0, sizeof(*info));
2844 else
2845 *info = _info;
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002846}
2847
2848template <typename A, typename R>
2849bool UnwindCursor<A, R>::getFunctionName(char *buf, size_t bufLen,
2850 unw_word_t *offset) {
2851 return _addressSpace.findFunctionName((pint_t)this->getReg(UNW_REG_IP),
2852 buf, bufLen, offset);
2853}
2854
gejin7f493162021-08-26 16:20:38 +08002855#if defined(_LIBUNWIND_USE_CET)
2856extern "C" void *__libunwind_cet_get_registers(unw_cursor_t *cursor) {
2857 AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
2858 return co->get_registers();
2859}
2860#endif
Saleem Abdulrasool17552662015-04-24 19:39:17 +00002861} // namespace libunwind
2862
2863#endif // __UNWINDCURSOR_HPP__