GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_report.cc Lines: 361 367 98.4 %
Date: 2020-09-03 22:13:26 Branches: 94 130 72.3 %

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

31
    for (uint32_t i = 0; i < keys_length; i++) {
484
      Local<Value> key;
485

48
      if (!keys->Get(context, i).ToLocal(&key) || !key->IsString()) {
486
        continue;
487
      }
488
      Local<Value> value;
489
      Local<String> value_string;
490

48
      if (!error->Get(context, key).ToLocal(&value) ||
491
36
          !value->ToString(context).ToLocal(&value_string)) {
492
        continue;
493
      }
494
24
      String::Utf8Value k(isolate, key);
495

12
      if (!strcmp(*k, "stack") || !strcmp(*k, "message")) continue;
496
24
      String::Utf8Value v(isolate, value_string);
497
24
      writer->json_keyvalue(std::string(*k, k.length()),
498
36
                            std::string(*v, v.length()));
499
    }
500
  }
501
22
  writer->json_objectend();  // the end of 'errorProperties'
502
}
503
504
// Report the JavaScript stack.
505
22
static void PrintJavaScriptErrorStack(JSONWriter* writer,
506
                                 Isolate* isolate,
507
                                 Local<Object> error,
508
                                 const char* trigger) {
509
  Local<Value> stackstr;
510
44
  std::string ss = "";
511
44
  TryCatch try_catch(isolate);
512

44
  if ((!strcmp(trigger, "FatalError")) ||
513
22
      (!strcmp(trigger, "Signal"))) {
514
1
    ss = "No stack.\nUnavailable.\n";
515

61
  } else if (!error.IsEmpty() &&
516
             error
517
40
                 ->Get(isolate->GetCurrentContext(),
518
                       node::FIXED_ONE_BYTE_STRING(isolate,
519
78
                                                   "stack"))
520
19
                 .ToLocal(&stackstr)) {
521
38
    String::Utf8Value sv(isolate, stackstr);
522
19
    ss = std::string(*sv, sv.length());
523
  }
524
22
  int line = ss.find('\n');
525
22
  if (line == -1) {
526
4
    writer->json_keyvalue("message", ss);
527
  } else {
528
36
    std::string l = ss.substr(0, line);
529
18
    writer->json_keyvalue("message", l);
530
18
    writer->json_arraystart("stack");
531
18
    ss = ss.substr(line + 1);
532
18
    line = ss.find('\n');
533
244
    while (line != -1) {
534
113
      l = ss.substr(0, line);
535
561
      l.erase(l.begin(), std::find_if(l.begin(), l.end(), [](int ch) {
536
561
                return !std::iswspace(ch);
537
674
              }));
538
113
      writer->json_element(l);
539
113
      ss = ss.substr(line + 1);
540
113
      line = ss.find('\n');
541
    }
542
18
    writer->json_arrayend();
543
  }
544
22
}
545
546
// Report a native stack backtrace
547
22
static void PrintNativeStack(JSONWriter* writer) {
548
44
  auto sym_ctx = NativeSymbolDebuggingContext::New();
549
  void* frames[256];
550
22
  const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
551
22
  writer->json_arraystart("nativeStack");
552
  int i;
553
191
  for (i = 1; i < size; i++) {
554
169
    void* frame = frames[i];
555
169
    writer->json_start();
556
    writer->json_keyvalue("pc",
557
169
                          ValueToHexString(reinterpret_cast<uintptr_t>(frame)));
558
169
    writer->json_keyvalue("symbol", sym_ctx->LookupSymbol(frame).Display());
559
169
    writer->json_end();
560
  }
561
22
  writer->json_arrayend();
562
22
}
563
564
// Report V8 JavaScript heap information.
565
// This uses the existing V8 HeapStatistics and HeapSpaceStatistics APIs.
566
// The isolate->GetGCStatistics(&heap_stats) internal V8 API could potentially
567
// provide some more useful information - the GC history and the handle counts
568
22
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate) {
569
22
  HeapStatistics v8_heap_stats;
570
22
  isolate->GetHeapStatistics(&v8_heap_stats);
571
22
  HeapSpaceStatistics v8_heap_space_stats;
572
573
22
  writer->json_objectstart("javascriptHeap");
574
22
  writer->json_keyvalue("totalMemory", v8_heap_stats.total_heap_size());
575
  writer->json_keyvalue("totalCommittedMemory",
576
22
                        v8_heap_stats.total_physical_size());
577
22
  writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
578
  writer->json_keyvalue("availableMemory",
579
22
                        v8_heap_stats.total_available_size());
580
22
  writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
581
582
22
  writer->json_objectstart("heapSpaces");
583
  // Loop through heap spaces
584
198
  for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
585
176
    isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
586
176
    writer->json_objectstart(v8_heap_space_stats.space_name());
587
176
    writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
588
    writer->json_keyvalue(
589
        "committedMemory",
590
176
        v8_heap_space_stats.physical_space_size());
591
    writer->json_keyvalue(
592
        "capacity",
593
528
        v8_heap_space_stats.space_used_size() +
594
352
            v8_heap_space_stats.space_available_size());
595
176
    writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
596
    writer->json_keyvalue(
597
176
        "available", v8_heap_space_stats.space_available_size());
598
176
    writer->json_objectend();
599
  }
