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: 1 357 0.3 %
Date: 2021-02-19 04:08:54 Branches: 2 130 1.5 %

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::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
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
  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
  if (!name.empty()) {
93
    // Filename was specified as API parameter.
94
    filename = name;
95
  } else {
96
    std::string report_filename;
97
    {
98
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
99
      report_filename = per_process::cli_options->report_filename;
100
    }
101
    if (report_filename.length() > 0) {
102
      // File name was supplied via start-up option.
103
      filename = report_filename;
104
    } else {
105
      filename = *DiagnosticFilename(env != nullptr ? env->thread_id() : 0,
106
          "report", "json");
107
    }
108
  }
109
110
  // Open the report file stream for writing. Supports stdout/err,
111
  // user-specified or (default) generated name
112
  std::ofstream outfile;
113
  std::ostream* outstream;
114
  if (filename == "stdout") {
115
    outstream = &std::cout;
116
  } else if (filename == "stderr") {
117
    outstream = &std::cerr;
118
  } else {
119
    std::string report_directory;
120
    {
121
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
122
      report_directory = per_process::cli_options->report_directory;
123
    }
124
    // Regular file. Append filename to directory path if one was specified
125
    if (report_directory.length() > 0) {
126
      std::string pathname = report_directory;
127
      pathname += node::kPathSeparator;
128
      pathname += filename;
129
      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
    if (!outfile.is_open()) {
135
      std::cerr << "\nFailed to open Node.js report file: " << filename;
136
137
      if (report_directory.length() > 0)
138
        std::cerr << " directory: " << report_directory;
139
140
      std::cerr << " (errno: " << errno << ")" << std::endl;
141
      return "";
142
    }
143
    outstream = &outfile;
144
    std::cerr << "\nWriting Node.js report to file: " << filename;
145
  }
146
147
  bool compact;
148
  {
149
    Mutex::ScopedLock lock(per_process::cli_options_mutex);
150
    compact = per_process::cli_options->report_compact;
151
  }
152
  WriteNodeReport(isolate, env, message, trigger, filename, *outstream,
153
                  error, compact);
154
155
  // Do not close stdout/stderr, only close files we opened.
156
  if (outfile.is_open()) {
157
    outfile.close();
158
  }
159
160
  // Do not mix JSON and free-form text on stderr.
161
  if (filename != "stderr") {
162
    std::cerr << "\nNode.js report completed" << std::endl;
163
  }
164
  return filename;
165
}
166
167
// External function to trigger a report, writing to a supplied stream.
168
void GetNodeReport(Isolate* isolate,
169
                   Environment* env,
170
                   const char* message,
171
                   const char* trigger,
172
                   Local<Object> error,
173
                   std::ostream& out) {
174
  WriteNodeReport(isolate, env, message, trigger, "", out, error, false);
175
}
176
177
// Internal function to coordinate and write the various
178
// sections of the report to the supplied stream
179
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
  DiagnosticFilename::LocalTime(&tm_struct);
190
  uv_pid_t pid = uv_os_getpid();
191
192
  // Save formatting for output stream.
193
  std::ios old_state(nullptr);
194
  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
  JSONWriter writer(out, compact);
200
  writer.json_start();
201
  writer.json_objectstart("header");
202
  writer.json_keyvalue("reportVersion", NODE_REPORT_VERSION);
203
  writer.json_keyvalue("event", message);
204
  writer.json_keyvalue("trigger", trigger);
205
  if (!filename.empty())
206
    writer.json_keyvalue("filename", filename);
207
  else
208
    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
  snprintf(timebuf,
225
           sizeof(timebuf),
226
           "%4d-%02d-%02dT%02d:%02d:%02dZ",
227
           tm_struct.tm_year + 1900,
228
           tm_struct.tm_mon + 1,
229
           tm_struct.tm_mday,
230
           tm_struct.tm_hour,
231
           tm_struct.tm_min,
232
           tm_struct.tm_sec);
233
  writer.json_keyvalue("dumpEventTime", timebuf);
234
#endif
235
236
  uv_timeval64_t ts;
237
  if (uv_gettimeofday(&ts) == 0) {
238
    writer.json_keyvalue("dumpEventTimeStamp",
239
                         std::to_string(ts.tv_sec * 1000 + ts.tv_usec / 1000));
240
  }
