GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_report.cc Lines: 386 393 98.2 %
Date: 2022-05-22 04:15:48 Branches: 105 142 73.9 %

Line Branch Exec Source
1
#include "env-inl.h"
2
#include "json_utils.h"
3
#include "node_report.h"
4
#include "debug_utils-inl.h"
5
#include "diagnosticfilename-inl.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
30
namespace report {
31
using node::arraysize;
32
using node::ConditionVariable;
33
using node::DiagnosticFilename;
34
using node::Environment;
35
using node::JSONWriter;
36
using node::Mutex;
37
using node::NativeSymbolDebuggingContext;
38
using node::TIME_TYPE;
39
using node::worker::Worker;
40
using v8::Array;
41
using v8::Context;
42
using v8::HandleScope;
43
using v8::HeapSpaceStatistics;
44
using v8::HeapStatistics;
45
using v8::Isolate;
46
using v8::Just;
47
using v8::Local;
48
using v8::Maybe;
49
using v8::MaybeLocal;
50
using v8::Nothing;
51
using v8::Object;
52
using v8::String;
53
using v8::TryCatch;
54
using v8::V8;
55
using v8::Value;
56
57
namespace per_process = node::per_process;
58
59
// Internal/static function declarations
60
static void WriteNodeReport(Isolate* isolate,
61
                            Environment* env,
62
                            const char* message,
63
                            const char* trigger,
64
                            const std::string& filename,
65
                            std::ostream& out,
66
                            Local<Value> error,
67
                            bool compact);
68
static void PrintVersionInformation(JSONWriter* writer);
69
static void PrintJavaScriptErrorStack(JSONWriter* writer,
70
                                      Isolate* isolate,
71
                                      Local<Value> error,
72
                                      const char* trigger);
73
static void PrintJavaScriptErrorProperties(JSONWriter* writer,
74
                                           Isolate* isolate,
75
                                           Local<Value> error);
76
static void PrintNativeStack(JSONWriter* writer);
77
static void PrintResourceUsage(JSONWriter* writer);
78
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate);
79
static void PrintSystemInformation(JSONWriter* writer);
80
static void PrintLoadedLibraries(JSONWriter* writer);
81
static void PrintComponentVersions(JSONWriter* writer);
82
static void PrintRelease(JSONWriter* writer);
83
static void PrintCpuInfo(JSONWriter* writer);
84
static void PrintNetworkInterfaceInfo(JSONWriter* writer);
85
86
// External function to trigger a report, writing to file.
87
15
std::string TriggerNodeReport(Isolate* isolate,
88
                              Environment* env,
89
                              const char* message,
90
                              const char* trigger,
91
                              const std::string& name,
92
                              Local<Value> error) {
93
30
  std::string filename;
94
95
  // Determine the required report filename. In order of priority:
96
  //   1) supplied on API 2) configured on startup 3) default generated
97
15
  if (!name.empty()) {
98
    // Filename was specified as API parameter.
99
4
    filename = name;
100
  } else {
101
22
    std::string report_filename;
102
    {
103
22
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
104
11
      report_filename = per_process::cli_options->report_filename;
105
    }
106
11
    if (report_filename.length() > 0) {
107
      // File name was supplied via start-up option.
108
1
      filename = report_filename;
109
    } else {
110
20
      filename = *DiagnosticFilename(env != nullptr ? env->thread_id() : 0,
111
10
          "report", "json");
112
    }
113
  }
114
115
  // Open the report file stream for writing. Supports stdout/err,
116
  // user-specified or (default) generated name
117
30
  std::ofstream outfile;
118
  std::ostream* outstream;
119
15
  if (filename == "stdout") {
120
1
    outstream = &std::cout;
121
14
  } else if (filename == "stderr") {
122
1
    outstream = &std::cerr;
123
  } else {
124
13
    std::string report_directory;
125
    {
126
26
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
127
13
      report_directory = per_process::cli_options->report_directory;
128
    }
129
    // Regular file. Append filename to directory path if one was specified
130
13
    if (report_directory.length() > 0) {
131
26
      std::string pathname = report_directory;
132
13
      pathname += node::kPathSeparator;
133
13
      pathname += filename;
134
13
      outfile.open(pathname, std::ios::out | std::ios::binary);
135
    } else {
136
      outfile.open(filename, std::ios::out | std::ios::binary);
137
    }
138
    // Check for errors on the file open
139
13
    if (!outfile.is_open()) {
140
1
      std::cerr << "\nFailed to open Node.js report file: " << filename;
141
142
1
      if (report_directory.length() > 0)
143
1
        std::cerr << " directory: " << report_directory;
144
145
1
      std::cerr << " (errno: " << errno << ")" << std::endl;
146
1
      return "";
147
    }
148
12
    outstream = &outfile;
149
12
    std::cerr << "\nWriting Node.js report to file: " << filename;
150
  }
151
152
  bool compact;
153
  {
154
14
    Mutex::ScopedLock lock(per_process::cli_options_mutex);
155
14
    compact = per_process::cli_options->report_compact;
156
  }
157
14
  WriteNodeReport(isolate, env, message, trigger, filename, *outstream,
158
                  error, compact);
159
160
  // Do not close stdout/stderr, only close files we opened.
161
14
  if (outfile.is_open()) {
162
12
    outfile.close();
163
  }
164
165
  // Do not mix JSON and free-form text on stderr.
166
14
  if (filename != "stderr") {
167
13
    std::cerr << "\nNode.js report completed" << std::endl;
168
  }
169
14
  return filename;
170
}
171
172
// External function to trigger a report, writing to a supplied stream.
173
10
void GetNodeReport(Isolate* isolate,
174
                   Environment* env,
175
                   const char* message,
176
                   const char* trigger,
177
                   Local<Value> error,
178
                   std::ostream& out) {
179
10
  WriteNodeReport(isolate, env, message, trigger, "", out, error, false);
180
10
}
181
182
// Internal function to coordinate and write the various
183
// sections of the report to the supplied stream
184
24
static void WriteNodeReport(Isolate* isolate,
185
                            Environment* env,
186
                            const char* message,
187
                            const char* trigger,
188
                            const std::string& filename,
189
                            std::ostream& out,
190
                            Local<Value> error,
191
                            bool compact) {
192
  // Obtain the current time and the pid.
193
  TIME_TYPE tm_struct;
194
24
  DiagnosticFilename::LocalTime(&tm_struct);
195
24
  uv_pid_t pid = uv_os_getpid();
196
197
  // Save formatting for output stream.
198
48
  std::ios old_state(nullptr);
199
24
  old_state.copyfmt(out);
200
201
  // File stream opened OK, now start printing the report content:
202
  // the title and header information (event, filename, timestamp and pid)
203
204
24
  JSONWriter writer(out, compact);
205
24
  writer.json_start();
206
24
  writer.json_objectstart("header");
207
24
  writer.json_keyvalue("reportVersion", NODE_REPORT_VERSION);
208
24
  writer.json_keyvalue("event", message);
209
24
  writer.json_keyvalue("trigger", trigger);
210
24
  if (!filename.empty())
211
14
    writer.json_keyvalue("filename", filename);
212
  else
213
10
    writer.json_keyvalue("filename", JSONWriter::Null{});
214
215
  // Report dump event and module load date/time stamps
216
  char timebuf[64];
217
#ifdef _WIN32
218
  snprintf(timebuf,
219
           sizeof(timebuf),
220
           "%4d-%02d-%02dT%02d:%02d:%02dZ",
221
           tm_struct.wYear,
222
           tm_struct.wMonth,
223
           tm_struct.wDay,
224
           tm_struct.wHour,
225
           tm_struct.wMinute,
226
           tm_struct.wSecond);
227
  writer.json_keyvalue("dumpEventTime", timebuf);
228
#else  // UNIX, OSX
229
72
  snprintf(timebuf,
230
           sizeof(timebuf),
231
           "%4d-%02d-%02dT%02d:%02d:%02dZ",
232
24
           tm_struct.tm_year + 1900,
233
24
           tm_struct.tm_mon + 1,
234
           tm_struct.tm_mday,
235
           tm_struct.tm_hour,
236
           tm_struct.tm_min,
237
           tm_struct.tm_sec);
238
24
  writer.json_keyvalue("dumpEventTime", timebuf);
239
#endif
240
241
  uv_timeval64_t ts;
242
24
  if (uv_gettimeofday(&ts) == 0) {
243
24
    writer.json_keyvalue("dumpEventTimeStamp",
244
48
                         std::to_string(ts.tv_sec * 1000 + ts.tv_usec / 1000));
245
  }
246
247
  // Report native process ID
248
24
  writer.json_keyvalue("processId", pid);
249
24
  if (env != nullptr)
250
24
    writer.json_keyvalue("threadId", env->thread_id());
251
  else
252
    writer.json_keyvalue("threadId", JSONWriter::Null{});
253
254
  {
255
    // Report the process cwd.
256
    char buf[PATH_MAX_BYTES];
257
24
    size_t cwd_size = sizeof(buf);
258
24
    if (uv_cwd(buf, &cwd_size) == 0)
259
24
      writer.json_keyvalue("cwd", buf);
260
  }
261
262
  // Report out the command line.
263
24
  if (!node::per_process::cli_options->cmdline.empty()) {
264
24
    writer.json_arraystart("commandLine");
265
82
    for (const std::string& arg : node::per_process::cli_options->cmdline) {
266
58
      writer.json_element(arg);
267
    }
268
24
    writer.json_arrayend();
269
  }
270
271
  // Report Node.js and OS version information
272
24
  PrintVersionInformation(&writer);
273
24
  writer.json_objectend();
274
275
24
  if (isolate != nullptr) {
276
24
    writer.json_objectstart("javascriptStack");
277
    // Report summary JavaScript error stack backtrace
278
24
    PrintJavaScriptErrorStack(&writer, isolate, error, trigger);
279
280
    // Report summary JavaScript error properties backtrace
281
24
    PrintJavaScriptErrorProperties(&writer, isolate, error);
282
24
    writer.json_objectend();  // the end of 'javascriptStack'
283
284
    // Report V8 Heap and Garbage Collector information
285
24
    PrintGCStatistics(&writer, isolate);
286
  }
287
288
  // Report native stack backtrace
289
24
  PrintNativeStack(&writer);
290
291
  // Report OS and current thread resource usage
292
24
  PrintResourceUsage(&writer);
293
294
24
  writer.json_arraystart("libuv");
295
24
  if (env != nullptr) {
296
24
    uv_walk(env->event_loop(), WalkHandle, static_cast<void*>(&writer));
297
298
24
    writer.json_start();
299
24
    writer.json_keyvalue("type", "loop");
300
24
    writer.json_keyvalue("is_active",
301
24
        static_cast<bool>(uv_loop_alive(env->event_loop())));
302
24
    writer.json_keyvalue("address",
303
48
        ValueToHexString(reinterpret_cast<int64_t>(env->event_loop())));
304
305
    // Report Event loop idle time
306
24
    uint64_t idle_time = uv_metrics_idle_time(env->event_loop());
307
24
    writer.json_keyvalue("loopIdleTimeSeconds", 1.0 * idle_time / 1e9);
308
24
    writer.json_end();
309
  }
310
311
24
  writer.json_arrayend();
312
313
24
  writer.json_arraystart("workers");
314
24
  if (env != nullptr) {
315
48
    Mutex workers_mutex;
316
48
    ConditionVariable notify;
317
48
    std::vector<std::string> worker_infos;
318
24
    size_t expected_results = 0;
319
320
24
    env->ForEachWorker([&](Worker* w) {
321
12
      expected_results += w->RequestInterrupt([&](Environment* env) {
322
4
        std::ostringstream os;
323
324
2
        GetNodeReport(env->isolate(),
325
                      env,
326
                      "Worker thread subreport",
327
2
                      trigger,
328
                      Local<Object>(),
329
                      os);
330
331
4
        Mutex::ScopedLock lock(workers_mutex);
332
2
        worker_infos.emplace_back(os.str());
333
4
        notify.Signal(lock);
334
2
      });
335
2
    });
336
337
48
    Mutex::ScopedLock lock(workers_mutex);
338
24
    worker_infos.reserve(expected_results);
339
26
    while (worker_infos.size() < expected_results)
340
2
      notify.Wait(lock);
341
26
    for (const std::string& worker_info : worker_infos)
342
2
      writer.json_element(JSONWriter::ForeignJSON { worker_info });
343
  }
344
24
  writer.json_arrayend();
345
346
  // Report operating system information
347
24
  PrintSystemInformation(&writer);
348
349
24
  writer.json_objectend();
350
351
  // Restore output stream formatting.
352
24
  out.copyfmt(old_state);
353
24
}
354
355
// Report Node.js version, OS version and machine information.
356
24
static void PrintVersionInformation(JSONWriter* writer) {
357
48
  std::ostringstream buf;
358
  // Report Node version
359
24
  buf << "v" << NODE_VERSION_STRING;
360
24
  writer->json_keyvalue("nodejsVersion", buf.str());
361
24
  buf.str("");
362
363
#ifndef _WIN32
364
  // Report compiler and runtime glibc versions where possible.
365
  const char* (*libc_version)();
366
48
  *(reinterpret_cast<void**>(&libc_version)) =
367
24
      dlsym(RTLD_DEFAULT, "gnu_get_libc_version");
368
24
  if (libc_version != nullptr)
369
24
    writer->json_keyvalue("glibcVersionRuntime", (*libc_version)());
370
#endif /* _WIN32 */
371
372
#ifdef __GLIBC__
373
24
  buf << __GLIBC__ << "." << __GLIBC_MINOR__;
374
24
  writer->json_keyvalue("glibcVersionCompiler", buf.str());
375
24
  buf.str("");
376
#endif
377
378
  // Report Process word size
379
24
  writer->json_keyvalue("wordSize", sizeof(void*) * 8);
380
24
  writer->json_keyvalue("arch", node::per_process::metadata.arch);
381
24
  writer->json_keyvalue("platform", node::per_process::metadata.platform);
382
383
  // Report deps component versions
384
24
  PrintComponentVersions(writer);
385
386
  // Report release metadata.
387
24
  PrintRelease(writer);
388
389
  // Report operating system and machine information
390
  uv_utsname_t os_info;
391
392
24
  if (uv_os_uname(&os_info) == 0) {
393
24
    writer->json_keyvalue("osName", os_info.sysname);
394
24
    writer->json_keyvalue("osRelease", os_info.release);
395
24
    writer->json_keyvalue("osVersion", os_info.version);
396
24
    writer->json_keyvalue("osMachine", os_info.machine);
397
  }
398
399
24
  PrintCpuInfo(writer);
400
24
  PrintNetworkInterfaceInfo(writer);
401
402
  char host[UV_MAXHOSTNAMESIZE];
403
24
  size_t host_size = sizeof(host);
404
405
24
  if (uv_os_gethostname(host, &host_size) == 0)
406
24
    writer->json_keyvalue("host", host);
407
24
}
408
409
// Report CPU info
410
24
static void PrintCpuInfo(JSONWriter* writer) {
411
  uv_cpu_info_t* cpu_info;
412
  int count;
413
24
  if (uv_cpu_info(&cpu_info, &count) == 0) {
414
24
    writer->json_arraystart("cpus");
415
2136
    for (int i = 0; i < count; i++) {
416
2112
      writer->json_start();
417
2112
      writer->json_keyvalue("model", cpu_info[i].model);
418
2112
      writer->json_keyvalue("speed", cpu_info[i].speed);
419
2112
      writer->json_keyvalue("user", cpu_info[i].cpu_times.user);
420
2112
      writer->json_keyvalue("nice", cpu_info[i].cpu_times.nice);
421
2112
      writer->json_keyvalue("sys", cpu_info[i].cpu_times.sys);
422
2112
      writer->json_keyvalue("idle", cpu_info[i].cpu_times.idle);
423
2112
      writer->json_keyvalue("irq", cpu_info[i].cpu_times.irq);
424
2112
      writer->json_end();
425
    }
426
24
    writer->json_arrayend();
427
24
    uv_free_cpu_info(cpu_info, count);
428
  }
429
24
}
430
431
24
static void PrintNetworkInterfaceInfo(JSONWriter* writer) {
432
  uv_interface_address_t* interfaces;
433
  char ip[INET6_ADDRSTRLEN];
434
  char netmask[INET6_ADDRSTRLEN];
435
  char mac[18];
436
  int count;
437
438
24
  if (uv_interface_addresses(&interfaces, &count) == 0) {
439
24
    writer->json_arraystart("networkInterfaces");
440
441
120
    for (int i = 0; i < count; i++) {
442
96
      writer->json_start();
443
96
      writer->json_keyvalue("name", interfaces[i].name);
444
96
      writer->json_keyvalue("internal", !!interfaces[i].is_internal);
445
576
      snprintf(mac,
446
               sizeof(mac),
447
               "%02x:%02x:%02x:%02x:%02x:%02x",
448
96
               static_cast<unsigned char>(interfaces[i].phys_addr[0]),
449
96
               static_cast<unsigned char>(interfaces[i].phys_addr[1]),
450
96
               static_cast<unsigned char>(interfaces[i].phys_addr[2]),
451
96
               static_cast<unsigned char>(interfaces[i].phys_addr[3]),
452
96
               static_cast<unsigned char>(interfaces[i].phys_addr[4]),
453
96
               static_cast<unsigned char>(interfaces[i].phys_addr[5]));
454
96
      writer->json_keyvalue("mac", mac);
455
456
96
      if (interfaces[i].address.address4.sin_family == AF_INET) {
457
48
        uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
458
48
        uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
459
48
        writer->json_keyvalue("address", ip);
460
48
        writer->json_keyvalue("netmask", netmask);
461
48
        writer->json_keyvalue("family", "IPv4");
462
48
      } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
463
48
        uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
464
48
        uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
465
48
        writer->json_keyvalue("address", ip);
466
48
        writer->json_keyvalue("netmask", netmask);
467
48
        writer->json_keyvalue("family", "IPv6");
468
48
        writer->json_keyvalue("scopeid",
469
48
                              interfaces[i].address.address6.sin6_scope_id);
470
      } else {
471
        writer->json_keyvalue("family", "unknown");
472
      }
473
474
96
      writer->json_end();
475
    }
476
477
24
    writer->json_arrayend();
478
24
    uv_free_interface_addresses(interfaces, count);
479
  }