600
601
22
  writer->json_objectend();
602
22
  writer->json_objectend();
603
22
}
604
605
22
static void PrintResourceUsage(JSONWriter* writer) {
606
  // Get process uptime in seconds
607
  uint64_t uptime =
608
22
      (uv_hrtime() - node::per_process::node_start_time) / (NANOS_PER_SEC);
609
22
  if (uptime == 0) uptime = 1;  // avoid division by zero.
610
611
  // Process and current thread usage statistics
612
  uv_rusage_t rusage;
613
22
  writer->json_objectstart("resourceUsage");
614
22
  if (uv_getrusage(&rusage) == 0) {
615
    double user_cpu =
616
22
        rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
617
    double kernel_cpu =
618
22
        rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
619
22
    writer->json_keyvalue("userCpuSeconds", user_cpu);
620
22
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
621
22
    double cpu_abs = user_cpu + kernel_cpu;
622
22
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
623
22
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
624
22
    writer->json_keyvalue("maxRss", rusage.ru_maxrss * 1024);
625
22
    writer->json_objectstart("pageFaults");
626
22
    writer->json_keyvalue("IORequired", rusage.ru_majflt);
627
22
    writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
628
22
    writer->json_objectend();
629
22
    writer->json_objectstart("fsActivity");
630
22
    writer->json_keyvalue("reads", rusage.ru_inblock);
631
22
    writer->json_keyvalue("writes", rusage.ru_oublock);
632
22
    writer->json_objectend();
633
  }
634
22
  writer->json_objectend();
635
#ifdef RUSAGE_THREAD
636
  struct rusage stats;
637
22
  if (getrusage(RUSAGE_THREAD, &stats) == 0) {
638
22
    writer->json_objectstart("uvthreadResourceUsage");
639
    double user_cpu =
640
22
        stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
641
    double kernel_cpu =
642
22
        stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
643
22
    writer->json_keyvalue("userCpuSeconds", user_cpu);
644
22
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
645
22
    double cpu_abs = user_cpu + kernel_cpu;
646
22
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
647
22
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
648
22
    writer->json_objectstart("fsActivity");
649
22
    writer->json_keyvalue("reads", stats.ru_inblock);
650
22
    writer->json_keyvalue("writes", stats.ru_oublock);
651
22
    writer->json_objectend();
652
22
    writer->json_objectend();
653
  }
654
#endif
655
22
}
656
657
// Report operating system information.
658
22
static void PrintSystemInformation(JSONWriter* writer) {
659
  uv_env_item_t* envitems;
660
  int envcount;
661
  int r;
662
663
22
  writer->json_objectstart("environmentVariables");
664
665
  {
666
44
    Mutex::ScopedLock lock(node::per_process::env_var_mutex);
667
22
    r = uv_os_environ(&envitems, &envcount);
668
  }
669
670
22
  if (r == 0) {
671
1584
    for (int i = 0; i < envcount; i++)
672
1562
      writer->json_keyvalue(envitems[i].name, envitems[i].value);
673
674
22
    uv_os_free_environ(envitems, envcount);
675
  }
676
677
22
  writer->json_objectend();
678
679
#ifndef _WIN32
680
  static struct {
681
    const char* description;
682
    int id;
683
  } rlimit_strings[] = {
684
    {"core_file_size_blocks", RLIMIT_CORE},
685
    {"data_seg_size_kbytes", RLIMIT_DATA},
686
    {"file_size_blocks", RLIMIT_FSIZE},
687
#if !(defined(_AIX) || defined(__sun))
688
    {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
689
#endif
690
#ifndef __sun
691
    {"max_memory_size_kbytes", RLIMIT_RSS},
692
#endif
693
    {"open_files", RLIMIT_NOFILE},
694
    {"stack_size_bytes", RLIMIT_STACK},
695
    {"cpu_time_seconds", RLIMIT_CPU},
696
#ifndef __sun
697
    {"max_user_processes", RLIMIT_NPROC},
698
#endif
699
#ifndef __OpenBSD__
700
    {"virtual_memory_kbytes", RLIMIT_AS}
701
#endif
702
  };
703
704
22
  writer->json_objectstart("userLimits");
705
  struct rlimit limit;
706
44
  std::string soft, hard;
707
708
242
  for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
709
220
    if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
710
220
      writer->json_objectstart(rlimit_strings[i].description);
711
712
220
      if (limit.rlim_cur == RLIM_INFINITY)
713
132
        writer->json_keyvalue("soft", "unlimited");
714
      else
715
88
        writer->json_keyvalue("soft", limit.rlim_cur);
716
717
220
      if (limit.rlim_max == RLIM_INFINITY)
718
154
        writer->json_keyvalue("hard", "unlimited");
719
      else
720
66
        writer->json_keyvalue("hard", limit.rlim_max);
721
722
220
      writer->json_objectend();
723
    }
724
  }