241
242
  // Report native process ID
243
  writer.json_keyvalue("processId", pid);
244
  if (env != nullptr)
245
    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
    size_t cwd_size = sizeof(buf);
253
    if (uv_cwd(buf, &cwd_size) == 0)
254
      writer.json_keyvalue("cwd", buf);
255
  }
256
257
  // Report out the command line.
258
  if (!node::per_process::cli_options->cmdline.empty()) {
259
    writer.json_arraystart("commandLine");
260
    for (const std::string& arg : node::per_process::cli_options->cmdline) {
261
      writer.json_element(arg);
262
    }
263
    writer.json_arrayend();
264
  }
265
266
  // Report Node.js and OS version information
267
  PrintVersionInformation(&writer);
268
  writer.json_objectend();
269
270
  writer.json_objectstart("javascriptStack");
271
  // Report summary JavaScript error stack backtrace
272
  PrintJavaScriptErrorStack(&writer, isolate, error, trigger);
273
274
  // Report summary JavaScript error properties backtrace
275
  PrintJavaScriptErrorProperties(&writer, isolate, error);
276
  writer.json_objectend();  // the end of 'javascriptStack'
277
278
  // Report native stack backtrace
279
  PrintNativeStack(&writer);
280
281
  // Report V8 Heap and Garbage Collector information
282
  PrintGCStatistics(&writer, isolate);
283
284
  // Report OS and current thread resource usage
285
  PrintResourceUsage(&writer);
286
287
  writer.json_arraystart("libuv");
288
  if (env != nullptr) {
289
    uv_walk(env->event_loop(), WalkHandle, static_cast<void*>(&writer));
290
291
    writer.json_start();
292
    writer.json_keyvalue("type", "loop");
293
    writer.json_keyvalue("is_active",
294
        static_cast<bool>(uv_loop_alive(env->event_loop())));
295
    writer.json_keyvalue("address",
296
        ValueToHexString(reinterpret_cast<int64_t>(env->event_loop())));
297
298
    // Report Event loop idle time
299
    uint64_t idle_time = uv_metrics_idle_time(env->event_loop());
300
    writer.json_keyvalue("loopIdleTimeSeconds", 1.0 * idle_time / 1e9);
301
    writer.json_end();
302
  }
303
304
  writer.json_arrayend();
305
306
  writer.json_arraystart("workers");
307
  if (env != nullptr) {
308
    Mutex workers_mutex;
309
    ConditionVariable notify;
310
    std::vector<std::string> worker_infos;
311
    size_t expected_results = 0;
312
313
    env->ForEachWorker([&](Worker* w) {
314
      expected_results += w->RequestInterrupt([&](Environment* env) {
315
        std::ostringstream os;
316
317
        GetNodeReport(env->isolate(),
318
                      env,
319
                      "Worker thread subreport",
320
                      trigger,
321
                      Local<Object>(),
322
                      os);
323
324
        Mutex::ScopedLock lock(workers_mutex);
325
        worker_infos.emplace_back(os.str());
326
        notify.Signal(lock);
327
      });
328
    });
329
330
    Mutex::ScopedLock lock(workers_mutex);
331
    worker_infos.reserve(expected_results);
332
    while (worker_infos.size() < expected_results)
333
      notify.Wait(lock);
334
    for (const std::string& worker_info : worker_infos)
335
      writer.json_element(JSONWriter::ForeignJSON { worker_info });
336
  }
337
  writer.json_arrayend();
338
339
  // Report operating system information
340
  PrintSystemInformation(&writer);
341
342
  writer.json_objectend();
343
344
  // Restore output stream formatting.
345
  out.copyfmt(old_state);
