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