| 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 <windows.h> |
| 8 | #include <dbghelp.h> |
| 9 | #include <stddef.h> |
| 10 | |
| 11 | #include <algorithm> |
| 12 | #include <iostream> |
| 13 | #include <memory> |
| 14 | |
| 15 | #include "base/files/file_path.h" |
| 16 | #include "base/logging.h" |
| 17 | #include "base/memory/singleton.h" |
| 18 | #include "base/stl_util.h" |
| 19 | #include "base/strings/string_util.h" |
| 20 | #include "base/strings/stringprintf.h" |
| 21 | #include "base/synchronization/lock.h" |
| 22 | #include "build/build_config.h" |
| 23 | |
| 24 | namespace base { |
| 25 | namespace debug { |
| 26 | |
| 27 | namespace { |
| 28 | |
| 29 | // Previous unhandled filter. Will be called if not NULL when we intercept an |
| 30 | // exception. Only used in unit tests. |
| 31 | LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = NULL; |
| 32 | |
| 33 | bool g_initialized_symbols = false; |
| 34 | DWORD g_init_error = ERROR_SUCCESS; |
| 35 | |
| 36 | // Prints the exception call stack. |
| 37 | // This is the unit tests exception filter. |
| 38 | long WINAPI StackDumpExceptionFilter(EXCEPTION_POINTERS* info) { |
| 39 | DWORD exc_code = info->ExceptionRecord->ExceptionCode; |
| 40 | std::cerr << "Received fatal exception "; |
| 41 | switch (exc_code) { |
| 42 | case EXCEPTION_ACCESS_VIOLATION: |
| 43 | std::cerr << "EXCEPTION_ACCESS_VIOLATION"; |
| 44 | break; |
| 45 | case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: |
| 46 | std::cerr << "EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; |
| 47 | break; |
| 48 | case EXCEPTION_BREAKPOINT: |
| 49 | std::cerr << "EXCEPTION_BREAKPOINT"; |
| 50 | break; |
| 51 | case EXCEPTION_DATATYPE_MISALIGNMENT: |
| 52 | std::cerr << "EXCEPTION_DATATYPE_MISALIGNMENT"; |
| 53 | break; |
| 54 | case EXCEPTION_FLT_DENORMAL_OPERAND: |
| 55 | std::cerr << "EXCEPTION_FLT_DENORMAL_OPERAND"; |
| 56 | break; |
| 57 | case EXCEPTION_FLT_DIVIDE_BY_ZERO: |
| 58 | std::cerr << "EXCEPTION_FLT_DIVIDE_BY_ZERO"; |
| 59 | break; |
| 60 | case EXCEPTION_FLT_INEXACT_RESULT: |
| 61 | std::cerr << "EXCEPTION_FLT_INEXACT_RESULT"; |
| 62 | break; |
| 63 | case EXCEPTION_FLT_INVALID_OPERATION: |
| 64 | std::cerr << "EXCEPTION_FLT_INVALID_OPERATION"; |
| 65 | break; |
| 66 | case EXCEPTION_FLT_OVERFLOW: |
| 67 | std::cerr << "EXCEPTION_FLT_OVERFLOW"; |
| 68 | break; |
| 69 | case EXCEPTION_FLT_STACK_CHECK: |
| 70 | std::cerr << "EXCEPTION_FLT_STACK_CHECK"; |
| 71 | break; |
| 72 | case EXCEPTION_FLT_UNDERFLOW: |
| 73 | std::cerr << "EXCEPTION_FLT_UNDERFLOW"; |
| 74 | break; |
| 75 | case EXCEPTION_ILLEGAL_INSTRUCTION: |
| 76 | std::cerr << "EXCEPTION_ILLEGAL_INSTRUCTION"; |
| 77 | break; |
| 78 | case EXCEPTION_IN_PAGE_ERROR: |
| 79 | std::cerr << "EXCEPTION_IN_PAGE_ERROR"; |
| 80 | break; |
| 81 | case EXCEPTION_INT_DIVIDE_BY_ZERO: |
| 82 | std::cerr << "EXCEPTION_INT_DIVIDE_BY_ZERO"; |
| 83 | break; |
| 84 | case EXCEPTION_INT_OVERFLOW: |
| 85 | std::cerr << "EXCEPTION_INT_OVERFLOW"; |
| 86 | break; |
| 87 | case EXCEPTION_INVALID_DISPOSITION: |
| 88 | std::cerr << "EXCEPTION_INVALID_DISPOSITION"; |
| 89 | break; |
| 90 | case EXCEPTION_NONCONTINUABLE_EXCEPTION: |
| 91 | std::cerr << "EXCEPTION_NONCONTINUABLE_EXCEPTION"; |
| 92 | break; |
| 93 | case EXCEPTION_PRIV_INSTRUCTION: |
| 94 | std::cerr << "EXCEPTION_PRIV_INSTRUCTION"; |
| 95 | break; |
| 96 | case EXCEPTION_SINGLE_STEP: |
| 97 | std::cerr << "EXCEPTION_SINGLE_STEP"; |
| 98 | break; |
| 99 | case EXCEPTION_STACK_OVERFLOW: |
| 100 | std::cerr << "EXCEPTION_STACK_OVERFLOW"; |
| 101 | break; |
| 102 | default: |
| 103 | std::cerr << "0x" << std::hex << exc_code; |
| 104 | break; |
| 105 | } |
| 106 | std::cerr << "\n"; |
| 107 | |
| 108 | debug::StackTrace(info).Print(); |
| 109 | if (g_previous_filter) |
| 110 | return g_previous_filter(info); |
| 111 | return EXCEPTION_CONTINUE_SEARCH; |
| 112 | } |
| 113 | |
| 114 | FilePath GetExePath() { |
| 115 | wchar_t system_buffer[MAX_PATH]; |
| 116 | GetModuleFileName(NULL, system_buffer, MAX_PATH); |
| 117 | system_buffer[MAX_PATH - 1] = L'\0'; |
| 118 | return FilePath(system_buffer); |
| 119 | } |
| 120 | |
| 121 | bool InitializeSymbols() { |
| 122 | if (g_initialized_symbols) { |
| 123 | // Force a reinitialization. Will ensure any modules loaded after process |
| 124 | // startup also get symbolized. |
| 125 | SymCleanup(GetCurrentProcess()); |
| 126 | g_initialized_symbols = false; |
| 127 | } |
| 128 | g_initialized_symbols = true; |
| 129 | // Defer symbol load until they're needed, use undecorated names, and get line |
| 130 | // numbers. |
| 131 | SymSetOptions(SYMOPT_DEFERRED_LOADS | |
| 132 | SYMOPT_UNDNAME | |
| 133 | SYMOPT_LOAD_LINES); |
| 134 | if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) { |
| 135 | g_init_error = GetLastError(); |
| 136 | // TODO(awong): Handle error: SymInitialize can fail with |
| 137 | // ERROR_INVALID_PARAMETER. |
| 138 | // When it fails, we should not call debugbreak since it kills the current |
| 139 | // process (prevents future tests from running or kills the browser |
| 140 | // process). |
| 141 | DLOG(ERROR) << "SymInitialize failed: " << g_init_error; |
| 142 | return false; |
| 143 | } |
| 144 | |
| 145 | // When transferring the binaries e.g. between bots, path put |
| 146 | // into the executable will get off. To still retrieve symbols correctly, |
| 147 | // add the directory of the executable to symbol search path. |
| 148 | // All following errors are non-fatal. |
| 149 | static constexpr size_t kSymbolsArraySize = 1024; |
| 150 | wchar_t symbols_path[kSymbolsArraySize]; |
| 151 | |
| 152 | // Note: The below function takes buffer size as number of characters, |
| 153 | // not number of bytes! |
| 154 | if (!SymGetSearchPathW(GetCurrentProcess(), symbols_path, |
| 155 | kSymbolsArraySize)) { |
| 156 | g_init_error = GetLastError(); |
| 157 | DLOG(WARNING) << "SymGetSearchPath failed: " << g_init_error; |
| 158 | return false; |
| 159 | } |
| 160 | |
| 161 | std::wstring new_path = StringPrintf(L"%ls;%ls", symbols_path, |
| 162 | GetExePath().DirName().value().c_str()); |
| 163 | if (!SymSetSearchPathW(GetCurrentProcess(), new_path.c_str())) { |
| 164 | g_init_error = GetLastError(); |
| 165 | DLOG(WARNING) << "SymSetSearchPath failed." << g_init_error; |
| 166 | return false; |
| 167 | } |
| 168 | |
| 169 | g_init_error = ERROR_SUCCESS; |
| 170 | return true; |
| 171 | } |
| 172 | |
| 173 | // SymbolContext is a threadsafe singleton that wraps the DbgHelp Sym* family |
| 174 | // of functions. The Sym* family of functions may only be invoked by one |
| 175 | // thread at a time. SymbolContext code may access a symbol server over the |
| 176 | // network while holding the lock for this singleton. In the case of high |
| 177 | // latency, this code will adversely affect performance. |
| 178 | // |
| 179 | // There is also a known issue where this backtrace code can interact |
| 180 | // badly with breakpad if breakpad is invoked in a separate thread while |
| 181 | // we are using the Sym* functions. This is because breakpad does now |
| 182 | // share a lock with this function. See this related bug: |
| 183 | // |
| 184 | // https://crbug.com/google-breakpad/311 |
| 185 | // |
| 186 | // This is a very unlikely edge case, and the current solution is to |
| 187 | // just ignore it. |
| 188 | class SymbolContext { |
| 189 | public: |
| 190 | static SymbolContext* GetInstance() { |
| 191 | // We use a leaky singleton because code may call this during process |
| 192 | // termination. |
| 193 | return |
| 194 | Singleton<SymbolContext, LeakySingletonTraits<SymbolContext> >::get(); |
| 195 | } |
| 196 | |
| 197 | // For the given trace, attempts to resolve the symbols, and output a trace |
| 198 | // to the ostream os. The format for each line of the backtrace is: |
| 199 | // |
| 200 | // <tab>SymbolName[0xAddress+Offset] (FileName:LineNo) |
| 201 | // |
| 202 | // This function should only be called if Init() has been called. We do not |
| 203 | // LOG(FATAL) here because this code is called might be triggered by a |
| 204 | // LOG(FATAL) itself. Also, it should not be calling complex code that is |
| 205 | // extensible like PathService since that can in turn fire CHECKs. |
| 206 | void OutputTraceToStream(const void* const* trace, |
| 207 | size_t count, |
| 208 | std::ostream* os, |
| 209 | const char* prefix_string) { |
| 210 | AutoLock lock(lock_); |
| 211 | |
| 212 | for (size_t i = 0; (i < count) && os->good(); ++i) { |
| 213 | const int kMaxNameLength = 256; |
| 214 | DWORD_PTR frame = reinterpret_cast<DWORD_PTR>(trace[i]); |
| 215 | |
| 216 | // Code adapted from MSDN example: |
| 217 | // http://msdn.microsoft.com/en-us/library/ms680578(VS.85).aspx |
| 218 | ULONG64 buffer[ |
| 219 | (sizeof(SYMBOL_INFO) + |
| 220 | kMaxNameLength * sizeof(wchar_t) + |
| 221 | sizeof(ULONG64) - 1) / |
| 222 | sizeof(ULONG64)]; |
| 223 | memset(buffer, 0, sizeof(buffer)); |
| 224 | |
| 225 | // Initialize symbol information retrieval structures. |
| 226 | DWORD64 sym_displacement = 0; |
| 227 | PSYMBOL_INFO symbol = reinterpret_cast<PSYMBOL_INFO>(&buffer[0]); |
| 228 | symbol->SizeOfStruct = sizeof(SYMBOL_INFO); |
| 229 | symbol->MaxNameLen = kMaxNameLength - 1; |
| 230 | BOOL has_symbol = SymFromAddr(GetCurrentProcess(), frame, |
| 231 | &sym_displacement, symbol); |
| 232 | |
| 233 | // Attempt to retrieve line number information. |
| 234 | DWORD line_displacement = 0; |
| 235 | IMAGEHLP_LINE64 line = {}; |
| 236 | line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); |
| 237 | BOOL has_line = SymGetLineFromAddr64(GetCurrentProcess(), frame, |
| 238 | &line_displacement, &line); |
| 239 | |
| 240 | // Output the backtrace line. |
| 241 | if (prefix_string) |
| 242 | (*os) << prefix_string; |
| 243 | (*os) << "\t"; |
| 244 | if (has_symbol) { |
| 245 | (*os) << symbol->Name << " [0x" << trace[i] << "+" |
| 246 | << sym_displacement << "]"; |
| 247 | } else { |
| 248 | // If there is no symbol information, add a spacer. |
| 249 | (*os) << "(No symbol) [0x" << trace[i] << "]"; |
| 250 | } |
| 251 | if (has_line) { |
| 252 | (*os) << " (" << line.FileName << ":" << line.LineNumber << ")"; |
| 253 | } |
| 254 | (*os) << "\n"; |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | private: |
| 259 | friend struct DefaultSingletonTraits<SymbolContext>; |
| 260 | |
| 261 | SymbolContext() { |
| 262 | InitializeSymbols(); |
| 263 | } |
| 264 | |
| 265 | Lock lock_; |
| 266 | DISALLOW_COPY_AND_ASSIGN(SymbolContext); |
| 267 | }; |
| 268 | |
| 269 | } // namespace |
| 270 | |
| 271 | bool EnableInProcessStackDumping() { |
| 272 | // Add stack dumping support on exception on windows. Similar to OS_POSIX |
| 273 | // signal() handling in process_util_posix.cc. |
| 274 | g_previous_filter = SetUnhandledExceptionFilter(&StackDumpExceptionFilter); |
| 275 | |
| 276 | // Need to initialize symbols early in the process or else this fails on |
| 277 | // swarming (since symbols are in different directory than in the exes) and |
| 278 | // also release x64. |
| 279 | return InitializeSymbols(); |
| 280 | } |
| 281 | |
| 282 | NOINLINE size_t CollectStackTrace(void** trace, size_t count) { |
| 283 | // When walking our own stack, use CaptureStackBackTrace(). |
| 284 | return CaptureStackBackTrace(0, count, trace, NULL); |
| 285 | } |
| 286 | |
| 287 | StackTrace::StackTrace(EXCEPTION_POINTERS* exception_pointers) { |
| 288 | InitTrace(exception_pointers->ContextRecord); |
| 289 | } |
| 290 | |
| 291 | StackTrace::StackTrace(const CONTEXT* context) { |
| 292 | InitTrace(context); |
| 293 | } |
| 294 | |
| 295 | void StackTrace::InitTrace(const CONTEXT* context_record) { |
| 296 | // StackWalk64 modifies the register context in place, so we have to copy it |
| 297 | // so that downstream exception handlers get the right context. The incoming |
| 298 | // context may have had more register state (YMM, etc) than we need to unwind |
| 299 | // the stack. Typically StackWalk64 only needs integer and control registers. |
| 300 | CONTEXT context_copy; |
| 301 | memcpy(&context_copy, context_record, sizeof(context_copy)); |
| 302 | context_copy.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL; |
| 303 | |
| 304 | // When walking an exception stack, we need to use StackWalk64(). |
| 305 | count_ = 0; |
| 306 | // Initialize stack walking. |
| 307 | STACKFRAME64 stack_frame; |
| 308 | memset(&stack_frame, 0, sizeof(stack_frame)); |
| 309 | #if defined(ARCH_CPU_X86_64) |
| 310 | int machine_type = IMAGE_FILE_MACHINE_AMD64; |
| 311 | stack_frame.AddrPC.Offset = context_record->Rip; |
| 312 | stack_frame.AddrFrame.Offset = context_record->Rbp; |
| 313 | stack_frame.AddrStack.Offset = context_record->Rsp; |
| 314 | #elif defined(ARCH_CPU_ARM64) |
| 315 | int machine_type = IMAGE_FILE_MACHINE_ARM64; |
| 316 | stack_frame.AddrPC.Offset = context_record->Pc; |
| 317 | stack_frame.AddrFrame.Offset = context_record->Fp; |
| 318 | stack_frame.AddrStack.Offset = context_record->Sp; |
| 319 | #elif defined(ARCH_CPU_X86) |
| 320 | int machine_type = IMAGE_FILE_MACHINE_I386; |
| 321 | stack_frame.AddrPC.Offset = context_record->Eip; |
| 322 | stack_frame.AddrFrame.Offset = context_record->Ebp; |
| 323 | stack_frame.AddrStack.Offset = context_record->Esp; |
| 324 | #else |
| 325 | #error Unsupported Windows Arch |
| 326 | #endif |
| 327 | stack_frame.AddrPC.Mode = AddrModeFlat; |
| 328 | stack_frame.AddrFrame.Mode = AddrModeFlat; |
| 329 | stack_frame.AddrStack.Mode = AddrModeFlat; |
| 330 | while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(), |
| 331 | &stack_frame, &context_copy, NULL, |
| 332 | &SymFunctionTableAccess64, &SymGetModuleBase64, NULL) && |
| 333 | count_ < size(trace_)) { |
| 334 | trace_[count_++] = reinterpret_cast<void*>(stack_frame.AddrPC.Offset); |
| 335 | } |
| 336 | |
| 337 | for (size_t i = count_; i < size(trace_); ++i) |
| 338 | trace_[i] = NULL; |
| 339 | } |
| 340 | |
| 341 | void StackTrace::PrintWithPrefix(const char* prefix_string) const { |
| 342 | OutputToStreamWithPrefix(&std::cerr, prefix_string); |
| 343 | } |
| 344 | |
| 345 | void StackTrace::OutputToStreamWithPrefix(std::ostream* os, |
| 346 | const char* prefix_string) const { |
| 347 | SymbolContext* context = SymbolContext::GetInstance(); |
| 348 | if (g_init_error != ERROR_SUCCESS) { |
| 349 | (*os) << "Error initializing symbols (" << g_init_error |
| 350 | << "). Dumping unresolved backtrace:\n"; |
| 351 | for (size_t i = 0; (i < count_) && os->good(); ++i) { |
| 352 | if (prefix_string) |
| 353 | (*os) << prefix_string; |
| 354 | (*os) << "\t" << trace_[i] << "\n"; |
| 355 | } |
| 356 | } else { |
| 357 | (*os) << "Backtrace:\n"; |
| 358 | context->OutputTraceToStream(trace_, count_, os, prefix_string); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | } // namespace debug |
| 363 | } // namespace base |
| 364 | |