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