Home | History | Annotate | Download | only in debug
      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 NULL when we intercept an
     28 // exception. Only used in unit tests.
     29 LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = NULL;
     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.
     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 
     45 void GetExePath(wchar_t* path_out) {
     46   GetModuleFileName(NULL, path_out, MAX_PATH);
     47   path_out[MAX_PATH - 1] = L'\0';
     48   PathRemoveFileSpec(path_out);
     49 }
     50 
     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(), 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
     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.
    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 
    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 
    162 void DisableSignalStackDump() {
    163   g_dump_stack_in_signal_handler = false;
    164 }
    165 
    166 // Disable optimizations for the StackTrace::StackTrace function. It is
    167 // important to disable at least frame pointer optimization ("y"), since
    168 // that breaks CaptureStackBackTrace() and prevents StackTrace from working
    169 // in Release builds (it may still be janky if other frames are using FPO,
    170 // but at least it will make it further).
    171 #if defined(COMPILER_MSVC)
    172 #pragma optimize("", off)
    173 #endif
    174 
    175 StackTrace::StackTrace() {
    176   // When walking our own stack, use CaptureStackBackTrace().
    177   count_ = CaptureStackBackTrace(0, arraysize(trace_), trace_, NULL);
    178 }
    179 
    180 #if defined(COMPILER_MSVC)
    181 #pragma optimize("", on)
    182 #endif
    183 
    184 StackTrace::StackTrace(EXCEPTION_POINTERS* exception_pointers) {
    185   InitTrace(exception_pointers->ContextRecord);
    186 }
    187 
    188 StackTrace::StackTrace(const CONTEXT* context) { InitTrace(context); }
    189 
    190 void StackTrace::InitTrace(const CONTEXT* context_record) {
    191   // StackWalk64 modifies the register context in place, so we have to copy it
    192   // so that downstream exception handlers get the right context.  The incoming
    193   // context may have had more register state (YMM, etc) than we need to unwind
    194   // the stack. Typically StackWalk64 only needs integer and control registers.
    195   CONTEXT context_copy;
    196   memcpy(&context_copy, context_record, sizeof(context_copy));
    197   context_copy.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
    198 
    199   // When walking an exception stack, we need to use StackWalk64().
    200   count_ = 0;
    201   // Initialize stack walking.
    202   STACKFRAME64 stack_frame;
    203   memset(&stack_frame, 0, sizeof(stack_frame));
    204 #if defined(_WIN64)
    205   int machine_type = IMAGE_FILE_MACHINE_AMD64;
    206   stack_frame.AddrPC.Offset = context_record->Rip;
    207   stack_frame.AddrFrame.Offset = context_record->Rbp;
    208   stack_frame.AddrStack.Offset = context_record->Rsp;
    209 #else
    210   int machine_type = IMAGE_FILE_MACHINE_I386;
    211   stack_frame.AddrPC.Offset = context_record->Eip;
    212   stack_frame.AddrFrame.Offset = context_record->Ebp;
    213   stack_frame.AddrStack.Offset = context_record->Esp;
    214 #endif
    215   stack_frame.AddrPC.Mode = AddrModeFlat;
    216   stack_frame.AddrFrame.Mode = AddrModeFlat;
    217   stack_frame.AddrStack.Mode = AddrModeFlat;
    218   while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
    219                      &stack_frame, &context_copy, NULL,
    220                      &SymFunctionTableAccess64, &SymGetModuleBase64, NULL) &&
    221          count_ < arraysize(trace_)) {
    222     trace_[count_++] = reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
    223   }
    224 
    225   for (size_t i = count_; i < arraysize(trace_); ++i) trace_[i] = NULL;
    226 }
    227 
    228 void StackTrace::Print() const { OutputToStream(&std::cerr); }
    229 
    230 void StackTrace::OutputToStream(std::ostream* os) const {
    231   InitializeSymbols();
    232   if (g_init_error != ERROR_SUCCESS) {
    233     (*os) << "Error initializing symbols (" << g_init_error
    234           << ").  Dumping unresolved backtrace:\n";
    235     for (size_t i = 0; (i < count_) && os->good(); ++i) {
    236       (*os) << "\t" << trace_[i] << "\n";
    237     }
    238   } else {
    239     (*os) << "\n";
    240     (*os) << "==== C stack trace ===============================\n";
    241     (*os) << "\n";
    242     OutputTraceToStream(trace_, count_, os);
    243   }
    244 }
    245 
    246 }  // namespace debug
    247 }  // namespace base
    248 }  // namespace v8
    249