GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/debug_utils.cc Lines: 48 77 62.3 %
Date: 2019-02-13 22:28:58 Branches: 15 26 57.7 %

Line Branch Exec Source
1
#include "debug_utils.h"
2
3
#ifdef __POSIX__
4
#if defined(__linux__)
5
#include <features.h>
6
#endif
7
8
#if defined(__linux__) && !defined(__GLIBC__) || \
9
    defined(__UCLIBC__) || \
10
    defined(_AIX)
11
#define HAVE_EXECINFO_H 0
12
#else
13
#define HAVE_EXECINFO_H 1
14
#endif
15
16
#if HAVE_EXECINFO_H
17
#include <cxxabi.h>
18
#include <dlfcn.h>
19
#include <execinfo.h>
20
#include <unistd.h>
21
#include <sys/mman.h>
22
#include <stdio.h>
23
#endif
24
25
#else  // __POSIX__
26
27
#include <windows.h>
28
#include <dbghelp.h>
29
30
#endif  // __POSIX__
31
32
#if defined(__linux__) || defined(__sun) || defined(__FreeBSD__)
33
#include <link.h>
34
#endif  // (__linux__) || defined(__sun) || defined(__FreeBSD__)
35
36
#ifdef __APPLE__
37
#include <mach-o/dyld.h>  // _dyld_get_image_name()
38
#endif                    // __APPLE__
39
40
#ifdef _AIX
41
#include <sys/ldr.h>  // ld_info structure
42
#endif                // _AIX
43
44
#ifdef _WIN32
45
#include <Lm.h>
46
#include <Windows.h>
47
#include <dbghelp.h>
48
#include <process.h>
49
#include <psapi.h>
50
#include <tchar.h>
51
#endif  // _WIN32
52
53
namespace node {
54
55
#ifdef __POSIX__
56
#if HAVE_EXECINFO_H
57
20
class PosixSymbolDebuggingContext final : public NativeSymbolDebuggingContext {
58
 public:
59
10
  PosixSymbolDebuggingContext() : pagesize_(getpagesize()) { }
60
61
68
  SymbolInfo LookupSymbol(void* address) override {
62
    Dl_info info;
63
68
    const bool have_info = dladdr(address, &info);
64
68
    SymbolInfo ret;
65
68
    if (!have_info)
66
      return ret;
67
68
68
    if (info.dli_sname != nullptr) {
69
37
      if (char* demangled =
70
37
              abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, nullptr)) {
71
35
        ret.name = demangled;
72
35
        free(demangled);
73
      } else {
74
2
        ret.name = info.dli_sname;
75
      }
76
    }
77
78
68
    if (info.dli_fname != nullptr) {
79
68
      ret.filename = info.dli_fname;
80
    }
81
82
68
    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
10
  int GetStackTrace(void** frames, int count) override {
92
10
    return backtrace(frames, count);
93
  }
94
95
 private:
96
  uintptr_t pagesize_;
97
};
98
99
std::unique_ptr<NativeSymbolDebuggingContext>
100
10
NativeSymbolDebuggingContext::New() {
101
  return std::unique_ptr<NativeSymbolDebuggingContext>(
102
10
      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
68
std::string NativeSymbolDebuggingContext::SymbolInfo::Display() const {
258
68
  std::ostringstream oss;
259
68
  oss << name;
260
68
  if (dis != 0) {
261
    oss << "+" << dis;
262
  }
263
68
  if (!filename.empty()) {
264
68
    oss << " [" << filename << ']';
265
  }
266
68
  if (line != 0) {
267
    oss << ":L" << line;
268
  }
269
68
  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
12562
void CheckedUvLoopClose(uv_loop_t* loop) {
284
25124
  if (uv_loop_close(loop) == 0) return;
285
286
  PrintLibuvHandleInformation(loop, stderr);
287
288
  fflush(stderr);
289
  // Finally, abort.
290
  CHECK(0 && "uv_loop_close() while having open handles");
291
}
292
293
void PrintLibuvHandleInformation(uv_loop_t* loop, FILE* stream) {
294
  struct Info {
295
    std::unique_ptr<NativeSymbolDebuggingContext> ctx;
296
    FILE* stream;
297
  };
298
299
  Info info { NativeSymbolDebuggingContext::New(), stream };
300
301
  fprintf(stream, "uv loop at [%p] has %d active handles\n",
302
          loop, loop->active_handles);
303
304
  uv_walk(loop, [](uv_handle_t* handle, void* arg) {
305
    Info* info = static_cast<Info*>(arg);
306
    NativeSymbolDebuggingContext* sym_ctx = info->ctx.get();
307
    FILE* stream = info->stream;
308
309
    fprintf(stream, "[%p] %s\n", handle, uv_handle_type_name(handle->type));
310
311
    void* close_cb = reinterpret_cast<void*>(handle->close_cb);
312
    fprintf(stream, "\tClose callback: %p %s\n",
313
        close_cb, sym_ctx->LookupSymbol(close_cb).Display().c_str());
314
315
    fprintf(stream, "\tData: %p %s\n",
316
        handle->data, sym_ctx->LookupSymbol(handle->data).Display().c_str());
317
318
    // We are also interested in the first field of what `handle->data`
319
    // points to, because for C++ code that is usually the virtual table pointer
320
    // and gives us information about the exact kind of object we're looking at.
321
    void* first_field = nullptr;
322
    // `handle->data` might be any value, including `nullptr`, or something
323
    // cast from a completely different type; therefore, check that it’s
324
    // dereferencable first.
325
    if (sym_ctx->IsMapped(handle->data))
326
      first_field = *reinterpret_cast<void**>(handle->data);
327
328
    if (first_field != nullptr) {
329
      fprintf(stream, "\t(First field): %p %s\n",
330
          first_field, sym_ctx->LookupSymbol(first_field).Display().c_str());
331
    }
332
  }, &info);
333
}
334
335
6
std::vector<std::string> NativeSymbolDebuggingContext::GetLoadedLibraries() {
336
6
  std::vector<std::string> list;
337
#if defined(__linux__) || defined(__FreeBSD__)
338
  dl_iterate_phdr(
339
132
      [](struct dl_phdr_info* info, size_t size, void* data) {
340
63
        auto list = static_cast<std::vector<std::string>*>(data);
341
63
        if (*info->dlpi_name != '\0') {
342
51
          list->push_back(info->dlpi_name);
343
        }
344
63
        return 0;
345
69
      },
346
6
      &list);
347
#elif __APPLE__
348
  uint32_t i = 0;
349
  for (const char* name = _dyld_get_image_name(i); name != nullptr;
350
       name = _dyld_get_image_name(++i)) {
351
    list.push_back(name);
352
  }
353
354
#elif _AIX
355
  // We can't tell in advance how large the buffer needs to be.
356
  // Retry until we reach too large a size (1Mb).
357
  const unsigned int kBufferGrowStep = 4096;
358
  MallocedBuffer<char> buffer(kBufferGrowStep);
359
  int rc = -1;
360
  do {
361
    rc = loadquery(L_GETINFO, buffer.data, buffer.size);
362
    if (rc == 0) break;
363
    buffer = MallocedBuffer<char>(buffer.size + kBufferGrowStep);
364
  } while (buffer.size < 1024 * 1024);
365
366
  if (rc == 0) {
367
    char* buf = buffer.data;
368
    ld_info* cur_info = nullptr;
369
    do {
370
      std::ostringstream str;
371
      cur_info = reinterpret_cast<ld_info*>(buf);
372
      char* member_name = cur_info->ldinfo_filename +
373
          strlen(cur_info->ldinfo_filename) + 1;
374
      if (*member_name != '\0') {
375
        str << cur_info->ldinfo_filename << "(" << member_name << ")";
376
        list.push_back(str.str());
377
        str.str("");
378
      } else {
379
        list.push_back(cur_info->ldinfo_filename);
380
      }
381
      buf += cur_info->ldinfo_next;
382
    } while (cur_info->ldinfo_next != 0);
383
  }
384
#elif __sun
385
  Link_map* p;
386
387
  if (dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &p) != -1) {
388
    for (Link_map* l = p; l != nullptr; l = l->l_next) {
389
      list.push_back(l->l_name);
390
    }
391
  }
392
393
#elif _WIN32
394
  // Windows implementation - get a handle to the process.
395
  HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
396
                                      FALSE, GetCurrentProcessId());
397
  if (process_handle == nullptr) {
398
    // Cannot proceed, return an empty list.
399
    return list;
400
  }
401
  // Get a list of all the modules in this process
402
  DWORD size_1 = 0;
403
  DWORD size_2 = 0;
404
  // First call to get the size of module array needed
405
  if (EnumProcessModules(process_handle, nullptr, 0, &size_1)) {
406
    MallocedBuffer<HMODULE> modules(size_1);
407
408
    // Second call to populate the module array
409
    if (EnumProcessModules(process_handle, modules.data, size_1, &size_2)) {
410
      for (DWORD i = 0;
411
           i < (size_1 / sizeof(HMODULE)) && i < (size_2 / sizeof(HMODULE));
412
           i++) {
413
        WCHAR module_name[MAX_PATH];
414
        // Obtain and report the full pathname for each module
415
        if (GetModuleFileNameExW(process_handle,
416
                                 modules.data[i],
417
                                 module_name,
418
                                 arraysize(module_name) / sizeof(WCHAR))) {
419
          DWORD size = WideCharToMultiByte(
420
              CP_UTF8, 0, module_name, -1, nullptr, 0, nullptr, nullptr);
421
          char* str = new char[size];
422
          WideCharToMultiByte(
423
              CP_UTF8, 0, module_name, -1, str, size, nullptr, nullptr);
424
          list.push_back(str);
425
        }
426
      }
427
    }
428
  }
429
430
  // Release the handle to the process.
431
  CloseHandle(process_handle);
432
#endif
433
6
  return list;
434
}
435
436
437
}  // namespace node
438
439
extern "C" void __DumpBacktrace(FILE* fp) {
440
  node::DumpBacktrace(fp);
441
}