• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_AARCH64_INL_H_
2#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_AARCH64_INL_H_
3
4// Generate stack tracer for aarch64
5
6#if defined(__linux__)
7#include <sys/mman.h>
8#include <ucontext.h>
9#include <unistd.h>
10#endif
11
12#include <atomic>
13#include <cassert>
14#include <cstdint>
15#include <iostream>
16
17#include "absl/base/attributes.h"
18#include "absl/debugging/internal/address_is_readable.h"
19#include "absl/debugging/internal/vdso_support.h"  // a no-op on non-elf or non-glibc systems
20#include "absl/debugging/stacktrace.h"
21
22static const size_t kUnknownFrameSize = 0;
23
24#if defined(__linux__)
25// Returns the address of the VDSO __kernel_rt_sigreturn function, if present.
26static const unsigned char* GetKernelRtSigreturnAddress() {
27  constexpr uintptr_t kImpossibleAddress = 1;
28  ABSL_CONST_INIT static std::atomic<uintptr_t> memoized{kImpossibleAddress};
29  uintptr_t address = memoized.load(std::memory_order_relaxed);
30  if (address != kImpossibleAddress) {
31    return reinterpret_cast<const unsigned char*>(address);
32  }
33
34  address = reinterpret_cast<uintptr_t>(nullptr);
35
36#ifdef ABSL_HAVE_VDSO_SUPPORT
37  absl::debugging_internal::VDSOSupport vdso;
38  if (vdso.IsPresent()) {
39    absl::debugging_internal::VDSOSupport::SymbolInfo symbol_info;
40    auto lookup = [&](int type) {
41      return vdso.LookupSymbol("__kernel_rt_sigreturn", "LINUX_2.6.39", type,
42                               &symbol_info);
43    };
44    if ((!lookup(STT_FUNC) && !lookup(STT_NOTYPE)) ||
45        symbol_info.address == nullptr) {
46      // Unexpected: VDSO is present, yet the expected symbol is missing
47      // or null.
48      assert(false && "VDSO is present, but doesn't have expected symbol");
49    } else {
50      if (reinterpret_cast<uintptr_t>(symbol_info.address) !=
51          kImpossibleAddress) {
52        address = reinterpret_cast<uintptr_t>(symbol_info.address);
53      } else {
54        assert(false && "VDSO returned invalid address");
55      }
56    }
57  }
58#endif
59
60  memoized.store(address, std::memory_order_relaxed);
61  return reinterpret_cast<const unsigned char*>(address);
62}
63#endif  // __linux__
64
65// Compute the size of a stack frame in [low..high).  We assume that
66// low < high.  Return size of kUnknownFrameSize.
67template<typename T>
68static inline size_t ComputeStackFrameSize(const T* low,
69                                           const T* high) {
70  const char* low_char_ptr = reinterpret_cast<const char *>(low);
71  const char* high_char_ptr = reinterpret_cast<const char *>(high);
72  return low < high ? static_cast<size_t>(high_char_ptr - low_char_ptr)
73                    : kUnknownFrameSize;
74}
75
76// Given a pointer to a stack frame, locate and return the calling
77// stackframe, or return null if no stackframe can be found. Perform sanity
78// checks (the strictness of which is controlled by the boolean parameter
79// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
80template<bool STRICT_UNWINDING, bool WITH_CONTEXT>
81ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS  // May read random elements from stack.
82ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY   // May read random elements from stack.
83static void **NextStackFrame(void **old_frame_pointer, const void *uc) {
84  void **new_frame_pointer = reinterpret_cast<void**>(*old_frame_pointer);
85  bool check_frame_size = true;
86
87#if defined(__linux__)
88  if (WITH_CONTEXT && uc != nullptr) {
89    // Check to see if next frame's return address is __kernel_rt_sigreturn.
90    if (old_frame_pointer[1] == GetKernelRtSigreturnAddress()) {
91      const ucontext_t *ucv = static_cast<const ucontext_t *>(uc);
92      // old_frame_pointer[0] is not suitable for unwinding, look at
93      // ucontext to discover frame pointer before signal.
94      void **const pre_signal_frame_pointer =
95          reinterpret_cast<void **>(ucv->uc_mcontext.regs[29]);
96
97      // Check that alleged frame pointer is actually readable. This is to
98      // prevent "double fault" in case we hit the first fault due to e.g.
99      // stack corruption.
100      if (!absl::debugging_internal::AddressIsReadable(
101              pre_signal_frame_pointer))
102        return nullptr;
103
104      // Alleged frame pointer is readable, use it for further unwinding.
105      new_frame_pointer = pre_signal_frame_pointer;
106
107      // Skip frame size check if we return from a signal. We may be using a
108      // an alternate stack for signals.
109      check_frame_size = false;
110    }
111  }
112#endif
113
114  // The frame pointer should be 8-byte aligned.
115  if ((reinterpret_cast<uintptr_t>(new_frame_pointer) & 7) != 0)
116    return nullptr;
117
118  // Check frame size.  In strict mode, we assume frames to be under
119  // 100,000 bytes.  In non-strict mode, we relax the limit to 1MB.
120  if (check_frame_size) {
121    const size_t max_size = STRICT_UNWINDING ? 100000 : 1000000;
122    const size_t frame_size =
123        ComputeStackFrameSize(old_frame_pointer, new_frame_pointer);
124    if (frame_size == kUnknownFrameSize || frame_size > max_size)
125      return nullptr;
126  }
127
128  return new_frame_pointer;
129}
130
131template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
132ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS  // May read random elements from stack.
133ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY   // May read random elements from stack.
134static int UnwindImpl(void** result, int* sizes, int max_depth, int skip_count,
135                      const void *ucp, int *min_dropped_frames) {
136#ifdef __GNUC__
137  void **frame_pointer = reinterpret_cast<void**>(__builtin_frame_address(0));
138#else
139# error reading stack point not yet supported on this platform.
140#endif
141
142  skip_count++;    // Skip the frame for this function.
143  int n = 0;
144
145  // The frame pointer points to low address of a frame.  The first 64-bit
146  // word of a frame points to the next frame up the call chain, which normally
147  // is just after the high address of the current frame.  The second word of
148  // a frame contains return adress of to the caller.   To find a pc value
149  // associated with the current frame, we need to go down a level in the call
150  // chain.  So we remember return the address of the last frame seen.  This
151  // does not work for the first stack frame, which belongs to UnwindImp() but
152  // we skip the frame for UnwindImp() anyway.
153  void* prev_return_address = nullptr;
154
155  while (frame_pointer && n < max_depth) {
156    // The absl::GetStackFrames routine is called when we are in some
157    // informational context (the failure signal handler for example).
158    // Use the non-strict unwinding rules to produce a stack trace
159    // that is as complete as possible (even if it contains a few bogus
160    // entries in some rare cases).
161    void **next_frame_pointer =
162        NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(frame_pointer, ucp);
163
164    if (skip_count > 0) {
165      skip_count--;
166    } else {
167      result[n] = prev_return_address;
168      if (IS_STACK_FRAMES) {
169        sizes[n] = static_cast<int>(
170            ComputeStackFrameSize(frame_pointer, next_frame_pointer));
171      }
172      n++;
173    }
174    prev_return_address = frame_pointer[1];
175    frame_pointer = next_frame_pointer;
176  }
177  if (min_dropped_frames != nullptr) {
178    // Implementation detail: we clamp the max of frames we are willing to
179    // count, so as not to spend too much time in the loop below.
180    const int kMaxUnwind = 200;
181    int num_dropped_frames = 0;
182    for (int j = 0; frame_pointer != nullptr && j < kMaxUnwind; j++) {
183      if (skip_count > 0) {
184        skip_count--;
185      } else {
186        num_dropped_frames++;
187      }
188      frame_pointer =
189          NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(frame_pointer, ucp);
190    }
191    *min_dropped_frames = num_dropped_frames;
192  }
193  return n;
194}
195
196namespace absl {
197ABSL_NAMESPACE_BEGIN
198namespace debugging_internal {
199bool StackTraceWorksForTest() {
200  return true;
201}
202}  // namespace debugging_internal
203ABSL_NAMESPACE_END
204}  // namespace absl
205
206#endif  // ABSL_DEBUGGING_INTERNAL_STACKTRACE_AARCH64_INL_H_
207