GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_report.cc Lines: 451 460 98.0 %
Date: 2022-08-28 04:20:35 Branches: 117 150 78.0 %

Line Branch Exec Source
1
#include "node_report.h"
2
#include "debug_utils-inl.h"
3
#include "diagnosticfilename-inl.h"
4
#include "env-inl.h"
5
#include "json_utils.h"
6
#include "node_internals.h"
7
#include "node_metadata.h"
8
#include "node_mutex.h"
9
#include "node_worker.h"
10
#include "util.h"
11
12
#ifdef _WIN32
13
#include <Windows.h>
14
#else  // !_WIN32
15
#include <cxxabi.h>
16
#include <sys/resource.h>
17
#include <dlfcn.h>
18
#endif
19
20
#include <iostream>
21
#include <cstring>
22
#include <ctime>
23
#include <cwctype>
24
#include <fstream>
25
26
constexpr int NODE_REPORT_VERSION = 2;
27
constexpr int NANOS_PER_SEC = 1000 * 1000 * 1000;
28
constexpr double SEC_PER_MICROS = 1e-6;
29
constexpr int MAX_FRAME_COUNT = 10;
30
31
namespace node {
32
using node::worker::Worker;
33
using v8::Array;
34
using v8::Context;
35
using v8::HandleScope;
36
using v8::HeapSpaceStatistics;
37
using v8::HeapStatistics;
38
using v8::Isolate;
39
using v8::Just;
40
using v8::Local;
41
using v8::Maybe;
42
using v8::MaybeLocal;
43
using v8::Nothing;
44
using v8::Object;
45
using v8::RegisterState;
46
using v8::SampleInfo;
47
using v8::StackFrame;
48
using v8::StackTrace;
49
using v8::String;
50
using v8::TryCatch;
51
using v8::V8;
52
using v8::Value;
53
54
namespace report {
55
// Internal/static function declarations
56
static void WriteNodeReport(Isolate* isolate,
57
                            Environment* env,
58
                            const char* message,
59
                            const char* trigger,
60
                            const std::string& filename,
61
                            std::ostream& out,
62
                            Local<Value> error,
63
                            bool compact);
64
static void PrintVersionInformation(JSONWriter* writer);
65
static void PrintJavaScriptErrorStack(JSONWriter* writer,
66
                                      Isolate* isolate,
67
                                      Local<Value> error,
68
                                      const char* trigger);
69
static void PrintJavaScriptStack(JSONWriter* writer,
70
                                 Isolate* isolate,
71
                                 const char* trigger);
72
static void PrintJavaScriptErrorProperties(JSONWriter* writer,
73
                                           Isolate* isolate,
74
                                           Local<Value> error);
75
static void PrintNativeStack(JSONWriter* writer);
76
static void PrintResourceUsage(JSONWriter* writer);
77
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate);
78
static void PrintSystemInformation(JSONWriter* writer);
79
static void PrintLoadedLibraries(JSONWriter* writer);
80
static void PrintComponentVersions(JSONWriter* writer);
81
static void PrintRelease(JSONWriter* writer);
82
static void PrintCpuInfo(JSONWriter* writer);
83
static void PrintNetworkInterfaceInfo(JSONWriter* writer);
84
85
// Internal function to coordinate and write the various
86
// sections of the report to the supplied stream
87
33
static void WriteNodeReport(Isolate* isolate,
88
                            Environment* env,
89
                            const char* message,
90
                            const char* trigger,
91
                            const std::string& filename,
92
                            std::ostream& out,
93
                            Local<Value> error,
94
                            bool compact) {
95
  // Obtain the current time and the pid.
96
  TIME_TYPE tm_struct;
97
33
  DiagnosticFilename::LocalTime(&tm_struct);
98
33
  uv_pid_t pid = uv_os_getpid();
99
100
  // Save formatting for output stream.
101
66
  std::ios old_state(nullptr);
102
33
  old_state.copyfmt(out);
103
104
  // File stream opened OK, now start printing the report content:
105
  // the title and header information (event, filename, timestamp and pid)
106
107
33
  JSONWriter writer(out, compact);
108
33
  writer.json_start();
109
33
  writer.json_objectstart("header");
110
33
  writer.json_keyvalue("reportVersion", NODE_REPORT_VERSION);
111
33
  writer.json_keyvalue("event", message);
112
33
  writer.json_keyvalue("trigger", trigger);
113
33
  if (!filename.empty())
114
18
    writer.json_keyvalue("filename", filename);
115
  else
116
15
    writer.json_keyvalue("filename", JSONWriter::Null{});
117
118
  // Report dump event and module load date/time stamps
119
  char timebuf[64];
120
#ifdef _WIN32
121
  snprintf(timebuf,
122
           sizeof(timebuf),
123
           "%4d-%02d-%02dT%02d:%02d:%02dZ",
124
           tm_struct.wYear,
125
           tm_struct.wMonth,
126
           tm_struct.wDay,
127
           tm_struct.wHour,
128
           tm_struct.wMinute,
129
           tm_struct.wSecond);
130
  writer.json_keyvalue("dumpEventTime", timebuf);
131
#else  // UNIX, OSX
132
99
  snprintf(timebuf,
133
           sizeof(timebuf),
134
           "%4d-%02d-%02dT%02d:%02d:%02dZ",
135
33
           tm_struct.tm_year + 1900,
136
33
           tm_struct.tm_mon + 1,
137
           tm_struct.tm_mday,
138
           tm_struct.tm_hour,
139
           tm_struct.tm_min,
140
           tm_struct.tm_sec);
141
33
  writer.json_keyvalue("dumpEventTime", timebuf);
142
#endif
143
144
  uv_timeval64_t ts;
145
33
  if (uv_gettimeofday(&ts) == 0) {
146
33
    writer.json_keyvalue("dumpEventTimeStamp",
147
66
                         std::to_string(ts.tv_sec * 1000 + ts.tv_usec / 1000));
148
  }
149
150
  // Report native process ID
151
33
  writer.json_keyvalue("processId", pid);
152
33
  if (env != nullptr)
153
29
    writer.json_keyvalue("threadId", env->thread_id());
154
  else
155
4
    writer.json_keyvalue("threadId", JSONWriter::Null{});
156
157
  {
158
    // Report the process cwd.
159
    char buf[PATH_MAX_BYTES];
160
33
    size_t cwd_size = sizeof(buf);
161
33
    if (uv_cwd(buf, &cwd_size) == 0)
162
33
      writer.json_keyvalue("cwd", buf);
163
  }
164
165
  // Report out the command line.
166
33
  if (!per_process::cli_options->cmdline.empty()) {
167
33
    writer.json_arraystart("commandLine");
168
108
    for (const std::string& arg : per_process::cli_options->cmdline) {
169
75
      writer.json_element(arg);
170
    }
171
33
    writer.json_arrayend();
172
  }
173
174
  // Report Node.js and OS version information
175
33
  PrintVersionInformation(&writer);
176
33
  writer.json_objectend();
177
178
33
  if (isolate != nullptr) {
179
29
    writer.json_objectstart("javascriptStack");
180
    // Report summary JavaScript error stack backtrace
181
29
    PrintJavaScriptErrorStack(&writer, isolate, error, trigger);
182
183
29
    writer.json_objectend();  // the end of 'javascriptStack'
184
185
    // Report V8 Heap and Garbage Collector information
186
29
    PrintGCStatistics(&writer, isolate);
187
  }
188
189
  // Report native stack backtrace
190
33
  PrintNativeStack(&writer);
191
192
  // Report OS and current thread resource usage
193
33
  PrintResourceUsage(&writer);
194
195
33
  writer.json_arraystart("libuv");
196
33
  if (env != nullptr) {
197
29
    uv_walk(env->event_loop(), WalkHandle, static_cast<void*>(&writer));
198
199
29
    writer.json_start();
200
29
    writer.json_keyvalue("type", "loop");
201
29
    writer.json_keyvalue("is_active",
202
29
        static_cast<bool>(uv_loop_alive(env->event_loop())));
203
29
    writer.json_keyvalue("address",
204
58
        ValueToHexString(reinterpret_cast<int64_t>(env->event_loop())));
205
206
    // Report Event loop idle time
207
29
    uint64_t idle_time = uv_metrics_idle_time(env->event_loop());
208
29
    writer.json_keyvalue("loopIdleTimeSeconds", 1.0 * idle_time / 1e9);
209
29
    writer.json_end();
210
  }
211
212
33
  writer.json_arrayend();
213
214
33
  writer.json_arraystart("workers");
215
33
  if (env != nullptr) {
216
58
    Mutex workers_mutex;
217
58
    ConditionVariable notify;
218
58
    std::vector<std::string> worker_infos;
219
29
    size_t expected_results = 0;
220
221
29
    env->ForEachWorker([&](Worker* w) {
222
12
      expected_results += w->RequestInterrupt([&](Environment* env) {
223
4
        std::ostringstream os;
224
225
4
        GetNodeReport(
226
2
            env, "Worker thread subreport", trigger, Local<Value>(), os);
227
228
4
        Mutex::ScopedLock lock(workers_mutex);
229
2
        worker_infos.emplace_back(os.str());
230
4
        notify.Signal(lock);
231
2
      });
232
2
    });
233
234
58
    Mutex::ScopedLock lock(workers_mutex);
235
29
    worker_infos.reserve(expected_results);
236
31
    while (worker_infos.size() < expected_results)
237
2
      notify.Wait(lock);
238
31
    for (const std::string& worker_info : worker_infos)
239
2
      writer.json_element(JSONWriter::ForeignJSON { worker_info });
240
  }
241
33
  writer.json_arrayend();
242
243
  // Report operating system information
244
33
  PrintSystemInformation(&writer);
245
246
33
  writer.json_objectend();
247
248
  // Restore output stream formatting.
249
33
  out.copyfmt(old_state);
250
33
}
251
252
// Report Node.js version, OS version and machine information.
253
33
static void PrintVersionInformation(JSONWriter* writer) {
254
66
  std::ostringstream buf;
255
  // Report Node version
256
33
  buf << "v" << NODE_VERSION_STRING;
257
33
  writer->json_keyvalue("nodejsVersion", buf.str());
258
33
  buf.str("");
259
260
#ifndef _WIN32
261
  // Report compiler and runtime glibc versions where possible.
262
  const char* (*libc_version)();
263
66
  *(reinterpret_cast<void**>(&libc_version)) =
264
33
      dlsym(RTLD_DEFAULT, "gnu_get_libc_version");
265
33
  if (libc_version != nullptr)
266
33
    writer->json_keyvalue("glibcVersionRuntime", (*libc_version)());
267
#endif /* _WIN32 */
268
269
#ifdef __GLIBC__
270
33
  buf << __GLIBC__ << "." << __GLIBC_MINOR__;
271
33
  writer->json_keyvalue("glibcVersionCompiler", buf.str());
272
33
  buf.str("");
273
#endif
274
275
  // Report Process word size
276
33
  writer->json_keyvalue("wordSize", sizeof(void*) * 8);
277
33
  writer->json_keyvalue("arch", per_process::metadata.arch);
278
33
  writer->json_keyvalue("platform", per_process::metadata.platform);
279
280
  // Report deps component versions
281
33
  PrintComponentVersions(writer);
282
283
  // Report release metadata.
284
33
  PrintRelease(writer);
285
286
  // Report operating system and machine information
287
  uv_utsname_t os_info;
288
289
33
  if (uv_os_uname(&os_info) == 0) {
290
33
    writer->json_keyvalue("osName", os_info.sysname);
291
33
    writer->json_keyvalue("osRelease", os_info.release);
292
33
    writer->json_keyvalue("osVersion", os_info.version);
293
33
    writer->json_keyvalue("osMachine", os_info.machine);
294
  }
295
296
33
  PrintCpuInfo(writer);
297
33
  PrintNetworkInterfaceInfo(writer);
298
299
  char host[UV_MAXHOSTNAMESIZE];
300
33
  size_t host_size = sizeof(host);
301
302
33
  if (uv_os_gethostname(host, &host_size) == 0)
303
33
    writer->json_keyvalue("host", host);
304
33
}
305
306
// Report CPU info
307
33
static void PrintCpuInfo(JSONWriter* writer) {
308
  uv_cpu_info_t* cpu_info;
309
  int count;
310
33
  if (uv_cpu_info(&cpu_info, &count) == 0) {
311
33
    writer->json_arraystart("cpus");
312
2937
    for (int i = 0; i < count; i++) {
313
2904
      writer->json_start();
314
2904
      writer->json_keyvalue("model", cpu_info[i].model);
315
2904
      writer->json_keyvalue("speed", cpu_info[i].speed);
316
2904
      writer->json_keyvalue("user", cpu_info[i].cpu_times.user);
317
2904
      writer->json_keyvalue("nice", cpu_info[i].cpu_times.nice);
318
2904
      writer->json_keyvalue("sys", cpu_info[i].cpu_times.sys);
319
2904
      writer->json_keyvalue("idle", cpu_info[i].cpu_times.idle);
320
2904
      writer->json_keyvalue("irq", cpu_info[i].cpu_times.irq);
321
2904
      writer->json_end();
322
    }
323
33
    writer->json_arrayend();
324
33
    uv_free_cpu_info(cpu_info, count);
325
  }
326
33
}
327
328
33
static void PrintNetworkInterfaceInfo(JSONWriter* writer) {
329
  uv_interface_address_t* interfaces;
330
  char ip[INET6_ADDRSTRLEN];
331
  char netmask[INET6_ADDRSTRLEN];
332
  char mac[18];
333
  int count;
334
335
33
  if (uv_interface_addresses(&interfaces, &count) == 0) {
336
33
    writer->json_arraystart("networkInterfaces");
337
338
165
    for (int i = 0; i < count; i++) {
339
132
      writer->json_start();
340
132
      writer->json_keyvalue("name", interfaces[i].name);
341
132
      writer->json_keyvalue("internal", !!interfaces[i].is_internal);
342
792
      snprintf(mac,
343
               sizeof(mac),
344
               "%02x:%02x:%02x:%02x:%02x:%02x",
345
132
               static_cast<unsigned char>(interfaces[i].phys_addr[0]),
346
132
               static_cast<unsigned char>(interfaces[i].phys_addr[1]),
347
132
               static_cast<unsigned char>(interfaces[i].phys_addr[2]),
348
132
               static_cast<unsigned char>(interfaces[i].phys_addr[3]),
349
132
               static_cast<unsigned char>(interfaces[i].phys_addr[4]),
350
132
               static_cast<unsigned char>(interfaces[i].phys_addr[5]));
351
132
      writer->json_keyvalue("mac", mac);
352
353
132
      if (interfaces[i].address.address4.sin_family == AF_INET) {
354
66
        uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
355
66
        uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
356
66
        writer->json_keyvalue("address", ip);
357
66
        writer->json_keyvalue("netmask", netmask);
358
66
        writer->json_keyvalue("family", "IPv4");
359
66
      } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
360
66
        uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
361
66
        uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
362
66
        writer->json_keyvalue("address", ip);
363
66
        writer->json_keyvalue("netmask", netmask);
364
66
        writer->json_keyvalue("family", "IPv6");
365
66
        writer->json_keyvalue("scopeid",
366
66
                              interfaces[i].address.address6.sin6_scope_id);
367
      } else {
368
        writer->json_keyvalue("family", "unknown");
369
      }
370
371
132
      writer->json_end();
372
    }
373
374
33
    writer->json_arrayend();
375
33
    uv_free_interface_addresses(interfaces, count);
376
  }
377
33
}
378
379
25
static void PrintJavaScriptErrorProperties(JSONWriter* writer,
380
                                           Isolate* isolate,
381
                                           Local<Value> error) {
382
25
  writer->json_objectstart("errorProperties");
383

50
  if (!error.IsEmpty() && error->IsObject()) {
384
20
    TryCatch try_catch(isolate);
385
20
    Local<Object> error_obj = error.As<Object>();
386
20
    Local<Context> context = error_obj->GetIsolate()->GetCurrentContext();
387
    Local<Array> keys;
388
40
    if (!error_obj->GetOwnPropertyNames(context).ToLocal(&keys)) {
389
      return writer->json_objectend();  // the end of 'errorProperties'
390
    }
391
20
    uint32_t keys_length = keys->Length();
392
33
    for (uint32_t i = 0; i < keys_length; i++) {
393
      Local<Value> key;
394

52
      if (!keys->Get(context, i).ToLocal(&key) || !key->IsString()) {
395
        continue;
396
      }
397
      Local<Value> value;
398
      Local<String> value_string;
399
39
      if (!error_obj->Get(context, key).ToLocal(&value) ||
400

39
          !value->ToString(context).ToLocal(&value_string)) {
401
        continue;
402
      }
403
13
      String::Utf8Value k(isolate, key);
404

13
      if (!strcmp(*k, "stack") || !strcmp(*k, "message")) continue;
405
13
      String::Utf8Value v(isolate, value_string);
406
13
      writer->json_keyvalue(std::string(*k, k.length()),
407
26
                            std::string(*v, v.length()));
408
    }
409
  }
410
25
  writer->json_objectend();  // the end of 'errorProperties'
411
}
412
413
25
static Maybe<std::string> ErrorToString(Isolate* isolate,
414
                                        Local<Context> context,
415
                                        Local<Value> error) {
416
25
  if (error.IsEmpty()) {
417
    return Nothing<std::string>();
418
  }
419
420
  MaybeLocal<String> maybe_str;
421
  // `ToString` is not available to Symbols.
422
25
  if (error->IsSymbol()) {
423
1
    maybe_str = error.As<v8::Symbol>()->ToDetailString(context);
424
24
  } else if (!error->IsObject()) {
425
4
    maybe_str = error->ToString(context);
426
20
  } else if (error->IsObject()) {
427
20
    MaybeLocal<Value> stack = error.As<Object>()->Get(
428
40
        context, FIXED_ONE_BYTE_STRING(isolate, "stack"));
429

60
    if (!stack.IsEmpty() && stack.ToLocalChecked()->IsString()) {
430
40
      maybe_str = stack.ToLocalChecked().As<String>();
431
    }
432
  }
433
434
  Local<String> js_str;
435
25
  if (!maybe_str.ToLocal(&js_str)) {
436
    return Nothing<std::string>();
437
  }
438
25
  String::Utf8Value sv(isolate, js_str);
439
25
  return Just<>(std::string(*sv, sv.length()));
440
}
441
442
1
static void PrintEmptyJavaScriptStack(JSONWriter* writer) {
443
1
  writer->json_keyvalue("message", "No stack.");
444
1
  writer->json_arraystart("stack");
445
1
  writer->json_element("Unavailable.");
446
1
  writer->json_arrayend();
447
448
1
  writer->json_objectstart("errorProperties");
449
1
  writer->json_objectend();
450
1
}
451
452
// Do our best to report the JavaScript stack without calling into JavaScript.
453
4
static void PrintJavaScriptStack(JSONWriter* writer,
454
                                 Isolate* isolate,
455
                                 const char* trigger) {
456
  // Can not capture the stacktrace when the isolate is in a OOM state.
457
4
  if (!strcmp(trigger, "OOMError")) {
458
    PrintEmptyJavaScriptStack(writer);
459
1
    return;
460
  }
461
462
4
  HandleScope scope(isolate);
463
4
  RegisterState state;
464
4
  state.pc = nullptr;
465
4
  state.fp = &state;
466
4
  state.sp = &state;
467
468
  // in-out params
469
  SampleInfo info;
470
  void* samples[MAX_FRAME_COUNT];
471
4
  isolate->GetStackSample(state, samples, MAX_FRAME_COUNT, &info);
472
473
  Local<StackTrace> stack = StackTrace::CurrentStackTrace(
474
4
      isolate, MAX_FRAME_COUNT, StackTrace::kDetailed);
475
476
4
  if (stack->GetFrameCount() == 0) {
477
1
    PrintEmptyJavaScriptStack(writer);
478
1
    return;
479
  }
480
481
3
  writer->json_keyvalue("message", trigger);
482
3
  writer->json_arraystart("stack");
483
58
  for (int i = 0; i < stack->GetFrameCount(); i++) {
484
26
    Local<StackFrame> frame = stack->GetFrame(isolate, i);
485
486
78
    Utf8Value function_name(isolate, frame->GetFunctionName());
487
78
    Utf8Value script_name(isolate, frame->GetScriptName());
488
26
    const int line_number = frame->GetLineNumber();
489
26
    const int column = frame->GetColumn();
490
491
    std::string stack_line = SPrintF(
492
52
        "at %s (%s:%d:%d)", *function_name, *script_name, line_number, column);
493
26
    writer->json_element(stack_line);
494
  }
495
3
  writer->json_arrayend();
496
3
  writer->json_objectstart("errorProperties");
497
3
  writer->json_objectend();
498
}
499
500
// Report the JavaScript stack.
501
29
static void PrintJavaScriptErrorStack(JSONWriter* writer,
502
                                      Isolate* isolate,
503
                                      Local<Value> error,
504
                                      const char* trigger) {
505
29
  if (error.IsEmpty()) {
506
4
    return PrintJavaScriptStack(writer, isolate, trigger);
507
  }
508
509
25
  TryCatch try_catch(isolate);
510
25
  HandleScope scope(isolate);
511
25
  Local<Context> context = isolate->GetCurrentContext();
512
25
  std::string ss = "";
513
50
  if (!ErrorToString(isolate, context, error).To(&ss)) {
514
    PrintEmptyJavaScriptStack(writer);
515
    return;
516
  }
517
518
25
  int line = ss.find('\n');
519
25
  if (line == -1) {
520
7
    writer->json_keyvalue("message", ss);
521
  } else {
522
36
    std::string l = ss.substr(0, line);
523
18
    writer->json_keyvalue("message", l);
524
18
    writer->json_arraystart("stack");
525
18
    ss = ss.substr(line + 1);
526
18
    line = ss.find('\n');
527
131
    while (line != -1) {
528
113
      l = ss.substr(0, line);
529
113
      l.erase(l.begin(), std::find_if(l.begin(), l.end(), [](int ch) {
530
565
                return !std::iswspace(ch);
531
226
              }));
532
113
      writer->json_element(l);
533
113
      ss = ss.substr(line + 1);
534
113
      line = ss.find('\n');
535
    }
536
18
    writer->json_arrayend();
537
  }
538
539
  // Report summary JavaScript error properties backtrace
540
25
  PrintJavaScriptErrorProperties(writer, isolate, error);
541
}
542
543
// Report a native stack backtrace
544
33
static void PrintNativeStack(JSONWriter* writer) {
545
66
  auto sym_ctx = NativeSymbolDebuggingContext::New();
546
  void* frames[256];
547
33
  const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
548
33
  writer->json_arraystart("nativeStack");
549
  int i;
550
358
  for (i = 1; i < size; i++) {
551
325
    void* frame = frames[i];
552
325
    writer->json_start();
553
325
    writer->json_keyvalue("pc",
554
650
                          ValueToHexString(reinterpret_cast<uintptr_t>(frame)));
555
325
    writer->json_keyvalue("symbol", sym_ctx->LookupSymbol(frame).Display());
556
325
    writer->json_end();
557
  }
558
33
  writer->json_arrayend();
559
33
}
560
561
// Report V8 JavaScript heap information.
562
// This uses the existing V8 HeapStatistics and HeapSpaceStatistics APIs.
563
// The isolate->GetGCStatistics(&heap_stats) internal V8 API could potentially
564
// provide some more useful information - the GC history and the handle counts
565
29
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate) {
566
29
  HeapStatistics v8_heap_stats;
567
29
  isolate->GetHeapStatistics(&v8_heap_stats);
568
29
  HeapSpaceStatistics v8_heap_space_stats;
569
570
29
  writer->json_objectstart("javascriptHeap");
571
29
  writer->json_keyvalue("totalMemory", v8_heap_stats.total_heap_size());
572
29
  writer->json_keyvalue("executableMemory",
573
29
                        v8_heap_stats.total_heap_size_executable());
574
29
  writer->json_keyvalue("totalCommittedMemory",
575
29
                        v8_heap_stats.total_physical_size());
576
29
  writer->json_keyvalue("availableMemory",
577
29
                        v8_heap_stats.total_available_size());
578
29
  writer->json_keyvalue("totalGlobalHandlesMemory",
579
29
                        v8_heap_stats.total_global_handles_size());
580
29
  writer->json_keyvalue("usedGlobalHandlesMemory",
581
29
                        v8_heap_stats.used_global_handles_size());
582
29
  writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
583
29
  writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
584
29
  writer->json_keyvalue("mallocedMemory", v8_heap_stats.malloced_memory());
585
29
  writer->json_keyvalue("externalMemory", v8_heap_stats.external_memory());
586
29
  writer->json_keyvalue("peakMallocedMemory",
587
29
                        v8_heap_stats.peak_malloced_memory());
588
29
  writer->json_keyvalue("nativeContextCount",
589
29
                        v8_heap_stats.number_of_native_contexts());
590
29
  writer->json_keyvalue("detachedContextCount",
591
29
                        v8_heap_stats.number_of_detached_contexts());
592
29
  writer->json_keyvalue("doesZapGarbage", v8_heap_stats.does_zap_garbage());
593
594
29
  writer->json_objectstart("heapSpaces");
595
  // Loop through heap spaces
596
261
  for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
597
232
    isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
598
232
    writer->json_objectstart(v8_heap_space_stats.space_name());
599
232
    writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
600
232
    writer->json_keyvalue(
601
        "committedMemory",
602
232
        v8_heap_space_stats.physical_space_size());
603
232
    writer->json_keyvalue(
604
        "capacity",
605
464
        v8_heap_space_stats.space_used_size() +
606
232
            v8_heap_space_stats.space_available_size());
607
232
    writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
608
232
    writer->json_keyvalue(
609
232
        "available", v8_heap_space_stats.space_available_size());
610
232
    writer->json_objectend();
611
  }