346
}
347
348
// Report Node.js version, OS version and machine information.
349
static void PrintVersionInformation(JSONWriter* writer) {
350
  std::ostringstream buf;
351
  // Report Node version
352
  buf << "v" << NODE_VERSION_STRING;
353
  writer->json_keyvalue("nodejsVersion", buf.str());
354
  buf.str("");
355
356
#ifndef _WIN32
357
  // Report compiler and runtime glibc versions where possible.
358
  const char* (*libc_version)();
359
  *(reinterpret_cast<void**>(&libc_version)) =
360
      dlsym(RTLD_DEFAULT, "gnu_get_libc_version");
361
  if (libc_version != nullptr)
362
    writer->json_keyvalue("glibcVersionRuntime", (*libc_version)());
363
#endif /* _WIN32 */
364
365
#ifdef __GLIBC__
366
  buf << __GLIBC__ << "." << __GLIBC_MINOR__;
367
  writer->json_keyvalue("glibcVersionCompiler", buf.str());
368
  buf.str("");
369
#endif
370
371
  // Report Process word size
372
  writer->json_keyvalue("wordSize", sizeof(void*) * 8);
373
  writer->json_keyvalue("arch", node::per_process::metadata.arch);
374
  writer->json_keyvalue("platform", node::per_process::metadata.platform);
375
376
  // Report deps component versions
377
  PrintComponentVersions(writer);
378
379
  // Report release metadata.
380
  PrintRelease(writer);
381
382
  // Report operating system and machine information
383
  uv_utsname_t os_info;
384
385
  if (uv_os_uname(&os_info) == 0) {
386
    writer->json_keyvalue("osName", os_info.sysname);
387
    writer->json_keyvalue("osRelease", os_info.release);
388
    writer->json_keyvalue("osVersion", os_info.version);
389
    writer->json_keyvalue("osMachine", os_info.machine);
390
  }
391
392
  PrintCpuInfo(writer);
393
  PrintNetworkInterfaceInfo(writer);
394
395
  char host[UV_MAXHOSTNAMESIZE];
396
  size_t host_size = sizeof(host);
397
398
  if (uv_os_gethostname(host, &host_size) == 0)
399
    writer->json_keyvalue("host", host);
400
}
401
402
// Report CPU info
403
static void PrintCpuInfo(JSONWriter* writer) {
404
  uv_cpu_info_t* cpu_info;
405
  int count;
406
  if (uv_cpu_info(&cpu_info, &count) == 0) {
407
    writer->json_arraystart("cpus");
408
    for (int i = 0; i < count; i++) {
409
      writer->json_start();
410
      writer->json_keyvalue("model", cpu_info[i].model);
411
      writer->json_keyvalue("speed", cpu_info[i].speed);
412
      writer->json_keyvalue("user", cpu_info[i].cpu_times.user);
413
      writer->json_keyvalue("nice", cpu_info[i].cpu_times.nice);
414
      writer->json_keyvalue("sys", cpu_info[i].cpu_times.sys);
415
      writer->json_keyvalue("idle", cpu_info[i].cpu_times.idle);
416
      writer->json_keyvalue("irq", cpu_info[i].cpu_times.irq);
417
      writer->json_end();
418
    }
419
    writer->json_arrayend();
420
    uv_free_cpu_info(cpu_info, count);
421
  }
422
}
423
424
static void PrintNetworkInterfaceInfo(JSONWriter* writer) {
425
  uv_interface_address_t* interfaces;
426
  char ip[INET6_ADDRSTRLEN];
427
  char netmask[INET6_ADDRSTRLEN];
428
  char mac[18];
429
  int count;
430
431
  if (uv_interface_addresses(&interfaces, &count) == 0) {
432
    writer->json_arraystart("networkInterfaces");
433
434
    for (int i = 0; i < count; i++) {
435
      writer->json_start();
436
      writer->json_keyvalue("name", interfaces[i].name);
437
      writer->json_keyvalue("internal", !!interfaces[i].is_internal);
438
      snprintf(mac,
439
               sizeof(mac),
440
               "%02x:%02x:%02x:%02x:%02x:%02x",
441
               static_cast<unsigned char>(interfaces[i].phys_addr[0]),
442
               static_cast<unsigned char>(interfaces[i].phys_addr[1]),
443
               static_cast<unsigned char>(interfaces[i].phys_addr[2]),
444
               static_cast<unsigned char>(interfaces[i].phys_addr[3]),
445
               static_cast<unsigned char>(interfaces[i].phys_addr[4]),
446
               static_cast<unsigned char>(interfaces[i].phys_addr[5]));
447
      writer->json_keyvalue("mac", mac);
448
449
      if (interfaces[i].address.address4.sin_family == AF_INET) {
450
        uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
451
        uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
452
        writer->json_keyvalue("address", ip);
453
        writer->json_keyvalue("netmask", netmask);
454
        writer->json_keyvalue("family", "IPv4");
455
      } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
456
        uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
457
        uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
458
        writer->json_keyvalue("address", ip);
459
        writer->json_keyvalue("netmask", netmask);
460
        writer->json_keyvalue("family", "IPv6");
461
        writer->json_keyvalue("scopeid",
462
                              interfaces[i].address.address6.sin6_scope_id);
463
      } else {
464
        writer->json_keyvalue("family", "unknown");
465
      }
466
467
      writer->json_end();
468
    }
469
470
    writer->json_arrayend();
471
    uv_free_interface_addresses(interfaces, count);
472
  }
