stacktrace_x86-inl.inc 14 KB

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