612
613
29
  writer->json_objectend();
614
29
  writer->json_objectend();
615
29
}
616
617
33
static void PrintResourceUsage(JSONWriter* writer) {
618
  // Get process uptime in seconds
619
  uint64_t uptime =
620
33
      (uv_hrtime() - per_process::node_start_time) / (NANOS_PER_SEC);
621
33
  if (uptime == 0) uptime = 1;  // avoid division by zero.
622
623
  // Process and current thread usage statistics
624
  uv_rusage_t rusage;
625
33
  writer->json_objectstart("resourceUsage");
626
33
  if (uv_getrusage(&rusage) == 0) {
627
33
    double user_cpu =
628
33
        rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
629
33
    double kernel_cpu =
630
33
        rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
631
33
    writer->json_keyvalue("userCpuSeconds", user_cpu);
632
33
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
633
33
    double cpu_abs = user_cpu + kernel_cpu;
634
33
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
635
33
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
636
33
    writer->json_keyvalue("maxRss", rusage.ru_maxrss * 1024);
637
33
    writer->json_objectstart("pageFaults");
638
33
    writer->json_keyvalue("IORequired", rusage.ru_majflt);
639
33
    writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
640
33
    writer->json_objectend();
641
33
    writer->json_objectstart("fsActivity");
642
33
    writer->json_keyvalue("reads", rusage.ru_inblock);
643
33
    writer->json_keyvalue("writes", rusage.ru_oublock);
644
33
    writer->json_objectend();
645
  }
646
33
  writer->json_objectend();
647
#ifdef RUSAGE_THREAD
648
  struct rusage stats;
649
33
  if (getrusage(RUSAGE_THREAD, &stats) == 0) {
650
33
    writer->json_objectstart("uvthreadResourceUsage");
651
33
    double user_cpu =
652
33
        stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
653
33
    double kernel_cpu =
654
33
        stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
655
33
    writer->json_keyvalue("userCpuSeconds", user_cpu);
656
33
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
657
33
    double cpu_abs = user_cpu + kernel_cpu;
658
33
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
659
33
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
660
33
    writer->json_objectstart("fsActivity");
661
33
    writer->json_keyvalue("reads", stats.ru_inblock);
662
33
    writer->json_keyvalue("writes", stats.ru_oublock);
663
33
    writer->json_objectend();
664
33
    writer->json_objectend();
665
  }
666
#endif  // RUSAGE_THREAD
667
33
}
668
669
// Report operating system information.
670
33
static void PrintSystemInformation(JSONWriter* writer) {
671
  uv_env_item_t* envitems;
672
  int envcount;
673
  int r;
674
675
33
  writer->json_objectstart("environmentVariables");
676
677
  {
678
66
    Mutex::ScopedLock lock(per_process::env_var_mutex);
679
33
    r = uv_os_environ(&envitems, &envcount);
680
  }
681
682
33
  if (r == 0) {
683
2356
    for (int i = 0; i < envcount; i++)
684
2323
      writer->json_keyvalue(envitems[i].name, envitems[i].value);
685
686
33
    uv_os_free_environ(envitems, envcount);
687
  }
688
689
33
  writer->json_objectend();
690
691
#ifndef _WIN32
692
  static struct {
693
    const char* description;
694
    int id;
695
  } rlimit_strings[] = {
696
    {"core_file_size_blocks", RLIMIT_CORE},
697
    {"data_seg_size_kbytes", RLIMIT_DATA},
698
    {"file_size_blocks", RLIMIT_FSIZE},
699
#if !(defined(_AIX) || defined(__sun))
700
    {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
701
#endif
702
#ifndef __sun
703
    {"max_memory_size_kbytes", RLIMIT_RSS},
704
#endif
705
    {"open_files", RLIMIT_NOFILE},
706
    {"stack_size_bytes", RLIMIT_STACK},
707
    {"cpu_time_seconds", RLIMIT_CPU},
708
#ifndef __sun
709
    {"max_user_processes", RLIMIT_NPROC},
710
#endif
711
#ifndef __OpenBSD__
712
    {"virtual_memory_kbytes", RLIMIT_AS}
713
#endif
714
  };
715
716
33
  writer->json_objectstart("userLimits");
717
  struct rlimit limit;
718
66
  std::string soft, hard;
719
720
363
  for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
721
330
    if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
722
330
      writer->json_objectstart(rlimit_strings[i].description);
723
724
330
      if (limit.rlim_cur == RLIM_INFINITY)
725
165
        writer->json_keyvalue("soft", "unlimited");
726
      else
727
165
        writer->json_keyvalue("soft", limit.rlim_cur);
728
729
330
      if (limit.rlim_max == RLIM_INFINITY)
730
231
        writer->json_keyvalue("hard", "unlimited");
731
      else
732
99
        writer->json_keyvalue("hard", limit.rlim_max);
733
734
330
      writer->json_objectend();
735
    }
736
  }