473
}
474
475
static void PrintJavaScriptErrorProperties(JSONWriter* writer,
476
                                           Isolate* isolate,
477
                                           Local<Object> error) {
478
  writer->json_objectstart("errorProperties");
479
  if (!error.IsEmpty()) {
480
    TryCatch try_catch(isolate);
481
    Local<Context> context = error->GetIsolate()->GetCurrentContext();
482
    Local<Array> keys;
483
    if (!error->GetOwnPropertyNames(context).ToLocal(&keys)) {
484
      return writer->json_objectend();  // the end of 'errorProperties'
485
    }
486
    uint32_t keys_length = keys->Length();
487
    for (uint32_t i = 0; i < keys_length; i++) {
488
      Local<Value> key;
489
      if (!keys->Get(context, i).ToLocal(&key) || !key->IsString()) {
490
        continue;
491
      }
492
      Local<Value> value;
493
      Local<String> value_string;
494
      if (!error->Get(context, key).ToLocal(&value) ||
495
          !value->ToString(context).ToLocal(&value_string)) {
496
        continue;
497
      }
498
      String::Utf8Value k(isolate, key);
499
      if (!strcmp(*k, "stack") || !strcmp(*k, "message")) continue;
500
      String::Utf8Value v(isolate, value_string);
501
      writer->json_keyvalue(std::string(*k, k.length()),
502
                            std::string(*v, v.length()));
503
    }
504
  }
505
  writer->json_objectend();  // the end of 'errorProperties'
506
}
507
508
// Report the JavaScript stack.
509
static void PrintJavaScriptErrorStack(JSONWriter* writer,
510
                                 Isolate* isolate,
511
                                 Local<Object> error,
512
                                 const char* trigger) {
513
  Local<Value> stackstr;
514
  std::string ss = "";
515
  TryCatch try_catch(isolate);
516
  if ((!strcmp(trigger, "FatalError")) ||
517
      (!strcmp(trigger, "Signal"))) {
518
    ss = "No stack.\nUnavailable.\n";
519
  } else if (!error.IsEmpty() &&
520
             error
521
                 ->Get(isolate->GetCurrentContext(),
522
                       node::FIXED_ONE_BYTE_STRING(isolate,
523
                                                   "stack"))
524
                 .ToLocal(&stackstr)) {
525
    String::Utf8Value sv(isolate, stackstr);
526
    ss = std::string(*sv, sv.length());
527
  }
528
  int line = ss.find('\n');
529
  if (line == -1) {
530
    writer->json_keyvalue("message", ss);
531
  } else {
532
    std::string l = ss.substr(0, line);
533
    writer->json_keyvalue("message", l);
534
    writer->json_arraystart("stack");
535
    ss = ss.substr(line + 1);
536
    line = ss.find('\n');
537
    while (line != -1) {
538
      l = ss.substr(0, line);
539
      l.erase(l.begin(), std::find_if(l.begin(), l.end(), [](int ch) {
540
                return !std::iswspace(ch);
541
              }));
542
      writer->json_element(l);
543
      ss = ss.substr(line + 1);
544
      line = ss.find('\n');
545
    }
546
    writer->json_arrayend();
547
  }
548
}
549
550
// Report a native stack backtrace
551
static void PrintNativeStack(JSONWriter* writer) {
552
  auto sym_ctx = NativeSymbolDebuggingContext::New();
553
  void* frames[256];
554
  const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
555
  writer->json_arraystart("nativeStack");
556
  int i;
557
  for (i = 1; i < size; i++) {
558
    void* frame = frames[i];
559
    writer->json_start();
560
    writer->json_keyvalue("pc",
561
                          ValueToHexString(reinterpret_cast<uintptr_t>(frame)));
562
    writer->json_keyvalue("symbol", sym_ctx->LookupSymbol(frame).Display());
563
    writer->json_end();
564
  }
565
  writer->json_arrayend();
566
}
567
568
// Report V8 JavaScript heap information.
569
// This uses the existing V8 HeapStatistics and HeapSpaceStatistics APIs.
570
// The isolate->GetGCStatistics(&heap_stats) internal V8 API could potentially
571
// provide some more useful information - the GC history and the handle counts
572
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate) {
573
  HeapStatistics v8_heap_stats;
574
  isolate->GetHeapStatistics(&v8_heap_stats);
575
  HeapSpaceStatistics v8_heap_space_stats;
576
577
  writer->json_objectstart("javascriptHeap");
578
  writer->json_keyvalue("totalMemory", v8_heap_stats.total_heap_size());
579
  writer->json_keyvalue("totalCommittedMemory",
580
                        v8_heap_stats.total_physical_size());
581
  writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
582
  writer->json_keyvalue("availableMemory",
583
                        v8_heap_stats.total_available_size());
584
  writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
585
586
  writer->json_objectstart("heapSpaces");
587
  // Loop through heap spaces
588
  for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
589
    isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
590
    writer->json_objectstart(v8_heap_space_stats.space_name());
591
    writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
592
    writer->json_keyvalue(
593
        "committedMemory",
594
        v8_heap_space_stats.physical_space_size());
595
    writer->json_keyvalue(
596
        "capacity",
597
        v8_heap_space_stats.space_used_size() +
598
            v8_heap_space_stats.space_available_size());
599
    writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
600
    writer->json_keyvalue(
601
        "available", v8_heap_space_stats.space_available_size());
602
    writer->json_objectend();
603
  }