480
24
}
481
482
24
static void PrintJavaScriptErrorProperties(JSONWriter* writer,
483
                                           Isolate* isolate,
484
                                           Local<Value> error) {
485
24
  writer->json_objectstart("errorProperties");
486

46
  if (!error.IsEmpty() && error->IsObject()) {
487
19
    TryCatch try_catch(isolate);
488
19
    Local<Object> error_obj = error.As<Object>();
489
19
    Local<Context> context = error_obj->GetIsolate()->GetCurrentContext();
490
    Local<Array> keys;
491
38
    if (!error_obj->GetOwnPropertyNames(context).ToLocal(&keys)) {
492
      return writer->json_objectend();  // the end of 'errorProperties'
493
    }
494
19
    uint32_t keys_length = keys->Length();
495
31
    for (uint32_t i = 0; i < keys_length; i++) {
496
      Local<Value> key;
497

48
      if (!keys->Get(context, i).ToLocal(&key) || !key->IsString()) {
498
        continue;
499
      }
500
      Local<Value> value;
501
      Local<String> value_string;
502
36
      if (!error_obj->Get(context, key).ToLocal(&value) ||
503

36
          !value->ToString(context).ToLocal(&value_string)) {
504
        continue;
505
      }
506
12
      String::Utf8Value k(isolate, key);
507

12
      if (!strcmp(*k, "stack") || !strcmp(*k, "message")) continue;
508
12
      String::Utf8Value v(isolate, value_string);
509
12
      writer->json_keyvalue(std::string(*k, k.length()),
510
24
                            std::string(*v, v.length()));
511
    }
512
  }
513
24
  writer->json_objectend();  // the end of 'errorProperties'
514
}
515
516
23
static Maybe<std::string> ErrorToString(Isolate* isolate,
517
                                        Local<Context> context,
518
                                        Local<Value> error) {
519
23
  if (error.IsEmpty()) {
520
2
    return Nothing<std::string>();
521
  }
522
523
  MaybeLocal<String> maybe_str;
524
  // `ToString` is not available to Symbols.
525
21
  if (error->IsSymbol()) {
526
1
    maybe_str = error.As<v8::Symbol>()->ToDetailString(context);
527
20
  } else if (!error->IsObject()) {
528
1
    maybe_str = error->ToString(context);
529
19
  } else if (error->IsObject()) {
530
19
    MaybeLocal<Value> stack = error.As<Object>()->Get(
531
38
        context, node::FIXED_ONE_BYTE_STRING(isolate, "stack"));
532

57
    if (!stack.IsEmpty() && stack.ToLocalChecked()->IsString()) {
533
38
      maybe_str = stack.ToLocalChecked().As<String>();
534
    }
535
  }
536
537
  Local<String> js_str;
538
21
  if (!maybe_str.ToLocal(&js_str)) {
539
    return Nothing<std::string>();
540
  }
541
21
  String::Utf8Value sv(isolate, js_str);
542
21
  return Just<>(std::string(*sv, sv.length()));
543
}
544
545
// Report the JavaScript stack.
546
24
static void PrintJavaScriptErrorStack(JSONWriter* writer,
547
                                      Isolate* isolate,
548
                                      Local<Value> error,
549
                                      const char* trigger) {
550
48
  TryCatch try_catch(isolate);
551
48
  HandleScope scope(isolate);
552
24
  Local<Context> context = isolate->GetCurrentContext();
553
48
  std::string ss = "";
554
72
  if ((!strcmp(trigger, "FatalError")) ||
555

70
      (!strcmp(trigger, "Signal")) ||
556

70
      (!ErrorToString(isolate, context, error).To(&ss))) {
557
3
    ss = "No stack.\nUnavailable.\n";
558
  }
559
560
24
  int line = ss.find('\n');
561
24
  if (line == -1) {
562
4
    writer->json_keyvalue("message", ss);
563
  } else {
564
40
    std::string l = ss.substr(0, line);
565
20
    writer->json_keyvalue("message", l);
566
20
    writer->json_arraystart("stack");
567
20
    ss = ss.substr(line + 1);
568
20
    line = ss.find('\n');
569
133
    while (line != -1) {
570
113
      l = ss.substr(0, line);
571
113
      l.erase(l.begin(), std::find_if(l.begin(), l.end(), [](int ch) {
572
553
                return !std::iswspace(ch);
573
226
              }));
574
113
      writer->json_element(l);
575
113
      ss = ss.substr(line + 1);
576
113
      line = ss.find('\n');
577
    }
578
20
    writer->json_arrayend();
579
  }
580
24
}
581
582
// Report a native stack backtrace
583
24
static void PrintNativeStack(JSONWriter* writer) {
584
48
  auto sym_ctx = NativeSymbolDebuggingContext::New();
585
  void* frames[256];
586
24
  const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
587
24
  writer->json_arraystart("nativeStack");
588
  int i;
589
208
  for (i = 1; i < size; i++) {
590
184
    void* frame = frames[i];
591
184
    writer->json_start();
592
184
    writer->json_keyvalue("pc",
593
368
                          ValueToHexString(reinterpret_cast<uintptr_t>(frame)));
594
184
    writer->json_keyvalue("symbol", sym_ctx->LookupSymbol(frame).Display());
595
184
    writer->json_end();
596
  }
597
24
  writer->json_arrayend();
598
24
}
599
600
// Report V8 JavaScript heap information.
601
// This uses the existing V8 HeapStatistics and HeapSpaceStatistics APIs.
602
// The isolate->GetGCStatistics(&heap_stats) internal V8 API could potentially
603
// provide some more useful information - the GC history and the handle counts
604
24
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate) {
605
24
  HeapStatistics v8_heap_stats;
606
24
  isolate->GetHeapStatistics(&v8_heap_stats);
607
24
  HeapSpaceStatistics v8_heap_space_stats;
608
609
24
  writer->json_objectstart("javascriptHeap");
610
24
  writer->json_keyvalue("totalMemory", v8_heap_stats.total_heap_size());
611
24
  writer->json_keyvalue("totalCommittedMemory",
612
24
                        v8_heap_stats.total_physical_size());
613
24
  writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
614
24
  writer->json_keyvalue("availableMemory",
615
24
                        v8_heap_stats.total_available_size());
616
24
  writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
617
618
24
  writer->json_objectstart("heapSpaces");
619
  // Loop through heap spaces
620
216
  for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
621
192
    isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
622
192
    writer->json_objectstart(v8_heap_space_stats.space_name());
623
192
    writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
624
192
    writer->json_keyvalue(
625
        "committedMemory",
626
192
        v8_heap_space_stats.physical_space_size());
627
192
    writer->json_keyvalue(
628
        "capacity",
629
384
        v8_heap_space_stats.space_used_size() +
630
192
            v8_heap_space_stats.space_available_size());
631
192
    writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
632
192
    writer->json_keyvalue(
633
192
        "available", v8_heap_space_stats.space_available_size());
634
192
    writer->json_objectend();
635
  }
