• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2017 The Abseil Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// Produce stack trace
16
17#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_
18#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_
19
20#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
21#include <ucontext.h>  // for ucontext_t
22#endif
23
24#if !defined(_WIN32)
25#include <unistd.h>
26#endif
27
28#include <cassert>
29#include <cstdint>
30#include <limits>
31
32#include "absl/base/macros.h"
33#include "absl/base/port.h"
34#include "absl/debugging/internal/address_is_readable.h"
35#include "absl/debugging/internal/vdso_support.h"  // a no-op on non-elf or non-glibc systems
36#include "absl/debugging/stacktrace.h"
37
38#include "absl/base/internal/raw_logging.h"
39
40using absl::debugging_internal::AddressIsReadable;
41
42#if defined(__linux__) && defined(__i386__)
43// Count "push %reg" instructions in VDSO __kernel_vsyscall(),
44// preceeding "syscall" or "sysenter".
45// If __kernel_vsyscall uses frame pointer, answer 0.
46//
47// kMaxBytes tells how many instruction bytes of __kernel_vsyscall
48// to analyze before giving up. Up to kMaxBytes+1 bytes of
49// instructions could be accessed.
50//
51// Here are known __kernel_vsyscall instruction sequences:
52//
53// SYSENTER (linux-2.6.26/arch/x86/vdso/vdso32/sysenter.S).
54// Used on Intel.
55//  0xffffe400 <__kernel_vsyscall+0>:       push   %ecx
56//  0xffffe401 <__kernel_vsyscall+1>:       push   %edx
57//  0xffffe402 <__kernel_vsyscall+2>:       push   %ebp
58//  0xffffe403 <__kernel_vsyscall+3>:       mov    %esp,%ebp
59//  0xffffe405 <__kernel_vsyscall+5>:       sysenter
60//
61// SYSCALL (see linux-2.6.26/arch/x86/vdso/vdso32/syscall.S).
62// Used on AMD.
63//  0xffffe400 <__kernel_vsyscall+0>:       push   %ebp
64//  0xffffe401 <__kernel_vsyscall+1>:       mov    %ecx,%ebp
65//  0xffffe403 <__kernel_vsyscall+3>:       syscall
66//
67
68// The sequence below isn't actually expected in Google fleet,
69// here only for completeness. Remove this comment from OSS release.
70
71// i386 (see linux-2.6.26/arch/x86/vdso/vdso32/int80.S)
72//  0xffffe400 <__kernel_vsyscall+0>:       int $0x80
73//  0xffffe401 <__kernel_vsyscall+1>:       ret
74//
75static const int kMaxBytes = 10;
76
77// We use assert()s instead of DCHECK()s -- this is too low level
78// for DCHECK().
79
80static int CountPushInstructions(const unsigned char *const addr) {
81  int result = 0;
82  for (int i = 0; i < kMaxBytes; ++i) {
83    if (addr[i] == 0x89) {
84      // "mov reg,reg"
85      if (addr[i + 1] == 0xE5) {
86        // Found "mov %esp,%ebp".
87        return 0;
88      }
89      ++i;  // Skip register encoding byte.
90    } else if (addr[i] == 0x0F &&
91               (addr[i + 1] == 0x34 || addr[i + 1] == 0x05)) {
92      // Found "sysenter" or "syscall".
93      return result;
94    } else if ((addr[i] & 0xF0) == 0x50) {
95      // Found "push %reg".
96      ++result;
97    } else if (addr[i] == 0xCD && addr[i + 1] == 0x80) {
98      // Found "int $0x80"
99      assert(result == 0);
100      return 0;
101    } else {
102      // Unexpected instruction.
103      assert(false && "unexpected instruction in __kernel_vsyscall");
104      return 0;
105    }
106  }
107  // Unexpected: didn't find SYSENTER or SYSCALL in
108  // [__kernel_vsyscall, __kernel_vsyscall + kMaxBytes) interval.
109  assert(false && "did not find SYSENTER or SYSCALL in __kernel_vsyscall");
110  return 0;
111}
112#endif
113
114// Assume stack frames larger than 100,000 bytes are bogus.
115static const int kMaxFrameBytes = 100000;
116
117// Returns the stack frame pointer from signal context, 0 if unknown.
118// vuc is a ucontext_t *.  We use void* to avoid the use
119// of ucontext_t on non-POSIX systems.
120static uintptr_t GetFP(const void *vuc) {
121#if !defined(__linux__)
122  static_cast<void>(vuc);  // Avoid an unused argument compiler warning.
123#else
124  if (vuc != nullptr) {
125    auto *uc = reinterpret_cast<const ucontext_t *>(vuc);
126#if defined(__i386__)
127    const auto bp = uc->uc_mcontext.gregs[REG_EBP];
128    const auto sp = uc->uc_mcontext.gregs[REG_ESP];
129#elif defined(__x86_64__)
130    const auto bp = uc->uc_mcontext.gregs[REG_RBP];
131    const auto sp = uc->uc_mcontext.gregs[REG_RSP];
132#else
133    const uintptr_t bp = 0;
134    const uintptr_t sp = 0;
135#endif
136    // Sanity-check that the base pointer is valid. It's possible that some
137    // code in the process is compiled with --copt=-fomit-frame-pointer or
138    // --copt=-momit-leaf-frame-pointer.
139    //
140    // TODO(bcmills): -momit-leaf-frame-pointer is currently the default
141    // behavior when building with clang.  Talk to the C++ toolchain team about
142    // fixing that.
143    if (bp >= sp && bp - sp <= kMaxFrameBytes) return bp;
144
145    // If bp isn't a plausible frame pointer, return the stack pointer instead.
146    // If we're lucky, it points to the start of a stack frame; otherwise, we'll
147    // get one frame of garbage in the stack trace and fail the sanity check on
148    // the next iteration.
149    return sp;
150  }
151#endif
152  return 0;
153}
154
155// Given a pointer to a stack frame, locate and return the calling
156// stackframe, or return null if no stackframe can be found. Perform sanity
157// checks (the strictness of which is controlled by the boolean parameter
158// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
159template <bool STRICT_UNWINDING, bool WITH_CONTEXT>
160ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS  // May read random elements from stack.
161ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY   // May read random elements from stack.
162static void **NextStackFrame(void **old_fp, const void *uc,
163                             size_t stack_low, size_t stack_high) {
164  void **new_fp = (void **)*old_fp;
165
166#if defined(__linux__) && defined(__i386__)
167  if (WITH_CONTEXT && uc != nullptr) {
168    // How many "push %reg" instructions are there at __kernel_vsyscall?
169    // This is constant for a given kernel and processor, so compute
170    // it only once.
171    static int num_push_instructions = -1;  // Sentinel: not computed yet.
172    // Initialize with sentinel value: __kernel_rt_sigreturn can not possibly
173    // be there.
174    static const unsigned char *kernel_rt_sigreturn_address = nullptr;
175    static const unsigned char *kernel_vsyscall_address = nullptr;
176    if (num_push_instructions == -1) {
177#ifdef ABSL_HAVE_VDSO_SUPPORT
178      absl::debugging_internal::VDSOSupport vdso;
179      if (vdso.IsPresent()) {
180        absl::debugging_internal::VDSOSupport::SymbolInfo
181            rt_sigreturn_symbol_info;
182        absl::debugging_internal::VDSOSupport::SymbolInfo vsyscall_symbol_info;
183        if (!vdso.LookupSymbol("__kernel_rt_sigreturn", "LINUX_2.5", STT_FUNC,
184                               &rt_sigreturn_symbol_info) ||
185            !vdso.LookupSymbol("__kernel_vsyscall", "LINUX_2.5", STT_FUNC,
186                               &vsyscall_symbol_info) ||
187            rt_sigreturn_symbol_info.address == nullptr ||
188            vsyscall_symbol_info.address == nullptr) {
189          // Unexpected: 32-bit VDSO is present, yet one of the expected
190          // symbols is missing or null.
191          assert(false && "VDSO is present, but doesn't have expected symbols");
192          num_push_instructions = 0;
193        } else {
194          kernel_rt_sigreturn_address =
195              reinterpret_cast<const unsigned char *>(
196                  rt_sigreturn_symbol_info.address);
197          kernel_vsyscall_address =
198              reinterpret_cast<const unsigned char *>(
199                  vsyscall_symbol_info.address);
200          num_push_instructions =
201              CountPushInstructions(kernel_vsyscall_address);
202        }
203      } else {
204        num_push_instructions = 0;
205      }
206#else  // ABSL_HAVE_VDSO_SUPPORT
207      num_push_instructions = 0;
208#endif  // ABSL_HAVE_VDSO_SUPPORT
209    }
210    if (num_push_instructions != 0 && kernel_rt_sigreturn_address != nullptr &&
211        old_fp[1] == kernel_rt_sigreturn_address) {
212      const ucontext_t *ucv = static_cast<const ucontext_t *>(uc);
213      // This kernel does not use frame pointer in its VDSO code,
214      // and so %ebp is not suitable for unwinding.
215      void **const reg_ebp =
216          reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_EBP]);
217      const unsigned char *const reg_eip =
218          reinterpret_cast<unsigned char *>(ucv->uc_mcontext.gregs[REG_EIP]);
219      if (new_fp == reg_ebp && kernel_vsyscall_address <= reg_eip &&
220          reg_eip - kernel_vsyscall_address < kMaxBytes) {
221        // We "stepped up" to __kernel_vsyscall, but %ebp is not usable.
222        // Restore from 'ucv' instead.
223        void **const reg_esp =
224            reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_ESP]);
225        // Check that alleged %esp is not null and is reasonably aligned.
226        if (reg_esp &&
227            ((uintptr_t)reg_esp & (sizeof(reg_esp) - 1)) == 0) {
228          // Check that alleged %esp is actually readable. This is to prevent
229          // "double fault" in case we hit the first fault due to e.g. stack
230          // corruption.
231          void *const reg_esp2 = reg_esp[num_push_instructions - 1];
232          if (AddressIsReadable(reg_esp2)) {
233            // Alleged %esp is readable, use it for further unwinding.
234            new_fp = reinterpret_cast<void **>(reg_esp2);
235          }
236        }
237      }
238    }
239  }
240#endif
241
242  const uintptr_t old_fp_u = reinterpret_cast<uintptr_t>(old_fp);
243  const uintptr_t new_fp_u = reinterpret_cast<uintptr_t>(new_fp);
244
245  // Check that the transition from frame pointer old_fp to frame
246  // pointer new_fp isn't clearly bogus.  Skip the checks if new_fp
247  // matches the signal context, so that we don't skip out early when
248  // using an alternate signal stack.
249  //
250  // TODO(bcmills): The GetFP call should be completely unnecessary when
251  // ENABLE_COMBINED_UNWINDER is set (because we should be back in the thread's
252  // stack by this point), but it is empirically still needed (e.g. when the
253  // stack includes a call to abort).  unw_get_reg returns UNW_EBADREG for some
254  // frames.  Figure out why GetValidFrameAddr and/or libunwind isn't doing what
255  // it's supposed to.
256  if (STRICT_UNWINDING &&
257      (!WITH_CONTEXT || uc == nullptr || new_fp_u != GetFP(uc))) {
258    // With the stack growing downwards, older stack frame must be
259    // at a greater address that the current one.
260    if (new_fp_u <= old_fp_u) return nullptr;
261    if (new_fp_u - old_fp_u > kMaxFrameBytes) return nullptr;
262
263    if (stack_low < old_fp_u && old_fp_u <= stack_high) {
264      // Old BP was in the expected stack region...
265      if (!(stack_low < new_fp_u && new_fp_u <= stack_high)) {
266        // ... but new BP is outside of expected stack region.
267        // It is most likely bogus.
268        return nullptr;
269      }
270    } else {
271      // We may be here if we are executing in a co-routine with a
272      // separate stack. We can't do safety checks in this case.
273    }
274  } else {
275    if (new_fp == nullptr) return nullptr;  // skip AddressIsReadable() below
276    // In the non-strict mode, allow discontiguous stack frames.
277    // (alternate-signal-stacks for example).
278    if (new_fp == old_fp) return nullptr;
279  }
280
281  if (new_fp_u & (sizeof(void *) - 1)) return nullptr;
282#ifdef __i386__
283  // On 32-bit machines, the stack pointer can be very close to
284  // 0xffffffff, so we explicitly check for a pointer into the
285  // last two pages in the address space
286  if (new_fp_u >= 0xffffe000) return nullptr;
287#endif
288#if !defined(_WIN32)
289  if (!STRICT_UNWINDING) {
290    // Lax sanity checks cause a crash in 32-bit tcmalloc/crash_reason_test
291    // on AMD-based machines with VDSO-enabled kernels.
292    // Make an extra sanity check to insure new_fp is readable.
293    // Note: NextStackFrame<false>() is only called while the program
294    //       is already on its last leg, so it's ok to be slow here.
295
296    if (!AddressIsReadable(new_fp)) {
297      return nullptr;
298    }
299  }
300#endif
301  return new_fp;
302}
303
304template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
305ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS  // May read random elements from stack.
306ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY   // May read random elements from stack.
307ABSL_ATTRIBUTE_NOINLINE
308static int UnwindImpl(void **result, int *sizes, int max_depth, int skip_count,
309                      const void *ucp, int *min_dropped_frames) {
310  int n = 0;
311  void **fp = reinterpret_cast<void **>(__builtin_frame_address(0));
312
313  size_t stack_low = getpagesize();  // Assume that the first page is not stack.
314  size_t stack_high = std::numeric_limits<size_t>::max() - sizeof(void *);
315
316  while (fp && n < max_depth) {
317    if (*(fp + 1) == reinterpret_cast<void *>(0)) {
318      // In 64-bit code, we often see a frame that
319      // points to itself and has a return address of 0.
320      break;
321    }
322    void **next_fp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(
323        fp, ucp, stack_low, stack_high);
324    if (skip_count > 0) {
325      skip_count--;
326    } else {
327      result[n] = *(fp + 1);
328      if (IS_STACK_FRAMES) {
329        if (next_fp > fp) {
330          sizes[n] = (uintptr_t)next_fp - (uintptr_t)fp;
331        } else {
332          // A frame-size of 0 is used to indicate unknown frame size.
333          sizes[n] = 0;
334        }
335      }
336      n++;
337    }
338    fp = next_fp;
339  }
340  if (min_dropped_frames != nullptr) {
341    // Implementation detail: we clamp the max of frames we are willing to
342    // count, so as not to spend too much time in the loop below.
343    const int kMaxUnwind = 1000;
344    int num_dropped_frames = 0;
345    for (int j = 0; fp != nullptr && j < kMaxUnwind; j++) {
346      if (skip_count > 0) {
347        skip_count--;
348      } else {
349        num_dropped_frames++;
350      }
351      fp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(fp, ucp, stack_low,
352                                                             stack_high);
353    }
354    *min_dropped_frames = num_dropped_frames;
355  }
356  return n;
357}
358
359namespace absl {
360ABSL_NAMESPACE_BEGIN
361namespace debugging_internal {
362bool StackTraceWorksForTest() {
363  return true;
364}
365}  // namespace debugging_internal
366ABSL_NAMESPACE_END
367}  // namespace absl
368
369#endif  // ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_
370