| 6 |
| 7 | #include <errno.h> |
| 8 | #include <fcntl.h> |
| 9 | #include <signal.h> |
| 10 | #include <stddef.h> |
| 11 | #include <stdint.h> |
| 12 | #include <stdio.h> |
| 13 | #include <stdlib.h> |
| 14 | #include <string.h> |
| 15 | #include <sys/param.h> |
| 16 | #include <sys/stat.h> |
| 17 | #include <sys/types.h> |
| 18 | #include <unistd.h> |
| 19 |
| 20 | #include <algorithm> |
| 21 | #include <map> |
| 22 | #include <memory> |
| 23 | #include <ostream> |
| 24 | #include <string> |
| 25 | #include <vector> |
| 26 |
| 27 | #if !defined(USE_SYMBOLIZE) |
| 28 | #include <cxxabi.h> |
| 29 | #endif |
| 30 | #if !defined(__UCLIBC__) && !defined(_AIX) |
| 31 | #include <execinfo.h> |
| 32 | #endif |
| 33 |
| 34 | #if defined(OS_MACOSX) |
| 35 | #include <AvailabilityMacros.h> |
| 36 | #endif |
| 37 |
| 38 | #if defined(OS_LINUX) |
| 39 | #include "base/debug/proc_maps_linux.h" |
| 40 | #endif |
| 41 |
| 42 | #include "base/cfi_buildflags.h" |
| 43 | #include "base/debug/debugger.h" |
| 44 | #include "base/files/scoped_file.h" |
| 45 | #include "base/logging.h" |
| 46 | #include "base/memory/free_deleter.h" |
| 47 | #include "base/memory/singleton.h" |
| 48 | #include "base/numerics/safe_conversions.h" |
| 49 | #include "base/posix/eintr_wrapper.h" |
| 50 | #include "base/stl_util.h" |
| 51 | #include "base/strings/string_number_conversions.h" |
| 52 | #include "base/strings/string_util.h" |
| 53 | #include "build/build_config.h" |
| 54 |
| 55 | #if defined(USE_SYMBOLIZE) |
| 56 | #include "base/third_party/symbolize/symbolize.h" |
| 57 | #endif |
| 58 |
| 59 | namespace base { |
| 60 | namespace debug { |
| 61 |
| 62 | namespace { |
| 63 |
| 64 | volatile sig_atomic_t in_signal_handler = 0; |
| 65 |
| 66 | #if !defined(OS_NACL) |
| 67 | bool (*try_handle_signal)(int, siginfo_t*, void*) = nullptr; |
| 68 | #endif |
| 69 |
| 70 | #if !defined(USE_SYMBOLIZE) |
| 71 | // The prefix used for mangled symbols, per the Itanium C++ ABI: |
| 72 | // http://www.codesourcery.com/cxx-abi/abi.html#mangling |
| 73 | const char kMangledSymbolPrefix[] = "_Z"; |
| 74 |
| 75 | // Characters that can be used for symbols, generated by Ruby: |
| 76 | // (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join |
| 77 | const char kSymbolCharacters[] = |
| 78 | "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; |
| 79 | #endif // !defined(USE_SYMBOLIZE) |
| 80 |
| 81 | #if !defined(USE_SYMBOLIZE) |
| 82 | // Demangles C++ symbols in the given text. Example: |
| 83 | // |
| 84 | // "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]" |
| 85 | // => |
| 86 | // "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]" |
| 87 | void DemangleSymbols(std::string* text) { |
| 88 | // Note: code in this function is NOT async-signal safe (std::string uses |
| 89 | // malloc internally). |
| 90 |
| 91 | #if !defined(__UCLIBC__) && !defined(_AIX) |
| 92 | std::string::size_type search_from = 0; |
| 93 | while (search_from < text->size()) { |
| 94 | // Look for the start of a mangled symbol, from search_from. |
| 95 | std::string::size_type mangled_start = |
| 96 | text->find(kMangledSymbolPrefix, search_from); |
| 97 | if (mangled_start == std::string::npos) { |
| 98 | break; // Mangled symbol not found. |
| 99 | } |
| 100 |
| 101 | // Look for the end of the mangled symbol. |
| 102 | std::string::size_type mangled_end = |
| 103 | text->find_first_not_of(kSymbolCharacters, mangled_start); |
| 104 | if (mangled_end == std::string::npos) { |
| 105 | mangled_end = text->size(); |
| 106 | } |
| 107 | std::string mangled_symbol = |
| 108 | text->substr(mangled_start, mangled_end - mangled_start); |
| 109 |
| 110 | // Try to demangle the mangled symbol candidate. |
| 111 | int status = 0; |
| 112 | std::unique_ptr<char, base::FreeDeleter> demangled_symbol( |
| 113 | abi::__cxa_demangle(mangled_symbol.c_str(), nullptr, 0, &status)); |
| 114 | if (status == 0) { // Demangling is successful. |
| 115 | // Remove the mangled symbol. |
| 116 | text->erase(mangled_start, mangled_end - mangled_start); |
| 117 | // Insert the demangled symbol. |
| 118 | text->insert(mangled_start, demangled_symbol.get()); |
| 119 | // Next time, we'll start right after the demangled symbol we inserted. |
| 120 | search_from = mangled_start + strlen(demangled_symbol.get()); |
| 121 | } else { |
| 122 | // Failed to demangle. Retry after the "_Z" we just found. |
| 123 | search_from = mangled_start + 2; |
| 124 | } |
| 125 | } |
| 126 | #endif // !defined(__UCLIBC__) && !defined(_AIX) |
| 127 | } |
| 128 | #endif // !defined(USE_SYMBOLIZE) |
| 129 |
| 130 | class BacktraceOutputHandler { |
| 131 | public: |
| 132 | virtual void HandleOutput(const char* output) = 0; |
| 133 |
| 134 | protected: |
| 135 | virtual ~BacktraceOutputHandler() = default; |
| 136 | }; |
| 137 |
| 138 | #if !defined(__UCLIBC__) && !defined(_AIX) |
| 139 | void OutputPointer(void* pointer, BacktraceOutputHandler* handler) { |
| 140 | // This should be more than enough to store a 64-bit number in hex: |
| 141 | // 16 hex digits + 1 for null-terminator. |
| 142 | char buf[17] = { '\0' }; |
| 143 | handler->HandleOutput("0x"); |
| 144 | internal::itoa_r(reinterpret_cast<intptr_t>(pointer), |
| 145 | buf, sizeof(buf), 16, 12); |
| 146 | handler->HandleOutput(buf); |
| 147 | } |
| 148 |
| 149 | #if defined(USE_SYMBOLIZE) |
| 150 | void OutputFrameId(intptr_t frame_id, BacktraceOutputHandler* handler) { |
| 151 | // Max unsigned 64-bit number in decimal has 20 digits (18446744073709551615). |
| 152 | // Hence, 30 digits should be more than enough to represent it in decimal |
| 153 | // (including the null-terminator). |
| 154 | char buf[30] = { '\0' }; |
| 155 | handler->HandleOutput("#"); |
| 156 | internal::itoa_r(frame_id, buf, sizeof(buf), 10, 1); |
| 157 | handler->HandleOutput(buf); |
| 158 | } |
| 159 | #endif // defined(USE_SYMBOLIZE) |
| 160 |
| 161 | void ProcessBacktrace(void* const* trace, |
| 162 | size_t size, |
| 163 | const char* prefix_string, |
| 164 | BacktraceOutputHandler* handler) { |
| 165 | // NOTE: This code MUST be async-signal safe (it's used by in-process |
| 166 | // stack dumping signal handler). NO malloc or stdio is allowed here. |
| 167 |
| 168 | #if defined(USE_SYMBOLIZE) |
| 169 | for (size_t i = 0; i < size; ++i) { |
| 170 | if (prefix_string) |
| 171 | handler->HandleOutput(prefix_string); |
| 172 |
| 173 | OutputFrameId(i, handler); |
| 174 | handler->HandleOutput(" "); |
| 175 | OutputPointer(trace[i], handler); |
| 176 | handler->HandleOutput(" "); |
| 177 |
| 178 | char buf[1024] = { '\0' }; |
| 179 |
| 180 | // Subtract by one as return address of function may be in the next |
| 181 | // function when a function is annotated as noreturn. |
| 182 | void* address = static_cast<char*>(trace[i]) - 1; |
| 183 | if (google::Symbolize(address, buf, sizeof(buf))) |
| 184 | handler->HandleOutput(buf); |
| 185 | else |
| 186 | handler->HandleOutput("<unknown>"); |
| 187 |
| 188 | handler->HandleOutput("\n"); |
| 189 | } |
| 190 | #else |
| 191 | bool printed = false; |
| 192 |
| 193 | // Below part is async-signal unsafe (uses malloc), so execute it only |
| 194 | // when we are not executing the signal handler. |
| 195 | if (in_signal_handler == 0) { |
| 196 | std::unique_ptr<char*, FreeDeleter> trace_symbols( |
| 197 | backtrace_symbols(trace, size)); |
| 198 | if (trace_symbols.get()) { |
| 199 | for (size_t i = 0; i < size; ++i) { |
| 200 | std::string trace_symbol = trace_symbols.get()[i]; |
| 201 | DemangleSymbols(&trace_symbol); |
| 202 | if (prefix_string) |
| 203 | handler->HandleOutput(prefix_string); |
| 204 | handler->HandleOutput(trace_symbol.c_str()); |
| 205 | handler->HandleOutput("\n"); |
| 206 | } |
| 207 |
| 208 | printed = true; |
| 209 | } |
| 210 | } |
| 211 |
| 212 | if (!printed) { |
| 213 | for (size_t i = 0; i < size; ++i) { |
| 214 | handler->HandleOutput(" ["); |
| 215 | OutputPointer(trace[i], handler); |
| 216 | handler->HandleOutput("]\n"); |
| 217 | } |
| 218 | } |
| 219 | #endif // defined(USE_SYMBOLIZE) |
| 220 | } |
| 221 | #endif // !defined(__UCLIBC__) && !defined(_AIX) |
| 222 |
| 223 | void PrintToStderr(const char* output) { |
| 224 | // NOTE: This code MUST be async-signal safe (it's used by in-process |
| 225 | // stack dumping signal handler). NO malloc or stdio is allowed here. |
| 226 | ignore_result(HANDLE_EINTR(write(STDERR_FILENO, output, strlen(output)))); |
| 227 | } |
| 228 |
| 229 | void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) { |
| 230 | // NOTE: This code MUST be async-signal safe. |
| 231 | // NO malloc or stdio is allowed here. |
| 232 |
| 233 | #if !defined(OS_NACL) |
| 234 | // Give a registered callback a chance to recover from this signal |
| 235 | // |
| 236 | // V8 uses guard regions to guarantee memory safety in WebAssembly. This means |
| 237 | // some signals might be expected if they originate from Wasm code while |
| 238 | // accessing the guard region. We give V8 the chance to handle and recover |
| 239 | // from these signals first. |
| 240 | if (try_handle_signal != nullptr && |
| 241 | try_handle_signal(signal, info, void_context)) { |
| 242 | // The first chance handler took care of this. The SA_RESETHAND flag |
| 243 | // replaced this signal handler upon entry, but we want to stay |
| 244 | // installed. Thus, we reinstall ourselves before returning. |
| 245 | struct sigaction action; |
| 246 | memset(&action, 0, sizeof(action)); |
| 247 | action.sa_flags = SA_RESETHAND | SA_SIGINFO; |
| 248 | action.sa_sigaction = &StackDumpSignalHandler; |
| 249 | sigemptyset(&action.sa_mask); |
| 250 |
| 251 | sigaction(signal, &action, nullptr); |
| 252 | return; |
| 253 | } |
| 254 | #endif |
| 255 |
| 256 | // Do not take the "in signal handler" code path on Mac in a DCHECK-enabled |
| 257 | // build, as this prevents seeing a useful (symbolized) stack trace on a crash |
| 258 | // or DCHECK() failure. While it may not be fully safe to run the stack symbol |
| 259 | // printing code, in practice it's better to provide meaningful stack traces - |
| 260 | // and the risk is low given we're likely crashing already. |
| 261 | #if !defined(OS_MACOSX) || !DCHECK_IS_ON() |
| 262 | // Record the fact that we are in the signal handler now, so that the rest |
| 263 | // of StackTrace can behave in an async-signal-safe manner. |
| 264 | in_signal_handler = 1; |
| 265 | #endif |
| 266 |
| 267 | if (BeingDebugged()) |
| 268 | BreakDebugger(); |
| 269 |
| 270 | PrintToStderr("Received signal "); |
| 271 | char buf[1024] = { 0 }; |
| 272 | internal::itoa_r(signal, buf, sizeof(buf), 10, 0); |
| 273 | PrintToStderr(buf); |
| 274 | if (signal == SIGBUS) { |
| 275 | if (info->si_code == BUS_ADRALN) |
| 276 | PrintToStderr(" BUS_ADRALN "); |
| 277 | else if (info->si_code == BUS_ADRERR) |
| 278 | PrintToStderr(" BUS_ADRERR "); |
| 279 | else if (info->si_code == BUS_OBJERR) |
| 280 | PrintToStderr(" BUS_OBJERR "); |
| 281 | else |
| 282 | PrintToStderr(" <unknown> "); |
| 283 | } else if (signal == SIGFPE) { |
| 284 | if (info->si_code == FPE_FLTDIV) |
| 285 | PrintToStderr(" FPE_FLTDIV "); |
| 286 | else if (info->si_code == FPE_FLTINV) |
| 287 | PrintToStderr(" FPE_FLTINV "); |
| 288 | else if (info->si_code == FPE_FLTOVF) |
| 289 | PrintToStderr(" FPE_FLTOVF "); |
| 290 | else if (info->si_code == FPE_FLTRES) |
| 291 | PrintToStderr(" FPE_FLTRES "); |
| 292 | else if (info->si_code == FPE_FLTSUB) |
| 293 | PrintToStderr(" FPE_FLTSUB "); |
| 294 | else if (info->si_code == FPE_FLTUND) |
| 295 | PrintToStderr(" FPE_FLTUND "); |
| 296 | else if (info->si_code == FPE_INTDIV) |
| 297 | PrintToStderr(" FPE_INTDIV "); |
| 298 | else if (info->si_code == FPE_INTOVF) |
| 299 | PrintToStderr(" FPE_INTOVF "); |
| 300 | else |
| 301 | PrintToStderr(" <unknown> "); |
| 302 | } else if (signal == SIGILL) { |
| 303 | if (info->si_code == ILL_BADSTK) |
| 304 | PrintToStderr(" ILL_BADSTK "); |
| 305 | else if (info->si_code == ILL_COPROC) |
| 306 | PrintToStderr(" ILL_COPROC "); |
| 307 | else if (info->si_code == ILL_ILLOPN) |
| 308 | PrintToStderr(" ILL_ILLOPN "); |
| 309 | else if (info->si_code == ILL_ILLADR) |
| 310 | PrintToStderr(" ILL_ILLADR "); |
| 311 | else if (info->si_code == ILL_ILLTRP) |
| 312 | PrintToStderr(" ILL_ILLTRP "); |
| 313 | else if (info->si_code == ILL_PRVOPC) |
| 314 | PrintToStderr(" ILL_PRVOPC "); |
| 315 | else if (info->si_code == ILL_PRVREG) |
| 316 | PrintToStderr(" ILL_PRVREG "); |
| 317 | else |
| 318 | PrintToStderr(" <unknown> "); |
| 319 | } else if (signal == SIGSEGV) { |
| 320 | if (info->si_code == SEGV_MAPERR) |
| 321 | PrintToStderr(" SEGV_MAPERR "); |
| 322 | else if (info->si_code == SEGV_ACCERR) |
| 323 | PrintToStderr(" SEGV_ACCERR "); |
| 324 | else |
| 325 | PrintToStderr(" <unknown> "); |
| 326 | } |
| 327 | if (signal == SIGBUS || signal == SIGFPE || |
| 328 | signal == SIGILL || signal == SIGSEGV) { |
| 329 | internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr), |
| 330 | buf, sizeof(buf), 16, 12); |
| 331 | PrintToStderr(buf); |
| 332 | } |
| 333 | PrintToStderr("\n"); |
| 334 |
| 335 | #if BUILDFLAG(CFI_ENFORCEMENT_TRAP) |
| 336 | if (signal == SIGILL && info->si_code == ILL_ILLOPN) { |
| 337 | PrintToStderr( |
| 338 | "CFI: Most likely a control flow integrity violation; for more " |
| 339 | "information see:\n"); |
| 340 | PrintToStderr( |
| 341 | "https://www.chromium.org/developers/testing/control-flow-integrity\n"); |
| 342 | } |
| 343 | #endif // BUILDFLAG(CFI_ENFORCEMENT_TRAP) |
| 344 |
| 345 | debug::StackTrace().Print(); |
| 346 |
| 347 | #if defined(OS_LINUX) |
| 348 | #if ARCH_CPU_X86_FAMILY |
| 349 | ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context); |
| 350 | const struct { |
| 351 | const char* label; |
| 352 | greg_t value; |
| 353 | } registers[] = { |
| 354 | #if ARCH_CPU_32_BITS |
| 355 | { " gs: ", context->uc_mcontext.gregs[REG_GS] }, |
| 356 | { " fs: ", context->uc_mcontext.gregs[REG_FS] }, |
| 357 | { " es: ", context->uc_mcontext.gregs[REG_ES] }, |
| 358 | { " ds: ", context->uc_mcontext.gregs[REG_DS] }, |
| 359 | { " edi: ", context->uc_mcontext.gregs[REG_EDI] }, |
| 360 | { " esi: ", context->uc_mcontext.gregs[REG_ESI] }, |
| 361 | { " ebp: ", context->uc_mcontext.gregs[REG_EBP] }, |
| 362 | { " esp: ", context->uc_mcontext.gregs[REG_ESP] }, |
| 363 | { " ebx: ", context->uc_mcontext.gregs[REG_EBX] }, |
| 364 | { " edx: ", context->uc_mcontext.gregs[REG_EDX] }, |
| 365 | { " ecx: ", context->uc_mcontext.gregs[REG_ECX] }, |
| 366 | { " eax: ", context->uc_mcontext.gregs[REG_EAX] }, |
| 367 | { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] }, |
| 368 | { " err: ", context->uc_mcontext.gregs[REG_ERR] }, |
| 369 | { " ip: ", context->uc_mcontext.gregs[REG_EIP] }, |
| 370 | { " cs: ", context->uc_mcontext.gregs[REG_CS] }, |
| 371 | { " efl: ", context->uc_mcontext.gregs[REG_EFL] }, |
| 372 | { " usp: ", context->uc_mcontext.gregs[REG_UESP] }, |
| 373 | { " ss: ", context->uc_mcontext.gregs[REG_SS] }, |
| 374 | #elif ARCH_CPU_64_BITS |
| 375 | { " r8: ", context->uc_mcontext.gregs[REG_R8] }, |
| 376 | { " r9: ", context->uc_mcontext.gregs[REG_R9] }, |
| 377 | { " r10: ", context->uc_mcontext.gregs[REG_R10] }, |
| 378 | { " r11: ", context->uc_mcontext.gregs[REG_R11] }, |
| 379 | { " r12: ", context->uc_mcontext.gregs[REG_R12] }, |
| 380 | { " r13: ", context->uc_mcontext.gregs[REG_R13] }, |
| 381 | { " r14: ", context->uc_mcontext.gregs[REG_R14] }, |
| 382 | { " r15: ", context->uc_mcontext.gregs[REG_R15] }, |
| 383 | { " di: ", context->uc_mcontext.gregs[REG_RDI] }, |
| 384 | { " si: ", context->uc_mcontext.gregs[REG_RSI] }, |
| 385 | { " bp: ", context->uc_mcontext.gregs[REG_RBP] }, |
| 386 | { " bx: ", context->uc_mcontext.gregs[REG_RBX] }, |
| 387 | { " dx: ", context->uc_mcontext.gregs[REG_RDX] }, |
| 388 | { " ax: ", context->uc_mcontext.gregs[REG_RAX] }, |
| 389 | { " cx: ", context->uc_mcontext.gregs[REG_RCX] }, |
| 390 | { " sp: ", context->uc_mcontext.gregs[REG_RSP] }, |
| 391 | { " ip: ", context->uc_mcontext.gregs[REG_RIP] }, |
| 392 | { " efl: ", context->uc_mcontext.gregs[REG_EFL] }, |
| 393 | { " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] }, |
| 394 | { " erf: ", context->uc_mcontext.gregs[REG_ERR] }, |
| 395 | { " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] }, |
| 396 | { " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] }, |
| 397 | { " cr2: ", context->uc_mcontext.gregs[REG_CR2] }, |
| 398 | #endif // ARCH_CPU_32_BITS |
| 399 | }; |
| 400 |
| 401 | #if ARCH_CPU_32_BITS |
| 402 | const int kRegisterPadding = 8; |
| 403 | #elif ARCH_CPU_64_BITS |
| 404 | const int kRegisterPadding = 16; |
| 405 | #endif |
| 406 |
| 407 | for (size_t i = 0; i < base::size(registers); i++) { |
| 408 | PrintToStderr(registers[i].label); |
| 409 | internal::itoa_r(registers[i].value, buf, sizeof(buf), |
| 410 | 16, kRegisterPadding); |
| 411 | PrintToStderr(buf); |
| 412 |
| 413 | if ((i + 1) % 4 == 0) |
| 414 | PrintToStderr("\n"); |
| 415 | } |
| 416 | PrintToStderr("\n"); |
| 417 | #endif // ARCH_CPU_X86_FAMILY |
| 418 | #endif // defined(OS_LINUX) |
| 419 |
| 420 | PrintToStderr("[end of stack trace]\n"); |
| 421 |
| 422 | #if defined(OS_MACOSX) && !defined(OS_IOS) |
| 423 | if (::signal(signal, SIG_DFL) == SIG_ERR) |
| 424 | _exit(1); |
| 425 | #else |
| 426 | // Non-Mac OSes should probably reraise the signal as well, but the Linux |
| 427 | // sandbox tests break on CrOS devices. |
| 428 | // https://code.google.com/p/chromium/issues/detail?id=551681 |
| 429 | PrintToStderr("Calling _exit(1). Core file will not be generated.\n"); |
| 430 | _exit(1); |
| 431 | #endif // defined(OS_MACOSX) && !defined(OS_IOS) |
| 432 | } |
| 433 |
| 434 | class PrintBacktraceOutputHandler : public BacktraceOutputHandler { |
| 435 | public: |
| 436 | PrintBacktraceOutputHandler() = default; |
| 437 |
| 438 | void HandleOutput(const char* output) override { |
| 439 | // NOTE: This code MUST be async-signal safe (it's used by in-process |
| 440 | // stack dumping signal handler). NO malloc or stdio is allowed here. |
| 441 | PrintToStderr(output); |
| 442 | } |
| 443 |
| 444 | private: |
| 445 | DISALLOW_COPY_AND_ASSIGN(PrintBacktraceOutputHandler); |
| 446 | }; |
| 447 |
| 448 | class StreamBacktraceOutputHandler : public BacktraceOutputHandler { |
| 449 | public: |
| 450 | explicit StreamBacktraceOutputHandler(std::ostream* os) : os_(os) { |
| 451 | } |
| 452 |
| 453 | void HandleOutput(const char* output) override { (*os_) << output; } |
| 454 |
| 455 | private: |
| 456 | std::ostream* os_; |
| 457 |
| 458 | DISALLOW_COPY_AND_ASSIGN(StreamBacktraceOutputHandler); |
| 459 | }; |
| 460 |
| 461 | void WarmUpBacktrace() { |
| 462 | // Warm up stack trace infrastructure. It turns out that on the first |
| 463 | // call glibc initializes some internal data structures using pthread_once, |
| 464 | // and even backtrace() can call malloc(), leading to hangs. |
| 465 | // |
| 466 | // Example stack trace snippet (with tcmalloc): |
| 467 | // |
| 468 | // #8 0x0000000000a173b5 in tc_malloc |
| 469 | // at ./third_party/tcmalloc/chromium/src/debugallocation.cc:1161 |
| 470 | // #9 0x00007ffff7de7900 in _dl_map_object_deps at dl-deps.c:517 |
| 471 | // #10 0x00007ffff7ded8a9 in dl_open_worker at dl-open.c:262 |
| 472 | // #11 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178 |
| 473 | // #12 0x00007ffff7ded31a in _dl_open (file=0x7ffff625e298 "libgcc_s.so.1") |
| 474 | // at dl-open.c:639 |
| 475 | // #13 0x00007ffff6215602 in do_dlopen at dl-libc.c:89 |
| 476 | // #14 0x00007ffff7de9176 in _dl_catch_error at dl-error.c:178 |
| 477 | // #15 0x00007ffff62156c4 in dlerror_run at dl-libc.c:48 |
| 478 | // #16 __GI___libc_dlopen_mode at dl-libc.c:165 |
| 479 | // #17 0x00007ffff61ef8f5 in init |
| 480 | // at ../sysdeps/x86_64/../ia64/backtrace.c:53 |
| 481 | // #18 0x00007ffff6aad400 in pthread_once |
| 482 | // at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_once.S:104 |
| 483 | // #19 0x00007ffff61efa14 in __GI___backtrace |
| 484 | // at ../sysdeps/x86_64/../ia64/backtrace.c:104 |
| 485 | // #20 0x0000000000752a54 in base::debug::StackTrace::StackTrace |
| 486 | // at base/debug/stack_trace_posix.cc:175 |
| 487 | // #21 0x00000000007a4ae5 in |
| 488 | // base::(anonymous namespace)::StackDumpSignalHandler |
| 489 | // at base/process_util_posix.cc:172 |
| 490 | // #22 <signal handler called> |
| 491 | StackTrace stack_trace; |
| 492 | } |
| 493 |
| 494 | #if defined(USE_SYMBOLIZE) |
| 495 |
| 496 | // class SandboxSymbolizeHelper. |
| 497 | // |
| 498 | // The purpose of this class is to prepare and install a "file open" callback |
| 499 | // needed by the stack trace symbolization code |
| 500 | // (base/third_party/symbolize/symbolize.h) so that it can function properly |
| 501 | // in a sandboxed process. The caveat is that this class must be instantiated |
| 502 | // before the sandboxing is enabled so that it can get the chance to open all |
| 503 | // the object files that are loaded in the virtual address space of the current |
| 504 | // process. |
| 505 | class SandboxSymbolizeHelper { |
| 506 | public: |
| 507 | // Returns the singleton instance. |
| 508 | static SandboxSymbolizeHelper* GetInstance() { |
| 509 | return Singleton<SandboxSymbolizeHelper, |
| 510 | LeakySingletonTraits<SandboxSymbolizeHelper>>::get(); |
| 511 | } |
| 512 |
| 513 | private: |
| 514 | friend struct DefaultSingletonTraits<SandboxSymbolizeHelper>; |
| 515 |
| 516 | SandboxSymbolizeHelper() |
| 517 | : is_initialized_(false) { |
| 518 | Init(); |
| 519 | } |
| 520 |
| 521 | ~SandboxSymbolizeHelper() { |
| 522 | UnregisterCallback(); |
| 523 | CloseObjectFiles(); |
| 524 | } |
| 525 |
| 526 | // Returns a O_RDONLY file descriptor for |file_path| if it was opened |
| 527 | // successfully during the initialization. The file is repositioned at |
| 528 | // offset 0. |
| 529 | // IMPORTANT: This function must be async-signal-safe because it can be |
| 530 | // called from a signal handler (symbolizing stack frames for a crash). |
| 531 | int GetFileDescriptor(const char* file_path) { |
| 532 | int fd = -1; |
| 533 |
| 534 | #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 535 | if (file_path) { |
| 536 | // The assumption here is that iterating over std::map<std::string, int> |
| 537 | // using a const_iterator does not allocate dynamic memory, hense it is |
| 538 | // async-signal-safe. |
| 539 | std::map<std::string, int>::const_iterator it; |
| 540 | for (it = modules_.begin(); it != modules_.end(); ++it) { |
| 541 | if (strcmp((it->first).c_str(), file_path) == 0) { |
| 542 | // POSIX.1-2004 requires an implementation to guarantee that dup() |
| 543 | // is async-signal-safe. |
| 544 | fd = HANDLE_EINTR(dup(it->second)); |
| 545 | break; |
| 546 | } |
| 547 | } |
| 548 | // POSIX.1-2004 requires an implementation to guarantee that lseek() |
| 549 | // is async-signal-safe. |
| 550 | if (fd >= 0 && lseek(fd, 0, SEEK_SET) < 0) { |
| 551 | // Failed to seek. |
| 552 | fd = -1; |
| 553 | } |
| 554 | } |
| 555 | #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 556 |
| 557 | return fd; |
| 558 | } |
| 559 |
| 560 | // Searches for the object file (from /proc/self/maps) that contains |
| 561 | // the specified pc. If found, sets |start_address| to the start address |
| 562 | // of where this object file is mapped in memory, sets the module base |
| 563 | // address into |base_address|, copies the object file name into |
| 564 | // |out_file_name|, and attempts to open the object file. If the object |
| 565 | // file is opened successfully, returns the file descriptor. Otherwise, |
| 566 | // returns -1. |out_file_name_size| is the size of the file name buffer |
| 567 | // (including the null terminator). |
| 568 | // IMPORTANT: This function must be async-signal-safe because it can be |
| 569 | // called from a signal handler (symbolizing stack frames for a crash). |
| 570 | static int OpenObjectFileContainingPc(uint64_t pc, uint64_t& start_address, |
| 571 | uint64_t& base_address, char* file_path, |
| 572 | int file_path_size) { |
| 573 | // This method can only be called after the singleton is instantiated. |
| 574 | // This is ensured by the following facts: |
| 575 | // * This is the only static method in this class, it is private, and |
| 576 | // the class has no friends (except for the DefaultSingletonTraits). |
| 577 | // The compiler guarantees that it can only be called after the |
| 578 | // singleton is instantiated. |
| 579 | // * This method is used as a callback for the stack tracing code and |
| 580 | // the callback registration is done in the constructor, so logically |
| 581 | // it cannot be called before the singleton is created. |
| 582 | SandboxSymbolizeHelper* instance = GetInstance(); |
| 583 |
| 584 | // Cannot use STL iterators here, since debug iterators use locks. |
| 585 | // NOLINTNEXTLINE(modernize-loop-convert) |
| 586 | for (size_t i = 0; i < instance->regions_.size(); ++i) { |
| 587 | const MappedMemoryRegion& region = instance->regions_[i]; |
| 588 | if (region.start <= pc && pc < region.end) { |
| 589 | start_address = region.start; |
| 590 | base_address = region.base; |
| 591 | if (file_path && file_path_size > 0) { |
| 592 | strncpy(file_path, region.path.c_str(), file_path_size); |
| 593 | // Ensure null termination. |
| 594 | file_path[file_path_size - 1] = '\0'; |
| 595 | } |
| 596 | return instance->GetFileDescriptor(region.path.c_str()); |
| 597 | } |
| 598 | } |
| 599 | return -1; |
| 600 | } |
| 601 |
| 602 | // Set the base address for each memory region by reading ELF headers in |
| 603 | // process memory. |
| 604 | void SetBaseAddressesForMemoryRegions() { |
| 605 | base::ScopedFD mem_fd( |
| 606 | HANDLE_EINTR(open("/proc/self/mem", O_RDONLY | O_CLOEXEC))); |
| 607 | if (!mem_fd.is_valid()) |
| 608 | return; |
| 609 |
| 610 | auto safe_memcpy = [&mem_fd](void* dst, uintptr_t src, size_t size) { |
| 611 | return HANDLE_EINTR(pread(mem_fd.get(), dst, size, src)) == ssize_t(size); |
| 612 | }; |
| 613 |
| 614 | uintptr_t cur_base = 0; |
| 615 | for (auto& r : regions_) { |
| 616 | ElfW(Ehdr) ehdr; |
| 617 | static_assert(SELFMAG <= sizeof(ElfW(Ehdr)), "SELFMAG too large"); |
| 618 | if ((r.permissions & MappedMemoryRegion::READ) && |
| 619 | safe_memcpy(&ehdr, r.start, sizeof(ElfW(Ehdr))) && |
| 620 | memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) { |
| 621 | switch (ehdr.e_type) { |
| 622 | case ET_EXEC: |
| 623 | cur_base = 0; |
| 624 | break; |
| 625 | case ET_DYN: |
| 626 | // Find the segment containing file offset 0. This will correspond |
| 627 | // to the ELF header that we just read. Normally this will have |
| 628 | // virtual address 0, but this is not guaranteed. We must subtract |
| 629 | // the virtual address from the address where the ELF header was |
| 630 | // mapped to get the base address. |
| 631 | // |
| 632 | // If we fail to find a segment for file offset 0, use the address |
| 633 | // of the ELF header as the base address. |
| 634 | cur_base = r.start; |
| 635 | for (unsigned i = 0; i != ehdr.e_phnum; ++i) { |
| 636 | ElfW(Phdr) phdr; |
| 637 | if (safe_memcpy(&phdr, r.start + ehdr.e_phoff + i * sizeof(phdr), |
| 638 | sizeof(phdr)) && |
| 639 | phdr.p_type == PT_LOAD && phdr.p_offset == 0) { |
| 640 | cur_base = r.start - phdr.p_vaddr; |
| 641 | break; |
| 642 | } |
| 643 | } |
| 644 | break; |
| 645 | default: |
| 646 | // ET_REL or ET_CORE. These aren't directly executable, so they |
| 647 | // don't affect the base address. |
| 648 | break; |
| 649 | } |
| 650 | } |
| 651 |
| 652 | r.base = cur_base; |
| 653 | } |
| 654 | } |
| 655 |
| 656 | // Parses /proc/self/maps in order to compile a list of all object file names |
| 657 | // for the modules that are loaded in the current process. |
| 658 | // Returns true on success. |
| 659 | bool CacheMemoryRegions() { |
| 660 | // Reads /proc/self/maps. |
| 661 | std::string contents; |
| 662 | if (!ReadProcMaps(&contents)) { |
| 663 | LOG(ERROR) << "Failed to read /proc/self/maps"; |
| 664 | return false; |
| 665 | } |
| 666 |
| 667 | // Parses /proc/self/maps. |
| 668 | if (!ParseProcMaps(contents, ®ions_)) { |
| 669 | LOG(ERROR) << "Failed to parse the contents of /proc/self/maps"; |
| 670 | return false; |
| 671 | } |
| 672 |
| 673 | SetBaseAddressesForMemoryRegions(); |
| 674 |
| 675 | is_initialized_ = true; |
| 676 | return true; |
| 677 | } |
| 678 |
| 679 | // Opens all object files and caches their file descriptors. |
| 680 | void OpenSymbolFiles() { |
| 681 | // Pre-opening and caching the file descriptors of all loaded modules is |
| 682 | // not safe for production builds. Hence it is only done in non-official |
| 683 | // builds. For more details, take a look at: http://crbug.com/341966. |
| 684 | #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 685 | // Open the object files for all read-only executable regions and cache |
| 686 | // their file descriptors. |
| 687 | std::vector<MappedMemoryRegion>::const_iterator it; |
| 688 | for (it = regions_.begin(); it != regions_.end(); ++it) { |
| 689 | const MappedMemoryRegion& region = *it; |
| 690 | // Only interesed in read-only executable regions. |
| 691 | if ((region.permissions & MappedMemoryRegion::READ) == |
| 692 | MappedMemoryRegion::READ && |
| 693 | (region.permissions & MappedMemoryRegion::WRITE) == 0 && |
| 694 | (region.permissions & MappedMemoryRegion::EXECUTE) == |
| 695 | MappedMemoryRegion::EXECUTE) { |
| 696 | if (region.path.empty()) { |
| 697 | // Skip regions with empty file names. |
| 698 | continue; |
| 699 | } |
| 700 | if (region.path[0] == '[') { |
| 701 | // Skip pseudo-paths, like [stack], [vdso], [heap], etc ... |
| 702 | continue; |
| 703 | } |
| 704 | if (base::EndsWith(region.path, " (deleted)", |
| 705 | base::CompareCase::SENSITIVE)) { |
| 706 | // Skip deleted files. |
| 707 | continue; |
| 708 | } |
| 709 | // Avoid duplicates. |
| 710 | if (modules_.find(region.path) == modules_.end()) { |
| 711 | int fd = open(region.path.c_str(), O_RDONLY | O_CLOEXEC); |
| 712 | if (fd >= 0) { |
| 713 | modules_.insert(std::make_pair(region.path, fd)); |
| 714 | } else { |
| 715 | LOG(WARNING) << "Failed to open file: " << region.path |
| 716 | << "\n Error: " << strerror(errno); |
| 717 | } |
| 718 | } |
| 719 | } |
| 720 | } |
| 721 | #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 722 | } |
| 723 |
| 724 | // Initializes and installs the symbolization callback. |
| 725 | void Init() { |
| 726 | if (CacheMemoryRegions()) { |
| 727 | OpenSymbolFiles(); |
| 728 | google::InstallSymbolizeOpenObjectFileCallback( |
| 729 | &OpenObjectFileContainingPc); |
| 730 | } |
| 731 | } |
| 732 |
| 733 | // Unregister symbolization callback. |
| 734 | void UnregisterCallback() { |
| 735 | if (is_initialized_) { |
| 736 | google::InstallSymbolizeOpenObjectFileCallback(nullptr); |
| 737 | is_initialized_ = false; |
| 738 | } |
| 739 | } |
| 740 |
| 741 | // Closes all file descriptors owned by this instance. |
| 742 | void CloseObjectFiles() { |
| 743 | #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 744 | std::map<std::string, int>::iterator it; |
| 745 | for (it = modules_.begin(); it != modules_.end(); ++it) { |
| 746 | int ret = IGNORE_EINTR(close(it->second)); |
| 747 | DCHECK(!ret); |
| 748 | it->second = -1; |
| 749 | } |
| 750 | modules_.clear(); |
| 751 | #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 752 | } |
| 753 |
| 754 | // Set to true upon successful initialization. |
| 755 | bool is_initialized_; |
| 756 |
| 757 | #if !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 758 | // Mapping from file name to file descriptor. Includes file descriptors |
| 759 | // for all successfully opened object files and the file descriptor for |
| 760 | // /proc/self/maps. This code is not safe for production builds. |
| 761 | std::map<std::string, int> modules_; |
| 762 | #endif // !defined(OFFICIAL_BUILD) || !defined(NO_UNWIND_TABLES) |
| 763 |
| 764 | // Cache for the process memory regions. Produced by parsing the contents |
| 765 | // of /proc/self/maps cache. |
| 766 | std::vector<MappedMemoryRegion> regions_; |
| 767 |
| 768 | DISALLOW_COPY_AND_ASSIGN(SandboxSymbolizeHelper); |
| 769 | }; |
| 770 | #endif // USE_SYMBOLIZE |
| 771 |
| 772 | } // namespace |
| 773 |
| 774 | bool EnableInProcessStackDumping() { |
| 775 | #if defined(USE_SYMBOLIZE) |
| 776 | SandboxSymbolizeHelper::GetInstance(); |
| 777 | #endif // USE_SYMBOLIZE |
| 778 |
| 779 | // When running in an application, our code typically expects SIGPIPE |
| 780 | // to be ignored. Therefore, when testing that same code, it should run |
| 781 | // with SIGPIPE ignored as well. |
| 782 | struct sigaction sigpipe_action; |
| 783 | memset(&sigpipe_action, 0, sizeof(sigpipe_action)); |
| 784 | sigpipe_action.sa_handler = SIG_IGN; |
| 785 | sigemptyset(&sigpipe_action.sa_mask); |
| 786 | bool success = (sigaction(SIGPIPE, &sigpipe_action, nullptr) == 0); |
| 787 |
| 788 | // Avoid hangs during backtrace initialization, see above. |
| 789 | WarmUpBacktrace(); |
| 790 |
| 791 | struct sigaction action; |
| 792 | memset(&action, 0, sizeof(action)); |
| 793 | action.sa_flags = SA_RESETHAND | SA_SIGINFO; |
| 794 | action.sa_sigaction = &StackDumpSignalHandler; |
| 795 | sigemptyset(&action.sa_mask); |
| 796 |
| 797 | success &= (sigaction(SIGILL, &action, nullptr) == 0); |
| 798 | success &= (sigaction(SIGABRT, &action, nullptr) == 0); |
| 799 | success &= (sigaction(SIGFPE, &action, nullptr) == 0); |
| 800 | success &= (sigaction(SIGBUS, &action, nullptr) == 0); |
| 801 | success &= (sigaction(SIGSEGV, &action, nullptr) == 0); |
| 802 | // On Linux, SIGSYS is reserved by the kernel for seccomp-bpf sandboxing. |
| 803 | #if !defined(OS_LINUX) |
| 804 | success &= (sigaction(SIGSYS, &action, nullptr) == 0); |
| 805 | #endif // !defined(OS_LINUX) |
| 806 |
| 807 | return success; |
| 808 | } |
| 809 |
| 810 | #if !defined(OS_NACL) |
| 811 | bool SetStackDumpFirstChanceCallback(bool (*handler)(int, siginfo_t*, void*)) { |
| 812 | DCHECK(try_handle_signal == nullptr || handler == nullptr); |
| 813 | try_handle_signal = handler; |
| 814 |
| 815 | #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ |
| 816 | defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) || \ |
| 817 | defined(UNDEFINED_SANITIZER) |
| 818 | struct sigaction installed_handler; |
| 819 | CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0); |
| 820 | // If the installed handler does not point to StackDumpSignalHandler, then |
| 821 | // allow_user_segv_handler is 0. |
| 822 | if (installed_handler.sa_sigaction != StackDumpSignalHandler) { |
| 823 | LOG(WARNING) |
| 824 | << "WARNING: sanitizers are preventing signal handler installation. " |
| 825 | << "WebAssembly trap handlers are disabled.\n"; |
| 826 | return false; |
| 827 | } |
| 828 | #endif |
| 829 | return true; |
| 830 | } |
| 831 | #endif |
| 832 |
| 833 | size_t CollectStackTrace(void** trace, size_t count) { |
| 834 | // NOTE: This code MUST be async-signal safe (it's used by in-process |
| 835 | // stack dumping signal handler). NO malloc or stdio is allowed here. |
| 836 |
| 837 | #if !defined(__UCLIBC__) && !defined(_AIX) |
| 838 | // Though the backtrace API man page does not list any possible negative |
| 839 | // return values, we take no chance. |
| 840 | return base::saturated_cast<size_t>(backtrace(trace, count)); |
| 841 | #else |
| 842 | return 0; |
| 843 | #endif |
| 844 | } |
| 845 |
| 846 | void StackTrace::PrintWithPrefix(const char* prefix_string) const { |
| 847 | // NOTE: This code MUST be async-signal safe (it's used by in-process |
| 848 | // stack dumping signal handler). NO malloc or stdio is allowed here. |
| 849 |
| 850 | #if !defined(__UCLIBC__) && !defined(_AIX) |
| 851 | PrintBacktraceOutputHandler handler; |
| 852 | ProcessBacktrace(trace_, count_, prefix_string, &handler); |
| 853 | #endif |
| 854 | } |
| 855 |
| 856 | #if !defined(__UCLIBC__) && !defined(_AIX) |
| 857 | void StackTrace::OutputToStreamWithPrefix(std::ostream* os, |
| 858 | const char* prefix_string) const { |
| 859 | StreamBacktraceOutputHandler handler(os); |
| 860 | ProcessBacktrace(trace_, count_, prefix_string, &handler); |
| 861 | } |
| 862 | #endif |
| 863 |
| 864 | namespace internal { |
| 865 |
| 866 | // NOTE: code from sandbox/linux/seccomp-bpf/demo.cc. |
| 867 | char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) { |
| 868 | // Make sure we can write at least one NUL byte. |
| 869 | size_t n = 1; |
| 870 | if (n > sz) |
| 871 | return nullptr; |
| 872 |
| 873 | if (base < 2 || base > 16) { |
| 874 | buf[0] = '\000'; |
| 875 | return nullptr; |
| 876 | } |
| 877 |
| 878 | char* start = buf; |
| 879 |
| 880 | uintptr_t j = i; |
| 881 |
| 882 | // Handle negative numbers (only for base 10). |
| 883 | if (i < 0 && base == 10) { |
| 884 | // This does "j = -i" while avoiding integer overflow. |
| 885 | j = static_cast<uintptr_t>(-(i + 1)) + 1; |
| 886 |
| 887 | // Make sure we can write the '-' character. |
| 888 | if (++n > sz) { |
| 889 | buf[0] = '\000'; |
| 890 | return nullptr; |
| 891 | } |
| 892 | *start++ = '-'; |
| 893 | } |
| 894 |
| 895 | // Loop until we have converted the entire number. Output at least one |
| 896 | // character (i.e. '0'). |
| 897 | char* ptr = start; |
| 898 | do { |
| 899 | // Make sure there is still enough space left in our output buffer. |
| 900 | if (++n > sz) { |
| 901 | buf[0] = '\000'; |
| 902 | return nullptr; |
| 903 | } |
| 904 |
| 905 | // Output the next digit. |
| 906 | *ptr++ = "0123456789abcdef"[j % base]; |
| 907 | j /= base; |
| 908 |
| 909 | if (padding > 0) |
| 910 | padding--; |
| 911 | } while (j > 0 || padding > 0); |
| 912 |
| 913 | // Terminate the output with a NUL character. |
| 914 | *ptr = '\000'; |
| 915 |
| 916 | // Conversion to ASCII actually resulted in the digits being in reverse |
| 917 | // order. We can't easily generate them in forward order, as we can't tell |
| 918 | // the number of characters needed until we are done converting. |
| 919 | // So, now, we reverse the string (except for the possible "-" sign). |
| 920 | while (--ptr > start) { |
| 921 | char ch = *ptr; |
| 922 | *ptr = *start; |
| 923 | *start++ = ch; |
| 924 | } |
| 925 | return buf; |
| 926 | } |
| 927 |
| 928 | } // namespace internal |
| 929 |
| 930 | } // namespace debug |
| 931 | } // namespace base |
| 932 |