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/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"
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
;
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
).Print();
34 if (g_previous_filter
)
35 return g_previous_filter(info
);
36 return EXCEPTION_CONTINUE_SEARCH
;
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.
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:
50 // http://code.google.com/p/google-breakpad/issues/detail?id=311
52 // This is a very unlikely edge case, and the current solution is to
56 static SymbolContext
* GetInstance() {
57 // We use a leaky singleton because code may call this during process
60 Singleton
<SymbolContext
, LeakySingletonTraits
<SymbolContext
> >::get();
63 // Returns the error code of a failed initialization.
64 DWORD
init_error() const {
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:
71 // <tab>SymbolName[0xAddress+Offset] (FileName:LineNo)
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
76 void OutputTraceToStream(const void* const* trace
,
79 base::AutoLock
lock(lock_
);
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
]);
85 // Code adapted from MSDN example:
86 // http://msdn.microsoft.com/en-us/library/ms680578(VS.85).aspx
88 (sizeof(SYMBOL_INFO
) +
89 kMaxNameLength
* sizeof(wchar_t) +
90 sizeof(ULONG64
) - 1) /
92 memset(buffer
, 0, sizeof(buffer
));
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
);
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
);
109 // Output the backtrace line.
112 (*os
) << symbol
->Name
<< " [0x" << trace
[i
] << "+"
113 << sym_displacement
<< "]";
115 // If there is no symbol information, add a spacer.
116 (*os
) << "(No symbol) [0x" << trace
[i
] << "]";
119 (*os
) << " (" << line
.FileName
<< ":" << line
.LineNumber
<< ")";
126 friend struct DefaultSingletonTraits
<SymbolContext
>;
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
132 SymSetOptions(SYMOPT_DEFERRED_LOADS
|
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
142 DLOG(ERROR
) << "SymInitialize failed: " << init_error_
;
146 init_error_
= ERROR_SUCCESS
;
148 // Work around a mysterious hang on Windows XP.
149 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
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];
158 // Note: The below function takes buffer size as number of characters,
159 // not number of bytes!
160 if (!SymGetSearchPathW(GetCurrentProcess(),
162 arraysize(symbols_path
))) {
163 DLOG(WARNING
) << "SymGetSearchPath failed: ";
167 FilePath module_path
;
168 if (!PathService::Get(FILE_EXE
, &module_path
)) {
169 DLOG(WARNING
) << "PathService::Get(FILE_EXE) failed.";
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.";
183 DISALLOW_COPY_AND_ASSIGN(SymbolContext
);
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();
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)
205 StackTrace::StackTrace() {
206 // When walking our own stack, use CaptureStackBackTrace().
207 count_
= CaptureStackBackTrace(0, arraysize(trace_
), trace_
, NULL
);
210 #if defined(COMPILER_MSVC)
211 #pragma optimize("", on)
214 StackTrace::StackTrace(EXCEPTION_POINTERS
* exception_pointers
) {
215 // When walking an exception stack, we need to use StackWalk64().
217 // Initialize stack walking.
218 STACKFRAME64 stack_frame
;
219 memset(&stack_frame
, 0, sizeof(stack_frame
));
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
;
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
;
231 stack_frame
.AddrPC
.Mode
= AddrModeFlat
;
232 stack_frame
.AddrFrame
.Mode
= AddrModeFlat
;
233 stack_frame
.AddrStack
.Mode
= AddrModeFlat
;
234 while (StackWalk64(machine_type
,
238 exception_pointers
->ContextRecord
,
240 &SymFunctionTableAccess64
,
243 count_
< arraysize(trace_
)) {
244 trace_
[count_
++] = reinterpret_cast<void*>(stack_frame
.AddrPC
.Offset
);
247 for (size_t i
= count_
; i
< arraysize(trace_
); ++i
)
251 void StackTrace::Print() const {
252 OutputToStream(&std::cerr
);
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";
265 (*os
) << "Backtrace:\n";
266 context
->OutputTraceToStream(trace_
, count_
, os
);