737
33
  writer->json_objectend();
738
#endif  // _WIN32
739
740
33
  PrintLoadedLibraries(writer);
741
33
}
742
743
// Report a list of loaded native libraries.
744
33
static void PrintLoadedLibraries(JSONWriter* writer) {
745
33
  writer->json_arraystart("sharedObjects");
746
  std::vector<std::string> modules =
747
66
      NativeSymbolDebuggingContext::GetLoadedLibraries();
748
272
  for (auto const& module_name : modules) writer->json_element(module_name);
749
33
  writer->json_arrayend();
750
33
}
751
752
// Obtain and report the node and subcomponent version strings.
753
33
static void PrintComponentVersions(JSONWriter* writer) {
754
66
  std::stringstream buf;
755
756
33
  writer->json_objectstart("componentVersions");
757
758
#define V(key) writer->json_keyvalue(#key, per_process::metadata.versions.key);
759
33
  NODE_VERSIONS_KEYS(V)
760
#undef V
761
762
33
  writer->json_objectend();
763
33
}
764
765
// Report runtime release information.
766
33
static void PrintRelease(JSONWriter* writer) {
767
33
  writer->json_objectstart("release");
768
33
  writer->json_keyvalue("name", per_process::metadata.release.name);
769
#if NODE_VERSION_IS_LTS
770
  writer->json_keyvalue("lts", per_process::metadata.release.lts);
771
#endif
772
773
#ifdef NODE_HAS_RELEASE_URLS
774
  writer->json_keyvalue("headersUrl",
775
                        per_process::metadata.release.headers_url);
776
  writer->json_keyvalue("sourceUrl", per_process::metadata.release.source_url);
777
#ifdef _WIN32
778
  writer->json_keyvalue("libUrl", per_process::metadata.release.lib_url);
779
#endif  // _WIN32
780
#endif  // NODE_HAS_RELEASE_URLS
781
782
33
  writer->json_objectend();
783
33
}
784
785
}  // namespace report
786
787
// External function to trigger a report, writing to file.
788
2
std::string TriggerNodeReport(Isolate* isolate,
789
                              const char* message,
790
                              const char* trigger,
791
                              const std::string& name,
792
                              Local<Value> error) {
793
2
  Environment* env = nullptr;
794
2
  if (isolate != nullptr) {
795
1
    env = Environment::GetCurrent(isolate);
796
  }
797
2
  return TriggerNodeReport(env, message, trigger, name, error);
798
}
799
800
// External function to trigger a report, writing to file.
801
19
std::string TriggerNodeReport(Environment* env,
802
                              const char* message,
803
                              const char* trigger,
804
                              const std::string& name,
805
                              Local<Value> error) {
806
38
  std::string filename;
807
808
  // Determine the required report filename. In order of priority:
809
  //   1) supplied on API 2) configured on startup 3) default generated
810
19
  if (!name.empty()) {
811
    // Filename was specified as API parameter.
812
4
    filename = name;
813
  } else {
814
30
    std::string report_filename;
815
    {
816
30
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
817
15
      report_filename = per_process::cli_options->report_filename;
818
    }
819
15
    if (report_filename.length() > 0) {
820
      // File name was supplied via start-up option.
821
1
      filename = report_filename;
822
    } else {
823
40
      filename = *DiagnosticFilename(
824
26
          env != nullptr ? env->thread_id() : 0, "report", "json");
825
    }
826
  }
827
828
  // Open the report file stream for writing. Supports stdout/err,
829
  // user-specified or (default) generated name
830
38
  std::ofstream outfile;
831
  std::ostream* outstream;
832
19
  if (filename == "stdout") {
833
1
    outstream = &std::cout;
834
18
  } else if (filename == "stderr") {
835
1
    outstream = &std::cerr;
836
  } else {
837
17
    std::string report_directory;
838
    {
839
34
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
840
17
      report_directory = per_process::cli_options->report_directory;
841
    }
842
    // Regular file. Append filename to directory path if one was specified
843
17
    if (report_directory.length() > 0) {
844
26
      std::string pathname = report_directory;
845
13
      pathname += kPathSeparator;
846
13
      pathname += filename;
847
13
      outfile.open(pathname, std::ios::out | std::ios::binary);
848
    } else {
849
4
      outfile.open(filename, std::ios::out | std::ios::binary);
850
    }
851
    // Check for errors on the file open
852
17
    if (!outfile.is_open()) {
853
1
      std::cerr << "\nFailed to open Node.js report file: " << filename;
854
855
1
      if (report_directory.length() > 0)
856
1
        std::cerr << " directory: " << report_directory;
857
858
1
      std::cerr << " (errno: " << errno << ")" << std::endl;
859
1
      return "";
860
    }
861
16
    outstream = &outfile;
862
16
    std::cerr << "\nWriting Node.js report to file: " << filename;
863
  }
864
865
  bool compact;
866
  {
867
18
    Mutex::ScopedLock lock(per_process::cli_options_mutex);
868
18
    compact = per_process::cli_options->report_compact;
869
  }
870
871
18
  Isolate* isolate = nullptr;
872
18
  if (env != nullptr) {
873
16
    isolate = env->isolate();
874
  }
875
18
  report::WriteNodeReport(
876
      isolate, env, message, trigger, filename, *outstream, error, compact);
877
878
  // Do not close stdout/stderr, only close files we opened.
879
18
  if (outfile.is_open()) {
880
16
    outfile.close();
881
  }
882
883
  // Do not mix JSON and free-form text on stderr.
884
18
  if (filename != "stderr") {
885
17
    std::cerr << "\nNode.js report completed" << std::endl;
886
  }
887
18
  return filename;
888
}
889
890
// External function to trigger a report, writing to a supplied stream.
891
2
void GetNodeReport(Isolate* isolate,
892
                   const char* message,
893
                   const char* trigger,
894
                   Local<Value> error,
895
                   std::ostream& out) {
896
2
  Environment* env = nullptr;
897
2
  if (isolate != nullptr) {
898
1
    env = Environment::GetCurrent(isolate);
899
  }
900
2
  report::WriteNodeReport(
901
      isolate, env, message, trigger, "", out, error, false);
902
2
}
903
904
// External function to trigger a report, writing to a supplied stream.
905
13
void GetNodeReport(Environment* env,
906
                   const char* message,
907
                   const char* trigger,
908
                   Local<Value> error,
909
                   std::ostream& out) {
910
13
  Isolate* isolate = nullptr;
911
13
  if (env != nullptr) {
912
12
    isolate = env->isolate();
913
  }
914
13
  report::WriteNodeReport(
915
      isolate, env, message, trigger, "", out, error, false);
916
13
}
917
918
}  // namespace node