blob: dfafc13bfae55a632dae35aa05971aea40082d81 [file] [log] [blame]
[email protected]f1633932010-08-17 23:05:281// Copyright (c) 2010 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
5#include "base/debug_util.h"
6
[email protected]96fd0032009-04-24 00:13:087#include <errno.h>
[email protected]e6f456242008-10-08 15:27:408#include <fcntl.h>
[email protected]d1fc4372009-01-16 22:06:199#include <stdio.h>
[email protected]54823b0f2010-03-18 04:30:1410#include <stdlib.h>
[email protected]e6f456242008-10-08 15:27:4011#include <sys/stat.h>
[email protected]1ffe08c12008-08-13 11:15:1112#include <sys/sysctl.h>
13#include <sys/types.h>
[email protected]e6f456242008-10-08 15:27:4014#include <unistd.h>
[email protected]1ffe08c12008-08-13 11:15:1115
[email protected]f1633932010-08-17 23:05:2816#include <string>
17#include <vector>
18
[email protected]79b6fa62009-10-14 03:01:4419#if defined(__GLIBCXX__)
20#include <cxxabi.h>
21#endif
22
[email protected]6e4bf0b2009-09-17 16:12:3623#if defined(OS_MACOSX)
24#include <AvailabilityMacros.h>
25#endif
26
[email protected]54823b0f2010-03-18 04:30:1427#include <iostream>
[email protected]54823b0f2010-03-18 04:30:1428
[email protected]e6f456242008-10-08 15:27:4029#include "base/basictypes.h"
[email protected]9543af052009-09-15 22:42:5930#include "base/compat_execinfo.h"
[email protected]157c61b2009-05-01 21:37:3131#include "base/eintr_wrapper.h"
[email protected]0dfc81b2008-08-25 03:44:4032#include "base/logging.h"
[email protected]57b765672009-10-13 18:27:4033#include "base/safe_strerror_posix.h"
[email protected]96fd0032009-04-24 00:13:0834#include "base/scoped_ptr.h"
[email protected]1ffe08c12008-08-13 11:15:1135#include "base/string_piece.h"
[email protected]f1633932010-08-17 23:05:2836#include "base/stringprintf.h"
[email protected]48c27f72010-01-26 06:26:2637
38#if defined(USE_SYMBOLIZE)
39#include "base/third_party/symbolize/symbolize.h"
40#endif
[email protected]1ffe08c12008-08-13 11:15:1141
[email protected]79b6fa62009-10-14 03:01:4442namespace {
43// The prefix used for mangled symbols, per the Itanium C++ ABI:
44// http://www.codesourcery.com/cxx-abi/abi.html#mangling
45const char kMangledSymbolPrefix[] = "_Z";
46
47// Characters that can be used for symbols, generated by Ruby:
48// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
49const char kSymbolCharacters[] =
50 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
51
[email protected]ffa59d62010-09-13 18:17:4152#if !defined(USE_SYMBOLIZE)
[email protected]79b6fa62009-10-14 03:01:4453// Demangles C++ symbols in the given text. Example:
54//
55// "sconsbuild/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
56// =>
57// "sconsbuild/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
58void DemangleSymbols(std::string* text) {
59#if defined(__GLIBCXX__)
60
61 std::string::size_type search_from = 0;
62 while (search_from < text->size()) {
63 // Look for the start of a mangled symbol, from search_from.
64 std::string::size_type mangled_start =
65 text->find(kMangledSymbolPrefix, search_from);
66 if (mangled_start == std::string::npos) {
67 break; // Mangled symbol not found.
68 }
69
70 // Look for the end of the mangled symbol.
71 std::string::size_type mangled_end =
72 text->find_first_not_of(kSymbolCharacters, mangled_start);
73 if (mangled_end == std::string::npos) {
74 mangled_end = text->size();
75 }
76 std::string mangled_symbol =
77 text->substr(mangled_start, mangled_end - mangled_start);
78
79 // Try to demangle the mangled symbol candidate.
80 int status = 0;
81 scoped_ptr_malloc<char> demangled_symbol(
82 abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
83 if (status == 0) { // Demangling is successful.
84 // Remove the mangled symbol.
85 text->erase(mangled_start, mangled_end - mangled_start);
86 // Insert the demangled symbol.
87 text->insert(mangled_start, demangled_symbol.get());
88 // Next time, we'll start right after the demangled symbol we inserted.
89 search_from = mangled_start + strlen(demangled_symbol.get());
90 } else {
91 // Failed to demangle. Retry after the "_Z" we just found.
92 search_from = mangled_start + 2;
93 }
94 }
95
96#endif // defined(__GLIBCXX__)
97}
[email protected]ffa59d62010-09-13 18:17:4198#endif // !defined(USE_SYMBOLIZE)
[email protected]48c27f72010-01-26 06:26:2699
100// Gets the backtrace as a vector of strings. If possible, resolve symbol
101// names and attach these. Otherwise just use raw addresses. Returns true
102// if any symbol name is resolved.
103bool GetBacktraceStrings(void **trace, int size,
104 std::vector<std::string>* trace_strings) {
105 bool symbolized = false;
106
107#if defined(USE_SYMBOLIZE)
108 for (int i = 0; i < size; ++i) {
109 char symbol[1024];
110 // Subtract by one as return address of function may be in the next
111 // function when a function is annotated as noreturn.
112 if (google::Symbolize(static_cast<char *>(trace[i]) - 1,
113 symbol, sizeof(symbol))) {
114 // Don't call DemangleSymbols() here as the symbol is demangled by
115 // google::Symbolize().
[email protected]f1633932010-08-17 23:05:28116 trace_strings->push_back(
117 base::StringPrintf("%s [%p]", symbol, trace[i]));
[email protected]48c27f72010-01-26 06:26:26118 symbolized = true;
119 } else {
[email protected]f1633932010-08-17 23:05:28120 trace_strings->push_back(base::StringPrintf("%p", trace[i]));
[email protected]48c27f72010-01-26 06:26:26121 }
122 }
123#else
124 scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
125 if (trace_symbols.get()) {
126 for (int i = 0; i < size; ++i) {
127 std::string trace_symbol = trace_symbols.get()[i];
128 DemangleSymbols(&trace_symbol);
129 trace_strings->push_back(trace_symbol);
130 }
131 symbolized = true;
132 } else {
133 for (int i = 0; i < size; ++i) {
[email protected]f1633932010-08-17 23:05:28134 trace_strings->push_back(base::StringPrintf("%p", trace[i]));
[email protected]48c27f72010-01-26 06:26:26135 }
136 }
137#endif // defined(USE_SYMBOLIZE)
138
139 return symbolized;
140}
141
[email protected]79b6fa62009-10-14 03:01:44142} // namespace
143
[email protected]e6f456242008-10-08 15:27:40144// static
[email protected]1ffe08c12008-08-13 11:15:11145bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
146 NOTIMPLEMENTED();
147 return false;
148}
149
150#if defined(OS_MACOSX)
[email protected]e6f456242008-10-08 15:27:40151
152// Based on Apple's recommended method as described in
[email protected]1ffe08c12008-08-13 11:15:11153// http://developer.apple.com/qa/qa2004/qa1361.html
[email protected]e6f456242008-10-08 15:27:40154// static
[email protected]1ffe08c12008-08-13 11:15:11155bool DebugUtil::BeingDebugged() {
[email protected]dbd9bfc2009-02-05 18:25:20156 // If the process is sandboxed then we can't use the sysctl, so cache the
157 // value.
158 static bool is_set = false;
159 static bool being_debugged = false;
160
161 if (is_set) {
162 return being_debugged;
163 }
164
[email protected]e6f456242008-10-08 15:27:40165 // Initialize mib, which tells sysctl what info we want. In this case,
166 // we're looking for information about a specific process ID.
167 int mib[] = {
168 CTL_KERN,
169 KERN_PROC,
170 KERN_PROC_PID,
171 getpid()
172 };
173
174 // Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and
175 // binary interfaces may change.
176 struct kinfo_proc info;
177 size_t info_size = sizeof(info);
178
179 int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
[email protected]54823b0f2010-03-18 04:30:14180 DCHECK_EQ(sysctl_result, 0);
[email protected]dbd9bfc2009-02-05 18:25:20181 if (sysctl_result != 0) {
182 is_set = true;
183 being_debugged = false;
184 return being_debugged;
185 }
[email protected]e6f456242008-10-08 15:27:40186
187 // This process is being debugged if the P_TRACED flag is set.
[email protected]dbd9bfc2009-02-05 18:25:20188 is_set = true;
189 being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;
190 return being_debugged;
[email protected]1ffe08c12008-08-13 11:15:11191}
192
193#elif defined(OS_LINUX)
[email protected]e6f456242008-10-08 15:27:40194
[email protected]1ffe08c12008-08-13 11:15:11195// We can look in /proc/self/status for TracerPid. We are likely used in crash
196// handling, so we are careful not to use the heap or have side effects.
197// Another option that is common is to try to ptrace yourself, but then we
198// can't detach without forking(), and that's not so great.
[email protected]e6f456242008-10-08 15:27:40199// static
[email protected]1ffe08c12008-08-13 11:15:11200bool DebugUtil::BeingDebugged() {
201 int status_fd = open("/proc/self/status", O_RDONLY);
202 if (status_fd == -1)
203 return false;
204
205 // We assume our line will be in the first 1024 characters and that we can
206 // read this much all at once. In practice this will generally be true.
207 // This simplifies and speeds up things considerably.
208 char buf[1024];
209
[email protected]157c61b2009-05-01 21:37:31210 ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
[email protected]cabe39c2010-02-02 02:28:16211 if (HANDLE_EINTR(close(status_fd)) < 0)
212 return false;
[email protected]1ffe08c12008-08-13 11:15:11213
214 if (num_read <= 0)
215 return false;
216
[email protected]8a16266e2009-09-10 21:08:39217 base::StringPiece status(buf, num_read);
218 base::StringPiece tracer("TracerPid:\t");
[email protected]1ffe08c12008-08-13 11:15:11219
[email protected]8a16266e2009-09-10 21:08:39220 base::StringPiece::size_type pid_index = status.find(tracer);
221 if (pid_index == base::StringPiece::npos)
[email protected]1ffe08c12008-08-13 11:15:11222 return false;
223
224 // Our pid is 0 without a debugger, assume this for any pid starting with 0.
225 pid_index += tracer.size();
226 return pid_index < status.size() && status[pid_index] != '0';
227}
[email protected]e6f456242008-10-08 15:27:40228
[email protected]e43eddf12009-12-29 00:32:52229#elif defined(OS_FREEBSD)
230
231bool DebugUtil::BeingDebugged() {
232 // TODO(benl): can we determine this under FreeBSD?
233 NOTIMPLEMENTED();
234 return false;
235}
236
[email protected]54823b0f2010-03-18 04:30:14237#endif // defined(OS_FREEBSD)
238
239// We want to break into the debugger in Debug mode, and cause a crash dump in
240// Release mode. Breakpad behaves as follows:
241//
242// +-------+-----------------+-----------------+
243// | OS | Dump on SIGTRAP | Dump on SIGABRT |
244// +-------+-----------------+-----------------+
245// | Linux | N | Y |
246// | Mac | Y | N |
247// +-------+-----------------+-----------------+
248//
249// Thus we do the following:
250// Linux: Debug mode, send SIGTRAP; Release mode, send SIGABRT.
251// Mac: Always send SIGTRAP.
252
253#if defined(NDEBUG) && !defined(OS_MACOSX)
254#define DEBUG_BREAK() abort()
255#elif defined(ARCH_CPU_ARM_FAMILY)
256#define DEBUG_BREAK() asm("bkpt 0")
257#else
258#define DEBUG_BREAK() asm("int3")
[email protected]e43eddf12009-12-29 00:32:52259#endif
[email protected]1ffe08c12008-08-13 11:15:11260
261// static
262void DebugUtil::BreakDebugger() {
[email protected]54823b0f2010-03-18 04:30:14263 DEBUG_BREAK();
[email protected]1ffe08c12008-08-13 11:15:11264}
[email protected]5485cdc2009-01-16 21:17:30265
[email protected]5485cdc2009-01-16 21:17:30266StackTrace::StackTrace() {
[email protected]6e4bf0b2009-09-17 16:12:36267#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
[email protected]f358a0a2009-09-18 15:27:56268 if (backtrace == NULL) {
[email protected]9543af052009-09-15 22:42:59269 count_ = 0;
[email protected]6e4bf0b2009-09-17 16:12:36270 return;
[email protected]9543af052009-09-15 22:42:59271 }
[email protected]6e4bf0b2009-09-17 16:12:36272#endif
273 // Though the backtrace API man page does not list any possible negative
274 // return values, we take no chance.
275 count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
[email protected]5485cdc2009-01-16 21:17:30276}
277
278void StackTrace::PrintBacktrace() {
[email protected]6e4bf0b2009-09-17 16:12:36279#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
[email protected]f358a0a2009-09-18 15:27:56280 if (backtrace_symbols_fd == NULL)
[email protected]6e4bf0b2009-09-17 16:12:36281 return;
282#endif
283 fflush(stderr);
[email protected]48c27f72010-01-26 06:26:26284 std::vector<std::string> trace_strings;
285 GetBacktraceStrings(trace_, count_, &trace_strings);
286 for (size_t i = 0; i < trace_strings.size(); ++i) {
287 std::cerr << "\t" << trace_strings[i] << "\n";
288 }
[email protected]5485cdc2009-01-16 21:17:30289}
[email protected]96fd0032009-04-24 00:13:08290
291void StackTrace::OutputToStream(std::ostream* os) {
[email protected]6e4bf0b2009-09-17 16:12:36292#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
[email protected]f358a0a2009-09-18 15:27:56293 if (backtrace_symbols == NULL)
[email protected]6e4bf0b2009-09-17 16:12:36294 return;
295#endif
[email protected]48c27f72010-01-26 06:26:26296 std::vector<std::string> trace_strings;
297 if (GetBacktraceStrings(trace_, count_, &trace_strings)) {
298 (*os) << "Backtrace:\n";
299 } else {
[email protected]57b765672009-10-13 18:27:40300 (*os) << "Unable get symbols for backtrace (" << safe_strerror(errno)
[email protected]6e4bf0b2009-09-17 16:12:36301 << "). Dumping raw addresses in trace:\n";
[email protected]48c27f72010-01-26 06:26:26302 }
303
304 for (size_t i = 0; i < trace_strings.size(); ++i) {
305 (*os) << "\t" << trace_strings[i] << "\n";
[email protected]96fd0032009-04-24 00:13:08306 }
307}