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