blob: 110cb20aed3892eb180257fe89d6efda4985f46c [file] [log] [blame]
[email protected]96fd0032009-04-24 00:13:081// Copyright (c) 2006-2009 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]79b6fa62009-10-14 03:01:4416#if defined(__GLIBCXX__)
17#include <cxxabi.h>
18#endif
19
[email protected]6e4bf0b2009-09-17 16:12:3620#if defined(OS_MACOSX)
21#include <AvailabilityMacros.h>
22#endif
23
[email protected]54823b0f2010-03-18 04:30:1424#include <iostream>
25#include <string>
26
[email protected]e6f456242008-10-08 15:27:4027#include "base/basictypes.h"
[email protected]9543af052009-09-15 22:42:5928#include "base/compat_execinfo.h"
[email protected]157c61b2009-05-01 21:37:3129#include "base/eintr_wrapper.h"
[email protected]0dfc81b2008-08-25 03:44:4030#include "base/logging.h"
[email protected]57b765672009-10-13 18:27:4031#include "base/safe_strerror_posix.h"
[email protected]96fd0032009-04-24 00:13:0832#include "base/scoped_ptr.h"
[email protected]1ffe08c12008-08-13 11:15:1133#include "base/string_piece.h"
[email protected]48c27f72010-01-26 06:26:2634#include "base/string_util.h"
35
36#if defined(USE_SYMBOLIZE)
37#include "base/third_party/symbolize/symbolize.h"
38#endif
[email protected]1ffe08c12008-08-13 11:15:1139
[email protected]79b6fa62009-10-14 03:01:4440namespace {
41// The prefix used for mangled symbols, per the Itanium C++ ABI:
42// http://www.codesourcery.com/cxx-abi/abi.html#mangling
43const char kMangledSymbolPrefix[] = "_Z";
44
45// Characters that can be used for symbols, generated by Ruby:
46// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
47const char kSymbolCharacters[] =
48 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
49
50// Demangles C++ symbols in the given text. Example:
51//
52// "sconsbuild/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
53// =>
54// "sconsbuild/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
55void DemangleSymbols(std::string* text) {
56#if defined(__GLIBCXX__)
57
58 std::string::size_type search_from = 0;
59 while (search_from < text->size()) {
60 // Look for the start of a mangled symbol, from search_from.
61 std::string::size_type mangled_start =
62 text->find(kMangledSymbolPrefix, search_from);
63 if (mangled_start == std::string::npos) {
64 break; // Mangled symbol not found.
65 }
66
67 // Look for the end of the mangled symbol.
68 std::string::size_type mangled_end =
69 text->find_first_not_of(kSymbolCharacters, mangled_start);
70 if (mangled_end == std::string::npos) {
71 mangled_end = text->size();
72 }
73 std::string mangled_symbol =
74 text->substr(mangled_start, mangled_end - mangled_start);
75
76 // Try to demangle the mangled symbol candidate.
77 int status = 0;
78 scoped_ptr_malloc<char> demangled_symbol(
79 abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
80 if (status == 0) { // Demangling is successful.
81 // Remove the mangled symbol.
82 text->erase(mangled_start, mangled_end - mangled_start);
83 // Insert the demangled symbol.
84 text->insert(mangled_start, demangled_symbol.get());
85 // Next time, we'll start right after the demangled symbol we inserted.
86 search_from = mangled_start + strlen(demangled_symbol.get());
87 } else {
88 // Failed to demangle. Retry after the "_Z" we just found.
89 search_from = mangled_start + 2;
90 }
91 }
92
93#endif // defined(__GLIBCXX__)
94}
[email protected]48c27f72010-01-26 06:26:2695
96// Gets the backtrace as a vector of strings. If possible, resolve symbol
97// names and attach these. Otherwise just use raw addresses. Returns true
98// if any symbol name is resolved.
99bool GetBacktraceStrings(void **trace, int size,
100 std::vector<std::string>* trace_strings) {
101 bool symbolized = false;
102
103#if defined(USE_SYMBOLIZE)
104 for (int i = 0; i < size; ++i) {
105 char symbol[1024];
106 // Subtract by one as return address of function may be in the next
107 // function when a function is annotated as noreturn.
108 if (google::Symbolize(static_cast<char *>(trace[i]) - 1,
109 symbol, sizeof(symbol))) {
110 // Don't call DemangleSymbols() here as the symbol is demangled by
111 // google::Symbolize().
112 trace_strings->push_back(StringPrintf("%s [%p]", symbol, trace[i]));
113 symbolized = true;
114 } else {
115 trace_strings->push_back(StringPrintf("%p", trace[i]));
116 }
117 }
118#else
119 scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
120 if (trace_symbols.get()) {
121 for (int i = 0; i < size; ++i) {
122 std::string trace_symbol = trace_symbols.get()[i];
123 DemangleSymbols(&trace_symbol);
124 trace_strings->push_back(trace_symbol);
125 }
126 symbolized = true;
127 } else {
128 for (int i = 0; i < size; ++i) {
129 trace_strings->push_back(StringPrintf("%p", trace[i]));
130 }
131 }
132#endif // defined(USE_SYMBOLIZE)
133
134 return symbolized;
135}
136
[email protected]79b6fa62009-10-14 03:01:44137} // namespace
138
[email protected]e6f456242008-10-08 15:27:40139// static
[email protected]1ffe08c12008-08-13 11:15:11140bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
141 NOTIMPLEMENTED();
142 return false;
143}
144
145#if defined(OS_MACOSX)
[email protected]e6f456242008-10-08 15:27:40146
147// Based on Apple's recommended method as described in
[email protected]1ffe08c12008-08-13 11:15:11148// http://developer.apple.com/qa/qa2004/qa1361.html
[email protected]e6f456242008-10-08 15:27:40149// static
[email protected]1ffe08c12008-08-13 11:15:11150bool DebugUtil::BeingDebugged() {
[email protected]dbd9bfc2009-02-05 18:25:20151 // If the process is sandboxed then we can't use the sysctl, so cache the
152 // value.
153 static bool is_set = false;
154 static bool being_debugged = false;
155
156 if (is_set) {
157 return being_debugged;
158 }
159
[email protected]e6f456242008-10-08 15:27:40160 // Initialize mib, which tells sysctl what info we want. In this case,
161 // we're looking for information about a specific process ID.
162 int mib[] = {
163 CTL_KERN,
164 KERN_PROC,
165 KERN_PROC_PID,
166 getpid()
167 };
168
169 // Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and
170 // binary interfaces may change.
171 struct kinfo_proc info;
172 size_t info_size = sizeof(info);
173
174 int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
[email protected]54823b0f2010-03-18 04:30:14175 DCHECK_EQ(sysctl_result, 0);
[email protected]dbd9bfc2009-02-05 18:25:20176 if (sysctl_result != 0) {
177 is_set = true;
178 being_debugged = false;
179 return being_debugged;
180 }
[email protected]e6f456242008-10-08 15:27:40181
182 // This process is being debugged if the P_TRACED flag is set.
[email protected]dbd9bfc2009-02-05 18:25:20183 is_set = true;
184 being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;
185 return being_debugged;
[email protected]1ffe08c12008-08-13 11:15:11186}
187
188#elif defined(OS_LINUX)
[email protected]e6f456242008-10-08 15:27:40189
[email protected]1ffe08c12008-08-13 11:15:11190// We can look in /proc/self/status for TracerPid. We are likely used in crash
191// handling, so we are careful not to use the heap or have side effects.
192// Another option that is common is to try to ptrace yourself, but then we
193// can't detach without forking(), and that's not so great.
[email protected]e6f456242008-10-08 15:27:40194// static
[email protected]1ffe08c12008-08-13 11:15:11195bool DebugUtil::BeingDebugged() {
196 int status_fd = open("/proc/self/status", O_RDONLY);
197 if (status_fd == -1)
198 return false;
199
200 // We assume our line will be in the first 1024 characters and that we can
201 // read this much all at once. In practice this will generally be true.
202 // This simplifies and speeds up things considerably.
203 char buf[1024];
204
[email protected]157c61b2009-05-01 21:37:31205 ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
[email protected]cabe39c2010-02-02 02:28:16206 if (HANDLE_EINTR(close(status_fd)) < 0)
207 return false;
[email protected]1ffe08c12008-08-13 11:15:11208
209 if (num_read <= 0)
210 return false;
211
[email protected]8a16266e2009-09-10 21:08:39212 base::StringPiece status(buf, num_read);
213 base::StringPiece tracer("TracerPid:\t");
[email protected]1ffe08c12008-08-13 11:15:11214
[email protected]8a16266e2009-09-10 21:08:39215 base::StringPiece::size_type pid_index = status.find(tracer);
216 if (pid_index == base::StringPiece::npos)
[email protected]1ffe08c12008-08-13 11:15:11217 return false;
218
219 // Our pid is 0 without a debugger, assume this for any pid starting with 0.
220 pid_index += tracer.size();
221 return pid_index < status.size() && status[pid_index] != '0';
222}
[email protected]e6f456242008-10-08 15:27:40223
[email protected]e43eddf12009-12-29 00:32:52224#elif defined(OS_FREEBSD)
225
226bool DebugUtil::BeingDebugged() {
227 // TODO(benl): can we determine this under FreeBSD?
228 NOTIMPLEMENTED();
229 return false;
230}
231
[email protected]54823b0f2010-03-18 04:30:14232#endif // defined(OS_FREEBSD)
233
234// We want to break into the debugger in Debug mode, and cause a crash dump in
235// Release mode. Breakpad behaves as follows:
236//
237// +-------+-----------------+-----------------+
238// | OS | Dump on SIGTRAP | Dump on SIGABRT |
239// +-------+-----------------+-----------------+
240// | Linux | N | Y |
241// | Mac | Y | N |
242// +-------+-----------------+-----------------+
243//
244// Thus we do the following:
245// Linux: Debug mode, send SIGTRAP; Release mode, send SIGABRT.
246// Mac: Always send SIGTRAP.
247
248#if defined(NDEBUG) && !defined(OS_MACOSX)
249#define DEBUG_BREAK() abort()
250#elif defined(ARCH_CPU_ARM_FAMILY)
251#define DEBUG_BREAK() asm("bkpt 0")
252#else
253#define DEBUG_BREAK() asm("int3")
[email protected]e43eddf12009-12-29 00:32:52254#endif
[email protected]1ffe08c12008-08-13 11:15:11255
256// static
257void DebugUtil::BreakDebugger() {
[email protected]54823b0f2010-03-18 04:30:14258 DEBUG_BREAK();
[email protected]1ffe08c12008-08-13 11:15:11259}
[email protected]5485cdc2009-01-16 21:17:30260
[email protected]5485cdc2009-01-16 21:17:30261StackTrace::StackTrace() {
[email protected]6e4bf0b2009-09-17 16:12:36262#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
[email protected]f358a0a2009-09-18 15:27:56263 if (backtrace == NULL) {
[email protected]9543af052009-09-15 22:42:59264 count_ = 0;
[email protected]6e4bf0b2009-09-17 16:12:36265 return;
[email protected]9543af052009-09-15 22:42:59266 }
[email protected]6e4bf0b2009-09-17 16:12:36267#endif
268 // Though the backtrace API man page does not list any possible negative
269 // return values, we take no chance.
270 count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
[email protected]5485cdc2009-01-16 21:17:30271}
272
273void StackTrace::PrintBacktrace() {
[email protected]6e4bf0b2009-09-17 16:12:36274#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
[email protected]f358a0a2009-09-18 15:27:56275 if (backtrace_symbols_fd == NULL)
[email protected]6e4bf0b2009-09-17 16:12:36276 return;
277#endif
278 fflush(stderr);
[email protected]48c27f72010-01-26 06:26:26279 std::vector<std::string> trace_strings;
280 GetBacktraceStrings(trace_, count_, &trace_strings);
281 for (size_t i = 0; i < trace_strings.size(); ++i) {
282 std::cerr << "\t" << trace_strings[i] << "\n";
283 }
[email protected]5485cdc2009-01-16 21:17:30284}
[email protected]96fd0032009-04-24 00:13:08285
286void StackTrace::OutputToStream(std::ostream* os) {
[email protected]6e4bf0b2009-09-17 16:12:36287#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
[email protected]f358a0a2009-09-18 15:27:56288 if (backtrace_symbols == NULL)
[email protected]6e4bf0b2009-09-17 16:12:36289 return;
290#endif
[email protected]48c27f72010-01-26 06:26:26291 std::vector<std::string> trace_strings;
292 if (GetBacktraceStrings(trace_, count_, &trace_strings)) {
293 (*os) << "Backtrace:\n";
294 } else {
[email protected]57b765672009-10-13 18:27:40295 (*os) << "Unable get symbols for backtrace (" << safe_strerror(errno)
[email protected]6e4bf0b2009-09-17 16:12:36296 << "). Dumping raw addresses in trace:\n";
[email protected]48c27f72010-01-26 06:26:26297 }
298
299 for (size_t i = 0; i < trace_strings.size(); ++i) {
300 (*os) << "\t" << trace_strings[i] << "\n";
[email protected]96fd0032009-04-24 00:13:08301 }
302}