Roll src/third_party/WebKit f36d5e0:68b67cd (svn 193299:193303)
[chromium-blink-merge.git] / base / debug / stack_trace_win.cc
blob55d55624088d59a0ac82f09da611b4ee48627ede
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.
5 #include "base/debug/stack_trace.h"
7 #include <windows.h>
8 #include <dbghelp.h>
10 #include <iostream>
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"
20 namespace base {
21 namespace debug {
23 namespace {
25 // Previous unhandled filter. Will be called if not NULL when we intercept an
26 // exception. Only used in unit tests.
27 LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = NULL;
29 // Prints the exception call stack.
30 // This is the unit tests exception filter.
31 long 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;
38 FilePath 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);
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.
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:
56 // http://code.google.com/p/google-breakpad/issues/detail?id=311
58 // This is a very unlikely edge case, and the current solution is to
59 // just ignore it.
60 class 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();
69 // Returns the error code of a failed initialization.
70 DWORD init_error() const {
71 return init_error_;
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:
77 // <tab>SymbolName[0xAddress+Offset] (FileName:LineNo)
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_);
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]);
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));
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);
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);
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] << "]";
125 if (has_line) {
126 (*os) << " (" << line.FileName << ":" << line.LineNumber << ")";
128 (*os) << "\n";
132 private:
133 friend struct DefaultSingletonTraits<SymbolContext>;
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;
153 init_error_ = ERROR_SUCCESS;
155 // When transferring the binaries e.g. between bots, path put
156 // into the executable will get off. To still retrieve symbols correctly,
157 // add the directory of the executable to symbol search path.
158 // All following errors are non-fatal.
159 const size_t kSymbolsArraySize = 1024;
160 scoped_ptr<wchar_t[]> symbols_path(new wchar_t[kSymbolsArraySize]);
162 // Note: The below function takes buffer size as number of characters,
163 // not number of bytes!
164 if (!SymGetSearchPathW(GetCurrentProcess(),
165 symbols_path.get(),
166 kSymbolsArraySize)) {
167 DLOG(WARNING) << "SymGetSearchPath failed: ";
168 return;
171 std::wstring new_path(std::wstring(symbols_path.get()) +
172 L";" + GetExePath().DirName().value());
173 if (!SymSetSearchPathW(GetCurrentProcess(), new_path.c_str())) {
174 DLOG(WARNING) << "SymSetSearchPath failed.";
175 return;
179 DWORD init_error_;
180 base::Lock lock_;
181 DISALLOW_COPY_AND_ASSIGN(SymbolContext);
184 } // namespace
186 bool EnableInProcessStackDumping() {
187 // Add stack dumping support on exception on windows. Similar to OS_POSIX
188 // signal() handling in process_util_posix.cc.
189 g_previous_filter = SetUnhandledExceptionFilter(&StackDumpExceptionFilter);
190 RouteStdioToConsole();
191 return true;
194 // Disable optimizations for the StackTrace::StackTrace function. It is
195 // important to disable at least frame pointer optimization ("y"), since
196 // that breaks CaptureStackBackTrace() and prevents StackTrace from working
197 // in Release builds (it may still be janky if other frames are using FPO,
198 // but at least it will make it further).
199 #if defined(COMPILER_MSVC)
200 #pragma optimize("", off)
201 #endif
203 StackTrace::StackTrace() {
204 // When walking our own stack, use CaptureStackBackTrace().
205 count_ = CaptureStackBackTrace(0, arraysize(trace_), trace_, NULL);
208 #if defined(COMPILER_MSVC)
209 #pragma optimize("", on)
210 #endif
212 StackTrace::StackTrace(const EXCEPTION_POINTERS* exception_pointers) {
213 // StackWalk64() may modify context record passed to it, so we will
214 // use a copy.
215 CONTEXT context_record = *exception_pointers->ContextRecord;
216 InitTrace(&context_record);
219 StackTrace::StackTrace(const CONTEXT* context) {
220 // StackWalk64() may modify context record passed to it, so we will
221 // use a copy.
222 CONTEXT context_record = *context;
223 InitTrace(&context_record);
226 void StackTrace::InitTrace(CONTEXT* context_record) {
227 // When walking an exception stack, we need to use StackWalk64().
228 count_ = 0;
229 // Initialize stack walking.
230 STACKFRAME64 stack_frame;
231 memset(&stack_frame, 0, sizeof(stack_frame));
232 #if defined(_WIN64)
233 int machine_type = IMAGE_FILE_MACHINE_AMD64;
234 stack_frame.AddrPC.Offset = context_record->Rip;
235 stack_frame.AddrFrame.Offset = context_record->Rbp;
236 stack_frame.AddrStack.Offset = context_record->Rsp;
237 #else
238 int machine_type = IMAGE_FILE_MACHINE_I386;
239 stack_frame.AddrPC.Offset = context_record->Eip;
240 stack_frame.AddrFrame.Offset = context_record->Ebp;
241 stack_frame.AddrStack.Offset = context_record->Esp;
242 #endif
243 stack_frame.AddrPC.Mode = AddrModeFlat;
244 stack_frame.AddrFrame.Mode = AddrModeFlat;
245 stack_frame.AddrStack.Mode = AddrModeFlat;
246 while (StackWalk64(machine_type,
247 GetCurrentProcess(),
248 GetCurrentThread(),
249 &stack_frame,
250 context_record,
251 NULL,
252 &SymFunctionTableAccess64,
253 &SymGetModuleBase64,
254 NULL) &&
255 count_ < arraysize(trace_)) {
256 trace_[count_++] = reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
259 for (size_t i = count_; i < arraysize(trace_); ++i)
260 trace_[i] = NULL;
263 void StackTrace::Print() const {
264 OutputToStream(&std::cerr);
267 void StackTrace::OutputToStream(std::ostream* os) const {
268 SymbolContext* context = SymbolContext::GetInstance();
269 DWORD error = context->init_error();
270 if (error != ERROR_SUCCESS) {
271 (*os) << "Error initializing symbols (" << error
272 << "). Dumping unresolved backtrace:\n";
273 for (size_t i = 0; (i < count_) && os->good(); ++i) {
274 (*os) << "\t" << trace_[i] << "\n";
276 } else {
277 (*os) << "Backtrace:\n";
278 context->OutputTraceToStream(trace_, count_, os);
282 } // namespace debug
283 } // namespace base