604
605
  writer->json_objectend();
606
  writer->json_objectend();
607
}
608
609
static void PrintResourceUsage(JSONWriter* writer) {
610
  // Get process uptime in seconds
611
  uint64_t uptime =
612
      (uv_hrtime() - node::per_process::node_start_time) / (NANOS_PER_SEC);
613
  if (uptime == 0) uptime = 1;  // avoid division by zero.
614
615
  // Process and current thread usage statistics
616
  uv_rusage_t rusage;
617
  writer->json_objectstart("resourceUsage");
618
  if (uv_getrusage(&rusage) == 0) {
619
    double user_cpu =
620
        rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
621
    double kernel_cpu =
622
        rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
623
    writer->json_keyvalue("userCpuSeconds", user_cpu);
624
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
625
    double cpu_abs = user_cpu + kernel_cpu;
626
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
627
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
628
    writer->json_keyvalue("maxRss", rusage.ru_maxrss * 1024);
629
    writer->json_objectstart("pageFaults");
630
    writer->json_keyvalue("IORequired", rusage.ru_majflt);
631
    writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
632
    writer->json_objectend();
633
    writer->json_objectstart("fsActivity");
634
    writer->json_keyvalue("reads", rusage.ru_inblock);
635
    writer->json_keyvalue("writes", rusage.ru_oublock);
636
    writer->json_objectend();
637
  }
638
  writer->json_objectend();
639
#ifdef RUSAGE_THREAD
640
  struct rusage stats;
641
  if (getrusage(RUSAGE_THREAD, &stats) == 0) {
642
    writer->json_objectstart("uvthreadResourceUsage");
643
    double user_cpu =
644
        stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
645
    double kernel_cpu =
646
        stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
647
    writer->json_keyvalue("userCpuSeconds", user_cpu);
648
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
649
    double cpu_abs = user_cpu + kernel_cpu;
650
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
651
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
652
    writer->json_objectstart("fsActivity");
653
    writer->json_keyvalue("reads", stats.ru_inblock);
654
    writer->json_keyvalue("writes", stats.ru_oublock);
655
    writer->json_objectend();
656
    writer->json_objectend();
657
  }
658
#endif
659
}
660
661
// Report operating system information.
662
static void PrintSystemInformation(JSONWriter* writer) {
663
  uv_env_item_t* envitems;
664
  int envcount;
665
  int r;
666
667
  writer->json_objectstart("environmentVariables");
668
669
  {
670
    Mutex::ScopedLock lock(node::per_process::env_var_mutex);
671
    r = uv_os_environ(&envitems, &envcount);
672
  }
673
674
  if (r == 0) {
675
    for (int i = 0; i < envcount; i++)
676
      writer->json_keyvalue(envitems[i].name, envitems[i].value);
677
678
    uv_os_free_environ(envitems, envcount);
679
  }
680
681
  writer->json_objectend();
682
683
#ifndef _WIN32
684
  static struct {
685
    const char* description;
686
    int id;
687
  } rlimit_strings[] = {
688
    {"core_file_size_blocks", RLIMIT_CORE},
689
    {"data_seg_size_kbytes", RLIMIT_DATA},
690
    {"file_size_blocks", RLIMIT_FSIZE},
691
#if !(defined(_AIX) || defined(__sun))
692
    {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
693
#endif
694
#ifndef __sun
695
    {"max_memory_size_kbytes", RLIMIT_RSS},
696
#endif
697
    {"open_files", RLIMIT_NOFILE},
698
    {"stack_size_bytes", RLIMIT_STACK},
699
    {"cpu_time_seconds", RLIMIT_CPU},
700
#ifndef __sun
701
    {"max_user_processes", RLIMIT_NPROC},
702
#endif
703
#ifndef __OpenBSD__
704
    {"virtual_memory_kbytes", RLIMIT_AS}
705
#endif
706
  };
707
708
  writer->json_objectstart("userLimits");
709
  struct rlimit limit;
710
  std::string soft, hard;
711
712
  for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
713
    if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
714
      writer->json_objectstart(rlimit_strings[i].description);
715
716
      if (limit.rlim_cur == RLIM_INFINITY)
717
        writer->json_keyvalue("soft", "unlimited");
718
      else
719
        writer->json_keyvalue("soft", limit.rlim_cur);
720
721
      if (limit.rlim_max == RLIM_INFINITY)
722
        writer->json_keyvalue("hard", "unlimited");
723
      else
724
        writer->json_keyvalue("hard", limit.rlim_max);
725
726
      writer->json_objectend();
727
    }
728
  }
