stacktrace_x86-inl.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 Y_ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_
  17. #define Y_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 "y_absl/base/attributes.h"
  28. #include "y_absl/base/macros.h"
  29. #include "y_absl/base/port.h"
  30. #include "y_absl/debugging/internal/address_is_readable.h"
  31. #include "y_absl/debugging/internal/vdso_support.h" // a no-op on non-elf or non-glibc systems
  32. #include "y_absl/debugging/stacktrace.h"
  33. using y_absl::debugging_internal::AddressIsReadable;
  34. #if defined(__linux__) && defined(__i386__)
  35. // Count "push %reg" instructions in VDSO __kernel_vsyscall(),
  36. // preceding "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. // Stack end to use when we don't know the actual stack end
  104. // (effectively just the end of address space).
  105. constexpr uintptr_t kUnknownStackEnd =
  106. std::numeric_limits<size_t>::max() - sizeof(void *);
  107. // Returns the stack frame pointer from signal context, 0 if unknown.
  108. // vuc is a ucontext_t *. We use void* to avoid the use
  109. // of ucontext_t on non-POSIX systems.
  110. static uintptr_t GetFP(const void *vuc) {
  111. #if !defined(__linux__)
  112. static_cast<void>(vuc); // Avoid an unused argument compiler warning.
  113. #else
  114. if (vuc != nullptr) {
  115. auto *uc = reinterpret_cast<const ucontext_t *>(vuc);
  116. #if defined(__i386__)
  117. const auto bp = uc->uc_mcontext.gregs[REG_EBP];
  118. const auto sp = uc->uc_mcontext.gregs[REG_ESP];
  119. #elif defined(__x86_64__)
  120. const auto bp = uc->uc_mcontext.gregs[REG_RBP];
  121. const auto sp = uc->uc_mcontext.gregs[REG_RSP];
  122. #else
  123. const uintptr_t bp = 0;
  124. const uintptr_t sp = 0;
  125. #endif
  126. // Sanity-check that the base pointer is valid. It's possible that some
  127. // code in the process is compiled with --copt=-fomit-frame-pointer or
  128. // --copt=-momit-leaf-frame-pointer.
  129. //
  130. // TODO(bcmills): -momit-leaf-frame-pointer is currently the default
  131. // behavior when building with clang. Talk to the C++ toolchain team about
  132. // fixing that.
  133. if (bp >= sp && bp - sp <= kMaxFrameBytes)
  134. return static_cast<uintptr_t>(bp);
  135. // If bp isn't a plausible frame pointer, return the stack pointer instead.
  136. // If we're lucky, it points to the start of a stack frame; otherwise, we'll
  137. // get one frame of garbage in the stack trace and fail the sanity check on
  138. // the next iteration.
  139. return static_cast<uintptr_t>(sp);
  140. }
  141. #endif
  142. return 0;
  143. }
  144. // Given a pointer to a stack frame, locate and return the calling
  145. // stackframe, or return null if no stackframe can be found. Perform sanity
  146. // checks (the strictness of which is controlled by the boolean parameter
  147. // "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
  148. template <bool STRICT_UNWINDING, bool WITH_CONTEXT>
  149. Y_ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
  150. Y_ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
  151. static void **NextStackFrame(void **old_fp, const void *uc,
  152. size_t stack_low, size_t stack_high) {
  153. void **new_fp = (void **)*old_fp;
  154. #if defined(__linux__) && defined(__i386__)
  155. if (WITH_CONTEXT && uc != nullptr) {
  156. // How many "push %reg" instructions are there at __kernel_vsyscall?
  157. // This is constant for a given kernel and processor, so compute
  158. // it only once.
  159. static int num_push_instructions = -1; // Sentinel: not computed yet.
  160. // Initialize with sentinel value: __kernel_rt_sigreturn can not possibly
  161. // be there.
  162. static const unsigned char *kernel_rt_sigreturn_address = nullptr;
  163. static const unsigned char *kernel_vsyscall_address = nullptr;
  164. if (num_push_instructions == -1) {
  165. #ifdef Y_ABSL_HAVE_VDSO_SUPPORT
  166. y_absl::debugging_internal::VDSOSupport vdso;
  167. if (vdso.IsPresent()) {
  168. y_absl::debugging_internal::VDSOSupport::SymbolInfo
  169. rt_sigreturn_symbol_info;
  170. y_absl::debugging_internal::VDSOSupport::SymbolInfo vsyscall_symbol_info;
  171. if (!vdso.LookupSymbol("__kernel_rt_sigreturn", "LINUX_2.5", STT_FUNC,
  172. &rt_sigreturn_symbol_info) ||
  173. !vdso.LookupSymbol("__kernel_vsyscall", "LINUX_2.5", STT_FUNC,
  174. &vsyscall_symbol_info) ||
  175. rt_sigreturn_symbol_info.address == nullptr ||
  176. vsyscall_symbol_info.address == nullptr) {
  177. // Unexpected: 32-bit VDSO is present, yet one of the expected
  178. // symbols is missing or null.
  179. assert(false && "VDSO is present, but doesn't have expected symbols");
  180. num_push_instructions = 0;
  181. } else {
  182. kernel_rt_sigreturn_address =
  183. reinterpret_cast<const unsigned char *>(
  184. rt_sigreturn_symbol_info.address);
  185. kernel_vsyscall_address =
  186. reinterpret_cast<const unsigned char *>(
  187. vsyscall_symbol_info.address);
  188. num_push_instructions =
  189. CountPushInstructions(kernel_vsyscall_address);
  190. }
  191. } else {
  192. num_push_instructions = 0;
  193. }
  194. #else // Y_ABSL_HAVE_VDSO_SUPPORT
  195. num_push_instructions = 0;
  196. #endif // Y_ABSL_HAVE_VDSO_SUPPORT
  197. }
  198. if (num_push_instructions != 0 && kernel_rt_sigreturn_address != nullptr &&
  199. old_fp[1] == kernel_rt_sigreturn_address) {
  200. const ucontext_t *ucv = static_cast<const ucontext_t *>(uc);
  201. // This kernel does not use frame pointer in its VDSO code,
  202. // and so %ebp is not suitable for unwinding.
  203. void **const reg_ebp =
  204. reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_EBP]);
  205. const unsigned char *const reg_eip =
  206. reinterpret_cast<unsigned char *>(ucv->uc_mcontext.gregs[REG_EIP]);
  207. if (new_fp == reg_ebp && kernel_vsyscall_address <= reg_eip &&
  208. reg_eip - kernel_vsyscall_address < kMaxBytes) {
  209. // We "stepped up" to __kernel_vsyscall, but %ebp is not usable.
  210. // Restore from 'ucv' instead.
  211. void **const reg_esp =
  212. reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_ESP]);
  213. // Check that alleged %esp is not null and is reasonably aligned.
  214. if (reg_esp &&
  215. ((uintptr_t)reg_esp & (sizeof(reg_esp) - 1)) == 0) {
  216. // Check that alleged %esp is actually readable. This is to prevent
  217. // "double fault" in case we hit the first fault due to e.g. stack
  218. // corruption.
  219. void *const reg_esp2 = reg_esp[num_push_instructions - 1];
  220. if (AddressIsReadable(reg_esp2)) {
  221. // Alleged %esp is readable, use it for further unwinding.
  222. new_fp = reinterpret_cast<void **>(reg_esp2);
  223. }
  224. }
  225. }
  226. }
  227. }
  228. #endif
  229. const uintptr_t old_fp_u = reinterpret_cast<uintptr_t>(old_fp);
  230. const uintptr_t new_fp_u = reinterpret_cast<uintptr_t>(new_fp);
  231. // Check that the transition from frame pointer old_fp to frame
  232. // pointer new_fp isn't clearly bogus. Skip the checks if new_fp
  233. // matches the signal context, so that we don't skip out early when
  234. // using an alternate signal stack.
  235. //
  236. // TODO(bcmills): The GetFP call should be completely unnecessary when
  237. // ENABLE_COMBINED_UNWINDER is set (because we should be back in the thread's
  238. // stack by this point), but it is empirically still needed (e.g. when the
  239. // stack includes a call to abort). unw_get_reg returns UNW_EBADREG for some
  240. // frames. Figure out why GetValidFrameAddr and/or libunwind isn't doing what
  241. // it's supposed to.
  242. if (STRICT_UNWINDING &&
  243. (!WITH_CONTEXT || uc == nullptr || new_fp_u != GetFP(uc))) {
  244. // With the stack growing downwards, older stack frame must be
  245. // at a greater address that the current one.
  246. if (new_fp_u <= old_fp_u) return nullptr;
  247. // If we get a very large frame size, it may be an indication that we
  248. // guessed frame pointers incorrectly and now risk a paging fault
  249. // dereferencing a wrong frame pointer. Or maybe not because large frames
  250. // are possible as well. The main stack is assumed to be readable,
  251. // so we assume the large frame is legit if we know the real stack bounds
  252. // and are within the stack.
  253. if (new_fp_u - old_fp_u > kMaxFrameBytes) {
  254. if (stack_high < kUnknownStackEnd &&
  255. static_cast<size_t>(getpagesize()) < stack_low) {
  256. // Stack bounds are known.
  257. if (!(stack_low < new_fp_u && new_fp_u <= stack_high)) {
  258. // new_fp_u is not within the known stack.
  259. return nullptr;
  260. }
  261. } else {
  262. // Stack bounds are unknown, prefer truncated stack to possible crash.
  263. return nullptr;
  264. }
  265. }
  266. if (stack_low < old_fp_u && old_fp_u <= stack_high) {
  267. // Old BP was in the expected stack region...
  268. if (!(stack_low < new_fp_u && new_fp_u <= stack_high)) {
  269. // ... but new BP is outside of expected stack region.
  270. // It is most likely bogus.
  271. return nullptr;
  272. }
  273. } else {
  274. // We may be here if we are executing in a co-routine with a
  275. // separate stack. We can't do safety checks in this case.
  276. }
  277. } else {
  278. if (new_fp == nullptr) return nullptr; // skip AddressIsReadable() below
  279. // In the non-strict mode, allow discontiguous stack frames.
  280. // (alternate-signal-stacks for example).
  281. if (new_fp == old_fp) return nullptr;
  282. }
  283. if (new_fp_u & (sizeof(void *) - 1)) return nullptr;
  284. #ifdef __i386__
  285. // On 32-bit machines, the stack pointer can be very close to
  286. // 0xffffffff, so we explicitly check for a pointer into the
  287. // last two pages in the address space
  288. if (new_fp_u >= 0xffffe000) return nullptr;
  289. #endif
  290. #if !defined(_WIN32)
  291. if (!STRICT_UNWINDING) {
  292. // Lax sanity checks cause a crash in 32-bit tcmalloc/crash_reason_test
  293. // on AMD-based machines with VDSO-enabled kernels.
  294. // Make an extra sanity check to insure new_fp is readable.
  295. // Note: NextStackFrame<false>() is only called while the program
  296. // is already on its last leg, so it's ok to be slow here.
  297. if (!AddressIsReadable(new_fp)) {
  298. return nullptr;
  299. }
  300. }
  301. #endif
  302. return new_fp;
  303. }
  304. template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
  305. Y_ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
  306. Y_ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
  307. Y_ABSL_ATTRIBUTE_NOINLINE
  308. static 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. // Assume that the first page is not stack.
  313. size_t stack_low = static_cast<size_t>(getpagesize());
  314. size_t stack_high = kUnknownStackEnd;
  315. while (fp && n < max_depth) {
  316. if (*(fp + 1) == reinterpret_cast<void *>(0)) {
  317. // In 64-bit code, we often see a frame that
  318. // points to itself and has a return address of 0.
  319. break;
  320. }
  321. void **next_fp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(
  322. fp, ucp, stack_low, stack_high);
  323. if (skip_count > 0) {
  324. skip_count--;
  325. } else {
  326. result[n] = *(fp + 1);
  327. if (IS_STACK_FRAMES) {
  328. if (next_fp > fp) {
  329. sizes[n] = static_cast<int>(
  330. reinterpret_cast<uintptr_t>(next_fp) -
  331. reinterpret_cast<uintptr_t>(fp));
  332. } else {
  333. // A frame-size of 0 is used to indicate unknown frame size.
  334. sizes[n] = 0;
  335. }
  336. }
  337. n++;
  338. }
  339. fp = next_fp;
  340. }
  341. if (min_dropped_frames != nullptr) {
  342. // Implementation detail: we clamp the max of frames we are willing to
  343. // count, so as not to spend too much time in the loop below.
  344. const int kMaxUnwind = 1000;
  345. int num_dropped_frames = 0;
  346. for (int j = 0; fp != nullptr && j < kMaxUnwind; j++) {
  347. if (skip_count > 0) {
  348. skip_count--;
  349. } else {
  350. num_dropped_frames++;
  351. }
  352. fp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(fp, ucp, stack_low,
  353. stack_high);
  354. }
  355. *min_dropped_frames = num_dropped_frames;
  356. }
  357. return n;
  358. }
  359. namespace y_absl {
  360. Y_ABSL_NAMESPACE_BEGIN
  361. namespace debugging_internal {
  362. bool StackTraceWorksForTest() {
  363. return true;
  364. }
  365. } // namespace debugging_internal
  366. Y_ABSL_NAMESPACE_END
  367. } // namespace y_absl
  368. #endif // Y_ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_