stack_trace_unittest.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // Copyright (c) 2011 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 <stddef.h>
  5. #include <limits>
  6. #include <sstream>
  7. #include <string>
  8. #include "base/debug/debugging_buildflags.h"
  9. #include "base/debug/stack_trace.h"
  10. #include "base/logging.h"
  11. #include "base/process/kill.h"
  12. #include "base/process/process_handle.h"
  13. #include "base/profiler/stack_buffer.h"
  14. #include "base/profiler/stack_copier.h"
  15. #include "base/test/test_timeouts.h"
  16. #include "build/build_config.h"
  17. #include "testing/gtest/include/gtest/gtest.h"
  18. #include "testing/multiprocess_func_list.h"
  19. #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  20. #include "base/test/multiprocess_test.h"
  21. #endif
  22. namespace base {
  23. namespace debug {
  24. #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  25. typedef MultiProcessTest StackTraceTest;
  26. #else
  27. typedef testing::Test StackTraceTest;
  28. #endif
  29. #if !defined(__UCLIBC__) && !defined(_AIX)
  30. // StackTrace::OutputToStream() is not implemented under uclibc, nor AIX.
  31. // See https://crbug.com/706728
  32. TEST_F(StackTraceTest, OutputToStream) {
  33. StackTrace trace;
  34. // Dump the trace into a string.
  35. std::ostringstream os;
  36. trace.OutputToStream(&os);
  37. std::string backtrace_message = os.str();
  38. // ToString() should produce the same output.
  39. EXPECT_EQ(backtrace_message, trace.ToString());
  40. size_t frames_found = 0;
  41. const void* const* addresses = trace.Addresses(&frames_found);
  42. #if defined(OFFICIAL_BUILD) && \
  43. ((BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)) || BUILDFLAG(IS_FUCHSIA))
  44. // Stack traces require an extra data table that bloats our binaries,
  45. // so they're turned off for official builds. Stop the test here, so
  46. // it at least verifies that StackTrace calls don't crash.
  47. return;
  48. #endif // defined(OFFICIAL_BUILD) &&
  49. // ((BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE)) ||
  50. // BUILDFLAG(IS_FUCHSIA))
  51. ASSERT_TRUE(addresses);
  52. ASSERT_GT(frames_found, 5u) << "Too few frames found.";
  53. if (!StackTrace::WillSymbolizeToStreamForTesting())
  54. return;
  55. // Check if the output has symbol initialization warning. If it does, fail.
  56. ASSERT_EQ(backtrace_message.find("Dumping unresolved backtrace"),
  57. std::string::npos)
  58. << "Unable to resolve symbols.";
  59. // Expect a demangled symbol.
  60. // Note that Windows Release builds omit the function parameters from the
  61. // demangled stack output, otherwise this could be "testing::UnitTest::Run()".
  62. EXPECT_TRUE(backtrace_message.find("testing::UnitTest::Run") !=
  63. std::string::npos)
  64. << "Expected a demangled symbol in backtrace:\n"
  65. << backtrace_message;
  66. // Expect to at least find main.
  67. EXPECT_TRUE(backtrace_message.find("main") != std::string::npos)
  68. << "Expected to find main in backtrace:\n"
  69. << backtrace_message;
  70. // Expect to find this function as well.
  71. // Note: This will fail if not linked with -rdynamic (aka -export_dynamic)
  72. EXPECT_TRUE(backtrace_message.find(__func__) != std::string::npos)
  73. << "Expected to find " << __func__ << " in backtrace:\n"
  74. << backtrace_message;
  75. }
  76. #if !defined(OFFICIAL_BUILD) && !defined(NO_UNWIND_TABLES)
  77. // Disabled in Official builds, where Link-Time Optimization can result in two
  78. // or fewer stack frames being available, causing the test to fail.
  79. TEST_F(StackTraceTest, TruncatedTrace) {
  80. StackTrace trace;
  81. size_t count = 0;
  82. trace.Addresses(&count);
  83. ASSERT_LT(2u, count);
  84. StackTrace truncated(2);
  85. truncated.Addresses(&count);
  86. EXPECT_EQ(2u, count);
  87. }
  88. #endif // !defined(OFFICIAL_BUILD) && !defined(NO_UNWIND_TABLES)
  89. // The test is used for manual testing, e.g., to see the raw output.
  90. TEST_F(StackTraceTest, DebugOutputToStream) {
  91. StackTrace trace;
  92. std::ostringstream os;
  93. trace.OutputToStream(&os);
  94. VLOG(1) << os.str();
  95. }
  96. // The test is used for manual testing, e.g., to see the raw output.
  97. TEST_F(StackTraceTest, DebugPrintBacktrace) {
  98. StackTrace().Print();
  99. }
  100. // The test is used for manual testing, e.g., to see the raw output.
  101. TEST_F(StackTraceTest, DebugPrintWithPrefixBacktrace) {
  102. StackTrace().PrintWithPrefix("[test]");
  103. }
  104. // Make sure nullptr prefix doesn't crash. Output not examined, much
  105. // like the DebugPrintBacktrace test above.
  106. TEST_F(StackTraceTest, DebugPrintWithNullPrefixBacktrace) {
  107. StackTrace().PrintWithPrefix(nullptr);
  108. }
  109. // Test OutputToStreamWithPrefix, mainly to make sure it doesn't
  110. // crash. Any "real" stack trace testing happens above.
  111. TEST_F(StackTraceTest, DebugOutputToStreamWithPrefix) {
  112. StackTrace trace;
  113. const char* prefix_string = "[test]";
  114. std::ostringstream os;
  115. trace.OutputToStreamWithPrefix(&os, prefix_string);
  116. std::string backtrace_message = os.str();
  117. // ToStringWithPrefix() should produce the same output.
  118. EXPECT_EQ(backtrace_message, trace.ToStringWithPrefix(prefix_string));
  119. }
  120. // Make sure nullptr prefix doesn't crash. Output not examined, much
  121. // like the DebugPrintBacktrace test above.
  122. TEST_F(StackTraceTest, DebugOutputToStreamWithNullPrefix) {
  123. StackTrace trace;
  124. std::ostringstream os;
  125. trace.OutputToStreamWithPrefix(&os, nullptr);
  126. trace.ToStringWithPrefix(nullptr);
  127. }
  128. #endif // !defined(__UCLIBC__) && !defined(_AIX)
  129. #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
  130. #if !BUILDFLAG(IS_IOS)
  131. static char* newArray() {
  132. // Clang warns about the mismatched new[]/delete if they occur in the same
  133. // function.
  134. return new char[10];
  135. }
  136. MULTIPROCESS_TEST_MAIN(MismatchedMallocChildProcess) {
  137. char* pointer = newArray();
  138. delete pointer;
  139. return 2;
  140. }
  141. // Regression test for StackDumpingSignalHandler async-signal unsafety.
  142. // Combined with tcmalloc's debugallocation, that signal handler
  143. // and e.g. mismatched new[]/delete would cause a hang because
  144. // of re-entering malloc.
  145. TEST_F(StackTraceTest, AsyncSignalUnsafeSignalHandlerHang) {
  146. Process child = SpawnChild("MismatchedMallocChildProcess");
  147. ASSERT_TRUE(child.IsValid());
  148. int exit_code;
  149. ASSERT_TRUE(
  150. child.WaitForExitWithTimeout(TestTimeouts::action_timeout(), &exit_code));
  151. }
  152. #endif // !BUILDFLAG(IS_IOS)
  153. namespace {
  154. std::string itoa_r_wrapper(intptr_t i, size_t sz, int base, size_t padding) {
  155. char buffer[1024];
  156. CHECK_LE(sz, sizeof(buffer));
  157. char* result = internal::itoa_r(i, buffer, sz, base, padding);
  158. EXPECT_TRUE(result);
  159. return std::string(buffer);
  160. }
  161. } // namespace
  162. TEST_F(StackTraceTest, itoa_r) {
  163. EXPECT_EQ("0", itoa_r_wrapper(0, 128, 10, 0));
  164. EXPECT_EQ("-1", itoa_r_wrapper(-1, 128, 10, 0));
  165. // Test edge cases.
  166. if (sizeof(intptr_t) == 4) {
  167. EXPECT_EQ("ffffffff", itoa_r_wrapper(-1, 128, 16, 0));
  168. EXPECT_EQ("-2147483648",
  169. itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 10, 0));
  170. EXPECT_EQ("2147483647",
  171. itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 10, 0));
  172. EXPECT_EQ("80000000",
  173. itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 16, 0));
  174. EXPECT_EQ("7fffffff",
  175. itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 16, 0));
  176. } else if (sizeof(intptr_t) == 8) {
  177. EXPECT_EQ("ffffffffffffffff", itoa_r_wrapper(-1, 128, 16, 0));
  178. EXPECT_EQ("-9223372036854775808",
  179. itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 10, 0));
  180. EXPECT_EQ("9223372036854775807",
  181. itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 10, 0));
  182. EXPECT_EQ("8000000000000000",
  183. itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 16, 0));
  184. EXPECT_EQ("7fffffffffffffff",
  185. itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 16, 0));
  186. } else {
  187. ADD_FAILURE() << "Missing test case for your size of intptr_t ("
  188. << sizeof(intptr_t) << ")";
  189. }
  190. // Test hex output.
  191. EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 0));
  192. EXPECT_EQ("deadbeef", itoa_r_wrapper(0xdeadbeef, 128, 16, 0));
  193. // Check that itoa_r respects passed buffer size limit.
  194. char buffer[1024];
  195. EXPECT_TRUE(internal::itoa_r(0xdeadbeef, buffer, 10, 16, 0));
  196. EXPECT_TRUE(internal::itoa_r(0xdeadbeef, buffer, 9, 16, 0));
  197. EXPECT_FALSE(internal::itoa_r(0xdeadbeef, buffer, 8, 16, 0));
  198. EXPECT_FALSE(internal::itoa_r(0xdeadbeef, buffer, 7, 16, 0));
  199. EXPECT_TRUE(internal::itoa_r(0xbeef, buffer, 5, 16, 4));
  200. EXPECT_FALSE(internal::itoa_r(0xbeef, buffer, 5, 16, 5));
  201. EXPECT_FALSE(internal::itoa_r(0xbeef, buffer, 5, 16, 6));
  202. // Test padding.
  203. EXPECT_EQ("1", itoa_r_wrapper(1, 128, 10, 0));
  204. EXPECT_EQ("1", itoa_r_wrapper(1, 128, 10, 1));
  205. EXPECT_EQ("01", itoa_r_wrapper(1, 128, 10, 2));
  206. EXPECT_EQ("001", itoa_r_wrapper(1, 128, 10, 3));
  207. EXPECT_EQ("0001", itoa_r_wrapper(1, 128, 10, 4));
  208. EXPECT_EQ("00001", itoa_r_wrapper(1, 128, 10, 5));
  209. EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 0));
  210. EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 1));
  211. EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 2));
  212. EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 3));
  213. EXPECT_EQ("0688", itoa_r_wrapper(0x688, 128, 16, 4));
  214. EXPECT_EQ("00688", itoa_r_wrapper(0x688, 128, 16, 5));
  215. }
  216. #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_ANDROID)
  217. #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  218. class CopyFunction : public StackCopier {
  219. public:
  220. using StackCopier::CopyStackContentsAndRewritePointers;
  221. };
  222. // Copies the current stack segment, starting from the frame pointer of the
  223. // caller frame. Also fills in |stack_end| for the copied stack.
  224. static std::unique_ptr<StackBuffer> NOINLINE
  225. CopyCurrentStackAndRewritePointers(uintptr_t* out_fp, uintptr_t* stack_end) {
  226. const uint8_t* fp =
  227. reinterpret_cast<const uint8_t*>(__builtin_frame_address(0));
  228. uintptr_t original_stack_end = GetStackEnd();
  229. size_t stack_size = original_stack_end - reinterpret_cast<uintptr_t>(fp);
  230. auto buffer = std::make_unique<StackBuffer>(stack_size);
  231. *out_fp = reinterpret_cast<uintptr_t>(
  232. CopyFunction::CopyStackContentsAndRewritePointers(
  233. fp, reinterpret_cast<const uintptr_t*>(original_stack_end),
  234. StackBuffer::kPlatformStackAlignment, buffer->buffer()));
  235. *stack_end = *out_fp + stack_size;
  236. return buffer;
  237. }
  238. template <size_t Depth>
  239. void NOINLINE ExpectStackFramePointers(const void** frames,
  240. size_t max_depth,
  241. bool copy_stack) {
  242. code_start:
  243. // Calling __builtin_frame_address() forces compiler to emit
  244. // frame pointers, even if they are not enabled.
  245. EXPECT_NE(nullptr, __builtin_frame_address(0));
  246. ExpectStackFramePointers<Depth - 1>(frames, max_depth, copy_stack);
  247. constexpr size_t frame_index = Depth - 1;
  248. const void* frame = frames[frame_index];
  249. EXPECT_GE(frame, &&code_start) << "For frame at index " << frame_index;
  250. EXPECT_LE(frame, &&code_end) << "For frame at index " << frame_index;
  251. code_end: return;
  252. }
  253. template <>
  254. void NOINLINE ExpectStackFramePointers<1>(const void** frames,
  255. size_t max_depth,
  256. bool copy_stack) {
  257. code_start:
  258. // Calling __builtin_frame_address() forces compiler to emit
  259. // frame pointers, even if they are not enabled.
  260. EXPECT_NE(nullptr, __builtin_frame_address(0));
  261. size_t count = 0;
  262. if (copy_stack) {
  263. uintptr_t stack_end = 0, fp = 0;
  264. std::unique_ptr<StackBuffer> copy =
  265. CopyCurrentStackAndRewritePointers(&fp, &stack_end);
  266. count =
  267. TraceStackFramePointersFromBuffer(fp, stack_end, frames, max_depth, 0);
  268. } else {
  269. count = TraceStackFramePointers(frames, max_depth, 0);
  270. }
  271. ASSERT_EQ(max_depth, count);
  272. const void* frame = frames[0];
  273. EXPECT_GE(frame, &&code_start) << "For the top frame";
  274. EXPECT_LE(frame, &&code_end) << "For the top frame";
  275. code_end: return;
  276. }
  277. #if defined(MEMORY_SANITIZER)
  278. // The test triggers use-of-uninitialized-value errors on MSan bots.
  279. // This is expected because we're walking and reading the stack, and
  280. // sometimes we read fp / pc from the place that previously held
  281. // uninitialized value.
  282. #define MAYBE_TraceStackFramePointers DISABLED_TraceStackFramePointers
  283. #else
  284. #define MAYBE_TraceStackFramePointers TraceStackFramePointers
  285. #endif
  286. TEST_F(StackTraceTest, MAYBE_TraceStackFramePointers) {
  287. constexpr size_t kDepth = 5;
  288. const void* frames[kDepth];
  289. ExpectStackFramePointers<kDepth>(frames, kDepth, /*copy_stack=*/false);
  290. }
  291. // The test triggers use-of-uninitialized-value errors on MSan bots.
  292. // This is expected because we're walking and reading the stack, and
  293. // sometimes we read fp / pc from the place that previously held
  294. // uninitialized value.
  295. // TODO(crbug.com/1132511): Enable this test on Fuchsia.
  296. #if defined(MEMORY_SANITIZER) || BUILDFLAG(IS_FUCHSIA)
  297. #define MAYBE_TraceStackFramePointersFromBuffer \
  298. DISABLED_TraceStackFramePointersFromBuffer
  299. #else
  300. #define MAYBE_TraceStackFramePointersFromBuffer \
  301. TraceStackFramePointersFromBuffer
  302. #endif
  303. TEST_F(StackTraceTest, MAYBE_TraceStackFramePointersFromBuffer) {
  304. constexpr size_t kDepth = 5;
  305. const void* frames[kDepth];
  306. ExpectStackFramePointers<kDepth>(frames, kDepth, /*copy_stack=*/true);
  307. }
  308. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
  309. #define MAYBE_StackEnd StackEnd
  310. #else
  311. #define MAYBE_StackEnd DISABLED_StackEnd
  312. #endif
  313. TEST_F(StackTraceTest, MAYBE_StackEnd) {
  314. EXPECT_NE(0u, GetStackEnd());
  315. }
  316. #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
  317. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID)
  318. #if !defined(ADDRESS_SANITIZER) && !defined(UNDEFINED_SANITIZER)
  319. #if !defined(ARCH_CPU_ARM_FAMILY)
  320. // On Arm architecture invalid math operations such as division by zero are not
  321. // trapped and do not trigger a SIGFPE.
  322. // Hence disable the test for Arm platforms.
  323. TEST(CheckExitCodeAfterSignalHandlerDeathTest, CheckSIGFPE) {
  324. // Values are volatile to prevent reordering of instructions, i.e. for
  325. // optimization. Reordering may lead to tests erroneously failing due to
  326. // SIGFPE being raised outside of EXPECT_EXIT.
  327. volatile int const nominator = 23;
  328. volatile int const denominator = 0;
  329. [[maybe_unused]] volatile int result;
  330. EXPECT_EXIT(result = nominator / denominator,
  331. ::testing::KilledBySignal(SIGFPE), "");
  332. }
  333. #endif // !defined(ARCH_CPU_ARM_FAMILY)
  334. TEST(CheckExitCodeAfterSignalHandlerDeathTest, CheckSIGSEGV) {
  335. // Pointee and pointer are volatile to prevent reordering of instructions,
  336. // i.e. for optimization. Reordering may lead to tests erroneously failing due
  337. // to SIGSEGV being raised outside of EXPECT_EXIT.
  338. volatile int* const volatile p_int = nullptr;
  339. EXPECT_EXIT(*p_int = 1234, ::testing::KilledBySignal(SIGSEGV), "");
  340. }
  341. #endif // #if !defined(ADDRESS_SANITIZER) && !defined(UNDEFINED_SANITIZER)
  342. TEST(CheckExitCodeAfterSignalHandlerDeathTest, CheckSIGILL) {
  343. auto const raise_sigill = []() {
  344. #if defined(ARCH_CPU_X86_FAMILY)
  345. asm("ud2");
  346. #elif defined(ARCH_CPU_ARM_FAMILY)
  347. asm("udf 0");
  348. #else
  349. #error Unsupported platform!
  350. #endif
  351. };
  352. EXPECT_EXIT(raise_sigill(), ::testing::KilledBySignal(SIGILL), "");
  353. }
  354. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID)
  355. } // namespace debug
  356. } // namespace base