stack_trace.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/debug/stack_trace.h"
  5. #include <string.h>
  6. #include <algorithm>
  7. #include <sstream>
  8. #include "base/check_op.h"
  9. #include "build/build_config.h"
  10. #include "build/config/compiler/compiler_buildflags.h"
  11. #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  12. #include "third_party/abseil-cpp/absl/types/optional.h"
  13. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  14. #include <pthread.h>
  15. #include "base/process/process_handle.h"
  16. #include "base/threading/platform_thread.h"
  17. #endif
  18. #if BUILDFLAG(IS_APPLE)
  19. #include <pthread.h>
  20. #endif
  21. #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
  22. extern "C" void* __libc_stack_end;
  23. #endif
  24. #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  25. namespace base {
  26. namespace debug {
  27. namespace {
  28. #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  29. #if defined(__arm__) && defined(__GNUC__) && !defined(__clang__)
  30. // GCC and LLVM generate slightly different frames on ARM, see
  31. // https://llvm.org/bugs/show_bug.cgi?id=18505 - LLVM generates
  32. // x86-compatible frame, while GCC needs adjustment.
  33. constexpr size_t kStackFrameAdjustment = sizeof(uintptr_t);
  34. #else
  35. constexpr size_t kStackFrameAdjustment = 0;
  36. #endif
  37. // On Arm-v8.3+ systems with pointer authentication codes (PAC), signature bits
  38. // are set in the top bits of the pointer, which confuses test assertions.
  39. // Because the signature size can vary based on the system configuration, use
  40. // the xpaclri instruction to remove the signature.
  41. static uintptr_t StripPointerAuthenticationBits(uintptr_t ptr) {
  42. #if defined(ARCH_CPU_ARM64)
  43. // A single Chromium binary currently spans all Arm systems (including those
  44. // with and without pointer authentication). xpaclri is used here because it's
  45. // in the HINT space and treated as a no-op on older Arm cores (unlike the
  46. // more generic xpaci which has a new encoding). The downside is that ptr has
  47. // to be moved to x30 to use this instruction. TODO(richard.townsend@arm.com):
  48. // replace with an intrinsic once that is available.
  49. register uintptr_t x30 __asm("x30") = ptr;
  50. asm("xpaclri" : "+r"(x30));
  51. return x30;
  52. #else
  53. // No-op on other platforms.
  54. return ptr;
  55. #endif
  56. }
  57. uintptr_t GetNextStackFrame(uintptr_t fp) {
  58. const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
  59. MSAN_UNPOISON(fp_addr, sizeof(uintptr_t));
  60. return fp_addr[0] - kStackFrameAdjustment;
  61. }
  62. uintptr_t GetStackFramePC(uintptr_t fp) {
  63. const uintptr_t* fp_addr = reinterpret_cast<const uintptr_t*>(fp);
  64. MSAN_UNPOISON(&fp_addr[1], sizeof(uintptr_t));
  65. return StripPointerAuthenticationBits(fp_addr[1]);
  66. }
  67. bool IsStackFrameValid(uintptr_t fp, uintptr_t prev_fp, uintptr_t stack_end) {
  68. // With the stack growing downwards, older stack frame must be
  69. // at a greater address that the current one.
  70. if (fp <= prev_fp) return false;
  71. // Assume huge stack frames are bogus.
  72. if (fp - prev_fp > 100000) return false;
  73. // Check alignment.
  74. if (fp & (sizeof(uintptr_t) - 1)) return false;
  75. if (stack_end) {
  76. // Both fp[0] and fp[1] must be within the stack.
  77. if (fp > stack_end - 2 * sizeof(uintptr_t)) return false;
  78. // Additional check to filter out false positives.
  79. if (GetStackFramePC(fp) < 32768) return false;
  80. }
  81. return true;
  82. }
  83. // ScanStackForNextFrame() scans the stack for a valid frame to allow unwinding
  84. // past system libraries. Only supported on Linux where system libraries are
  85. // usually in the middle of the trace:
  86. //
  87. // TraceStackFramePointers
  88. // <more frames from Chrome>
  89. // base::WorkSourceDispatch <-- unwinding stops (next frame is invalid),
  90. // g_main_context_dispatch ScanStackForNextFrame() is called
  91. // <more frames from glib>
  92. // g_main_context_iteration
  93. // base::MessagePumpGlib::Run <-- ScanStackForNextFrame() finds valid frame,
  94. // base::RunLoop::Run unwinding resumes
  95. // <more frames from Chrome>
  96. // __libc_start_main
  97. //
  98. // ScanStackForNextFrame() returns 0 if it couldn't find a valid frame
  99. // (or if stack scanning is not supported on the current platform).
  100. uintptr_t ScanStackForNextFrame(uintptr_t fp, uintptr_t stack_end) {
  101. // Enough to resume almost all prematurely terminated traces.
  102. constexpr size_t kMaxStackScanArea = 8192;
  103. if (!stack_end) {
  104. // Too dangerous to scan without knowing where the stack ends.
  105. return 0;
  106. }
  107. fp += sizeof(uintptr_t); // current frame is known to be invalid
  108. uintptr_t last_fp_to_scan = std::min(fp + kMaxStackScanArea, stack_end) -
  109. sizeof(uintptr_t);
  110. for (;fp <= last_fp_to_scan; fp += sizeof(uintptr_t)) {
  111. uintptr_t next_fp = GetNextStackFrame(fp);
  112. if (IsStackFrameValid(next_fp, fp, stack_end)) {
  113. // Check two frames deep. Since stack frame is just a pointer to
  114. // a higher address on the stack, it's relatively easy to find
  115. // something that looks like one. However two linked frames are
  116. // far less likely to be bogus.
  117. uintptr_t next2_fp = GetNextStackFrame(next_fp);
  118. if (IsStackFrameValid(next2_fp, next_fp, stack_end)) {
  119. return fp;
  120. }
  121. }
  122. }
  123. return 0;
  124. }
  125. // Links stack frame |fp| to |parent_fp|, so that during stack unwinding
  126. // TraceStackFramePointers() visits |parent_fp| after visiting |fp|.
  127. // Both frame pointers must come from __builtin_frame_address().
  128. // Returns previous stack frame |fp| was linked to.
  129. void* LinkStackFrames(void* fpp, void* parent_fp) {
  130. uintptr_t fp = reinterpret_cast<uintptr_t>(fpp) - kStackFrameAdjustment;
  131. void* prev_parent_fp = reinterpret_cast<void**>(fp)[0];
  132. reinterpret_cast<void**>(fp)[0] = parent_fp;
  133. return prev_parent_fp;
  134. }
  135. #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  136. } // namespace
  137. #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  138. uintptr_t GetStackEnd() {
  139. #if BUILDFLAG(IS_ANDROID)
  140. // Bionic reads proc/maps on every call to pthread_getattr_np() when called
  141. // from the main thread. So we need to cache end of stack in that case to get
  142. // acceptable performance.
  143. // For all other threads pthread_getattr_np() is fast enough as it just reads
  144. // values from its pthread_t argument.
  145. static uintptr_t main_stack_end = 0;
  146. bool is_main_thread = GetCurrentProcId() == PlatformThread::CurrentId();
  147. if (is_main_thread && main_stack_end) {
  148. return main_stack_end;
  149. }
  150. uintptr_t stack_begin = 0;
  151. size_t stack_size = 0;
  152. pthread_attr_t attributes;
  153. int error = pthread_getattr_np(pthread_self(), &attributes);
  154. if (!error) {
  155. error = pthread_attr_getstack(
  156. &attributes, reinterpret_cast<void**>(&stack_begin), &stack_size);
  157. pthread_attr_destroy(&attributes);
  158. }
  159. DCHECK(!error);
  160. uintptr_t stack_end = stack_begin + stack_size;
  161. if (is_main_thread) {
  162. main_stack_end = stack_end;
  163. }
  164. return stack_end; // 0 in case of error
  165. #elif BUILDFLAG(IS_APPLE)
  166. // No easy way to get end of the stack for non-main threads,
  167. // see crbug.com/617730.
  168. return reinterpret_cast<uintptr_t>(pthread_get_stackaddr_np(pthread_self()));
  169. #else
  170. #if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && defined(__GLIBC__)
  171. if (GetCurrentProcId() == PlatformThread::CurrentId()) {
  172. // For the main thread we have a shortcut.
  173. return reinterpret_cast<uintptr_t>(__libc_stack_end);
  174. }
  175. #endif
  176. // Don't know how to get end of the stack.
  177. return 0;
  178. #endif
  179. }
  180. #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  181. StackTrace::StackTrace() : StackTrace(std::size(trace_)) {}
  182. StackTrace::StackTrace(size_t count) {
  183. count_ = CollectStackTrace(trace_, std::min(count, std::size(trace_)));
  184. }
  185. StackTrace::StackTrace(const void* const* trace, size_t count) {
  186. count = std::min(count, std::size(trace_));
  187. if (count)
  188. memcpy(trace_, trace, count * sizeof(trace_[0]));
  189. count_ = count;
  190. }
  191. // static
  192. bool StackTrace::WillSymbolizeToStreamForTesting() {
  193. #if BUILDFLAG(SYMBOL_LEVEL) == 0
  194. // Symbols are not expected to be reliable when gn args specifies
  195. // symbol_level=0.
  196. return false;
  197. #elif defined(__UCLIBC__) || defined(_AIX)
  198. // StackTrace::OutputToStream() is not implemented under uclibc, nor AIX.
  199. // See https://crbug.com/706728
  200. return false;
  201. #elif defined(OFFICIAL_BUILD) && \
  202. ((BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)) || BUILDFLAG(IS_FUCHSIA))
  203. // On some platforms stack traces require an extra data table that bloats our
  204. // binaries, so they're turned off for official builds.
  205. return false;
  206. #elif defined(OFFICIAL_BUILD) && BUILDFLAG(IS_APPLE)
  207. // Official Mac OS X builds contain enough information to unwind the stack,
  208. // but not enough to symbolize the output.
  209. return false;
  210. #elif BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_ANDROID)
  211. // Under Fuchsia and Android, StackTrace emits executable build-Ids and
  212. // address offsets which are symbolized on the test host system, rather than
  213. // being symbolized in-process.
  214. return false;
  215. #elif defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
  216. defined(MEMORY_SANITIZER)
  217. // Sanitizer configurations (ASan, TSan, MSan) emit unsymbolized stacks.
  218. return false;
  219. #else
  220. return true;
  221. #endif
  222. }
  223. const void *const *StackTrace::Addresses(size_t* count) const {
  224. *count = count_;
  225. if (count_)
  226. return trace_;
  227. return nullptr;
  228. }
  229. void StackTrace::Print() const {
  230. PrintWithPrefix(nullptr);
  231. }
  232. void StackTrace::OutputToStream(std::ostream* os) const {
  233. OutputToStreamWithPrefix(os, nullptr);
  234. }
  235. std::string StackTrace::ToString() const {
  236. return ToStringWithPrefix(nullptr);
  237. }
  238. std::string StackTrace::ToStringWithPrefix(const char* prefix_string) const {
  239. std::stringstream stream;
  240. #if !defined(__UCLIBC__) && !defined(_AIX)
  241. OutputToStreamWithPrefix(&stream, prefix_string);
  242. #endif
  243. return stream.str();
  244. }
  245. std::ostream& operator<<(std::ostream& os, const StackTrace& s) {
  246. #if !defined(__UCLIBC__) && !defined(_AIX)
  247. s.OutputToStream(&os);
  248. #else
  249. os << "StackTrace::OutputToStream not implemented.";
  250. #endif
  251. return os;
  252. }
  253. #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  254. struct AddressRange {
  255. uintptr_t start;
  256. uintptr_t end;
  257. };
  258. bool IsWithinRange(uintptr_t address, const AddressRange& range) {
  259. return address >= range.start && address <= range.end;
  260. }
  261. // We force this function to be inlined into its callers (e.g.
  262. // TraceStackFramePointers()) in all build modes so we don't have to worry about
  263. // conditionally skipping a frame based on potential inlining or tail calls.
  264. __attribute__((always_inline)) size_t TraceStackFramePointersInternal(
  265. uintptr_t fp,
  266. uintptr_t stack_end,
  267. size_t max_depth,
  268. size_t skip_initial,
  269. bool enable_scanning,
  270. const void** out_trace) {
  271. size_t depth = 0;
  272. while (depth < max_depth) {
  273. uintptr_t pc = GetStackFramePC(fp);
  274. if (skip_initial != 0) {
  275. skip_initial--;
  276. } else {
  277. out_trace[depth++] = reinterpret_cast<const void*>(pc);
  278. }
  279. uintptr_t next_fp = GetNextStackFrame(fp);
  280. if (IsStackFrameValid(next_fp, fp, stack_end)) {
  281. fp = next_fp;
  282. continue;
  283. }
  284. if (!enable_scanning)
  285. break;
  286. next_fp = ScanStackForNextFrame(fp, stack_end);
  287. if (next_fp) {
  288. fp = next_fp;
  289. } else {
  290. break;
  291. }
  292. }
  293. return depth;
  294. }
  295. NOINLINE size_t TraceStackFramePointers(const void** out_trace,
  296. size_t max_depth,
  297. size_t skip_initial,
  298. bool enable_scanning) {
  299. return TraceStackFramePointersInternal(
  300. reinterpret_cast<uintptr_t>(__builtin_frame_address(0)) -
  301. kStackFrameAdjustment,
  302. GetStackEnd(), max_depth, skip_initial, enable_scanning, out_trace);
  303. }
  304. NOINLINE size_t TraceStackFramePointersFromBuffer(uintptr_t fp,
  305. uintptr_t stack_end,
  306. const void** out_trace,
  307. size_t max_depth,
  308. size_t skip_initial,
  309. bool enable_scanning) {
  310. return TraceStackFramePointersInternal(fp, stack_end, max_depth, skip_initial,
  311. enable_scanning, out_trace);
  312. }
  313. ScopedStackFrameLinker::ScopedStackFrameLinker(void* fp, void* parent_fp)
  314. : fp_(fp),
  315. parent_fp_(parent_fp),
  316. original_parent_fp_(LinkStackFrames(fp, parent_fp)) {}
  317. ScopedStackFrameLinker::~ScopedStackFrameLinker() {
  318. void* previous_parent_fp = LinkStackFrames(fp_, original_parent_fp_);
  319. CHECK_EQ(parent_fp_, previous_parent_fp)
  320. << "Stack frame's parent pointer has changed!";
  321. }
  322. #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  323. } // namespace debug
  324. } // namespace base