636
637
24
  writer->json_objectend();
638
24
  writer->json_objectend();
639
24
}
640
641
24
static void PrintResourceUsage(JSONWriter* writer) {
642
  // Get process uptime in seconds
643
  uint64_t uptime =
644
24
      (uv_hrtime() - node::per_process::node_start_time) / (NANOS_PER_SEC);
645
24
  if (uptime == 0) uptime = 1;  // avoid division by zero.
646
647
  // Process and current thread usage statistics
648
  uv_rusage_t rusage;
649
24
  writer->json_objectstart("resourceUsage");
650
24
  if (uv_getrusage(&rusage) == 0) {
651
24
    double user_cpu =
652
24
        rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
653
24
    double kernel_cpu =
654
24
        rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
655
24
    writer->json_keyvalue("userCpuSeconds", user_cpu);
656
24
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
657
24
    double cpu_abs = user_cpu + kernel_cpu;
658
24
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
659
24
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
660
24
    writer->json_keyvalue("maxRss", rusage.ru_maxrss * 1024);
661
24
    writer->json_objectstart("pageFaults");
662
24
    writer->json_keyvalue("IORequired", rusage.ru_majflt);
663
24
    writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
664
24
    writer->json_objectend();
665
24
    writer->json_objectstart("fsActivity");
666
24
    writer->json_keyvalue("reads", rusage.ru_inblock);
667
24
    writer->json_keyvalue("writes", rusage.ru_oublock);
668
24
    writer->json_objectend();
669
  }
670
24
  writer->json_objectend();
671
#ifdef RUSAGE_THREAD
672
  struct rusage stats;
673
24
  if (getrusage(RUSAGE_THREAD, &stats) == 0) {
674
24
    writer->json_objectstart("uvthreadResourceUsage");
675
24
    double user_cpu =
676
24
        stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
677
24
    double kernel_cpu =
678
24
        stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
679
24
    writer->json_keyvalue("userCpuSeconds", user_cpu);
680
24
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
681
24
    double cpu_abs = user_cpu + kernel_cpu;
682
24
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
683
24
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
684
24
    writer->json_objectstart("fsActivity");
685
24
    writer->json_keyvalue("reads", stats.ru_inblock);
686
24
    writer->json_keyvalue("writes", stats.ru_oublock);
687
24
    writer->json_objectend();
688
24
    writer->json_objectend();
689
  }
690
#endif  // RUSAGE_THREAD
691
24
}
692
693
// Report operating system information.
694
24
static void PrintSystemInformation(JSONWriter* writer) {
695
  uv_env_item_t* envitems;
696
  int envcount;
697
  int r;
698
699
24
  writer->json_objectstart("environmentVariables");
700
701
  {
702
48
    Mutex::ScopedLock lock(node::per_process::env_var_mutex);
703
24
    r = uv_os_environ(&envitems, &envcount);
704
  }
705
706
24
  if (r == 0) {
707
1752
    for (int i = 0; i < envcount; i++)
708
1728
      writer->json_keyvalue(envitems[i].name, envitems[i].value);
709
710
24
    uv_os_free_environ(envitems, envcount);
711
  }
712
713
24
  writer->json_objectend();
714
715
#ifndef _WIN32
716
  static struct {
717
    const char* description;
718
    int id;
719
  } rlimit_strings[] = {
720
    {"core_file_size_blocks", RLIMIT_CORE},
721
    {"data_seg_size_kbytes", RLIMIT_DATA},
722
    {"file_size_blocks", RLIMIT_FSIZE},
723
#if !(defined(_AIX) || defined(__sun))
724
    {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
725
#endif
726
#ifndef __sun
727
    {"max_memory_size_kbytes", RLIMIT_RSS},
728
#endif
729
    {"open_files", RLIMIT_NOFILE},
730
    {"stack_size_bytes", RLIMIT_STACK},
731
    {"cpu_time_seconds", RLIMIT_CPU},
732
#ifndef __sun
733
    {"max_user_processes", RLIMIT_NPROC},
734
#endif
735
#ifndef __OpenBSD__
736
    {"virtual_memory_kbytes", RLIMIT_AS}
737
#endif
738
  };
739
740
24
  writer->json_objectstart("userLimits");
741
  struct rlimit limit;
742
48
  std::string soft, hard;
743
744
264
  for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
745
240
    if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
746
240
      writer->json_objectstart(rlimit_strings[i].description);
747
748
240
      if (limit.rlim_cur == RLIM_INFINITY)
749
120
        writer->json_keyvalue("soft", "unlimited");
750
      else
751
120
        writer->json_keyvalue("soft", limit.rlim_cur);
752
753
240
      if (limit.rlim_max == RLIM_INFINITY)
754
168
        writer->json_keyvalue("hard", "unlimited");
755
      else
756
72
        writer->json_keyvalue("hard", limit.rlim_max);
757
758
240
      writer->json_objectend();
759
    }
760
  }
