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
5 #include <stddef.h>
6
7 #include <limits>
8 #include <sstream>
9 #include <string>
10
11 #include "base/debug/debugging_buildflags.h"
12 #include "base/debug/stack_trace.h"
13 #include "base/logging.h"
14 #include "base/process/kill.h"
15 #include "base/process/process_handle.h"
16 #include "base/test/test_timeouts.h"
17 #include "build/build_config.h"
18 #include "testing/gtest/include/gtest/gtest.h"
19 #include "testing/multiprocess_func_list.h"
20
21 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_IOS)
22 #include "base/test/multiprocess_test.h"
23 #endif
24
25 namespace base {
26 namespace debug {
27
28 #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_IOS)
29 typedef MultiProcessTest StackTraceTest;
30 #else
31 typedef testing::Test StackTraceTest;
32 #endif
33
34 // Note: On Linux, this test currently only fully works on Debug builds.
35 // See comments in the #ifdef soup if you intend to change this.
36 #if defined(OS_WIN)
37 // Always fails on Windows: crbug.com/32070
38 #define MAYBE_OutputToStream DISABLED_OutputToStream
39 #else
40 #define MAYBE_OutputToStream OutputToStream
41 #endif
42 #if !defined(__UCLIBC__) && !defined(_AIX)
TEST_F(StackTraceTest,MAYBE_OutputToStream)43 TEST_F(StackTraceTest, MAYBE_OutputToStream) {
44 StackTrace trace;
45
46 // Dump the trace into a string.
47 std::ostringstream os;
48 trace.OutputToStream(&os);
49 std::string backtrace_message = os.str();
50
51 // ToString() should produce the same output.
52 EXPECT_EQ(backtrace_message, trace.ToString());
53
54 #if defined(OS_POSIX) && !defined(OS_MACOSX) && NDEBUG
55 // Stack traces require an extra data table that bloats our binaries,
56 // so they're turned off for release builds. We stop the test here,
57 // at least letting us verify that the calls don't crash.
58 return;
59 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && NDEBUG
60
61 size_t frames_found = 0;
62 trace.Addresses(&frames_found);
63 ASSERT_GE(frames_found, 5u) <<
64 "No stack frames found. Skipping rest of test.";
65
66 // Check if the output has symbol initialization warning. If it does, fail.
67 ASSERT_EQ(backtrace_message.find("Dumping unresolved backtrace"),
68 std::string::npos) <<
69 "Unable to resolve symbols. Skipping rest of test.";
70
71 #if defined(OS_MACOSX)
72 #if 0
73 // Disabled due to -fvisibility=hidden in build config.
74
75 // Symbol resolution via the backtrace_symbol function does not work well
76 // in OS X.
77 // See this thread:
78 //
79 // http://lists.apple.com/archives/darwin-dev/2009/Mar/msg00111.html
80 //
81 // Just check instead that we find our way back to the "start" symbol
82 // which should be the first symbol in the trace.
83 //
84 // TODO(port): Find a more reliable way to resolve symbols.
85
86 // Expect to at least find main.
87 EXPECT_TRUE(backtrace_message.find("start") != std::string::npos)
88 << "Expected to find start in backtrace:\n"
89 << backtrace_message;
90
91 #endif
92 #elif defined(USE_SYMBOLIZE)
93 // This branch is for gcc-compiled code, but not Mac due to the
94 // above #if.
95 // Expect a demangled symbol.
96 EXPECT_TRUE(backtrace_message.find("testing::Test::Run()") !=
97 std::string::npos)
98 << "Expected a demangled symbol in backtrace:\n"
99 << backtrace_message;
100
101 #elif 0
102 // This is the fall-through case; it used to cover Windows.
103 // But it's disabled because of varying buildbot configs;
104 // some lack symbols.
105
106 // Expect to at least find main.
107 EXPECT_TRUE(backtrace_message.find("main") != std::string::npos)
108 << "Expected to find main in backtrace:\n"
109 << backtrace_message;
110
111 #if defined(OS_WIN)
112 // MSVC doesn't allow the use of C99's __func__ within C++, so we fake it with
113 // MSVC's __FUNCTION__ macro.
114 #define __func__ __FUNCTION__
115 #endif
116
117 // Expect to find this function as well.
118 // Note: This will fail if not linked with -rdynamic (aka -export_dynamic)
119 EXPECT_TRUE(backtrace_message.find(__func__) != std::string::npos)
120 << "Expected to find " << __func__ << " in backtrace:\n"
121 << backtrace_message;
122
123 #endif // define(OS_MACOSX)
124 }
125
126 #if !defined(OFFICIAL_BUILD) && !defined(NO_UNWIND_TABLES)
127 // Disabled in Official builds, where Link-Time Optimization can result in two
128 // or fewer stack frames being available, causing the test to fail.
TEST_F(StackTraceTest,TruncatedTrace)129 TEST_F(StackTraceTest, TruncatedTrace) {
130 StackTrace trace;
131
132 size_t count = 0;
133 trace.Addresses(&count);
134 ASSERT_LT(2u, count);
135
136 StackTrace truncated(2);
137 truncated.Addresses(&count);
138 EXPECT_EQ(2u, count);
139 }
140 #endif // !defined(OFFICIAL_BUILD)
141
142 // The test is used for manual testing, e.g., to see the raw output.
TEST_F(StackTraceTest,DebugOutputToStream)143 TEST_F(StackTraceTest, DebugOutputToStream) {
144 StackTrace trace;
145 std::ostringstream os;
146 trace.OutputToStream(&os);
147 VLOG(1) << os.str();
148 }
149
150 // The test is used for manual testing, e.g., to see the raw output.
TEST_F(StackTraceTest,DebugPrintBacktrace)151 TEST_F(StackTraceTest, DebugPrintBacktrace) {
152 StackTrace().Print();
153 }
154 #endif // !defined(__UCLIBC__)
155
156 #if defined(OS_POSIX) && !defined(OS_ANDROID)
157 #if !defined(OS_IOS)
newArray()158 static char* newArray() {
159 // Clang warns about the mismatched new[]/delete if they occur in the same
160 // function.
161 return new char[10];
162 }
163
MULTIPROCESS_TEST_MAIN(MismatchedMallocChildProcess)164 MULTIPROCESS_TEST_MAIN(MismatchedMallocChildProcess) {
165 char* pointer = newArray();
166 delete pointer;
167 return 2;
168 }
169
170 // Regression test for StackDumpingSignalHandler async-signal unsafety.
171 // Combined with tcmalloc's debugallocation, that signal handler
172 // and e.g. mismatched new[]/delete would cause a hang because
173 // of re-entering malloc.
TEST_F(StackTraceTest,AsyncSignalUnsafeSignalHandlerHang)174 TEST_F(StackTraceTest, AsyncSignalUnsafeSignalHandlerHang) {
175 Process child = SpawnChild("MismatchedMallocChildProcess");
176 ASSERT_TRUE(child.IsValid());
177 int exit_code;
178 ASSERT_TRUE(
179 child.WaitForExitWithTimeout(TestTimeouts::action_timeout(), &exit_code));
180 }
181 #endif // !defined(OS_IOS)
182
183 namespace {
184
itoa_r_wrapper(intptr_t i,size_t sz,int base,size_t padding)185 std::string itoa_r_wrapper(intptr_t i, size_t sz, int base, size_t padding) {
186 char buffer[1024];
187 CHECK_LE(sz, sizeof(buffer));
188
189 char* result = internal::itoa_r(i, buffer, sz, base, padding);
190 EXPECT_TRUE(result);
191 return std::string(buffer);
192 }
193
194 } // namespace
195
TEST_F(StackTraceTest,itoa_r)196 TEST_F(StackTraceTest, itoa_r) {
197 EXPECT_EQ("0", itoa_r_wrapper(0, 128, 10, 0));
198 EXPECT_EQ("-1", itoa_r_wrapper(-1, 128, 10, 0));
199
200 // Test edge cases.
201 if (sizeof(intptr_t) == 4) {
202 EXPECT_EQ("ffffffff", itoa_r_wrapper(-1, 128, 16, 0));
203 EXPECT_EQ("-2147483648",
204 itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 10, 0));
205 EXPECT_EQ("2147483647",
206 itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 10, 0));
207
208 EXPECT_EQ("80000000",
209 itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 16, 0));
210 EXPECT_EQ("7fffffff",
211 itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 16, 0));
212 } else if (sizeof(intptr_t) == 8) {
213 EXPECT_EQ("ffffffffffffffff", itoa_r_wrapper(-1, 128, 16, 0));
214 EXPECT_EQ("-9223372036854775808",
215 itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 10, 0));
216 EXPECT_EQ("9223372036854775807",
217 itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 10, 0));
218
219 EXPECT_EQ("8000000000000000",
220 itoa_r_wrapper(std::numeric_limits<intptr_t>::min(), 128, 16, 0));
221 EXPECT_EQ("7fffffffffffffff",
222 itoa_r_wrapper(std::numeric_limits<intptr_t>::max(), 128, 16, 0));
223 } else {
224 ADD_FAILURE() << "Missing test case for your size of intptr_t ("
225 << sizeof(intptr_t) << ")";
226 }
227
228 // Test hex output.
229 EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 0));
230 EXPECT_EQ("deadbeef", itoa_r_wrapper(0xdeadbeef, 128, 16, 0));
231
232 // Check that itoa_r respects passed buffer size limit.
233 char buffer[1024];
234 EXPECT_TRUE(internal::itoa_r(0xdeadbeef, buffer, 10, 16, 0));
235 EXPECT_TRUE(internal::itoa_r(0xdeadbeef, buffer, 9, 16, 0));
236 EXPECT_FALSE(internal::itoa_r(0xdeadbeef, buffer, 8, 16, 0));
237 EXPECT_FALSE(internal::itoa_r(0xdeadbeef, buffer, 7, 16, 0));
238 EXPECT_TRUE(internal::itoa_r(0xbeef, buffer, 5, 16, 4));
239 EXPECT_FALSE(internal::itoa_r(0xbeef, buffer, 5, 16, 5));
240 EXPECT_FALSE(internal::itoa_r(0xbeef, buffer, 5, 16, 6));
241
242 // Test padding.
243 EXPECT_EQ("1", itoa_r_wrapper(1, 128, 10, 0));
244 EXPECT_EQ("1", itoa_r_wrapper(1, 128, 10, 1));
245 EXPECT_EQ("01", itoa_r_wrapper(1, 128, 10, 2));
246 EXPECT_EQ("001", itoa_r_wrapper(1, 128, 10, 3));
247 EXPECT_EQ("0001", itoa_r_wrapper(1, 128, 10, 4));
248 EXPECT_EQ("00001", itoa_r_wrapper(1, 128, 10, 5));
249 EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 0));
250 EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 1));
251 EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 2));
252 EXPECT_EQ("688", itoa_r_wrapper(0x688, 128, 16, 3));
253 EXPECT_EQ("0688", itoa_r_wrapper(0x688, 128, 16, 4));
254 EXPECT_EQ("00688", itoa_r_wrapper(0x688, 128, 16, 5));
255 }
256 #endif // defined(OS_POSIX) && !defined(OS_ANDROID)
257
258 #if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
259
260 template <size_t Depth>
ExpectStackFramePointers(const void ** frames,size_t max_depth)261 void NOINLINE ExpectStackFramePointers(const void** frames,
262 size_t max_depth) {
263 code_start:
264 // Calling __builtin_frame_address() forces compiler to emit
265 // frame pointers, even if they are not enabled.
266 EXPECT_NE(nullptr, __builtin_frame_address(0));
267 ExpectStackFramePointers<Depth - 1>(frames, max_depth);
268
269 constexpr size_t frame_index = Depth - 1;
270 const void* frame = frames[frame_index];
271 EXPECT_GE(frame, &&code_start) << "For frame at index " << frame_index;
272 EXPECT_LE(frame, &&code_end) << "For frame at index " << frame_index;
273 code_end: return;
274 }
275
276 template <>
ExpectStackFramePointers(const void ** frames,size_t max_depth)277 void NOINLINE ExpectStackFramePointers<1>(const void** frames,
278 size_t max_depth) {
279 code_start:
280 // Calling __builtin_frame_address() forces compiler to emit
281 // frame pointers, even if they are not enabled.
282 EXPECT_NE(nullptr, __builtin_frame_address(0));
283 size_t count = TraceStackFramePointers(frames, max_depth, 0);
284 ASSERT_EQ(max_depth, count);
285
286 const void* frame = frames[0];
287 EXPECT_GE(frame, &&code_start) << "For the top frame";
288 EXPECT_LE(frame, &&code_end) << "For the top frame";
289 code_end: return;
290 }
291
292 #if defined(MEMORY_SANITIZER)
293 // The test triggers use-of-uninitialized-value errors on MSan bots.
294 // This is expected because we're walking and reading the stack, and
295 // sometimes we read fp / pc from the place that previously held
296 // uninitialized value.
297 #define MAYBE_TraceStackFramePointers DISABLED_TraceStackFramePointers
298 #else
299 #define MAYBE_TraceStackFramePointers TraceStackFramePointers
300 #endif
TEST_F(StackTraceTest,MAYBE_TraceStackFramePointers)301 TEST_F(StackTraceTest, MAYBE_TraceStackFramePointers) {
302 constexpr size_t kDepth = 5;
303 const void* frames[kDepth];
304 ExpectStackFramePointers<kDepth>(frames, kDepth);
305 }
306
307 #if defined(OS_ANDROID) || defined(OS_MACOSX)
308 #define MAYBE_StackEnd StackEnd
309 #else
310 #define MAYBE_StackEnd DISABLED_StackEnd
311 #endif
312
TEST_F(StackTraceTest,MAYBE_StackEnd)313 TEST_F(StackTraceTest, MAYBE_StackEnd) {
314 EXPECT_NE(0u, GetStackEnd());
315 }
316
317 #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
318
319 } // namespace debug
320 } // namespace base
321