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"
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"
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
54 SymSetOptions(SYMOPT_DEFERRED_LOADS
|
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
64 DLOG(ERROR
) << "SymInitialize failed: " << g_init_error
;
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(),
80 g_init_error
= GetLastError();
81 DLOG(WARNING
) << "SymGetSearchPath failed: " << g_init_error
;
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
;
93 g_init_error
= ERROR_SUCCESS
;
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
112 class SymbolContext
{
114 static SymbolContext
* GetInstance() {
115 // We use a leaky singleton because code may call this during process
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
,
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
142 (sizeof(SYMBOL_INFO
) +
143 kMaxNameLength
* sizeof(wchar_t) +
144 sizeof(ULONG64
) - 1) /
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.
166 (*os
) << symbol
->Name
<< " [0x" << trace
[i
] << "+"
167 << sym_displacement
<< "]";
169 // If there is no symbol information, add a spacer.
170 (*os
) << "(No symbol) [0x" << trace
[i
] << "]";
173 (*os
) << " (" << line
.FileName
<< ":" << line
.LineNumber
<< ")";
180 friend struct DefaultSingletonTraits
<SymbolContext
>;
187 DISALLOW_COPY_AND_ASSIGN(SymbolContext
);
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
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)
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)
221 StackTrace::StackTrace(EXCEPTION_POINTERS
* exception_pointers
) {
222 InitTrace(exception_pointers
->ContextRecord
);
225 StackTrace::StackTrace(CONTEXT
* context
) {
229 void StackTrace::InitTrace(CONTEXT
* context_record
) {
230 // When walking an exception stack, we need to use StackWalk64().
232 // Initialize stack walking.
233 STACKFRAME64 stack_frame
;
234 memset(&stack_frame
, 0, sizeof(stack_frame
));
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
;
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
;
246 stack_frame
.AddrPC
.Mode
= AddrModeFlat
;
247 stack_frame
.AddrFrame
.Mode
= AddrModeFlat
;
248 stack_frame
.AddrStack
.Mode
= AddrModeFlat
;
249 while (StackWalk64(machine_type
,
255 &SymFunctionTableAccess64
,
258 count_
< arraysize(trace_
)) {
259 trace_
[count_
++] = reinterpret_cast<void*>(stack_frame
.AddrPC
.Offset
);
262 for (size_t i
= count_
; i
< arraysize(trace_
); ++i
)
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";
279 (*os
) << "Backtrace:\n";
280 context
->OutputTraceToStream(trace_
, count_
, os
);