Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(60)

Side by Side Diff: base/debug/stack_trace_posix.cc

Issue 11362048: GTTF: Make Linux stack dump signal handler async-signal safe. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 8 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/debug/stack_trace.h" 5 #include "base/debug/stack_trace.h"
6 6
7 #include <errno.h> 7 #include <errno.h>
8 #include <execinfo.h> 8 #include <execinfo.h>
9 #include <fcntl.h> 9 #include <fcntl.h>
10 #include <signal.h> 10 #include <signal.h>
11 #include <stdio.h> 11 #include <stdio.h>
12 #include <stdlib.h> 12 #include <stdlib.h>
13 #include <sys/param.h> 13 #include <sys/param.h>
14 #include <sys/stat.h> 14 #include <sys/stat.h>
15 #include <sys/types.h> 15 #include <sys/types.h>
16 #include <unistd.h> 16 #include <unistd.h>
17 17
18 #include <string> 18 #include <ostream>
19 #include <vector>
20
21 #if defined(__GLIBCXX__)
22 #include <cxxabi.h>
23 #endif
24
25 #if defined(OS_MACOSX)
26 #include <AvailabilityMacros.h>
27 #endif
28 19
29 #include "base/basictypes.h" 20 #include "base/basictypes.h"
21 #include "base/debug/debugger.h"
30 #include "base/eintr_wrapper.h" 22 #include "base/eintr_wrapper.h"
31 #include "base/logging.h" 23 #include "base/logging.h"
32 #include "base/memory/scoped_ptr.h" 24 #include "base/string_number_conversions.h"
33 #include "base/safe_strerror_posix.h"
34 #include "base/string_piece.h"
35 #include "base/stringprintf.h"
36 25
37 #if defined(USE_SYMBOLIZE) 26 #if defined(USE_SYMBOLIZE)
38 #include "base/third_party/symbolize/symbolize.h" 27 #include "base/third_party/symbolize/symbolize.h"
39 #endif 28 #endif
40 29
41 namespace base { 30 namespace base {
42 namespace debug { 31 namespace debug {
43 32
44 namespace { 33 namespace {
45 34
46 // The prefix used for mangled symbols, per the Itanium C++ ABI: 35 class BacktraceOutputHandler {
47 // http://www.codesourcery.com/cxx-abi/abi.html#mangling 36 public:
48 const char kMangledSymbolPrefix[] = "_Z"; 37 virtual void HandleOutput(const char* output) = 0;
49 38
50 // Characters that can be used for symbols, generated by Ruby: 39 protected:
51 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join 40 virtual ~BacktraceOutputHandler() {}
52 const char kSymbolCharacters[] = 41 };
53 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
54 42
55 #if !defined(USE_SYMBOLIZE) 43 // POSIX doesn't define any async-signal safe function for converting
56 // Demangles C++ symbols in the given text. Example: 44 // an integer to ASCII. We'll have to define our own version.
45 // itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
46 // conversion was successful or NULL otherwise. It never writes more than "sz"
47 // bytes. Output will be truncated as needed, and a NUL character is always
48 // appended.
57 // 49 //
58 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]" 50 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
59 // => 51 static char *itoa_r(intptr_t i, char *buf, size_t sz, int base) {
60 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]" 52 // Make sure we can write at least one NUL byte.
61 void DemangleSymbols(std::string* text) { 53 size_t n = 1;
62 #if defined(__GLIBCXX__) 54 if (n > sz) {
55 return NULL;
56 }
63 57
64 std::string::size_type search_from = 0; 58 // Handle negative numbers.
jar (doing other things) 2012/11/02 02:36:57 Negative numbers are only supposed to be handled w
Paweł Hajdan Jr. 2012/11/06 17:58:46 Done.
65 while (search_from < text->size()) { 59 char *start = buf;
66 // Look for the start of a mangled symbol, from search_from. 60 int minint = 0;
67 std::string::size_type mangled_start = 61 if (i < 0) {
68 text->find(kMangledSymbolPrefix, search_from); 62 // Make sure we can write the '-' character.
69 if (mangled_start == std::string::npos) { 63 if (++n > sz) {
70 break; // Mangled symbol not found. 64 *start = '\000';
65 return NULL;
71 } 66 }
67 *start++ = '-';
72 68
73 // Look for the end of the mangled symbol. 69 // Turn our number positive.
74 std::string::size_type mangled_end = 70 if (i == -i) {
75 text->find_first_not_of(kSymbolCharacters, mangled_start); 71 // The lowest-most negative integer needs special treatment.
76 if (mangled_end == std::string::npos) { 72 minint = 1;
77 mangled_end = text->size(); 73 i = -(i + 1);
78 }
79 std::string mangled_symbol =
80 text->substr(mangled_start, mangled_end - mangled_start);
81
82 // Try to demangle the mangled symbol candidate.
83 int status = 0;
84 scoped_ptr_malloc<char> demangled_symbol(
85 abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
86 if (status == 0) { // Demangling is successful.
87 // Remove the mangled symbol.
88 text->erase(mangled_start, mangled_end - mangled_start);
89 // Insert the demangled symbol.
90 text->insert(mangled_start, demangled_symbol.get());
91 // Next time, we'll start right after the demangled symbol we inserted.
92 search_from = mangled_start + strlen(demangled_symbol.get());
93 } else { 74 } else {
94 // Failed to demangle. Retry after the "_Z" we just found. 75 // "Normal" negative numbers are easy.
95 search_from = mangled_start + 2; 76 i = -i;
96 } 77 }
97 } 78 }
98 79
99 #endif // defined(__GLIBCXX__) 80 // Loop until we have converted the entire number. Output at least one
jar (doing other things) 2012/11/02 02:36:57 At this point you should convert to an unsigned va
Paweł Hajdan Jr. 2012/11/06 17:58:46 I don't really understand this (read: I see a scar
jar (doing other things) 2012/11/06 20:40:03 Yeah... unsigned is broader... you don't need the
81 // character (i.e. '0').
82 char *ptr = start;
83 do {
84 // Make sure there is still enough space left in our output buffer.
85 if (++n > sz) {
86 buf = NULL;
87 goto truncate;
jar (doing other things) 2012/11/02 02:36:57 nit: better is "break"
Paweł Hajdan Jr. 2012/11/06 17:58:46 Done.
88 }
89
90 // Output the next digit and (if necessary) compensate for the lowest-most
91 // negative integer needing special treatment. This works because, no
92 // matter the bit width of the integer, the lowest-most integer always ends
93 // in 2, 4, 6, or 8.
jar (doing other things) 2012/11/02 02:36:57 The comment about the least-significant-character
Paweł Hajdan Jr. 2012/11/06 17:58:46 Done.
94 *ptr++ = "0123456789abcdef"[i % base] + minint;
jar (doing other things) 2012/11/02 02:36:57 This then seems wrong, in the case where minint ==
Paweł Hajdan Jr. 2012/11/06 17:58:46 Right, I was thinking about tests. For that, I'd n
95 minint = 0;
96 i /= base;
97 } while (i);
98 truncate: // Terminate the output with a NUL character.
99 *ptr = '\000';
100
101 // Conversion to ASCII actually resulted in the digits being in reverse
102 // order. We can't easily generate them in forward order, as we can't tell
103 // the number of characters needed until we are done converting.
104 // So, now, we reverse the string (except for the possible "-" sign).
105 while (--ptr > start) {
106 char ch = *ptr;
107 *ptr = *start;
108 *start++ = ch;
109 }
110 return buf;
100 } 111 }
101 #endif // !defined(USE_SYMBOLIZE)
102 112
103 // Gets the backtrace as a vector of strings. If possible, resolve symbol 113 void ProcessBacktrace(void *const *trace,
104 // names and attach these. Otherwise just use raw addresses. Returns true 114 int size,
105 // if any symbol name is resolved. Returns false on error and *may* fill 115 BacktraceOutputHandler* handler) {
106 // in |error_message| if an error message is available. 116 // NOTE: This code MUST be async-signal safe (it's used by in-process
107 bool GetBacktraceStrings(void *const *trace, int size, 117 // stack dumping signal handler). NO malloc or stdio is allowed here.
108 std::vector<std::string>* trace_strings, 118
109 std::string* error_message) { 119 for (int i = 0; i < size; ++i) {
110 bool symbolized = false; 120 handler->HandleOutput("\t");
121
122 char buf[1024] = { '\0' };
111 123
112 #if defined(USE_SYMBOLIZE) 124 #if defined(USE_SYMBOLIZE)
113 for (int i = 0; i < size; ++i) {
114 char symbol[1024];
115 // Subtract by one as return address of function may be in the next 125 // Subtract by one as return address of function may be in the next
116 // function when a function is annotated as noreturn. 126 // function when a function is annotated as noreturn.
117 if (google::Symbolize(static_cast<char *>(trace[i]) - 1, 127 void* address = static_cast<char*>(trace[i]) - 1;
118 symbol, sizeof(symbol))) { 128 if (google::Symbolize(address, buf, sizeof(buf)))
119 // Don't call DemangleSymbols() here as the symbol is demangled by 129 handler->HandleOutput(buf);
120 // google::Symbolize(). 130 else
121 trace_strings->push_back( 131 handler->HandleOutput("<unknown>");
122 base::StringPrintf("%s [%p]", symbol, trace[i])); 132
123 symbolized = true; 133 handler->HandleOutput(" ");
124 } else {
125 trace_strings->push_back(base::StringPrintf("%p", trace[i]));
126 }
127 }
128 #else
129 scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
130 if (trace_symbols.get()) {
131 for (int i = 0; i < size; ++i) {
132 std::string trace_symbol = trace_symbols.get()[i];
133 DemangleSymbols(&trace_symbol);
134 trace_strings->push_back(trace_symbol);
135 }
136 symbolized = true;
137 } else {
138 if (error_message)
139 *error_message = safe_strerror(errno);
140 for (int i = 0; i < size; ++i) {
141 trace_strings->push_back(base::StringPrintf("%p", trace[i]));
142 }
143 }
144 #endif // defined(USE_SYMBOLIZE) 134 #endif // defined(USE_SYMBOLIZE)
145 135
146 return symbolized; 136 handler->HandleOutput("[0x");
137 itoa_r(reinterpret_cast<intptr_t>(trace[i]), buf, sizeof(buf), 16);
138 handler->HandleOutput(buf);
139 handler->HandleOutput("]\n");
140 }
147 } 141 }
148 142
149 void StackDumpSignalHandler(int signal, siginfo_t* info, ucontext_t* context) { 143 void StackDumpSignalHandler(int signal, siginfo_t* info, ucontext_t* context) {
144 // NOTE: This code MUST be async-signal safe.
145 // NO malloc or stdio is allowed here.
146
150 if (BeingDebugged()) 147 if (BeingDebugged())
151 BreakDebugger(); 148 BreakDebugger();
152 149
153 #if defined(OS_MACOSX) 150 char buf[1024] = { '\0' };
154 // TODO(phajdan.jr): Fix async-signal non-safety (http://crbug.com/101155). 151 strncat(buf, "Received signal ", sizeof(buf) - 1);
155 DLOG(ERROR) << "Received signal " << signal; 152 itoa_r(signal, buf + strlen(buf), sizeof(buf) - strlen(buf), 10);
156 StackTrace().PrintBacktrace(); 153 RAW_LOG(ERROR, buf);
157 #endif 154
155 debug::StackTrace().PrintBacktrace();
158 156
159 // TODO(shess): Port to Linux. 157 // TODO(shess): Port to Linux.
160 #if defined(OS_MACOSX) 158 #if defined(OS_MACOSX)
161 // TODO(shess): Port to 64-bit. 159 // TODO(shess): Port to 64-bit.
162 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS 160 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
163 char buf[1024];
164 size_t len; 161 size_t len;
165 162
166 // NOTE: Even |snprintf()| is not on the approved list for signal 163 // NOTE: Even |snprintf()| is not on the approved list for signal
167 // handlers, but buffered I/O is definitely not on the list due to 164 // handlers, but buffered I/O is definitely not on the list due to
168 // potential for |malloc()|. 165 // potential for |malloc()|.
169 len = static_cast<size_t>( 166 len = static_cast<size_t>(
170 snprintf(buf, sizeof(buf), 167 snprintf(buf, sizeof(buf),
171 "ax: %x, bx: %x, cx: %x, dx: %x\n", 168 "ax: %x, bx: %x, cx: %x, dx: %x\n",
172 context->uc_mcontext->__ss.__eax, 169 context->uc_mcontext->__ss.__eax,
173 context->uc_mcontext->__ss.__ebx, 170 context->uc_mcontext->__ss.__ebx,
(...skipping 20 matching lines...) Expand all
194 context->uc_mcontext->__ss.__ds, 191 context->uc_mcontext->__ss.__ds,
195 context->uc_mcontext->__ss.__es, 192 context->uc_mcontext->__ss.__es,
196 context->uc_mcontext->__ss.__fs, 193 context->uc_mcontext->__ss.__fs,
197 context->uc_mcontext->__ss.__gs)); 194 context->uc_mcontext->__ss.__gs));
198 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1)); 195 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
199 #endif // ARCH_CPU_32_BITS 196 #endif // ARCH_CPU_32_BITS
200 #endif // defined(OS_MACOSX) 197 #endif // defined(OS_MACOSX)
201 _exit(1); 198 _exit(1);
202 } 199 }
203 200
201 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
202 public:
203 PrintBacktraceOutputHandler() {}
204
205 virtual void HandleOutput(const char* output) {
206 // NOTE: This code MUST be async-signal safe (it's used by in-process
207 // stack dumping signal handler). NO malloc or stdio is allowed here.
208 HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output)));
209 }
210
211 private:
212 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
213 };
214
215 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
216 public:
217 StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
218 }
219
220 virtual void HandleOutput(const char* output) {
221 (*os_) << output;
222 }
223
224 private:
225 std::ostream* os_;
226
227 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
228 };
229
230 void WarmUpBacktrace() {
231 // Warm up stack trace infrastructure. It turns out that on the first
232 // call glibc initializes some internal data structures using pthread_once,
233 // and even backtrace() can call malloc(), leading to hangs.
234 //
235 // Example stack trace snippet (with tcmalloc):
236 //
237 // #8 0x0000000000a173b5 in tc_malloc
238 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
239 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
240 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
241 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
242 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
243 // at dl-open.c:639
244 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
245 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
246 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
247 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
248 // #17 0x00007ffff61ef8f5 in init
249 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
250 // #18 0x00007ffff6aad400 in pthread_once
251 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
252 // #19 0x00007ffff61efa14 in __GI___backtrace
253 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
254 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
255 // at base/debug/stack_trace_posix.cc:175
256 // #21 0x00000000007a4ae5 in
257 // base::(anonymous namespace)::StackDumpSignalHandler
258 // at base/process_util_posix.cc:172
259 // #22 <signal handler called>
260 StackTrace stack_trace;
261 }
262
204 } // namespace 263 } // namespace
205 264
206 #if !defined(OS_IOS) 265 #if !defined(OS_IOS)
207 bool EnableInProcessStackDumping() { 266 bool EnableInProcessStackDumping() {
208 // When running in an application, our code typically expects SIGPIPE 267 // When running in an application, our code typically expects SIGPIPE
209 // to be ignored. Therefore, when testing that same code, it should run 268 // to be ignored. Therefore, when testing that same code, it should run
210 // with SIGPIPE ignored as well. 269 // with SIGPIPE ignored as well.
211 struct sigaction action; 270 struct sigaction action;
212 memset(&action, 0, sizeof(action)); 271 memset(&action, 0, sizeof(action));
213 action.sa_handler = SIG_IGN; 272 action.sa_handler = SIG_IGN;
214 sigemptyset(&action.sa_mask); 273 sigemptyset(&action.sa_mask);
215 bool success = (sigaction(SIGPIPE, &action, NULL) == 0); 274 bool success = (sigaction(SIGPIPE, &action, NULL) == 0);
216 275
276 // Avoid hangs during backtrace initialization, see above.
277 WarmUpBacktrace();
278
217 sig_t handler = reinterpret_cast<sig_t>(&StackDumpSignalHandler); 279 sig_t handler = reinterpret_cast<sig_t>(&StackDumpSignalHandler);
218 success &= (signal(SIGILL, handler) != SIG_ERR); 280 success &= (signal(SIGILL, handler) != SIG_ERR);
219 success &= (signal(SIGABRT, handler) != SIG_ERR); 281 success &= (signal(SIGABRT, handler) != SIG_ERR);
220 success &= (signal(SIGFPE, handler) != SIG_ERR); 282 success &= (signal(SIGFPE, handler) != SIG_ERR);
221 success &= (signal(SIGBUS, handler) != SIG_ERR); 283 success &= (signal(SIGBUS, handler) != SIG_ERR);
222 success &= (signal(SIGSEGV, handler) != SIG_ERR); 284 success &= (signal(SIGSEGV, handler) != SIG_ERR);
223 success &= (signal(SIGSYS, handler) != SIG_ERR); 285 success &= (signal(SIGSYS, handler) != SIG_ERR);
224 286
225 return success; 287 return success;
226 } 288 }
227 #endif // !defined(OS_IOS) 289 #endif // !defined(OS_IOS)
228 290
229 StackTrace::StackTrace() { 291 StackTrace::StackTrace() {
292 // NOTE: This code MUST be async-signal safe (it's used by in-process
293 // stack dumping signal handler). NO malloc or stdio is allowed here.
294
230 // Though the backtrace API man page does not list any possible negative 295 // Though the backtrace API man page does not list any possible negative
231 // return values, we take no chance. 296 // return values, we take no chance.
232 count_ = std::max(backtrace(trace_, arraysize(trace_)), 0); 297 count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
233 } 298 }
234 299
235 void StackTrace::PrintBacktrace() const { 300 void StackTrace::PrintBacktrace() const {
236 fflush(stderr); 301 // NOTE: This code MUST be async-signal safe (it's used by in-process
237 std::vector<std::string> trace_strings; 302 // stack dumping signal handler). NO malloc or stdio is allowed here.
238 GetBacktraceStrings(trace_, count_, &trace_strings, NULL); 303
239 for (size_t i = 0; i < trace_strings.size(); ++i) { 304 PrintBacktraceOutputHandler handler;
240 fprintf(stderr, "\t%s\n", trace_strings[i].c_str()); 305 ProcessBacktrace(trace_, count_, &handler);
241 }
242 } 306 }
243 307
244 void StackTrace::OutputToStream(std::ostream* os) const { 308 void StackTrace::OutputToStream(std::ostream* os) const {
245 std::vector<std::string> trace_strings; 309 StreamBacktraceOutputHandler handler(os);
246 std::string error_message; 310 ProcessBacktrace(trace_, count_, &handler);
247 if (GetBacktraceStrings(trace_, count_, &trace_strings, &error_message)) {
248 (*os) << "Backtrace:\n";
249 } else {
250 if (!error_message.empty())
251 error_message = " (" + error_message + ")";
252 (*os) << "Unable to get symbols for backtrace" << error_message << ". "
253 << "Dumping raw addresses in trace:\n";
254 }
255
256 for (size_t i = 0; i < trace_strings.size(); ++i) {
257 (*os) << "\t" << trace_strings[i] << "\n";
258 }
259 } 311 }
260 312
261 } // namespace debug 313 } // namespace debug
262 } // namespace base 314 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698