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