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

48
  if (!error.IsEmpty() && error->IsObject()) {
479
20
    TryCatch try_catch(isolate);
480
20
    Local<Object> error_obj = error.As<Object>();
481
20
    Local<Context> context = error_obj->GetIsolate()->GetCurrentContext();
482
    Local<Array> keys;
483
40
    if (!error_obj->GetOwnPropertyNames(context).ToLocal(&keys)) {
484
      return writer->json_objectend();  // the end of 'errorProperties'
485
    }
486
20
    uint32_t keys_length = keys->Length();
487
33
    for (uint32_t i = 0; i < keys_length; i++) {
488
      Local<Value> key;
489

52
      if (!keys->Get(context, i).ToLocal(&key) || !key->IsString()) {
490
        continue;
491
      }
492
      Local<Value> value;
493
      Local<String> value_string;
494
39
      if (!error_obj->Get(context, key).ToLocal(&value) ||
495

39
          !value->ToString(context).ToLocal(&value_string)) {
496
        continue;
497
      }
498
13
      String::Utf8Value k(isolate, key);
499

13
      if (!strcmp(*k, "stack") || !strcmp(*k, "message")) continue;
500
13
      String::Utf8Value v(isolate, value_string);
501
13
      writer->json_keyvalue(std::string(*k, k.length()),
502
26
                            std::string(*v, v.length()));
503
    }
504
  }
505
25
  writer->json_objectend();  // the end of 'errorProperties'
506
}
507
508
24
static Maybe<std::string> ErrorToString(Isolate* isolate,
509
                                        Local<Context> context,
510
                                        Local<Value> error) {
511
24
  if (error.IsEmpty()) {
512
2
    return Nothing<std::string>();
513
  }
514
515
  MaybeLocal<String> maybe_str;
516
  // `ToString` is not available to Symbols.
517
22
  if (error->IsSymbol()) {
518
1
    maybe_str = error.As<v8::Symbol>()->ToDetailString(context);
519
21
  } else if (!error->IsObject()) {
520
1
    maybe_str = error->ToString(context);
521
20
  } else if (error->IsObject()) {
522
20
    MaybeLocal<Value> stack = error.As<Object>()->Get(
523
40
        context, FIXED_ONE_BYTE_STRING(isolate, "stack"));
524

60
    if (!stack.IsEmpty() && stack.ToLocalChecked()->IsString()) {
525
40
      maybe_str = stack.ToLocalChecked().As<String>();
526
    }
527
  }
528
529
  Local<String> js_str;
530
22
  if (!maybe_str.ToLocal(&js_str)) {
531
    return Nothing<std::string>();
532
  }
533
22
  String::Utf8Value sv(isolate, js_str);
534
22
  return Just<>(std::string(*sv, sv.length()));
535
}
536
537
// Report the JavaScript stack.
538
25
static void PrintJavaScriptErrorStack(JSONWriter* writer,
539
                                      Isolate* isolate,
540
                                      Local<Value> error,
541
                                      const char* trigger) {
542
50
  TryCatch try_catch(isolate);
543
50
  HandleScope scope(isolate);
544
25
  Local<Context> context = isolate->GetCurrentContext();
545
50
  std::string ss = "";
546
75
  if ((!strcmp(trigger, "FatalError")) ||
547

73
      (!strcmp(trigger, "Signal")) ||
548

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