GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/debug_utils.cc Lines: 37 71 52.1 %
Date: 2019-01-07 12:15:22 Branches: 13 26 50.0 %

Line Branch Exec Source
1
#include "debug_utils.h"
2
#include "node_internals.h"
3
4
#ifdef __POSIX__
5
#if defined(__linux__)
6
#include <features.h>
7
#endif
8
9
#if defined(__linux__) && !defined(__GLIBC__) || \
10
    defined(__UCLIBC__) || \
11
    defined(_AIX)
12
#define HAVE_EXECINFO_H 0
13
#else
14
#define HAVE_EXECINFO_H 1
15
#endif
16
17
#if HAVE_EXECINFO_H
18
#include <cxxabi.h>
19
#include <dlfcn.h>
20
#include <execinfo.h>
21
#include <unistd.h>
22
#include <sys/mman.h>
23
#include <stdio.h>
24
#endif
25
26
#else  // __POSIX__
27
28
#include <windows.h>
29
#include <dbghelp.h>
30
31
#endif  // __POSIX__
32
33
#if defined(__linux__) || defined(__sun) || defined(__FreeBSD__)
34
#include <link.h>
35
#endif  // (__linux__) || defined(__sun) || defined(__FreeBSD__)
36
37
#ifdef __APPLE__
38
#include <mach-o/dyld.h>  // _dyld_get_image_name()
39
#endif                    // __APPLE__
40
41
#ifdef _AIX
42
#include <sys/ldr.h>  // ld_info structure
43
#endif                // _AIX
44
45
#ifdef _WIN32
46
#include <Lm.h>
47
#include <Windows.h>
48
#include <dbghelp.h>
49
#include <process.h>
50
#include <psapi.h>
51
#include <tchar.h>
52
#endif  // _WIN32
53
54
namespace node {
55
56
#ifdef __POSIX__
57
#if HAVE_EXECINFO_H
58
8
class PosixSymbolDebuggingContext final : public NativeSymbolDebuggingContext {
59
 public:
60
4
  PosixSymbolDebuggingContext() : pagesize_(getpagesize()) { }
61
62
26
  SymbolInfo LookupSymbol(void* address) override {
63
    Dl_info info;
64
26
    const bool have_info = dladdr(address, &info);
65
26
    SymbolInfo ret;
66
26
    if (!have_info)
67
      return ret;
68
69
26
    if (info.dli_sname != nullptr) {
70
19
      if (char* demangled = abi::__cxa_demangle(info.dli_sname, 0, 0, 0)) {
71
17
        ret.name = demangled;
72
17
        free(demangled);
73
      } else {
74
2
        ret.name = info.dli_sname;
75
      }
76
    }
77
78
26
    if (info.dli_fname != nullptr) {
79
26
      ret.filename = info.dli_fname;
80
    }
81
82
26
    return ret;
83
  }
84
85
  bool IsMapped(void* address) override {
86
    void* page_aligned = reinterpret_cast<void*>(
87
        reinterpret_cast<uintptr_t>(address) & ~(pagesize_ - 1));
88
    return msync(page_aligned, pagesize_, MS_ASYNC) == 0;
89
  }
90
91
4
  int GetStackTrace(void** frames, int count) override {
92
4
    return backtrace(frames, count);
93
  }
94
95
 private:
96
  uintptr_t pagesize_;
97
};
98
99
std::unique_ptr<NativeSymbolDebuggingContext>
100
4
NativeSymbolDebuggingContext::New() {
101
  return std::unique_ptr<NativeSymbolDebuggingContext>(
102
4
      new PosixSymbolDebuggingContext());
103
}
104
105
#else  // HAVE_EXECINFO_H
106
107
std::unique_ptr<NativeSymbolDebuggingContext>
108
NativeSymbolDebuggingContext::New() {
109
  return std::unique_ptr<NativeSymbolDebuggingContext>(
110
      new NativeSymbolDebuggingContext());
111
}
112
113
#endif  // HAVE_EXECINFO_H
114
115
#else  // __POSIX__
116
117
class Win32SymbolDebuggingContext final : public NativeSymbolDebuggingContext {
118
 public:
119
  Win32SymbolDebuggingContext() {
120
    current_process_ = GetCurrentProcess();
121
    USE(SymInitialize(current_process_, nullptr, true));
122
  }
123
124
  ~Win32SymbolDebuggingContext() override {
125
    USE(SymCleanup(current_process_));
126
  }
127
128
  using NameAndDisplacement = std::pair<std::string, DWORD64>;
129
  NameAndDisplacement WrappedSymFromAddr(DWORD64 dwAddress) const {
130
    // Refs: https://docs.microsoft.com/en-us/windows/desktop/Debug/retrieving-symbol-information-by-address
131
    // Patches:
132
    // Use `fprintf(stderr, ` instead of `printf`
133
    // `sym.filename = pSymbol->Name` on success
134
    // `current_process_` instead of `hProcess.
135
    DWORD64 dwDisplacement = 0;
136
    // Patch: made into arg - DWORD64  dwAddress = SOME_ADDRESS;
137
138
    char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
139
    const auto pSymbol = reinterpret_cast<PSYMBOL_INFO>(buffer);
140
141
    pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
142
    pSymbol->MaxNameLen = MAX_SYM_NAME;
143
144
    if (SymFromAddr(current_process_, dwAddress, &dwDisplacement, pSymbol)) {
145
      // SymFromAddr returned success
146
      return NameAndDisplacement(pSymbol->Name, dwDisplacement);
147
    } else {
148
      // SymFromAddr failed
149
      const DWORD error = GetLastError();  // "eat" the error anyway
150
#ifdef DEBUG
151
      fprintf(stderr, "SymFromAddr returned error : %lu\n", error);
152
#endif
153
    }
154
    // End MSDN code
155
156
    return NameAndDisplacement();
157
  }
158
159
  SymbolInfo WrappedGetLine(DWORD64 dwAddress) const {
160
    SymbolInfo sym{};
161
162
    // Refs: https://docs.microsoft.com/en-us/windows/desktop/Debug/retrieving-symbol-information-by-address
163
    // Patches:
164
    // Use `fprintf(stderr, ` instead of `printf`.
165
    // Assign values to `sym` on success.
166
    // `current_process_` instead of `hProcess.
167
168
    // Patch: made into arg - DWORD64  dwAddress;
169
    DWORD dwDisplacement;
170
    IMAGEHLP_LINE64 line;
171
172
    SymSetOptions(SYMOPT_LOAD_LINES);
173
174
    line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
175
    // Patch: made into arg - dwAddress = 0x1000000;
176
177
    if (SymGetLineFromAddr64(current_process_, dwAddress,
178
                             &dwDisplacement, &line)) {
179
      // SymGetLineFromAddr64 returned success
180
      sym.filename = line.FileName;
181
      sym.line = line.LineNumber;
182
    } else {
183
      // SymGetLineFromAddr64 failed
184
      const DWORD error = GetLastError();  // "eat" the error anyway
185
#ifdef DEBUG
186
      fprintf(stderr, "SymGetLineFromAddr64 returned error : %lu\n", error);
187
#endif
188
    }
189
    // End MSDN code
190
191
    return sym;
192
  }
193
194
  // Fills the SymbolInfo::name of the io/out argument `sym`
195
  std::string WrappedUnDecorateSymbolName(const char* name) const {
196
    // Refs: https://docs.microsoft.com/en-us/windows/desktop/Debug/retrieving-undecorated-symbol-names
197
    // Patches:
198
    // Use `fprintf(stderr, ` instead of `printf`.
199
    // return `szUndName` instead of `printf` on success
200
    char szUndName[MAX_SYM_NAME];
201
    if (UnDecorateSymbolName(name, szUndName, sizeof(szUndName),
202
                             UNDNAME_COMPLETE)) {
203
      // UnDecorateSymbolName returned success
204
      return szUndName;
205
    } else {
206
      // UnDecorateSymbolName failed
207
      const DWORD error = GetLastError();  // "eat" the error anyway
208
#ifdef DEBUG
209
      fprintf(stderr, "UnDecorateSymbolName returned error %lu\n", error);
210
#endif
211
    }
212
    return nullptr;
213
  }
214
215
  SymbolInfo LookupSymbol(void* address) override {
216
    const DWORD64 dw_address = reinterpret_cast<DWORD64>(address);
217
    SymbolInfo ret = WrappedGetLine(dw_address);
218
    std::tie(ret.name, ret.dis) = WrappedSymFromAddr(dw_address);
219
    if (!ret.name.empty()) {
220
      ret.name = WrappedUnDecorateSymbolName(ret.name.c_str());
221
    }
222
    return ret;
223
  }
224
225
  bool IsMapped(void* address) override {
226
    MEMORY_BASIC_INFORMATION info;
227
228
    if (VirtualQuery(address, &info, sizeof(info)) != sizeof(info))
229
      return false;
230
231
    return info.State == MEM_COMMIT && info.Protect != 0;
232
  }
233
234
  int GetStackTrace(void** frames, int count) override {
235
    return CaptureStackBackTrace(0, count, frames, nullptr);
236
  }
237
238
  Win32SymbolDebuggingContext(const Win32SymbolDebuggingContext&) = delete;
239
  Win32SymbolDebuggingContext(Win32SymbolDebuggingContext&&) = delete;
240
  Win32SymbolDebuggingContext operator=(const Win32SymbolDebuggingContext&)
241
    = delete;
242
  Win32SymbolDebuggingContext operator=(Win32SymbolDebuggingContext&&)
243
    = delete;
244
245
 private:
246
  HANDLE current_process_;
247
};
248
249
std::unique_ptr<NativeSymbolDebuggingContext>
250
NativeSymbolDebuggingContext::New() {
251
  return std::unique_ptr<NativeSymbolDebuggingContext>(
252
      new Win32SymbolDebuggingContext());
253
}
254
255
#endif  // __POSIX__
256
257
26
std::string NativeSymbolDebuggingContext::SymbolInfo::Display() const {
258
26
  std::ostringstream oss;
259
26
  oss << name;
260
26
  if (dis != 0) {
261
    oss << "+" << dis;
262
  }
263
26
  if (!filename.empty()) {
264
26
    oss << " [" << filename << ']';
265
  }
266
26
  if (line != 0) {
267
    oss << ":L" << line;
268
  }
269
26
  return oss.str();
270
}
271
272
4
void DumpBacktrace(FILE* fp) {
273
4
  auto sym_ctx = NativeSymbolDebuggingContext::New();
274
  void* frames[256];
275
4
  const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
276
30
  for (int i = 1; i < size; i += 1) {
277
26
    void* frame = frames[i];
278
26
    NativeSymbolDebuggingContext::SymbolInfo s = sym_ctx->LookupSymbol(frame);
279
26
    fprintf(fp, "%2d: %p %s\n", i, frame, s.Display().c_str());
280
30
  }
281
4
}
282
283
7474
void CheckedUvLoopClose(uv_loop_t* loop) {
284
14948
  if (uv_loop_close(loop) == 0) return;
285
286
  auto sym_ctx = NativeSymbolDebuggingContext::New();
287
288
  fprintf(stderr, "uv loop at [%p] has active handles\n", loop);
289
290
  uv_walk(loop, [](uv_handle_t* handle, void* arg) {
291
    auto sym_ctx = static_cast<NativeSymbolDebuggingContext*>(arg);
292
293
    fprintf(stderr, "[%p] %s\n", handle, uv_handle_type_name(handle->type));
294
295
    void* close_cb = reinterpret_cast<void*>(handle->close_cb);
296
    fprintf(stderr, "\tClose callback: %p %s\n",
297
        close_cb, sym_ctx->LookupSymbol(close_cb).Display().c_str());
298
299
    fprintf(stderr, "\tData: %p %s\n",
300
        handle->data, sym_ctx->LookupSymbol(handle->data).Display().c_str());
301
302
    // We are also interested in the first field of what `handle->data`
303
    // points to, because for C++ code that is usually the virtual table pointer
304
    // and gives us information about the exact kind of object we're looking at.
305
    void* first_field = nullptr;
306
    // `handle->data` might be any value, including `nullptr`, or something
307
    // cast from a completely different type; therefore, check that it’s
308
    // dereferencable first.
309
    if (sym_ctx->IsMapped(handle->data))
310
      first_field = *reinterpret_cast<void**>(handle->data);
311
312
    if (first_field != nullptr) {
313
      fprintf(stderr, "\t(First field): %p %s\n",
314
          first_field, sym_ctx->LookupSymbol(first_field).Display().c_str());
315
    }
316
  }, sym_ctx.get());
317
318
  fflush(stderr);
319
  // Finally, abort.
320
  CHECK(0 && "uv_loop_close() while having open handles");
321
}
322
323
std::vector<std::string> NativeSymbolDebuggingContext::GetLoadedLibraries() {
324
  std::vector<std::string> list;
325
#if defined(__linux__) || defined(__FreeBSD__)
326
  dl_iterate_phdr(
327
      [](struct dl_phdr_info* info, size_t size, void* data) {
328
        auto list = static_cast<std::vector<std::string>*>(data);
329
        if (*info->dlpi_name != '\0') {
330
          list->push_back(info->dlpi_name);
331
        }
332
        return 0;
333
      },
334
      &list);
335
#elif __APPLE__
336
  uint32_t i = 0;
337
  for (const char* name = _dyld_get_image_name(i); name != nullptr;
338
       name = _dyld_get_image_name(++i)) {
339
    list.push_back(name);
340
  }
341
342
#elif _AIX
343
  // We can't tell in advance how large the buffer needs to be.
344
  // Retry until we reach too large a size (1Mb).
345
  const unsigned int kBufferGrowStep = 4096;
346
  MallocedBuffer<char> buffer(kBufferGrowStep);
347
  int rc = -1;
348
  do {
349
    rc = loadquery(L_GETINFO, buffer.data, buffer.size);
350
    if (rc == 0) break;
351
    buffer = MallocedBuffer<char>(buffer.size + kBufferGrowStep);
352
  } while (buffer.size < 1024 * 1024);
353
354
  if (rc == 0) {
355
    char* buf = buffer.data;
356
    ld_info* cur_info = nullptr;
357
    do {
358
      std::ostringstream str;
359
      cur_info = reinterpret_cast<ld_info*>(buf);
360
      char* member_name = cur_info->ldinfo_filename +
361
          strlen(cur_info->ldinfo_filename) + 1;
362
      if (*member_name != '\0') {
363
        str << cur_info->ldinfo_filename << "(" << member_name << ")";
364
        list.push_back(str.str());
365
        str.str("");
366
      } else {
367
        list.push_back(cur_info->ldinfo_filename);
368
      }
369
      buf += cur_info->ldinfo_next;
370
    } while (cur_info->ldinfo_next != 0);
371
  }
372
#elif __sun
373
  Link_map* p;
374
375
  if (dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &p) != -1) {
376
    for (Link_map* l = p; l != nullptr; l = l->l_next) {
377
      list.push_back(l->l_name);
378
    }
379
  }
380
381
#elif _WIN32
382
  // Windows implementation - get a handle to the process.
383
  HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
384
                                      FALSE, GetCurrentProcessId());
