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

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

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

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

48
      if (!error_obj->Get(context, key).ToLocal(&value) ||
501
36
          !value->ToString(context).ToLocal(&value_string)) {
502
        continue;
503
      }
504
24
      String::Utf8Value k(isolate, key);
505

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

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

96
  if ((!strcmp(trigger, "FatalError")) ||
553

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

14490
}  // namespace report