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 10 #include <iostream> 11 12 #include "base/basictypes.h" 13 #include "base/logging.h" 14 #include "base/memory/singleton.h" 15 #include "base/path_service.h" 16 #include "base/process/launch.h" 17 #include "base/strings/string_util.h" 18 #include "base/synchronization/lock.h" 19 #include "base/win/windows_version.h" 20 21 namespace base { 22 namespace debug { 23 24 namespace { 25 26 // Previous unhandled filter. Will be called if not NULL when we intercept an 27 // exception. Only used in unit tests. 28 LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = NULL; 29 30 // Prints the exception call stack. 31 // This is the unit tests exception filter. 32 long WINAPI StackDumpExceptionFilter(EXCEPTION_POINTERS* info) { 33 debug::StackTrace(info).PrintBacktrace(); 34 if (g_previous_filter) 35 return g_previous_filter(info); 36 return EXCEPTION_CONTINUE_SEARCH; 37 } 38 39 // SymbolContext is a threadsafe singleton that wraps the DbgHelp Sym* family 40 // of functions. The Sym* family of functions may only be invoked by one 41 // thread at a time. SymbolContext code may access a symbol server over the 42 // network while holding the lock for this singleton. In the case of high 43 // latency, this code will adversely affect performance. 44 // 45 // There is also a known issue where this backtrace code can interact 46 // badly with breakpad if breakpad is invoked in a separate thread while 47 // we are using the Sym* functions. This is because breakpad does now 48 // share a lock with this function. See this related bug: 49 // 50 // http://code.google.com/p/google-breakpad/issues/detail?id=311 51 // 52 // This is a very unlikely edge case, and the current solution is to 53 // just ignore it. 54 class SymbolContext { 55 public: 56 static SymbolContext* GetInstance() { 57 // We use a leaky singleton because code may call this during process 58 // termination. 59 return 60 Singleton<SymbolContext, LeakySingletonTraits<SymbolContext> >::get(); 61 } 62 63 // Returns the error code of a failed initialization. 64 DWORD init_error() const { 65 return init_error_; 66 } 67 68 // For the given trace, attempts to resolve the symbols, and output a trace 69 // to the ostream os. The format for each line of the backtrace is: 70 // 71 // <tab>SymbolName[0xAddress+Offset] (FileName:LineNo) 72 // 73 // This function should only be called if Init() has been called. We do not 74 // LOG(FATAL) here because this code is called might be triggered by a 75 // LOG(FATAL) itself. 76 void OutputTraceToStream(const void* const* trace, 77 size_t count, 78 std::ostream* os) { 79 base::AutoLock lock(lock_); 80 81 for (size_t i = 0; (i < count) && os->good(); ++i) { 82 const int kMaxNameLength = 256; 83 DWORD_PTR frame = reinterpret_cast<DWORD_PTR>(trace[i]); 84 85 // Code adapted from MSDN example: 86 // http://msdn.microsoft.com/en-us/library/ms680578(VS.85).aspx 87 ULONG64 buffer[ 88 (sizeof(SYMBOL_INFO) + 89 kMaxNameLength * sizeof(wchar_t) + 90 sizeof(ULONG64) - 1) / 91 sizeof(ULONG64)]; 92 memset(buffer, 0, sizeof(buffer)); 93 94 // Initialize symbol information retrieval structures. 95 DWORD64 sym_displacement = 0; 96 PSYMBOL_INFO symbol = reinterpret_cast<PSYMBOL_INFO>(&buffer[0]); 97 symbol->SizeOfStruct = sizeof(SYMBOL_INFO); 98 symbol->MaxNameLen = kMaxNameLength - 1; 99 BOOL has_symbol = SymFromAddr(GetCurrentProcess(), frame, 100 &sym_displacement, symbol); 101 102 // Attempt to retrieve line number information. 103 DWORD line_displacement = 0; 104 IMAGEHLP_LINE64 line = {}; 105 line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); 106 BOOL has_line = SymGetLineFromAddr64(GetCurrentProcess(), frame, 107 &line_displacement, &line); 108 109 // Output the backtrace line. 110 (*os) << "\t"; 111 if (has_symbol) { 112 (*os) << symbol->Name << " [0x" << trace[i] << "+" 113 << sym_displacement << "]"; 114 } else { 115 // If there is no symbol information, add a spacer. 116 (*os) << "(No symbol) [0x" << trace[i] << "]"; 117 } 118 if (has_line) { 119 (*os) << " (" << line.FileName << ":" << line.LineNumber << ")"; 120 } 121 (*os) << "\n"; 122 } 123 } 124 125 private: 126 friend struct DefaultSingletonTraits<SymbolContext>; 127 128 SymbolContext() : init_error_(ERROR_SUCCESS) { 129 // Initializes the symbols for the process. 130 // Defer symbol load until they're needed, use undecorated names, and 131 // get line numbers. 132 SymSetOptions(SYMOPT_DEFERRED_LOADS | 133 SYMOPT_UNDNAME | 134 SYMOPT_LOAD_LINES); 135 if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) { 136 init_error_ = GetLastError(); 137 // TODO(awong): Handle error: SymInitialize can fail with 138 // ERROR_INVALID_PARAMETER. 139 // When it fails, we should not call debugbreak since it kills the current 140 // process (prevents future tests from running or kills the browser 141 // process). 142 DLOG(ERROR) << "SymInitialize failed: " << init_error_; 143 return; 144 } 145 146 init_error_ = ERROR_SUCCESS; 147 148 // Work around a mysterious hang on Windows XP. 149 if (base::win::GetVersion() < base::win::VERSION_VISTA) 150 return; 151 152 // When transferring the binaries e.g. between bots, path put 153 // into the executable will get off. To still retrieve symbols correctly, 154 // add the directory of the executable to symbol search path. 155 // All following errors are non-fatal. 156 wchar_t symbols_path[1024]; 157 158 // Note: The below function takes buffer size as number of characters, 159 // not number of bytes! 160 if (!SymGetSearchPathW(GetCurrentProcess(), 161 symbols_path, 162 arraysize(symbols_path))) { 163 DLOG(WARNING) << "SymGetSearchPath failed: "; 164 return; 165 } 166 167 FilePath module_path; 168 if (!PathService::Get(FILE_EXE, &module_path)) { 169 DLOG(WARNING) << "PathService::Get(FILE_EXE) failed."; 170 return; 171 } 172 173 std::wstring new_path(std::wstring(symbols_path) + 174 L";" + module_path.DirName().value()); 175 if (!SymSetSearchPathW(GetCurrentProcess(), new_path.c_str())) { 176 DLOG(WARNING) << "SymSetSearchPath failed."; 177 return; 178 } 179 } 180 181 DWORD init_error_; 182 base::Lock lock_; 183 DISALLOW_COPY_AND_ASSIGN(SymbolContext); 184 }; 185 186 } // namespace 187 188 bool EnableInProcessStackDumping() { 189 // Add stack dumping support on exception on windows. Similar to OS_POSIX 190 // signal() handling in process_util_posix.cc. 191 g_previous_filter = SetUnhandledExceptionFilter(&StackDumpExceptionFilter); 192 RouteStdioToConsole(); 193 return true; 194 } 195 196 // Disable optimizations for the StackTrace::StackTrace function. It is 197 // important to disable at least frame pointer optimization ("y"), since 198 // that breaks CaptureStackBackTrace() and prevents StackTrace from working 199 // in Release builds (it may still be janky if other frames are using FPO, 200 // but at least it will make it further). 201 #if defined(COMPILER_MSVC) 202 #pragma optimize("", off) 203 #endif 204 205 StackTrace::StackTrace() { 206 // When walking our own stack, use CaptureStackBackTrace(). 207 count_ = CaptureStackBackTrace(0, arraysize(trace_), trace_, NULL); 208 } 209 210 #if defined(COMPILER_MSVC) 211 #pragma optimize("", on) 212 #endif 213 214 StackTrace::StackTrace(EXCEPTION_POINTERS* exception_pointers) { 215 // When walking an exception stack, we need to use StackWalk64(). 216 count_ = 0; 217 // Initialize stack walking. 218 STACKFRAME64 stack_frame; 219 memset(&stack_frame, 0, sizeof(stack_frame)); 220 #if defined(_WIN64) 221 int machine_type = IMAGE_FILE_MACHINE_AMD64; 222 stack_frame.AddrPC.Offset = exception_pointers->ContextRecord->Rip; 223 stack_frame.AddrFrame.Offset = exception_pointers->ContextRecord->Rbp; 224 stack_frame.AddrStack.Offset = exception_pointers->ContextRecord->Rsp; 225 #else 226 int machine_type = IMAGE_FILE_MACHINE_I386; 227 stack_frame.AddrPC.Offset = exception_pointers->ContextRecord->Eip; 228 stack_frame.AddrFrame.Offset = exception_pointers->ContextRecord->Ebp; 229 stack_frame.AddrStack.Offset = exception_pointers->ContextRecord->Esp; 230 #endif 231 stack_frame.AddrPC.Mode = AddrModeFlat; 232 stack_frame.AddrFrame.Mode = AddrModeFlat; 233 stack_frame.AddrStack.Mode = AddrModeFlat; 234 while (StackWalk64(machine_type, 235 GetCurrentProcess(), 236 GetCurrentThread(), 237 &stack_frame, 238 exception_pointers->ContextRecord, 239 NULL, 240 &SymFunctionTableAccess64, 241 &SymGetModuleBase64, 242 NULL) && 243 count_ < arraysize(trace_)) { 244 trace_[count_++] = reinterpret_cast<void*>(stack_frame.AddrPC.Offset); 245 } 246 247 for (size_t i = count_; i < arraysize(trace_); ++i) 248 trace_[i] = NULL; 249 } 250 251 void StackTrace::PrintBacktrace() const { 252 OutputToStream(&std::cerr); 253 } 254 255 void StackTrace::OutputToStream(std::ostream* os) const { 256 SymbolContext* context = SymbolContext::GetInstance(); 257 DWORD error = context->init_error(); 258 if (error != ERROR_SUCCESS) { 259 (*os) << "Error initializing symbols (" << error 260 << "). Dumping unresolved backtrace:\n"; 261 for (int i = 0; (i < count_) && os->good(); ++i) { 262 (*os) << "\t" << trace_[i] << "\n"; 263 } 264 } else { 265 (*os) << "Backtrace:\n"; 266 context->OutputTraceToStream(trace_, count_, os); 267 } 268 } 269 270 } // namespace debug 271 } // namespace base 272