GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_report.cc Lines: 401 408 98.3 %
Date: 2022-06-08 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("executableMemory",
612
24
                        v8_heap_stats.total_heap_size_executable());
613
24
  writer->json_keyvalue("totalCommittedMemory",
614
24
                        v8_heap_stats.total_physical_size());
615
24
  writer->json_keyvalue("availableMemory",
616
24
                        v8_heap_stats.total_available_size());
617
24
  writer->json_keyvalue("totalGlobalHandlesMemory",
618
24
                        v8_heap_stats.total_global_handles_size());
619
24
  writer->json_keyvalue("usedGlobalHandlesMemory",
620
24
                        v8_heap_stats.used_global_handles_size());
621
24
  writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
622
24
  writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
623
24
  writer->json_keyvalue("mallocedMemory", v8_heap_stats.malloced_memory());
624
24
  writer->json_keyvalue("externalMemory", v8_heap_stats.external_memory());
625
24
  writer->json_keyvalue("peakMallocedMemory",
626
24
                        v8_heap_stats.peak_malloced_memory());
627
24
  writer->json_keyvalue("nativeContextCount",
628
24
                        v8_heap_stats.number_of_native_contexts());
629
24
  writer->json_keyvalue("detachedContextCount",
630
24
                        v8_heap_stats.number_of_detached_contexts());
631
24
  writer->json_keyvalue("doesZapGarbage", v8_heap_stats.does_zap_garbage());
632
633
24
  writer->json_objectstart("heapSpaces");
634
  // Loop through heap spaces
635
216
  for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
636
192
    isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
637
192
    writer->json_objectstart(v8_heap_space_stats.space_name());
638
192
    writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
639
192
    writer->json_keyvalue(
640
        "committedMemory",
641
192
        v8_heap_space_stats.physical_space_size());
642
192
    writer->json_keyvalue(
643
        "capacity",
644
384
        v8_heap_space_stats.space_used_size() +
645
192
            v8_heap_space_stats.space_available_size());
646
192
    writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
647
192
    writer->json_keyvalue(
648
192
        "available", v8_heap_space_stats.space_available_size());
649
192
    writer->json_objectend();
650
  }
651
652
24
  writer->json_objectend();
653
24
  writer->json_objectend();
