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.
4
5 // Slightly adapted for inclusion in V8.
6 // Copyright 2016 the V8 project authors. All rights reserved.
7
8 #include "src/base/debug/stack_trace.h"
9
10 #include <windows.h>
11 #include <dbghelp.h>
12 #include <Shlwapi.h>
13 #include <stddef.h>
14
15 #include <iostream>
16 #include <memory>
17
18 #include "src/base/logging.h"
19 #include "src/base/macros.h"
20
21 namespace v8 {
22 namespace base {
23 namespace debug {
24
25 namespace {
26
27 // Previous unhandled filter. Will be called if not nullptr when we intercept an
28 // exception. Only used in unit tests.
29 LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
30
31 bool g_dump_stack_in_signal_handler = true;
32 bool g_initialized_symbols = false;
33 DWORD g_init_error = ERROR_SUCCESS;
34
35 // Prints the exception call stack.
36 // This is the unit tests exception filter.
StackDumpExceptionFilter(EXCEPTION_POINTERS * info)37 long WINAPI StackDumpExceptionFilter(EXCEPTION_POINTERS* info) { // NOLINT
38 if (g_dump_stack_in_signal_handler) {
39 debug::StackTrace(info).Print();
40 }
41 if (g_previous_filter) return g_previous_filter(info);
42 return EXCEPTION_CONTINUE_SEARCH;
43 }
44
GetExePath(wchar_t * path_out)45 void GetExePath(wchar_t* path_out) {
46 GetModuleFileName(nullptr, path_out, MAX_PATH);
47 path_out[MAX_PATH - 1] = L'\0';
48 PathRemoveFileSpec(path_out);
49 }
50
InitializeSymbols()51 bool InitializeSymbols() {
52 if (g_initialized_symbols) return g_init_error == ERROR_SUCCESS;
53 g_initialized_symbols = true;
54 // Defer symbol load until they're needed, use undecorated names, and get line
55 // numbers.
56 SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
57 if (!SymInitialize(GetCurrentProcess(), nullptr, 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 return false;
65 }
66
67 // When transferring the binaries e.g. between bots, path put
68 // into the executable will get off. To still retrieve symbols correctly,
69 // add the directory of the executable to symbol search path.
70 // All following errors are non-fatal.
71 const size_t kSymbolsArraySize = 1024;
72 std::unique_ptr<wchar_t[]> symbols_path(new wchar_t[kSymbolsArraySize]);
73
74 // Note: The below function takes buffer size as number of characters,
75 // not number of bytes!
76 if (!SymGetSearchPathW(GetCurrentProcess(), symbols_path.get(),
77 kSymbolsArraySize)) {
78 g_init_error = GetLastError();
79 return false;
80 }
81
82 wchar_t exe_path[MAX_PATH];
83 GetExePath(exe_path);
84 std::wstring new_path(std::wstring(symbols_path.get()) + L";" +
85 std::wstring(exe_path));
86 if (!SymSetSearchPathW(GetCurrentProcess(), new_path.c_str())) {
87 g_init_error = GetLastError();
88 return false;
89 }
90
91 g_init_error = ERROR_SUCCESS;
92 return true;
93 }
94
95 // For the given trace, attempts to resolve the symbols, and output a trace
96 // to the ostream os. The format for each line of the backtrace is:
97 //
98 // <tab>SymbolName[0xAddress+Offset] (FileName:LineNo)
99 //
100 // This function should only be called if Init() has been called. We do not
101 // LOG(FATAL) here because this code is called might be triggered by a
102 // LOG(FATAL) itself. Also, it should not be calling complex code that is
103 // extensible like PathService since that can in turn fire CHECKs.
OutputTraceToStream(const void * const * trace,size_t count,std::ostream * os)104 void OutputTraceToStream(const void* const* trace, size_t count,
105 std::ostream* os) {
106 for (size_t i = 0; (i < count) && os->good(); ++i) {
107 const int kMaxNameLength = 256;
108 DWORD_PTR frame = reinterpret_cast<DWORD_PTR>(trace[i]);
109
110 // Code adapted from MSDN example:
111 // http://msdn.microsoft.com/en-us/library/ms680578(VS.85).aspx
112 ULONG64 buffer[(sizeof(SYMBOL_INFO) + kMaxNameLength * sizeof(wchar_t) +
113 sizeof(ULONG64) - 1) /
114 sizeof(ULONG64)];
115 memset(buffer, 0, sizeof(buffer));
116
117 // Initialize symbol information retrieval structures.
118 DWORD64 sym_displacement = 0;
119 PSYMBOL_INFO symbol = reinterpret_cast<PSYMBOL_INFO>(&buffer[0]);
120 symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
121 symbol->MaxNameLen = kMaxNameLength - 1;
122 BOOL has_symbol =
123 SymFromAddr(GetCurrentProcess(), frame, &sym_displacement, symbol);
124
125 // Attempt to retrieve line number information.
126 DWORD line_displacement = 0;
127 IMAGEHLP_LINE64 line = {};
128 line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
129 BOOL has_line = SymGetLineFromAddr64(GetCurrentProcess(), frame,
130 &line_displacement, &line);
131
132 // Output the backtrace line.
133 (*os) << "\t";
134 if (has_symbol) {
135 (*os) << symbol->Name << " [0x" << trace[i] << "+" << sym_displacement
136 << "]";
137 } else {
138 // If there is no symbol information, add a spacer.
139 (*os) << "(No symbol) [0x" << trace[i] << "]";
140 }
141 if (has_line) {
142 (*os) << " (" << line.FileName << ":" << line.LineNumber << ")";
143 }
144 (*os) << "\n";
145 }
146 }
147
148 } // namespace
149
EnableInProcessStackDumping()150 bool EnableInProcessStackDumping() {
151 // Add stack dumping support on exception on windows. Similar to OS_POSIX
152 // signal() handling in process_util_posix.cc.
153 g_previous_filter = SetUnhandledExceptionFilter(&StackDumpExceptionFilter);
154 g_dump_stack_in_signal_handler = true;
155
156 // Need to initialize symbols early in the process or else this fails on
157 // swarming (since symbols are in different directory than in the exes) and
158 // also release x64.
159 return InitializeSymbols();
160 }
161
DisableSignalStackDump()162 void DisableSignalStackDump() {
163 g_dump_stack_in_signal_handler = false;
164 }
165
StackTrace()166 StackTrace::StackTrace() {
167 // When walking our own stack, use CaptureStackBackTrace().
168 count_ = CaptureStackBackTrace(0, arraysize(trace_), trace_, nullptr);
169 }
170
StackTrace(EXCEPTION_POINTERS * exception_pointers)171 StackTrace::StackTrace(EXCEPTION_POINTERS* exception_pointers) {
172 InitTrace(exception_pointers->ContextRecord);
173 }
174
StackTrace(const CONTEXT * context)175 StackTrace::StackTrace(const CONTEXT* context) { InitTrace(context); }
176
InitTrace(const CONTEXT * context_record)177 void StackTrace::InitTrace(const CONTEXT* context_record) {
178 // StackWalk64 modifies the register context in place, so we have to copy it
179 // so that downstream exception handlers get the right context. The incoming
180 // context may have had more register state (YMM, etc) than we need to unwind
181 // the stack. Typically StackWalk64 only needs integer and control registers.
182 CONTEXT context_copy;
183 memcpy(&context_copy, context_record, sizeof(context_copy));
184 context_copy.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
185
186 // When walking an exception stack, we need to use StackWalk64().
187 count_ = 0;
188 // Initialize stack walking.
189 STACKFRAME64 stack_frame;
190 memset(&stack_frame, 0, sizeof(stack_frame));
191 #if defined(_WIN64)
192 int machine_type = IMAGE_FILE_MACHINE_AMD64;
193 stack_frame.AddrPC.Offset = context_record->Rip;
194 stack_frame.AddrFrame.Offset = context_record->Rbp;
195 stack_frame.AddrStack.Offset = context_record->Rsp;
196 #else
197 int machine_type = IMAGE_FILE_MACHINE_I386;
198 stack_frame.AddrPC.Offset = context_record->Eip;
199 stack_frame.AddrFrame.Offset = context_record->Ebp;
200 stack_frame.AddrStack.Offset = context_record->Esp;
201 #endif
202 stack_frame.AddrPC.Mode = AddrModeFlat;
203 stack_frame.AddrFrame.Mode = AddrModeFlat;
204 stack_frame.AddrStack.Mode = AddrModeFlat;
205 while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
206 &stack_frame, &context_copy, nullptr,
207 &SymFunctionTableAccess64, &SymGetModuleBase64, nullptr) &&
208 count_ < arraysize(trace_)) {
209 trace_[count_++] = reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
210 }
211
212 for (size_t i = count_; i < arraysize(trace_); ++i) trace_[i] = nullptr;
213 }
214
Print() const215 void StackTrace::Print() const { OutputToStream(&std::cerr); }
216
OutputToStream(std::ostream * os) const217 void StackTrace::OutputToStream(std::ostream* os) const {
218 InitializeSymbols();
219 if (g_init_error != ERROR_SUCCESS) {
220 (*os) << "Error initializing symbols (" << g_init_error
221 << "). Dumping unresolved backtrace:\n";
222 for (size_t i = 0; (i < count_) && os->good(); ++i) {
223 (*os) << "\t" << trace_[i] << "\n";
224 }
225 } else {
226 (*os) << "\n";
227 (*os) << "==== C stack trace ===============================\n";
228 (*os) << "\n";
229 OutputTraceToStream(trace_, count_, os);
230 }
231 }
232
233 } // namespace debug
234 } // namespace base
235 } // namespace v8
236