385
  if (process_handle == nullptr) {
386
    // Cannot proceed, return an empty list.
387
    return list;
388
  }
389
  // Get a list of all the modules in this process
390
  DWORD size_1 = 0;
391
  DWORD size_2 = 0;
392
  // First call to get the size of module array needed
393
  if (EnumProcessModules(process_handle, nullptr, 0, &size_1)) {
394
    MallocedBuffer<HMODULE> modules(size_1);
395
396
    // Second call to populate the module array
397
    if (EnumProcessModules(process_handle, modules.data, size_1, &size_2)) {
398
      for (DWORD i = 0;
399
           i < (size_1 / sizeof(HMODULE)) && i < (size_2 / sizeof(HMODULE));
400
           i++) {
401
        WCHAR module_name[MAX_PATH];
402
        // Obtain and report the full pathname for each module
403
        if (GetModuleFileNameExW(process_handle,
404
                                 modules.data[i],
405
                                 module_name,
406
                                 arraysize(module_name) / sizeof(WCHAR))) {
407
          DWORD size = WideCharToMultiByte(
408
              CP_UTF8, 0, module_name, -1, nullptr, 0, nullptr, nullptr);
409
          char* str = new char[size];
410
          WideCharToMultiByte(
411
              CP_UTF8, 0, module_name, -1, str, size, nullptr, nullptr);
412
          list.push_back(str);
413
        }
414
      }
415
    }
416
  }
417
418
  // Release the handle to the process.
419
  CloseHandle(process_handle);
420
#endif
421
  return list;
422
}
423
424
425
}  // namespace node
426
427
extern "C" void __DumpBacktrace(FILE* fp) {
428
  node::DumpBacktrace(fp);
429
}