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

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: fixes 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
« no previous file with comments | « base/debug/debugger_posix.cc ('k') | base/debug/stack_trace_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 char *start = buf;
65 while (search_from < text->size()) { 59 int minint = 0;
66 // Look for the start of a mangled symbol, from search_from.
67 std::string::size_type mangled_start =
68 text->find(kMangledSymbolPrefix, search_from);
69 if (mangled_start == std::string::npos) {
70 break; // Mangled symbol not found.
71 }
72 60
73 // Look for the end of the mangled symbol. 61 if (base == 10) {
74 std::string::size_type mangled_end = 62 // Handle negative numbers.
75 text->find_first_not_of(kSymbolCharacters, mangled_start); 63 if (i < 0) {
76 if (mangled_end == std::string::npos) { 64 // Make sure we can write the '-' character.
77 mangled_end = text->size(); 65 if (++n > sz) {
78 } 66 *start = '\000';
79 std::string mangled_symbol = 67 return NULL;
80 text->substr(mangled_start, mangled_end - mangled_start); 68 }
69 *start++ = '-';
81 70
82 // Try to demangle the mangled symbol candidate. 71 // Turn our number positive.
83 int status = 0; 72 if (i == -i) {
84 scoped_ptr_malloc<char> demangled_symbol( 73 // The lowest-most negative integer needs special treatment.
85 abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status)); 74 minint = 1;
86 if (status == 0) { // Demangling is successful. 75 i = -(i + 1);
87 // Remove the mangled symbol. 76 } else {
88 text->erase(mangled_start, mangled_end - mangled_start); 77 // "Normal" negative numbers are easy.
89 // Insert the demangled symbol. 78 i = -i;
jar (doing other things) 2012/11/06 20:40:03 You don't actually need the minint game, now that
90 text->insert(mangled_start, demangled_symbol.get()); 79 }
91 // Next time, we'll start right after the demangled symbol we inserted.
92 search_from = mangled_start + strlen(demangled_symbol.get());
93 } else {
94 // Failed to demangle. Retry after the "_Z" we just found.
95 search_from = mangled_start + 2;
96 } 80 }
97 } 81 }
98 82
99 #endif // defined(__GLIBCXX__) 83 uintptr_t j = i;
84
85 // Loop until we have converted the entire number. Output at least one
86 // character (i.e. '0').
87 char *ptr = start;
88 do {
89 // Make sure there is still enough space left in our output buffer.
90 if (++n > sz) {
91 buf = NULL;
92 break;
93 }
94
95 // Output the next digit.
96 *ptr = "0123456789abcdef"[j % base] + minint;
97 if (base == 10) {
jar (doing other things) 2012/11/06 20:40:03 nit: Don't bother to test here. Minint will only
98 // If necessary compensate for the lowest-most negative integer needing
99 // special treatment. This works because, no matter the bit width of the
100 // integer, the lowest-most integer always ends in 2, 4, 6, or 8.
101 *ptr += minint;
102 }
103 ptr++;
104 minint = 0;
105 j /= base;
106 } while (j);
107
108 // Terminate the output with a NUL character.
109 *ptr = '\000';
110
111 // Conversion to ASCII actually resulted in the digits being in reverse
112 // order. We can't easily generate them in forward order, as we can't tell
113 // the number of characters needed until we are done converting.
114 // So, now, we reverse the string (except for the possible "-" sign).
115 while (--ptr > start) {
116 char ch = *ptr;
117 *ptr = *start;
118 *start++ = ch;
119 }
120 return buf;
100 } 121 }
101 #endif // !defined(USE_SYMBOLIZE)
102 122
103 // Gets the backtrace as a vector of strings. If possible, resolve symbol 123 void ProcessBacktrace(void *const *trace,
104 // names and attach these. Otherwise just use raw addresses. Returns true 124 int size,
105 // if any symbol name is resolved. Returns false on error and *may* fill 125 BacktraceOutputHandler* handler) {
106 // in |error_message| if an error message is available. 126 // NOTE: This code MUST be async-signal safe (it's used by in-process
107 bool GetBacktraceStrings(void *const *trace, int size, 127 // stack dumping signal handler). NO malloc or stdio is allowed here.
108 std::vector<std::string>* trace_strings, 128
109 std::string* error_message) { 129 for (int i = 0; i < size; ++i) {
110 bool symbolized = false; 130 handler->HandleOutput("\t");
131
132 char buf[1024] = { '\0' };
111 133
112 #if defined(USE_SYMBOLIZE) 134 #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 135 // Subtract by one as return address of function may be in the next
116 // function when a function is annotated as noreturn. 136 // function when a function is annotated as noreturn.
117 if (google::Symbolize(static_cast<char *>(trace[i]) - 1, 137 void* address = static_cast<char*>(trace[i]) - 1;
118 symbol, sizeof(symbol))) { 138 if (google::Symbolize(address, buf, sizeof(buf)))
119 // Don't call DemangleSymbols() here as the symbol is demangled by 139 handler->HandleOutput(buf);
120 // google::Symbolize(). 140 else
121 trace_strings->push_back( 141 handler->HandleOutput("<unknown>");
122 base::StringPrintf("%s [%p]", symbol, trace[i])); 142
123 symbolized = true; 143 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) 144 #endif // defined(USE_SYMBOLIZE)
145 145
146 return symbolized; 146 handler->HandleOutput("[0x");
147 itoa_r(reinterpret_cast<intptr_t>(trace[i]), buf, sizeof(buf), 16);
148 handler->HandleOutput(buf);
149 handler->HandleOutput("]\n");
150 }
147 } 151 }
148 152
149 void StackDumpSignalHandler(int signal, siginfo_t* info, ucontext_t* context) { 153 void StackDumpSignalHandler(int signal, siginfo_t* info, ucontext_t* context) {
154 // NOTE: This code MUST be async-signal safe.
155 // NO malloc or stdio is allowed here.
156
150 if (BeingDebugged()) 157 if (BeingDebugged())
151 BreakDebugger(); 158 BreakDebugger();
152 159
153 #if defined(OS_MACOSX) 160 char buf[1024] = { '\0' };
154 // TODO(phajdan.jr): Fix async-signal non-safety (http://crbug.com/101155). 161 strncat(buf, "Received signal ", sizeof(buf) - 1);
155 DLOG(ERROR) << "Received signal " << signal; 162 itoa_r(signal, buf + strlen(buf), sizeof(buf) - strlen(buf), 10);
156 StackTrace().PrintBacktrace(); 163 RAW_LOG(ERROR, buf);
157 #endif 164
165 debug::StackTrace().PrintBacktrace();
158 166
159 // TODO(shess): Port to Linux. 167 // TODO(shess): Port to Linux.
160 #if defined(OS_MACOSX) 168 #if defined(OS_MACOSX)
161 // TODO(shess): Port to 64-bit. 169 // TODO(shess): Port to 64-bit.
162 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS 170 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
163 char buf[1024];
164 size_t len; 171 size_t len;
165 172
166 // NOTE: Even |snprintf()| is not on the approved list for signal 173 // 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 174 // handlers, but buffered I/O is definitely not on the list due to
168 // potential for |malloc()|. 175 // potential for |malloc()|.
169 len = static_cast<size_t>( 176 len = static_cast<size_t>(
170 snprintf(buf, sizeof(buf), 177 snprintf(buf, sizeof(buf),
171 "ax: %x, bx: %x, cx: %x, dx: %x\n", 178 "ax: %x, bx: %x, cx: %x, dx: %x\n",
172 context->uc_mcontext->__ss.__eax, 179 context->uc_mcontext->__ss.__eax,
173 context->uc_mcontext->__ss.__ebx, 180 context->uc_mcontext->__ss.__ebx,
(...skipping 20 matching lines...) Expand all
194 context->uc_mcontext->__ss.__ds, 201 context->uc_mcontext->__ss.__ds,
195 context->uc_mcontext->__ss.__es, 202 context->uc_mcontext->__ss.__es,
196 context->uc_mcontext->__ss.__fs, 203 context->uc_mcontext->__ss.__fs,
197 context->uc_mcontext->__ss.__gs)); 204 context->uc_mcontext->__ss.__gs));
198 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1)); 205 write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
199 #endif // ARCH_CPU_32_BITS 206 #endif // ARCH_CPU_32_BITS
200 #endif // defined(OS_MACOSX) 207 #endif // defined(OS_MACOSX)
201 _exit(1); 208 _exit(1);
202 } 209 }
203 210
211 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
212 public:
213 PrintBacktraceOutputHandler() {}
214
215 virtual void HandleOutput(const char* output) {
216 // NOTE: This code MUST be async-signal safe (it's used by in-process
217 // stack dumping signal handler). NO malloc or stdio is allowed here.
218 HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output)));
219 }
220
221 private:
222 DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
223 };
224
225 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
226 public:
227 StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
228 }
229
230 virtual void HandleOutput(const char* output) {
231 (*os_) << output;
232 }
233
234 private:
235 std::ostream* os_;
236
237 DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
238 };
239
240 void WarmUpBacktrace() {
241 // Warm up stack trace infrastructure. It turns out that on the first
242 // call glibc initializes some internal data structures using pthread_once,
243 // and even backtrace() can call malloc(), leading to hangs.
244 //
245 // Example stack trace snippet (with tcmalloc):
246 //
247 // #8 0x0000000000a173b5 in tc_malloc
248 // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
249 // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
250 // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
251 // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
252 // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
253 // at dl-open.c:639
254 // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
255 // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
256 // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
257 // #16 __GI___libc_dlopen_mode at dl-libc.c:165
258 // #17 0x00007ffff61ef8f5 in init
259 // at ../sysdeps/x86_64/../ia64/backtrace.c:53
260 // #18 0x00007ffff6aad400 in pthread_once
261 // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
262 // #19 0x00007ffff61efa14 in __GI___backtrace
263 // at ../sysdeps/x86_64/../ia64/backtrace.c:104
264 // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
265 // at base/debug/stack_trace_posix.cc:175
266 // #21 0x00000000007a4ae5 in
267 // base::(anonymous namespace)::StackDumpSignalHandler
268 // at base/process_util_posix.cc:172
269 // #22 <signal handler called>
270 StackTrace stack_trace;
271 }
272
204 } // namespace 273 } // namespace
205 274
206 #if !defined(OS_IOS) 275 #if !defined(OS_IOS)
207 bool EnableInProcessStackDumping() { 276 bool EnableInProcessStackDumping() {
208 // When running in an application, our code typically expects SIGPIPE 277 // When running in an application, our code typically expects SIGPIPE
209 // to be ignored. Therefore, when testing that same code, it should run 278 // to be ignored. Therefore, when testing that same code, it should run
210 // with SIGPIPE ignored as well. 279 // with SIGPIPE ignored as well.
211 struct sigaction action; 280 struct sigaction action;
212 memset(&action, 0, sizeof(action)); 281 memset(&action, 0, sizeof(action));
213 action.sa_handler = SIG_IGN; 282 action.sa_handler = SIG_IGN;
214 sigemptyset(&action.sa_mask); 283 sigemptyset(&action.sa_mask);
215 bool success = (sigaction(SIGPIPE, &action, NULL) == 0); 284 bool success = (sigaction(SIGPIPE, &action, NULL) == 0);
216 285
286 // Avoid hangs during backtrace initialization, see above.
287 WarmUpBacktrace();
288
217 sig_t handler = reinterpret_cast<sig_t>(&StackDumpSignalHandler); 289 sig_t handler = reinterpret_cast<sig_t>(&StackDumpSignalHandler);
218 success &= (signal(SIGILL, handler) != SIG_ERR); 290 success &= (signal(SIGILL, handler) != SIG_ERR);
219 success &= (signal(SIGABRT, handler) != SIG_ERR); 291 success &= (signal(SIGABRT, handler) != SIG_ERR);
220 success &= (signal(SIGFPE, handler) != SIG_ERR); 292 success &= (signal(SIGFPE, handler) != SIG_ERR);
221 success &= (signal(SIGBUS, handler) != SIG_ERR); 293 success &= (signal(SIGBUS, handler) != SIG_ERR);
222 success &= (signal(SIGSEGV, handler) != SIG_ERR); 294 success &= (signal(SIGSEGV, handler) != SIG_ERR);
223 success &= (signal(SIGSYS, handler) != SIG_ERR); 295 success &= (signal(SIGSYS, handler) != SIG_ERR);
224 296
225 return success; 297 return success;
226 } 298 }
227 #endif // !defined(OS_IOS) 299 #endif // !defined(OS_IOS)
228 300
229 StackTrace::StackTrace() { 301 StackTrace::StackTrace() {
302 // NOTE: This code MUST be async-signal safe (it's used by in-process
303 // stack dumping signal handler). NO malloc or stdio is allowed here.
304
230 // Though the backtrace API man page does not list any possible negative 305 // Though the backtrace API man page does not list any possible negative
231 // return values, we take no chance. 306 // return values, we take no chance.
232 count_ = std::max(backtrace(trace_, arraysize(trace_)), 0); 307 count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
233 } 308 }
234 309
235 void StackTrace::PrintBacktrace() const { 310 void StackTrace::PrintBacktrace() const {
236 fflush(stderr); 311 // NOTE: This code MUST be async-signal safe (it's used by in-process
237 std::vector<std::string> trace_strings; 312 // stack dumping signal handler). NO malloc or stdio is allowed here.
238 GetBacktraceStrings(trace_, count_, &trace_strings, NULL); 313
239 for (size_t i = 0; i < trace_strings.size(); ++i) { 314 PrintBacktraceOutputHandler handler;
240 fprintf(stderr, "\t%s\n", trace_strings[i].c_str()); 315 ProcessBacktrace(trace_, count_, &handler);
241 }
242 } 316 }
243 317
244 void StackTrace::OutputToStream(std::ostream* os) const { 318 void StackTrace::OutputToStream(std::ostream* os) const {
245 std::vector<std::string> trace_strings; 319 StreamBacktraceOutputHandler handler(os);
246 std::string error_message; 320 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 } 321 }
260 322
261 } // namespace debug 323 } // namespace debug
262 } // namespace base 324 } // namespace base
OLDNEW
« no previous file with comments | « base/debug/debugger_posix.cc ('k') | base/debug/stack_trace_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698