729
  writer->json_objectend();
730
#endif  // _WIN32
731
732
  PrintLoadedLibraries(writer);
733
}
734
735
// Report a list of loaded native libraries.
736
static void PrintLoadedLibraries(JSONWriter* writer) {
737
  writer->json_arraystart("sharedObjects");
738
  std::vector<std::string> modules =
739
      NativeSymbolDebuggingContext::GetLoadedLibraries();
740
  for (auto const& module_name : modules) writer->json_element(module_name);
741
  writer->json_arrayend();
742
}
743
744
// Obtain and report the node and subcomponent version strings.
745
static void PrintComponentVersions(JSONWriter* writer) {
746
  std::stringstream buf;
747
748
  writer->json_objectstart("componentVersions");
749
750
#define V(key)                                                                 \
751
  writer->json_keyvalue(#key, node::per_process::metadata.versions.key);
752
  NODE_VERSIONS_KEYS(V)
753
#undef V
754
755
  writer->json_objectend();
756
}
757
758
// Report runtime release information.
759
static void PrintRelease(JSONWriter* writer) {
760
  writer->json_objectstart("release");
761
  writer->json_keyvalue("name", node::per_process::metadata.release.name);
762
#if NODE_VERSION_IS_LTS
763
  writer->json_keyvalue("lts", node::per_process::metadata.release.lts);
764
#endif
765
766
#ifdef NODE_HAS_RELEASE_URLS
767
  writer->json_keyvalue("headersUrl",
768
                        node::per_process::metadata.release.headers_url);
769
  writer->json_keyvalue("sourceUrl",
770
                        node::per_process::metadata.release.source_url);
771
#ifdef _WIN32
772
  writer->json_keyvalue("libUrl", node::per_process::metadata.release.lib_url);
773
#endif  // _WIN32
774
#endif  // NODE_HAS_RELEASE_URLS
775
776
  writer->json_objectend();
777
}
778
779

366
}  // namespace report