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 // 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
62 static SymbolContext
* GetInstance() {
63 // We use a leaky singleton because code may call this during process
66 Singleton
<SymbolContext
, LeakySingletonTraits
<SymbolContext
> >::get();
69 // Returns the error code of a failed initialization.
70 DWORD
init_error() const {
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
,
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
95 (sizeof(SYMBOL_INFO
) +
96 kMaxNameLength
* sizeof(wchar_t) +
97 sizeof(ULONG64
) - 1) /
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.
119 (*os
) << symbol
->Name
<< " [0x" << trace
[i
] << "+"
120 << sym_displacement
<< "]";
122 // If there is no symbol information, add a spacer.
123 (*os
) << "(No symbol) [0x" << trace
[i
] << "]";
126 (*os
) << " (" << line
.FileName
<< ":" << line
.LineNumber
<< ")";
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
139 SymSetOptions(SYMOPT_DEFERRED_LOADS
|
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
149 DLOG(ERROR
) << "SymInitialize failed: " << init_error_
;
153 init_error_
= ERROR_SUCCESS
;
155 // Work around a mysterious hang on Windows XP.
156 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
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
]);
166 // Note: The below function takes buffer size as number of characters,
167 // not number of bytes!
168 if (!SymGetSearchPathW(GetCurrentProcess(),
170 kSymbolsArraySize
)) {
171 DLOG(WARNING
) << "SymGetSearchPath failed: ";
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.";
185 DISALLOW_COPY_AND_ASSIGN(SymbolContext
);
190 bool 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();
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)
207 StackTrace::StackTrace() {
208 // When walking our own stack, use CaptureStackBackTrace().
209 count_
= CaptureStackBackTrace(0, arraysize(trace_
), trace_
, NULL
);
212 #if defined(COMPILER_MSVC)
213 #pragma optimize("", on)
216 StackTrace::StackTrace(const EXCEPTION_POINTERS
* exception_pointers
) {
217 // When walking an exception stack, we need to use StackWalk64().
219 // StackWalk64() may modify context record passed to it, so we will
221 CONTEXT context_record
= *exception_pointers
->ContextRecord
;
222 // Initialize stack walking.
223 STACKFRAME64 stack_frame
;
224 memset(&stack_frame
, 0, sizeof(stack_frame
));
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
;
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
;
236 stack_frame
.AddrPC
.Mode
= AddrModeFlat
;
237 stack_frame
.AddrFrame
.Mode
= AddrModeFlat
;
238 stack_frame
.AddrStack
.Mode
= AddrModeFlat
;
239 while (StackWalk64(machine_type
,
245 &SymFunctionTableAccess64
,
248 count_
< arraysize(trace_
)) {
249 trace_
[count_
++] = reinterpret_cast<void*>(stack_frame
.AddrPC
.Offset
);
252 for (size_t i
= count_
; i
< arraysize(trace_
); ++i
)
256 void StackTrace::Print() const {
257 OutputToStream(&std::cerr
);
260 void 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";
270 (*os
) << "Backtrace:\n";
271 context
->OutputTraceToStream(trace_
, count_
, os
);