725
22
  writer->json_objectend();
726
#endif  // _WIN32
727
728
22
  PrintLoadedLibraries(writer);
729
22
}
730
731
// Report a list of loaded native libraries.
732
22
static void PrintLoadedLibraries(JSONWriter* writer) {
733
22
  writer->json_arraystart("sharedObjects");
734
  std::vector<std::string> modules =
735
44
      NativeSymbolDebuggingContext::GetLoadedLibraries();
736
22
  for (auto const& module_name : modules) writer->json_element(module_name);
737
22
  writer->json_arrayend();
738
22
}
739
740
// Obtain and report the node and subcomponent version strings.
741
22
static void PrintComponentVersions(JSONWriter* writer) {
742
44
  std::stringstream buf;
743
744
22
  writer->json_objectstart("componentVersions");
745
746
#define V(key)                                                                 \
747
  writer->json_keyvalue(#key, node::per_process::metadata.versions.key);
748
22
  NODE_VERSIONS_KEYS(V)
749
#undef V
750
751
22
  writer->json_objectend();
752
22
}
753
754
// Report runtime release information.
755
22
static void PrintRelease(JSONWriter* writer) {
756
22
  writer->json_objectstart("release");
757
22
  writer->json_keyvalue("name", node::per_process::metadata.release.name);
758
#if NODE_VERSION_IS_LTS
759
  writer->json_keyvalue("lts", node::per_process::metadata.release.lts);
760
#endif
761
762
#ifdef NODE_HAS_RELEASE_URLS
763
  writer->json_keyvalue("headersUrl",
764
                        node::per_process::metadata.release.headers_url);
765
  writer->json_keyvalue("sourceUrl",
766
                        node::per_process::metadata.release.source_url);
767
#ifdef _WIN32
768
  writer->json_keyvalue("libUrl", node::per_process::metadata.release.lib_url);
769
#endif  // _WIN32
770
#endif  // NODE_HAS_RELEASE_URLS
771
772
22
  writer->json_objectend();
773
22
}
774
775

13416
}  // namespace report