blob: 35cbb4e4385c2aaefece9a8f243f1af37994f03d [file] [log] [blame]
[email protected]695f8dd2012-02-03 04:02:181// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
[email protected]1ffe08c12008-08-13 11:15:114
[email protected]58580352010-10-26 04:07:505#include "base/debug/stack_trace.h"
[email protected]1ffe08c12008-08-13 11:15:116
[email protected]96fd0032009-04-24 00:13:087#include <errno.h>
[email protected]e6f456242008-10-08 15:27:408#include <fcntl.h>
[email protected]11b93faa2012-11-01 21:58:309#include <signal.h>
aviebe805c2015-12-24 08:20:2810#include <stddef.h>
11#include <stdint.h>
[email protected]d1fc4372009-01-16 22:06:1912#include <stdio.h>
[email protected]54823b0f2010-03-18 04:30:1413#include <stdlib.h>
[email protected]0c6f3b0c2011-04-15 06:15:0414#include <sys/param.h>
[email protected]e6f456242008-10-08 15:27:4015#include <sys/stat.h>
[email protected]1ffe08c12008-08-13 11:15:1116#include <sys/types.h>
[email protected]e6f456242008-10-08 15:27:4017#include <unistd.h>
[email protected]1ffe08c12008-08-13 11:15:1118
[email protected]ad9a0122014-03-22 00:34:5219#include <map>
[email protected]1e218b72012-11-14 19:32:2320#include <ostream>
[email protected]ad9a0122014-03-22 00:34:5221#include <string>
22#include <vector>
[email protected]f1633932010-08-17 23:05:2823
[email protected]5b7f3e3a2014-04-08 14:33:5424#if defined(__GLIBCXX__)
[email protected]79b6fa62009-10-14 03:01:4425#include <cxxabi.h>
26#endif
[email protected]816e50452014-04-09 22:29:3827#if !defined(__UCLIBC__)
28#include <execinfo.h>
29#endif
[email protected]79b6fa62009-10-14 03:01:4430
[email protected]6e4bf0b2009-09-17 16:12:3631#if defined(OS_MACOSX)
32#include <AvailabilityMacros.h>
33#endif
34
[email protected]1e218b72012-11-14 19:32:2335#include "base/debug/debugger.h"
[email protected]ad9a0122014-03-22 00:34:5236#include "base/debug/proc_maps_linux.h"
[email protected]0dfc81b2008-08-25 03:44:4037#include "base/logging.h"
aviebe805c2015-12-24 08:20:2838#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1539#include "base/memory/scoped_ptr.h"
[email protected]ad9a0122014-03-22 00:34:5240#include "base/memory/singleton.h"
[email protected]82933a582014-03-12 09:28:1441#include "base/numerics/safe_conversions.h"
[email protected]2025d002012-11-14 20:54:3542#include "base/posix/eintr_wrapper.h"
[email protected]dfa049e2013-02-07 02:57:2243#include "base/strings/string_number_conversions.h"
[email protected]6c24cad2014-03-26 04:16:5844#include "build/build_config.h"
[email protected]48c27f72010-01-26 06:26:2645
46#if defined(USE_SYMBOLIZE)
47#include "base/third_party/symbolize/symbolize.h"
48#endif
[email protected]1ffe08c12008-08-13 11:15:1149
[email protected]58580352010-10-26 04:07:5050namespace base {
51namespace debug {
52
[email protected]79b6fa62009-10-14 03:01:4453namespace {
[email protected]58580352010-10-26 04:07:5054
[email protected]1e218b72012-11-14 19:32:2355volatile sig_atomic_t in_signal_handler = 0;
56
[email protected]f9b0ea5e2013-10-03 23:26:2257#if !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
[email protected]79b6fa62009-10-14 03:01:4458// The prefix used for mangled symbols, per the Itanium C++ ABI:
59// http://www.codesourcery.com/cxx-abi/abi.html#mangling
60const char kMangledSymbolPrefix[] = "_Z";
61
62// Characters that can be used for symbols, generated by Ruby:
63// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
64const char kSymbolCharacters[] =
65 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
[email protected]f9b0ea5e2013-10-03 23:26:2266#endif // !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
[email protected]79b6fa62009-10-14 03:01:4467
[email protected]ffa59d62010-09-13 18:17:4168#if !defined(USE_SYMBOLIZE)
[email protected]79b6fa62009-10-14 03:01:4469// Demangles C++ symbols in the given text. Example:
70//
[email protected]016498e2010-12-03 00:59:2371// "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
[email protected]79b6fa62009-10-14 03:01:4472// =>
[email protected]016498e2010-12-03 00:59:2373// "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
[email protected]79b6fa62009-10-14 03:01:4474void DemangleSymbols(std::string* text) {
[email protected]1e218b72012-11-14 19:32:2375 // Note: code in this function is NOT async-signal safe (std::string uses
76 // malloc internally).
77
[email protected]816e50452014-04-09 22:29:3878#if defined(__GLIBCXX__) && !defined(__UCLIBC__)
[email protected]79b6fa62009-10-14 03:01:4479
80 std::string::size_type search_from = 0;
81 while (search_from < text->size()) {
82 // Look for the start of a mangled symbol, from search_from.
83 std::string::size_type mangled_start =
84 text->find(kMangledSymbolPrefix, search_from);
85 if (mangled_start == std::string::npos) {
86 break; // Mangled symbol not found.
87 }
88
89 // Look for the end of the mangled symbol.
90 std::string::size_type mangled_end =
91 text->find_first_not_of(kSymbolCharacters, mangled_start);
92 if (mangled_end == std::string::npos) {
93 mangled_end = text->size();
94 }
95 std::string mangled_symbol =
96 text->substr(mangled_start, mangled_end - mangled_start);
97
98 // Try to demangle the mangled symbol candidate.
99 int status = 0;
[email protected]6ae7ee762014-02-16 22:18:43100 scoped_ptr<char, base::FreeDeleter> demangled_symbol(
[email protected]79b6fa62009-10-14 03:01:44101 abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
102 if (status == 0) { // Demangling is successful.
103 // Remove the mangled symbol.
104 text->erase(mangled_start, mangled_end - mangled_start);
105 // Insert the demangled symbol.
106 text->insert(mangled_start, demangled_symbol.get());
107 // Next time, we'll start right after the demangled symbol we inserted.
108 search_from = mangled_start + strlen(demangled_symbol.get());
109 } else {
110 // Failed to demangle. Retry after the "_Z" we just found.
111 search_from = mangled_start + 2;
112 }
113 }
114
[email protected]816e50452014-04-09 22:29:38115#endif // defined(__GLIBCXX__) && !defined(__UCLIBC__)
[email protected]79b6fa62009-10-14 03:01:44116}
[email protected]ffa59d62010-09-13 18:17:41117#endif // !defined(USE_SYMBOLIZE)
[email protected]48c27f72010-01-26 06:26:26118
[email protected]1e218b72012-11-14 19:32:23119class BacktraceOutputHandler {
120 public:
121 virtual void HandleOutput(const char* output) = 0;
122
123 protected:
124 virtual ~BacktraceOutputHandler() {}
125};
126
slan9cac7512016-02-02 22:18:14127#if !defined(__UCLIBC__)
[email protected]1e218b72012-11-14 19:32:23128void OutputPointer(void* pointer, BacktraceOutputHandler* handler) {
[email protected]ad9a0122014-03-22 00:34:52129 // This should be more than enough to store a 64-bit number in hex:
130 // 16 hex digits + 1 for null-terminator.
131 char buf[17] = { '\0' };
132 handler->HandleOutput("0x");
[email protected]22d5b9822013-01-10 18:21:52133 internal::itoa_r(reinterpret_cast<intptr_t>(pointer),
134 buf, sizeof(buf), 16, 12);
[email protected]1e218b72012-11-14 19:32:23135 handler->HandleOutput(buf);
[email protected]1e218b72012-11-14 19:32:23136}
137
[email protected]ad9a0122014-03-22 00:34:52138#if defined(USE_SYMBOLIZE)
139void OutputFrameId(intptr_t frame_id, BacktraceOutputHandler* handler) {
140 // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615).
141 // Hence, 30 digits should be more than enough to represent it in decimal
142 // (including the null-terminator).
143 char buf[30] = { '\0' };
144 handler->HandleOutput("#");
145 internal::itoa_r(frame_id, buf, sizeof(buf), 10, 1);
146 handler->HandleOutput(buf);
147}
148#endif // defined(USE_SYMBOLIZE)
149
[email protected]1e218b72012-11-14 19:32:23150void ProcessBacktrace(void *const *trace,
[email protected]675a9b5c2014-03-18 15:41:33151 size_t size,
[email protected]1e218b72012-11-14 19:32:23152 BacktraceOutputHandler* handler) {
153 // NOTE: This code MUST be async-signal safe (it's used by in-process
154 // stack dumping signal handler). NO malloc or stdio is allowed here.
[email protected]48c27f72010-01-26 06:26:26155
156#if defined(USE_SYMBOLIZE)
[email protected]675a9b5c2014-03-18 15:41:33157 for (size_t i = 0; i < size; ++i) {
[email protected]ad9a0122014-03-22 00:34:52158 OutputFrameId(i, handler);
159 handler->HandleOutput(" ");
[email protected]22d5b9822013-01-10 18:21:52160 OutputPointer(trace[i], handler);
161 handler->HandleOutput(" ");
[email protected]1e218b72012-11-14 19:32:23162
163 char buf[1024] = { '\0' };
164
[email protected]48c27f72010-01-26 06:26:26165 // Subtract by one as return address of function may be in the next
166 // function when a function is annotated as noreturn.
[email protected]1e218b72012-11-14 19:32:23167 void* address = static_cast<char*>(trace[i]) - 1;
168 if (google::Symbolize(address, buf, sizeof(buf)))
169 handler->HandleOutput(buf);
170 else
171 handler->HandleOutput("<unknown>");
172
[email protected]1e218b72012-11-14 19:32:23173 handler->HandleOutput("\n");
[email protected]48c27f72010-01-26 06:26:26174 }
slan9cac7512016-02-02 22:18:14175#else
[email protected]1e218b72012-11-14 19:32:23176 bool printed = false;
177
178 // Below part is async-signal unsafe (uses malloc), so execute it only
179 // when we are not executing the signal handler.
180 if (in_signal_handler == 0) {
[email protected]dedde4ad2014-02-26 20:29:57181 scoped_ptr<char*, FreeDeleter>
182 trace_symbols(backtrace_symbols(trace, size));
[email protected]1e218b72012-11-14 19:32:23183 if (trace_symbols.get()) {
[email protected]675a9b5c2014-03-18 15:41:33184 for (size_t i = 0; i < size; ++i) {
[email protected]1e218b72012-11-14 19:32:23185 std::string trace_symbol = trace_symbols.get()[i];
186 DemangleSymbols(&trace_symbol);
187 handler->HandleOutput(trace_symbol.c_str());
188 handler->HandleOutput("\n");
189 }
190
191 printed = true;
[email protected]48c27f72010-01-26 06:26:26192 }
[email protected]1e218b72012-11-14 19:32:23193 }
194
195 if (!printed) {
[email protected]675a9b5c2014-03-18 15:41:33196 for (size_t i = 0; i < size; ++i) {
[email protected]ad9a0122014-03-22 00:34:52197 handler->HandleOutput(" [");
[email protected]1e218b72012-11-14 19:32:23198 OutputPointer(trace[i], handler);
[email protected]ad9a0122014-03-22 00:34:52199 handler->HandleOutput("]\n");
[email protected]48c27f72010-01-26 06:26:26200 }
201 }
202#endif // defined(USE_SYMBOLIZE)
[email protected]48c27f72010-01-26 06:26:26203}
slan9cac7512016-02-02 22:18:14204#endif // !defined(__UCLIBC__)
[email protected]48c27f72010-01-26 06:26:26205
[email protected]fca279e2013-01-15 22:27:55206void PrintToStderr(const char* output) {
207 // NOTE: This code MUST be async-signal safe (it's used by in-process
208 // stack dumping signal handler). NO malloc or stdio is allowed here.
209 ignore_result(HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output))));
210}
211
[email protected]52e62b52013-01-14 18:53:56212void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
[email protected]1e218b72012-11-14 19:32:23213 // NOTE: This code MUST be async-signal safe.
214 // NO malloc or stdio is allowed here.
215
216 // Record the fact that we are in the signal handler now, so that the rest
217 // of StackTrace can behave in an async-signal-safe manner.
218 in_signal_handler = 1;
219
[email protected]11b93faa2012-11-01 21:58:30220 if (BeingDebugged())
221 BreakDebugger();
222
[email protected]fca279e2013-01-15 22:27:55223 PrintToStderr("Received signal ");
224 char buf[1024] = { 0 };
225 internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
226 PrintToStderr(buf);
227 if (signal == SIGBUS) {
228 if (info->si_code == BUS_ADRALN)
229 PrintToStderr(" BUS_ADRALN ");
230 else if (info->si_code == BUS_ADRERR)
231 PrintToStderr(" BUS_ADRERR ");
232 else if (info->si_code == BUS_OBJERR)
233 PrintToStderr(" BUS_OBJERR ");
234 else
235 PrintToStderr(" <unknown> ");
236 } else if (signal == SIGFPE) {
237 if (info->si_code == FPE_FLTDIV)
238 PrintToStderr(" FPE_FLTDIV ");
239 else if (info->si_code == FPE_FLTINV)
240 PrintToStderr(" FPE_FLTINV ");
241 else if (info->si_code == FPE_FLTOVF)
242 PrintToStderr(" FPE_FLTOVF ");
243 else if (info->si_code == FPE_FLTRES)
244 PrintToStderr(" FPE_FLTRES ");
245 else if (info->si_code == FPE_FLTSUB)
246 PrintToStderr(" FPE_FLTSUB ");
247 else if (info->si_code == FPE_FLTUND)
248 PrintToStderr(" FPE_FLTUND ");
249 else if (info->si_code == FPE_INTDIV)
250 PrintToStderr(" FPE_INTDIV ");
251 else if (info->si_code == FPE_INTOVF)
252 PrintToStderr(" FPE_INTOVF ");
253 else
254 PrintToStderr(" <unknown> ");
255 } else if (signal == SIGILL) {
256 if (info->si_code == ILL_BADSTK)
257 PrintToStderr(" ILL_BADSTK ");
258 else if (info->si_code == ILL_COPROC)
259 PrintToStderr(" ILL_COPROC ");
260 else if (info->si_code == ILL_ILLOPN)
261 PrintToStderr(" ILL_ILLOPN ");
262 else if (info->si_code == ILL_ILLADR)
263 PrintToStderr(" ILL_ILLADR ");
264 else if (info->si_code == ILL_ILLTRP)
265 PrintToStderr(" ILL_ILLTRP ");
266 else if (info->si_code == ILL_PRVOPC)
267 PrintToStderr(" ILL_PRVOPC ");
268 else if (info->si_code == ILL_PRVREG)
269 PrintToStderr(" ILL_PRVREG ");
270 else
271 PrintToStderr(" <unknown> ");
272 } else if (signal == SIGSEGV) {
273 if (info->si_code == SEGV_MAPERR)
274 PrintToStderr(" SEGV_MAPERR ");
275 else if (info->si_code == SEGV_ACCERR)
276 PrintToStderr(" SEGV_ACCERR ");
277 else
278 PrintToStderr(" <unknown> ");
279 }
280 if (signal == SIGBUS || signal == SIGFPE ||
281 signal == SIGILL || signal == SIGSEGV) {
282 internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
283 buf, sizeof(buf), 16, 12);
284 PrintToStderr(buf);
285 }
286 PrintToStderr("\n");
[email protected]1e218b72012-11-14 19:32:23287
pccff5504112015-08-07 00:50:36288#if defined(CFI_ENFORCEMENT)
289 if (signal == SIGILL && info->si_code == ILL_ILLOPN) {
290 PrintToStderr(
291 "CFI: Most likely a control flow integrity violation; for more "
292 "information see:\n");
293 PrintToStderr(
294 "https://www.chromium.org/developers/testing/control-flow-integrity\n");
295 }
296#endif
297
[email protected]5ddbf1c2013-08-29 01:59:38298 debug::StackTrace().Print();
[email protected]11b93faa2012-11-01 21:58:30299
[email protected]22d5b9822013-01-10 18:21:52300#if defined(OS_LINUX)
[email protected]52e62b52013-01-14 18:53:56301#if ARCH_CPU_X86_FAMILY
302 ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
[email protected]22d5b9822013-01-10 18:21:52303 const struct {
304 const char* label;
305 greg_t value;
306 } registers[] = {
[email protected]52e62b52013-01-14 18:53:56307#if ARCH_CPU_32_BITS
308 { " gs: ", context->uc_mcontext.gregs[REG_GS] },
309 { " fs: ", context->uc_mcontext.gregs[REG_FS] },
310 { " es: ", context->uc_mcontext.gregs[REG_ES] },
311 { " ds: ", context->uc_mcontext.gregs[REG_DS] },
312 { " edi: ", context->uc_mcontext.gregs[REG_EDI] },
313 { " esi: ", context->uc_mcontext.gregs[REG_ESI] },
314 { " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
315 { " esp: ", context->uc_mcontext.gregs[REG_ESP] },
316 { " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
317 { " edx: ", context->uc_mcontext.gregs[REG_EDX] },
318 { " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
319 { " eax: ", context->uc_mcontext.gregs[REG_EAX] },
320 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
321 { " err: ", context->uc_mcontext.gregs[REG_ERR] },
322 { " ip: ", context->uc_mcontext.gregs[REG_EIP] },
323 { " cs: ", context->uc_mcontext.gregs[REG_CS] },
324 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
325 { " usp: ", context->uc_mcontext.gregs[REG_UESP] },
326 { " ss: ", context->uc_mcontext.gregs[REG_SS] },
327#elif ARCH_CPU_64_BITS
[email protected]22d5b9822013-01-10 18:21:52328 { " r8: ", context->uc_mcontext.gregs[REG_R8] },
329 { " r9: ", context->uc_mcontext.gregs[REG_R9] },
330 { " r10: ", context->uc_mcontext.gregs[REG_R10] },
331 { " r11: ", context->uc_mcontext.gregs[REG_R11] },
332 { " r12: ", context->uc_mcontext.gregs[REG_R12] },
333 { " r13: ", context->uc_mcontext.gregs[REG_R13] },
334 { " r14: ", context->uc_mcontext.gregs[REG_R14] },
335 { " r15: ", context->uc_mcontext.gregs[REG_R15] },
336 { " di: ", context->uc_mcontext.gregs[REG_RDI] },
337 { " si: ", context->uc_mcontext.gregs[REG_RSI] },
338 { " bp: ", context->uc_mcontext.gregs[REG_RBP] },
339 { " bx: ", context->uc_mcontext.gregs[REG_RBX] },
340 { " dx: ", context->uc_mcontext.gregs[REG_RDX] },
341 { " ax: ", context->uc_mcontext.gregs[REG_RAX] },
342 { " cx: ", context->uc_mcontext.gregs[REG_RCX] },
343 { " sp: ", context->uc_mcontext.gregs[REG_RSP] },
344 { " ip: ", context->uc_mcontext.gregs[REG_RIP] },
345 { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
346 { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
347 { " erf: ", context->uc_mcontext.gregs[REG_ERR] },
348 { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
349 { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
350 { " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
erikchenff54ec02015-11-05 00:54:26351#endif // ARCH_CPU_32_BITS
[email protected]22d5b9822013-01-10 18:21:52352 };
353
[email protected]52e62b52013-01-14 18:53:56354#if ARCH_CPU_32_BITS
355 const int kRegisterPadding = 8;
356#elif ARCH_CPU_64_BITS
357 const int kRegisterPadding = 16;
358#endif
359
viettrungluu805eabb2014-10-16 04:02:49360 for (size_t i = 0; i < arraysize(registers); i++) {
[email protected]fca279e2013-01-15 22:27:55361 PrintToStderr(registers[i].label);
[email protected]52e62b52013-01-14 18:53:56362 internal::itoa_r(registers[i].value, buf, sizeof(buf),
363 16, kRegisterPadding);
[email protected]fca279e2013-01-15 22:27:55364 PrintToStderr(buf);
[email protected]22d5b9822013-01-10 18:21:52365
[email protected]fca279e2013-01-15 22:27:55366 if ((i + 1) % 4 == 0)
367 PrintToStderr("\n");
[email protected]22d5b9822013-01-10 18:21:52368 }
[email protected]fca279e2013-01-15 22:27:55369 PrintToStderr("\n");
erikchenff54ec02015-11-05 00:54:26370#endif // ARCH_CPU_X86_FAMILY
371#endif // defined(OS_LINUX)
pccff5504112015-08-07 00:50:36372
373 PrintToStderr("[end of stack trace]\n");
374
erikchenff54ec02015-11-05 00:54:26375#if defined(OS_MACOSX) && !defined(OS_IOS)
376 if (::signal(signal, SIG_DFL) == SIG_ERR)
377 _exit(1);
378#else
379 // Non-Mac OSes should probably reraise the signal as well, but the Linux
380 // sandbox tests break on CrOS devices.
381 // https://code.google.com/p/chromium/issues/detail?id=551681
jorgeloe5c3e3c62015-11-04 18:05:12382 _exit(1);
erikchenff54ec02015-11-05 00:54:26383#endif // defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]11b93faa2012-11-01 21:58:30384}
385
[email protected]1e218b72012-11-14 19:32:23386class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
387 public:
388 PrintBacktraceOutputHandler() {}
389
dcheng56488182014-10-21 10:54:51390 void HandleOutput(const char* output) override {
[email protected]1e218b72012-11-14 19:32:23391 // NOTE: This code MUST be async-signal safe (it's used by in-process
392 // stack dumping signal handler). NO malloc or stdio is allowed here.
[email protected]fca279e2013-01-15 22:27:55393 PrintToStderr(output);
[email protected]1e218b72012-11-14 19:32:23394 }
395
396 private:
397 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
398};
399
400class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
401 public:
[email protected]f3c697c52013-01-15 10:52:11402 explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
[email protected]1e218b72012-11-14 19:32:23403 }
404
dcheng56488182014-10-21 10:54:51405 void HandleOutput(const char* output) override { (*os_) << output; }
[email protected]1e218b72012-11-14 19:32:23406
407 private:
408 std::ostream* os_;
409
410 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
411};
412
413void WarmUpBacktrace() {
414 // Warm up stack trace infrastructure. It turns out that on the first
415 // call glibc initializes some internal data structures using pthread_once,
416 // and even backtrace() can call malloc(), leading to hangs.
417 //
418 // Example stack trace snippet (with tcmalloc):
419 //
420 // #8 0x0000000000a173b5 in tc_malloc
421 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
422 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
423 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
424 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
425 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
426 // at dl-open.c:639
427 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
428 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
429 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
430 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
431 // #17 0x00007ffff61ef8f5 in init
432 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
433 // #18 0x00007ffff6aad400 in pthread_once
434 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
435 // #19 0x00007ffff61efa14 in __GI___backtrace
436 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
437 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
438 // at base/debug/stack_trace_posix.cc:175
439 // #21 0x00000000007a4ae5 in
440 // base::(anonymous namespace)::StackDumpSignalHandler
441 // at base/process_util_posix.cc:172
442 // #22 <signal handler called>
443 StackTrace stack_trace;
444}
445
[email protected]79b6fa62009-10-14 03:01:44446} // namespace
447
[email protected]ad9a0122014-03-22 00:34:52448#if defined(USE_SYMBOLIZE)
449
450// class SandboxSymbolizeHelper.
451//
452// The purpose of this class is to prepare and install a "file open" callback
453// needed by the stack trace symbolization code
454// (base/third_party/symbolize/symbolize.h) so that it can function properly
455// in a sandboxed process. The caveat is that this class must be instantiated
456// before the sandboxing is enabled so that it can get the chance to open all
457// the object files that are loaded in the virtual address space of the current
458// process.
459class SandboxSymbolizeHelper {
460 public:
461 // Returns the singleton instance.
462 static SandboxSymbolizeHelper* GetInstance() {
463 return Singleton<SandboxSymbolizeHelper>::get();
464 }
465
466 private:
467 friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>;
468
469 SandboxSymbolizeHelper()
470 : is_initialized_(false) {
471 Init();
472 }
473
474 ~SandboxSymbolizeHelper() {
475 UnregisterCallback();
476 CloseObjectFiles();
477 }
478
479 // Returns a O_RDONLY file descriptor for |file_path| if it was opened
thestig259626c2015-11-23 20:18:11480 // successfully during the initialization. The file is repositioned at
[email protected]ad9a0122014-03-22 00:34:52481 // offset 0.
482 // IMPORTANT: This function must be async-signal-safe because it can be
483 // called from a signal handler (symbolizing stack frames for a crash).
484 int GetFileDescriptor(const char* file_path) {
485 int fd = -1;
486
jam79dc59a2015-08-17 03:38:16487#if !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52488 if (file_path) {
489 // The assumption here is that iterating over std::map<std::string, int>
490 // using a const_iterator does not allocate dynamic memory, hense it is
491 // async-signal-safe.
492 std::map<std::string, int>::const_iterator it;
493 for (it = modules_.begin(); it != modules_.end(); ++it) {
494 if (strcmp((it->first).c_str(), file_path) == 0) {
495 // POSIX.1-2004 requires an implementation to guarantee that dup()
496 // is async-signal-safe.
497 fd = dup(it->second);
498 break;
499 }
500 }
501 // POSIX.1-2004 requires an implementation to guarantee that lseek()
502 // is async-signal-safe.
503 if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) {
504 // Failed to seek.
505 fd = -1;
506 }
507 }
jam79dc59a2015-08-17 03:38:16508#endif // !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52509
510 return fd;
511 }
512
513 // Searches for the object file (from /proc/self/maps) that contains
514 // the specified pc. If found, sets |start_address| to the start address
515 // of where this object file is mapped in memory, sets the module base
516 // address into |base_address|, copies the object file name into
517 // |out_file_name|, and attempts to open the object file. If the object
518 // file is opened successfully, returns the file descriptor. Otherwise,
519 // returns -1. |out_file_name_size| is the size of the file name buffer
520 // (including the null terminator).
521 // IMPORTANT: This function must be async-signal-safe because it can be
522 // called from a signal handler (symbolizing stack frames for a crash).
523 static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address,
524 uint64_t& base_address, char* file_path,
525 int file_path_size) {
526 // This method can only be called after the singleton is instantiated.
527 // This is ensured by the following facts:
528 // * This is the only static method in this class, it is private, and
529 // the class has no friends (except for the DefaultSingletonTraits).
530 // The compiler guarantees that it can only be called after the
531 // singleton is instantiated.
532 // * This method is used as a callback for the stack tracing code and
533 // the callback registration is done in the constructor, so logically
534 // it cannot be called before the singleton is created.
535 SandboxSymbolizeHelper* instance = GetInstance();
536
537 // The assumption here is that iterating over
538 // std::vector<MappedMemoryRegion> using a const_iterator does not allocate
539 // dynamic memory, hence it is async-signal-safe.
540 std::vector<MappedMemoryRegion>::const_iterator it;
541 bool is_first = true;
542 for (it = instance->regions_.begin(); it != instance->regions_.end();
543 ++it, is_first = false) {
544 const MappedMemoryRegion& region = *it;
545 if (region.start <= pc && pc < region.end) {
546 start_address = region.start;
547 // Don't subtract 'start_address' from the first entry:
548 // * If a binary is compiled w/o -pie, then the first entry in
549 // process maps is likely the binary itself (all dynamic libs
550 // are mapped higher in address space). For such a binary,
551 // instruction offset in binary coincides with the actual
552 // instruction address in virtual memory (as code section
553 // is mapped to a fixed memory range).
554 // * If a binary is compiled with -pie, all the modules are
555 // mapped high at address space (in particular, higher than
556 // shadow memory of the tool), so the module can't be the
557 // first entry.
558 base_address = (is_first ? 0U : start_address) - region.offset;
559 if (file_path && file_path_size > 0) {
560 strncpy(file_path, region.path.c_str(), file_path_size);
561 // Ensure null termination.
562 file_path[file_path_size - 1] = '\0';
563 }
564 return instance->GetFileDescriptor(region.path.c_str());
565 }
566 }
567 return -1;
568 }
569
570 // Parses /proc/self/maps in order to compile a list of all object file names
571 // for the modules that are loaded in the current process.
572 // Returns true on success.
573 bool CacheMemoryRegions() {
574 // Reads /proc/self/maps.
575 std::string contents;
576 if (!ReadProcMaps(&contents)) {
577 LOG(ERROR) << "Failed to read /proc/self/maps";
578 return false;
579 }
580
581 // Parses /proc/self/maps.
582 if (!ParseProcMaps(contents, &regions_)) {
583 LOG(ERROR) << "Failed to parse the contents of /proc/self/maps";
584 return false;
585 }
586
587 is_initialized_ = true;
588 return true;
589 }
590
591 // Opens all object files and caches their file descriptors.
592 void OpenSymbolFiles() {
593 // Pre-opening and caching the file descriptors of all loaded modules is
jam79dc59a2015-08-17 03:38:16594 // not safe for production builds. Hence it is only done in non-official
595 // builds. For more details, take a look at: http://crbug.com/341966.
596#if !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52597 // Open the object files for all read-only executable regions and cache
598 // their file descriptors.
599 std::vector<MappedMemoryRegion>::const_iterator it;
600 for (it = regions_.begin(); it != regions_.end(); ++it) {
601 const MappedMemoryRegion& region = *it;
602 // Only interesed in read-only executable regions.
603 if ((region.permissions & MappedMemoryRegion::READ) ==
604 MappedMemoryRegion::READ &&
605 (region.permissions & MappedMemoryRegion::WRITE) == 0 &&
606 (region.permissions & MappedMemoryRegion::EXECUTE) ==
607 MappedMemoryRegion::EXECUTE) {
608 if (region.path.empty()) {
609 // Skip regions with empty file names.
610 continue;
611 }
612 if (region.path[0] == '[') {
613 // Skip pseudo-paths, like [stack], [vdso], [heap], etc ...
614 continue;
615 }
616 // Avoid duplicates.
617 if (modules_.find(region.path) == modules_.end()) {
618 int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC);
619 if (fd >= 0) {
620 modules_.insert(std::make_pair(region.path, fd));
621 } else {
622 LOG(WARNING) << "Failed to open file: " << region.path
623 << "\n Error: " << strerror(errno);
624 }
625 }
626 }
627 }
jam79dc59a2015-08-17 03:38:16628#endif // !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52629 }
630
631 // Initializes and installs the symbolization callback.
632 void Init() {
633 if (CacheMemoryRegions()) {
634 OpenSymbolFiles();
635 google::InstallSymbolizeOpenObjectFileCallback(
636 &OpenObjectFileContainingPc);
637 }
638 }
639
640 // Unregister symbolization callback.
641 void UnregisterCallback() {
642 if (is_initialized_) {
643 google::InstallSymbolizeOpenObjectFileCallback(NULL);
644 is_initialized_ = false;
645 }
646 }
647
648 // Closes all file descriptors owned by this instance.
649 void CloseObjectFiles() {
jam79dc59a2015-08-17 03:38:16650#if !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52651 std::map<std::string, int>::iterator it;
652 for (it = modules_.begin(); it != modules_.end(); ++it) {
653 int ret = IGNORE_EINTR(close(it->second));
654 DCHECK(!ret);
655 it->second = -1;
656 }
657 modules_.clear();
jam79dc59a2015-08-17 03:38:16658#endif // !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52659 }
660
661 // Set to true upon successful initialization.
662 bool is_initialized_;
663
jam79dc59a2015-08-17 03:38:16664#if !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52665 // Mapping from file name to file descriptor. Includes file descriptors
666 // for all successfully opened object files and the file descriptor for
jam79dc59a2015-08-17 03:38:16667 // /proc/self/maps. This code is not safe for production builds.
[email protected]ad9a0122014-03-22 00:34:52668 std::map<std::string, int> modules_;
jam79dc59a2015-08-17 03:38:16669#endif // !defined(OFFICIAL_BUILD)
[email protected]ad9a0122014-03-22 00:34:52670
671 // Cache for the process memory regions. Produced by parsing the contents
672 // of /proc/self/maps cache.
673 std::vector<MappedMemoryRegion> regions_;
674
675 DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper);
676};
677#endif // USE_SYMBOLIZE
678
jam79dc59a2015-08-17 03:38:16679bool EnableInProcessStackDumping() {
[email protected]ad9a0122014-03-22 00:34:52680#if defined(USE_SYMBOLIZE)
681 SandboxSymbolizeHelper::GetInstance();
682#endif // USE_SYMBOLIZE
683
[email protected]11b93faa2012-11-01 21:58:30684 // When running in an application, our code typically expects SIGPIPE
685 // to be ignored. Therefore, when testing that same code, it should run
686 // with SIGPIPE ignored as well.
[email protected]52e62b52013-01-14 18:53:56687 struct sigaction sigpipe_action;
688 memset(&sigpipe_action, 0, sizeof(sigpipe_action));
689 sigpipe_action.sa_handler = SIG_IGN;
690 sigemptyset(&sigpipe_action.sa_mask);
691 bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
[email protected]11b93faa2012-11-01 21:58:30692
[email protected]1e218b72012-11-14 19:32:23693 // Avoid hangs during backtrace initialization, see above.
694 WarmUpBacktrace();
695
[email protected]52e62b52013-01-14 18:53:56696 struct sigaction action;
697 memset(&action, 0, sizeof(action));
698 action.sa_flags = SA_RESETHAND | SA_SIGINFO;
699 action.sa_sigaction = &StackDumpSignalHandler;
700 sigemptyset(&action.sa_mask);
701
702 success &= (sigaction(SIGILL, &action, NULL) == 0);
703 success &= (sigaction(SIGABRT, &action, NULL) == 0);
704 success &= (sigaction(SIGFPE, &action, NULL) == 0);
705 success &= (sigaction(SIGBUS, &action, NULL) == 0);
706 success &= (sigaction(SIGSEGV, &action, NULL) == 0);
[email protected]6c24cad2014-03-26 04:16:58707// On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing.
708#if !defined(OS_LINUX)
[email protected]52e62b52013-01-14 18:53:56709 success &= (sigaction(SIGSYS, &action, NULL) == 0);
[email protected]6c24cad2014-03-26 04:16:58710#endif // !defined(OS_LINUX)
[email protected]11b93faa2012-11-01 21:58:30711
712 return success;
713}
[email protected]11b93faa2012-11-01 21:58:30714
[email protected]5485cdc2009-01-16 21:17:30715StackTrace::StackTrace() {
[email protected]1e218b72012-11-14 19:32:23716 // NOTE: This code MUST be async-signal safe (it's used by in-process
717 // stack dumping signal handler). NO malloc or stdio is allowed here.
718
[email protected]816e50452014-04-09 22:29:38719#if !defined(__UCLIBC__)
[email protected]6e4bf0b2009-09-17 16:12:36720 // Though the backtrace API man page does not list any possible negative
721 // return values, we take no chance.
[email protected]82933a582014-03-12 09:28:14722 count_ = base::saturated_cast<size_t>(backtrace(trace_, arraysize(trace_)));
[email protected]816e50452014-04-09 22:29:38723#else
724 count_ = 0;
725#endif
[email protected]5485cdc2009-01-16 21:17:30726}
727
[email protected]5ddbf1c2013-08-29 01:59:38728void StackTrace::Print() const {
[email protected]1e218b72012-11-14 19:32:23729 // NOTE: This code MUST be async-signal safe (it's used by in-process
730 // stack dumping signal handler). NO malloc or stdio is allowed here.
731
[email protected]7cf10ed2014-06-27 09:21:03732#if !defined(__UCLIBC__)
[email protected]1e218b72012-11-14 19:32:23733 PrintBacktraceOutputHandler handler;
734 ProcessBacktrace(trace_, count_, &handler);
[email protected]7cf10ed2014-06-27 09:21:03735#endif
[email protected]5485cdc2009-01-16 21:17:30736}
[email protected]96fd0032009-04-24 00:13:08737
[email protected]7cf10ed2014-06-27 09:21:03738#if !defined(__UCLIBC__)
[email protected]501dfc42011-04-14 16:34:00739void StackTrace::OutputToStream(std::ostream* os) const {
[email protected]1e218b72012-11-14 19:32:23740 StreamBacktraceOutputHandler handler(os);
741 ProcessBacktrace(trace_, count_, &handler);
742}
[email protected]816e50452014-04-09 22:29:38743#endif
[email protected]1e218b72012-11-14 19:32:23744
745namespace internal {
746
747// NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
thestig259626c2015-11-23 20:18:11748char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
[email protected]1e218b72012-11-14 19:32:23749 // Make sure we can write at least one NUL byte.
750 size_t n = 1;
751 if (n > sz)
752 return NULL;
753
754 if (base < 2 || base > 16) {
755 buf[0] = '\000';
756 return NULL;
[email protected]48c27f72010-01-26 06:26:26757 }
758
thestig259626c2015-11-23 20:18:11759 char* start = buf;
[email protected]1e218b72012-11-14 19:32:23760
761 uintptr_t j = i;
762
763 // Handle negative numbers (only for base 10).
764 if (i < 0 && base == 10) {
tnagelac4d28e2015-06-23 18:16:31765 // This does "j = -i" while avoiding integer overflow.
766 j = static_cast<uintptr_t>(-(i + 1)) + 1;
[email protected]1e218b72012-11-14 19:32:23767
768 // Make sure we can write the '-' character.
769 if (++n > sz) {
770 buf[0] = '\000';
771 return NULL;
772 }
773 *start++ = '-';
[email protected]96fd0032009-04-24 00:13:08774 }
[email protected]1e218b72012-11-14 19:32:23775
776 // Loop until we have converted the entire number. Output at least one
777 // character (i.e. '0').
thestig259626c2015-11-23 20:18:11778 char* ptr = start;
[email protected]1e218b72012-11-14 19:32:23779 do {
780 // Make sure there is still enough space left in our output buffer.
781 if (++n > sz) {
782 buf[0] = '\000';
783 return NULL;
784 }
785
786 // Output the next digit.
787 *ptr++ = "0123456789abcdef"[j % base];
788 j /= base;
[email protected]22d5b9822013-01-10 18:21:52789
790 if (padding > 0)
791 padding--;
792 } while (j > 0 || padding > 0);
[email protected]1e218b72012-11-14 19:32:23793
794 // Terminate the output with a NUL character.
795 *ptr = '\000';
796
797 // Conversion to ASCII actually resulted in the digits being in reverse
798 // order. We can't easily generate them in forward order, as we can't tell
799 // the number of characters needed until we are done converting.
800 // So, now, we reverse the string (except for the possible "-" sign).
801 while (--ptr > start) {
802 char ch = *ptr;
803 *ptr = *start;
804 *start++ = ch;
805 }
806 return buf;
[email protected]96fd0032009-04-24 00:13:08807}
[email protected]58580352010-10-26 04:07:50808
[email protected]1e218b72012-11-14 19:32:23809} // namespace internal
810
[email protected]58580352010-10-26 04:07:50811} // namespace debug
812} // namespace base