654
24
}
655
656
24
static void PrintResourceUsage(JSONWriter* writer) {
657
  // Get process uptime in seconds
658
  uint64_t uptime =
659
24
      (uv_hrtime() - node::per_process::node_start_time) / (NANOS_PER_SEC);
660
24
  if (uptime == 0) uptime = 1;  // avoid division by zero.
661
662
  // Process and current thread usage statistics
663
  uv_rusage_t rusage;
664
24
  writer->json_objectstart("resourceUsage");
665
24
  if (uv_getrusage(&rusage) == 0) {
666
24
    double user_cpu =
667
24
        rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
668
24
    double kernel_cpu =
669
24
        rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
670
24
    writer->json_keyvalue("userCpuSeconds", user_cpu);
671
24
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
672
24
    double cpu_abs = user_cpu + kernel_cpu;
673
24
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
674
24
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
675
24
    writer->json_keyvalue("maxRss", rusage.ru_maxrss * 1024);
676
24
    writer->json_objectstart("pageFaults");
677
24
    writer->json_keyvalue("IORequired", rusage.ru_majflt);
678
24
    writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
679
24
    writer->json_objectend();
680
24
    writer->json_objectstart("fsActivity");
681
24
    writer->json_keyvalue("reads", rusage.ru_inblock);
682
24
    writer->json_keyvalue("writes", rusage.ru_oublock);
683
24
    writer->json_objectend();
684
  }
685
24
  writer->json_objectend();
686
#ifdef RUSAGE_THREAD
687
  struct rusage stats;
688
24
  if (getrusage(RUSAGE_THREAD, &stats) == 0) {
689
24
    writer->json_objectstart("uvthreadResourceUsage");
690
24
    double user_cpu =
691
24
        stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
692
24
    double kernel_cpu =
693
24
        stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
694
24
    writer->json_keyvalue("userCpuSeconds", user_cpu);
695
24
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
696
24
    double cpu_abs = user_cpu + kernel_cpu;
697
24
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
698
24
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
699
24
    writer->json_objectstart("fsActivity");
700
24
    writer->json_keyvalue("reads", stats.ru_inblock);
701
24
    writer->json_keyvalue("writes", stats.ru_oublock);
702
24
    writer->json_objectend();
703
24
    writer->json_objectend();
704
  }
705
#endif  // RUSAGE_THREAD
706
24
}
707
708
// Report operating system information.
709
24
static void PrintSystemInformation(JSONWriter* writer) {
710
  uv_env_item_t* envitems;
711
  int envcount;
712
  int r;
713
714
24
  writer->json_objectstart("environmentVariables");
715
716
  {
717
48
    Mutex::ScopedLock lock(node::per_process::env_var_mutex);
718
24
    r = uv_os_environ(&envitems, &envcount);
719
  }
720
721
24
  if (r == 0) {
722
1752
    for (int i = 0; i < envcount; i++)
723
1728
      writer->json_keyvalue(envitems[i].name, envitems[i].value);
724
725
24
    uv_os_free_environ(envitems, envcount);
726
  }
727
728
24
  writer->json_objectend();
729
730
#ifndef _WIN32
731
  static struct {
732
    const char* description;
733
    int id;
734
  } rlimit_strings[] = {
735
    {"core_file_size_blocks", RLIMIT_CORE},
736
    {"data_seg_size_kbytes", RLIMIT_DATA},
737
    {"file_size_blocks", RLIMIT_FSIZE},
738
#if !(defined(_AIX) || defined(__sun))
739
    {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
740
#endif
741
#ifndef __sun
742
    {"max_memory_size_kbytes", RLIMIT_RSS},
743
#endif
744
    {"open_files", RLIMIT_NOFILE},
745
    {"stack_size_bytes", RLIMIT_STACK},
746
    {"cpu_time_seconds", RLIMIT_CPU},
747
#ifndef __sun
748
    {"max_user_processes", RLIMIT_NPROC},
749
#endif
750
#ifndef __OpenBSD__
751
    {"virtual_memory_kbytes", RLIMIT_AS}
752
#endif
753
  };
754
755
24
  writer->json_objectstart("userLimits");
756
  struct rlimit limit;
757
48
  std::string soft, hard;
758
759
264
  for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
760
240
    if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
761
240
      writer->json_objectstart(rlimit_strings[i].description);
762
763
240
      if (limit.rlim_cur == RLIM_INFINITY)
764
120
        writer->json_keyvalue("soft", "unlimited");
765
      else
766
120
        writer->json_keyvalue("soft", limit.rlim_cur);
767
768
240
      if (limit.rlim_max == RLIM_INFINITY)
769
168
        writer->json_keyvalue("hard", "unlimited");
770
      else
771
72
        writer->json_keyvalue("hard", limit.rlim_max);
772
773
240
      writer->json_objectend();
774
    }
775
  }
776
24
  writer->json_objectend();
777
#endif  // _WIN32
778
779
24
  PrintLoadedLibraries(writer);
780
24
}
781
782
// Report a list of loaded native libraries.
783
24
static void PrintLoadedLibraries(JSONWriter* writer) {
784
24
  writer->json_arraystart("sharedObjects");
785
  std::vector<std::string> modules =
786
48
      NativeSymbolDebuggingContext::GetLoadedLibraries();
787
195
  for (auto const& module_name : modules) writer->json_element(module_name);
788
24
  writer->json_arrayend();
789
24
}
790
791
// Obtain and report the node and subcomponent version strings.
792
24
static void PrintComponentVersions(JSONWriter* writer) {
793
48
  std::stringstream buf;
794
795
24
  writer->json_objectstart("componentVersions");
796
797
#define V(key)                                                                 \
798
  writer->json_keyvalue(#key, node::per_process::metadata.versions.key);
799
24
  NODE_VERSIONS_KEYS(V)
800
#undef V
801
802
24
  writer->json_objectend();
803
24
}
804
805
// Report runtime release information.
806
24
static void PrintRelease(JSONWriter* writer) {
807
24
  writer->json_objectstart("release");
808
24
  writer->json_keyvalue("name", node::per_process::metadata.release.name);
809
#if NODE_VERSION_IS_LTS
810
  writer->json_keyvalue("lts", node::per_process::metadata.release.lts);
811
#endif
812
813
#ifdef NODE_HAS_RELEASE_URLS
814
  writer->json_keyvalue("headersUrl",
815
                        node::per_process::metadata.release.headers_url);
816
  writer->json_keyvalue("sourceUrl",
817
                        node::per_process::metadata.release.source_url);
818
#ifdef _WIN32
819
  writer->json_keyvalue("libUrl", node::per_process::metadata.release.lib_url);
820
#endif  // _WIN32
821
#endif  // NODE_HAS_RELEASE_URLS
822
823
24
  writer->json_objectend();
824
24
}
825
826
}  // namespace report