- add sources.
[platform/framework/web/crosswalk.git] / src / base / debug / stack_trace_posix.cc
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
3 // found in the LICENSE file.
4
5 #include "base/debug/stack_trace.h"
6
7 #include <errno.h>
8 #include <execinfo.h>
9 #include <fcntl.h>
10 #include <signal.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <sys/param.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17
18 #include <ostream>
19
20 #if defined(__GLIBCXX__)
21 #include <cxxabi.h>
22 #endif
23
24 #if defined(OS_MACOSX)
25 #include <AvailabilityMacros.h>
26 #endif
27
28 #include "base/basictypes.h"
29 #include "base/debug/debugger.h"
30 #include "base/logging.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/posix/eintr_wrapper.h"
33 #include "base/strings/string_number_conversions.h"
34
35 #if defined(USE_SYMBOLIZE)
36 #include "base/third_party/symbolize/symbolize.h"
37 #endif
38
39 namespace base {
40 namespace debug {
41
42 namespace {
43
44 volatile sig_atomic_t in_signal_handler = 0;
45
46 #if !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
47 // The prefix used for mangled symbols, per the Itanium C++ ABI:
48 // http://www.codesourcery.com/cxx-abi/abi.html#mangling
49 const char kMangledSymbolPrefix[] = "_Z";
50
51 // Characters that can be used for symbols, generated by Ruby:
52 // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
53 const char kSymbolCharacters[] =
54     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
55 #endif  // !defined(USE_SYMBOLIZE) && defined(__GLIBCXX__)
56
57 #if !defined(USE_SYMBOLIZE)
58 // Demangles C++ symbols in the given text. Example:
59 //
60 // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
61 // =>
62 // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
63 void DemangleSymbols(std::string* text) {
64   // Note: code in this function is NOT async-signal safe (std::string uses
65   // malloc internally).
66
67 #if defined(__GLIBCXX__)
68
69   std::string::size_type search_from = 0;
70   while (search_from < text->size()) {
71     // Look for the start of a mangled symbol, from search_from.
72     std::string::size_type mangled_start =
73         text->find(kMangledSymbolPrefix, search_from);
74     if (mangled_start == std::string::npos) {
75       break;  // Mangled symbol not found.
76     }
77
78     // Look for the end of the mangled symbol.
79     std::string::size_type mangled_end =
80         text->find_first_not_of(kSymbolCharacters, mangled_start);
81     if (mangled_end == std::string::npos) {
82       mangled_end = text->size();
83     }
84     std::string mangled_symbol =
85         text->substr(mangled_start, mangled_end - mangled_start);
86
87     // Try to demangle the mangled symbol candidate.
88     int status = 0;
89     scoped_ptr_malloc<char> demangled_symbol(
90         abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
91     if (status == 0) {  // Demangling is successful.
92       // Remove the mangled symbol.
93       text->erase(mangled_start, mangled_end - mangled_start);
94       // Insert the demangled symbol.
95       text->insert(mangled_start, demangled_symbol.get());
96       // Next time, we'll start right after the demangled symbol we inserted.
97       search_from = mangled_start + strlen(demangled_symbol.get());
98     } else {
99       // Failed to demangle.  Retry after the "_Z" we just found.
100       search_from = mangled_start + 2;
101     }
102   }
103
104 #endif  // defined(__GLIBCXX__)
105 }
106 #endif  // !defined(USE_SYMBOLIZE)
107
108 class BacktraceOutputHandler {
109  public:
110   virtual void HandleOutput(const char* output) = 0;
111
112  protected:
113   virtual ~BacktraceOutputHandler() {}
114 };
115
116 void OutputPointer(void* pointer, BacktraceOutputHandler* handler) {
117   char buf[1024] = { '\0' };
118   handler->HandleOutput(" [0x");
119   internal::itoa_r(reinterpret_cast<intptr_t>(pointer),
120                    buf, sizeof(buf), 16, 12);
121   handler->HandleOutput(buf);
122   handler->HandleOutput("]");
123 }
124
125 void ProcessBacktrace(void *const *trace,
126                       int size,
127                       BacktraceOutputHandler* handler) {
128   // NOTE: This code MUST be async-signal safe (it's used by in-process
129   // stack dumping signal handler). NO malloc or stdio is allowed here.
130
131 #if defined(USE_SYMBOLIZE)
132   for (int i = 0; i < size; ++i) {
133     OutputPointer(trace[i], handler);
134     handler->HandleOutput(" ");
135
136     char buf[1024] = { '\0' };
137
138     // Subtract by one as return address of function may be in the next
139     // function when a function is annotated as noreturn.
140     void* address = static_cast<char*>(trace[i]) - 1;
141     if (google::Symbolize(address, buf, sizeof(buf)))
142       handler->HandleOutput(buf);
143     else
144       handler->HandleOutput("<unknown>");
145
146     handler->HandleOutput("\n");
147   }
148 #else
149   bool printed = false;
150
151   // Below part is async-signal unsafe (uses malloc), so execute it only
152   // when we are not executing the signal handler.
153   if (in_signal_handler == 0) {
154     scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
155     if (trace_symbols.get()) {
156       for (int i = 0; i < size; ++i) {
157         std::string trace_symbol = trace_symbols.get()[i];
158         DemangleSymbols(&trace_symbol);
159         handler->HandleOutput(trace_symbol.c_str());
160         handler->HandleOutput("\n");
161       }
162
163       printed = true;
164     }
165   }
166
167   if (!printed) {
168     for (int i = 0; i < size; ++i) {
169       OutputPointer(trace[i], handler);
170       handler->HandleOutput("\n");
171     }
172   }
173 #endif  // defined(USE_SYMBOLIZE)
174 }
175
176 void PrintToStderr(const char* output) {
177   // NOTE: This code MUST be async-signal safe (it's used by in-process
178   // stack dumping signal handler). NO malloc or stdio is allowed here.
179   ignore_result(HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output))));
180 }
181
182 void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
183   // NOTE: This code MUST be async-signal safe.
184   // NO malloc or stdio is allowed here.
185
186   // Record the fact that we are in the signal handler now, so that the rest
187   // of StackTrace can behave in an async-signal-safe manner.
188   in_signal_handler = 1;
189
190   if (BeingDebugged())
191     BreakDebugger();
192
193   PrintToStderr("Received signal ");
194   char buf[1024] = { 0 };
195   internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
196   PrintToStderr(buf);
197   if (signal == SIGBUS) {
198     if (info->si_code == BUS_ADRALN)
199       PrintToStderr(" BUS_ADRALN ");
200     else if (info->si_code == BUS_ADRERR)
201       PrintToStderr(" BUS_ADRERR ");
202     else if (info->si_code == BUS_OBJERR)
203       PrintToStderr(" BUS_OBJERR ");
204     else
205       PrintToStderr(" <unknown> ");
206   } else if (signal == SIGFPE) {
207     if (info->si_code == FPE_FLTDIV)
208       PrintToStderr(" FPE_FLTDIV ");
209     else if (info->si_code == FPE_FLTINV)
210       PrintToStderr(" FPE_FLTINV ");
211     else if (info->si_code == FPE_FLTOVF)
212       PrintToStderr(" FPE_FLTOVF ");
213     else if (info->si_code == FPE_FLTRES)
214       PrintToStderr(" FPE_FLTRES ");
215     else if (info->si_code == FPE_FLTSUB)
216       PrintToStderr(" FPE_FLTSUB ");
217     else if (info->si_code == FPE_FLTUND)
218       PrintToStderr(" FPE_FLTUND ");
219     else if (info->si_code == FPE_INTDIV)
220       PrintToStderr(" FPE_INTDIV ");
221     else if (info->si_code == FPE_INTOVF)
222       PrintToStderr(" FPE_INTOVF ");
223     else
224       PrintToStderr(" <unknown> ");
225   } else if (signal == SIGILL) {
226     if (info->si_code == ILL_BADSTK)
227       PrintToStderr(" ILL_BADSTK ");
228     else if (info->si_code == ILL_COPROC)
229       PrintToStderr(" ILL_COPROC ");
230     else if (info->si_code == ILL_ILLOPN)
231       PrintToStderr(" ILL_ILLOPN ");
232     else if (info->si_code == ILL_ILLADR)
233       PrintToStderr(" ILL_ILLADR ");
234     else if (info->si_code == ILL_ILLTRP)
235       PrintToStderr(" ILL_ILLTRP ");
236     else if (info->si_code == ILL_PRVOPC)
237       PrintToStderr(" ILL_PRVOPC ");
238     else if (info->si_code == ILL_PRVREG)
239       PrintToStderr(" ILL_PRVREG ");
240     else
241       PrintToStderr(" <unknown> ");
242   } else if (signal == SIGSEGV) {
243     if (info->si_code == SEGV_MAPERR)
244       PrintToStderr(" SEGV_MAPERR ");
245     else if (info->si_code == SEGV_ACCERR)
246       PrintToStderr(" SEGV_ACCERR ");
247     else
248       PrintToStderr(" <unknown> ");
249   }
250   if (signal == SIGBUS || signal == SIGFPE ||
251       signal == SIGILL || signal == SIGSEGV) {
252     internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
253                      buf, sizeof(buf), 16, 12);
254     PrintToStderr(buf);
255   }
256   PrintToStderr("\n");
257
258   debug::StackTrace().Print();
259
260 #if defined(OS_LINUX)
261 #if ARCH_CPU_X86_FAMILY
262   ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
263   const struct {
264     const char* label;
265     greg_t value;
266   } registers[] = {
267 #if ARCH_CPU_32_BITS
268     { "  gs: ", context->uc_mcontext.gregs[REG_GS] },
269     { "  fs: ", context->uc_mcontext.gregs[REG_FS] },
270     { "  es: ", context->uc_mcontext.gregs[REG_ES] },
271     { "  ds: ", context->uc_mcontext.gregs[REG_DS] },
272     { " edi: ", context->uc_mcontext.gregs[REG_EDI] },
273     { " esi: ", context->uc_mcontext.gregs[REG_ESI] },
274     { " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
275     { " esp: ", context->uc_mcontext.gregs[REG_ESP] },
276     { " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
277     { " edx: ", context->uc_mcontext.gregs[REG_EDX] },
278     { " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
279     { " eax: ", context->uc_mcontext.gregs[REG_EAX] },
280     { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
281     { " err: ", context->uc_mcontext.gregs[REG_ERR] },
282     { "  ip: ", context->uc_mcontext.gregs[REG_EIP] },
283     { "  cs: ", context->uc_mcontext.gregs[REG_CS] },
284     { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
285     { " usp: ", context->uc_mcontext.gregs[REG_UESP] },
286     { "  ss: ", context->uc_mcontext.gregs[REG_SS] },
287 #elif ARCH_CPU_64_BITS
288     { "  r8: ", context->uc_mcontext.gregs[REG_R8] },
289     { "  r9: ", context->uc_mcontext.gregs[REG_R9] },
290     { " r10: ", context->uc_mcontext.gregs[REG_R10] },
291     { " r11: ", context->uc_mcontext.gregs[REG_R11] },
292     { " r12: ", context->uc_mcontext.gregs[REG_R12] },
293     { " r13: ", context->uc_mcontext.gregs[REG_R13] },
294     { " r14: ", context->uc_mcontext.gregs[REG_R14] },
295     { " r15: ", context->uc_mcontext.gregs[REG_R15] },
296     { "  di: ", context->uc_mcontext.gregs[REG_RDI] },
297     { "  si: ", context->uc_mcontext.gregs[REG_RSI] },
298     { "  bp: ", context->uc_mcontext.gregs[REG_RBP] },
299     { "  bx: ", context->uc_mcontext.gregs[REG_RBX] },
300     { "  dx: ", context->uc_mcontext.gregs[REG_RDX] },
301     { "  ax: ", context->uc_mcontext.gregs[REG_RAX] },
302     { "  cx: ", context->uc_mcontext.gregs[REG_RCX] },
303     { "  sp: ", context->uc_mcontext.gregs[REG_RSP] },
304     { "  ip: ", context->uc_mcontext.gregs[REG_RIP] },
305     { " efl: ", context->uc_mcontext.gregs[REG_EFL] },
306     { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
307     { " erf: ", context->uc_mcontext.gregs[REG_ERR] },
308     { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
309     { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
310     { " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
311 #endif
312   };
313
314 #if ARCH_CPU_32_BITS
315   const int kRegisterPadding = 8;
316 #elif ARCH_CPU_64_BITS
317   const int kRegisterPadding = 16;
318 #endif
319
320   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(registers); i++) {
321     PrintToStderr(registers[i].label);
322     internal::itoa_r(registers[i].value, buf, sizeof(buf),
323                      16, kRegisterPadding);
324     PrintToStderr(buf);
325
326     if ((i + 1) % 4 == 0)
327       PrintToStderr("\n");
328   }
329   PrintToStderr("\n");
330 #endif
331 #elif defined(OS_MACOSX)
332   // TODO(shess): Port to 64-bit.
333 #if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
334   ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
335   size_t len;
336
337   // NOTE: Even |snprintf()| is not on the approved list for signal
338   // handlers, but buffered I/O is definitely not on the list due to
339   // potential for |malloc()|.
340   len = static_cast<size_t>(
341       snprintf(buf, sizeof(buf),
342                "ax: %x, bx: %x, cx: %x, dx: %x\n",
343                context->uc_mcontext->__ss.__eax,
344                context->uc_mcontext->__ss.__ebx,
345                context->uc_mcontext->__ss.__ecx,
346                context->uc_mcontext->__ss.__edx));
347   write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
348
349   len = static_cast<size_t>(
350       snprintf(buf, sizeof(buf),
351                "di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
352                context->uc_mcontext->__ss.__edi,
353                context->uc_mcontext->__ss.__esi,
354                context->uc_mcontext->__ss.__ebp,
355                context->uc_mcontext->__ss.__esp,
356                context->uc_mcontext->__ss.__ss,
357                context->uc_mcontext->__ss.__eflags));
358   write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
359
360   len = static_cast<size_t>(
361       snprintf(buf, sizeof(buf),
362                "ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
363                context->uc_mcontext->__ss.__eip,
364                context->uc_mcontext->__ss.__cs,
365                context->uc_mcontext->__ss.__ds,
366                context->uc_mcontext->__ss.__es,
367                context->uc_mcontext->__ss.__fs,
368                context->uc_mcontext->__ss.__gs));
369   write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
370 #endif  // ARCH_CPU_32_BITS
371 #endif  // defined(OS_MACOSX)
372   _exit(1);
373 }
374
375 class PrintBacktraceOutputHandler : public BacktraceOutputHandler {
376  public:
377   PrintBacktraceOutputHandler() {}
378
379   virtual void HandleOutput(const char* output) OVERRIDE {
380     // NOTE: This code MUST be async-signal safe (it's used by in-process
381     // stack dumping signal handler). NO malloc or stdio is allowed here.
382     PrintToStderr(output);
383   }
384
385  private:
386   DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler);
387 };
388
389 class StreamBacktraceOutputHandler : public BacktraceOutputHandler {
390  public:
391   explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) {
392   }
393
394   virtual void HandleOutput(const char* output) OVERRIDE {
395     (*os_) << output;
396   }
397
398  private:
399   std::ostream* os_;
400
401   DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler);
402 };
403
404 void WarmUpBacktrace() {
405   // Warm up stack trace infrastructure. It turns out that on the first
406   // call glibc initializes some internal data structures using pthread_once,
407   // and even backtrace() can call malloc(), leading to hangs.
408   //
409   // Example stack trace snippet (with tcmalloc):
410   //
411   // #8  0x0000000000a173b5 in tc_malloc
412   //             at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161
413   // #9  0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517
414   // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262
415   // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
416   // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1")
417   //             at dl-open.c:639
418   // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89
419   // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178
420   // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48
421   // #16 __GI___libc_dlopen_mode at dl-libc.c:165
422   // #17 0x00007ffff61ef8f5 in init
423   //             at ../sysdeps/x86_64/../ia64/backtrace.c:53
424   // #18 0x00007ffff6aad400 in pthread_once
425   //             at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104
426   // #19 0x00007ffff61efa14 in __GI___backtrace
427   //             at ../sysdeps/x86_64/../ia64/backtrace.c:104
428   // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace
429   //             at base/debug/stack_trace_posix.cc:175
430   // #21 0x00000000007a4ae5 in
431   //             base::(anonymous namespace)::StackDumpSignalHandler
432   //             at base/process_util_posix.cc:172
433   // #22 <signal handler called>
434   StackTrace stack_trace;
435 }
436
437 }  // namespace
438
439 #if !defined(OS_IOS)
440 bool EnableInProcessStackDumping() {
441   // When running in an application, our code typically expects SIGPIPE
442   // to be ignored.  Therefore, when testing that same code, it should run
443   // with SIGPIPE ignored as well.
444   struct sigaction sigpipe_action;
445   memset(&sigpipe_action, 0, sizeof(sigpipe_action));
446   sigpipe_action.sa_handler = SIG_IGN;
447   sigemptyset(&sigpipe_action.sa_mask);
448   bool success = (sigaction(SIGPIPE, &sigpipe_action, NULL) == 0);
449
450   // Avoid hangs during backtrace initialization, see above.
451   WarmUpBacktrace();
452
453   struct sigaction action;
454   memset(&action, 0, sizeof(action));
455   action.sa_flags = SA_RESETHAND | SA_SIGINFO;
456   action.sa_sigaction = &StackDumpSignalHandler;
457   sigemptyset(&action.sa_mask);
458
459   success &= (sigaction(SIGILL, &action, NULL) == 0);
460   success &= (sigaction(SIGABRT, &action, NULL) == 0);
461   success &= (sigaction(SIGFPE, &action, NULL) == 0);
462   success &= (sigaction(SIGBUS, &action, NULL) == 0);
463   success &= (sigaction(SIGSEGV, &action, NULL) == 0);
464   success &= (sigaction(SIGSYS, &action, NULL) == 0);
465
466   return success;
467 }
468 #endif  // !defined(OS_IOS)
469
470 StackTrace::StackTrace() {
471   // NOTE: This code MUST be async-signal safe (it's used by in-process
472   // stack dumping signal handler). NO malloc or stdio is allowed here.
473
474   // Though the backtrace API man page does not list any possible negative
475   // return values, we take no chance.
476   count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
477 }
478
479 void StackTrace::Print() const {
480   // NOTE: This code MUST be async-signal safe (it's used by in-process
481   // stack dumping signal handler). NO malloc or stdio is allowed here.
482
483   PrintBacktraceOutputHandler handler;
484   ProcessBacktrace(trace_, count_, &handler);
485 }
486
487 void StackTrace::OutputToStream(std::ostream* os) const {
488   StreamBacktraceOutputHandler handler(os);
489   ProcessBacktrace(trace_, count_, &handler);
490 }
491
492 namespace internal {
493
494 // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
495 char *itoa_r(intptr_t i, char *buf, size_t sz, int base, size_t padding) {
496   // Make sure we can write at least one NUL byte.
497   size_t n = 1;
498   if (n > sz)
499     return NULL;
500
501   if (base < 2 || base > 16) {
502     buf[0] = '\000';
503     return NULL;
504   }
505
506   char *start = buf;
507
508   uintptr_t j = i;
509
510   // Handle negative numbers (only for base 10).
511   if (i < 0 && base == 10) {
512     j = -i;
513
514     // Make sure we can write the '-' character.
515     if (++n > sz) {
516       buf[0] = '\000';
517       return NULL;
518     }
519     *start++ = '-';
520   }
521
522   // Loop until we have converted the entire number. Output at least one
523   // character (i.e. '0').
524   char *ptr = start;
525   do {
526     // Make sure there is still enough space left in our output buffer.
527     if (++n > sz) {
528       buf[0] = '\000';
529       return NULL;
530     }
531
532     // Output the next digit.
533     *ptr++ = "0123456789abcdef"[j % base];
534     j /= base;
535
536     if (padding > 0)
537       padding--;
538   } while (j > 0 || padding > 0);
539
540   // Terminate the output with a NUL character.
541   *ptr = '\000';
542
543   // Conversion to ASCII actually resulted in the digits being in reverse
544   // order. We can't easily generate them in forward order, as we can't tell
545   // the number of characters needed until we are done converting.
546   // So, now, we reverse the string (except for the possible "-" sign).
547   while (--ptr > start) {
548     char ch = *ptr;
549     *ptr = *start;
550     *start++ = ch;
551   }
552   return buf;
553 }
554
555 }  // namespace internal
556
557 }  // namespace debug
558 }  // namespace base