761
24
  writer->json_objectend();
762
#endif  // _WIN32
763
764
24
  PrintLoadedLibraries(writer);
765
24
}
766
767
// Report a list of loaded native libraries.
768
24
static void PrintLoadedLibraries(JSONWriter* writer) {
769
24
  writer->json_arraystart("sharedObjects");
770
  std::vector<std::string> modules =
771
48
      NativeSymbolDebuggingContext::GetLoadedLibraries();
772
195
  for (auto const& module_name : modules) writer->json_element(module_name);
773
24
  writer->json_arrayend();
774
24
}
775
776
// Obtain and report the node and subcomponent version strings.
777
24
static void PrintComponentVersions(JSONWriter* writer) {
778
48
  std::stringstream buf;
779
780
24
  writer->json_objectstart("componentVersions");
781
782
#define V(key)                                                                 \
783
  writer->json_keyvalue(#key, node::per_process::metadata.versions.key);
784
24
  NODE_VERSIONS_KEYS(V)
785
#undef V
786
787
24
  writer->json_objectend();
788
24
}
789
790
// Report runtime release information.
791
24
static void PrintRelease(JSONWriter* writer) {
792
24
  writer->json_objectstart("release");
793
24
  writer->json_keyvalue("name", node::per_process::metadata.release.name);
794
#if NODE_VERSION_IS_LTS
795
  writer->json_keyvalue("lts", node::per_process::metadata.release.lts);
796
#endif
797
798
#ifdef NODE_HAS_RELEASE_URLS
799
  writer->json_keyvalue("headersUrl",
800
                        node::per_process::metadata.release.headers_url);
801
  writer->json_keyvalue("sourceUrl",
802
                        node::per_process::metadata.release.source_url);
803
#ifdef _WIN32
804
  writer->json_keyvalue("libUrl", node::per_process::metadata.release.lib_url);
805
#endif  // _WIN32
806
#endif  // NODE_HAS_RELEASE_URLS
807
808
24
  writer->json_objectend();
809
24
}
810
811
}  // namespace report