GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_report.cc Lines: 474 484 97.9 %
Date: 2022-11-04 03:21:42 Branches: 122 160 76.2 %

Line Branch Exec Source
1
#include "node_report.h"
2
#include "debug_utils-inl.h"
3
#include "diagnosticfilename-inl.h"
4
#include "env-inl.h"
5
#include "json_utils.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 = 3;
27
constexpr int NANOS_PER_SEC = 1000 * 1000 * 1000;
28
constexpr double SEC_PER_MICROS = 1e-6;
29
constexpr int MAX_FRAME_COUNT = 10;
30
31
namespace node {
32
using node::worker::Worker;
33
using v8::Array;
34
using v8::Context;
35
using v8::HandleScope;
36
using v8::HeapSpaceStatistics;
37
using v8::HeapStatistics;
38
using v8::Isolate;
39
using v8::Just;
40
using v8::Local;
41
using v8::Maybe;
42
using v8::MaybeLocal;
43
using v8::Nothing;
44
using v8::Object;
45
using v8::RegisterState;
46
using v8::SampleInfo;
47
using v8::StackFrame;
48
using v8::StackTrace;
49
using v8::String;
50
using v8::TryCatch;
51
using v8::V8;
52
using v8::Value;
53
54
namespace report {
55
// Internal/static function declarations
56
static void WriteNodeReport(Isolate* isolate,
57
                            Environment* env,
58
                            const char* message,
59
                            const char* trigger,
60
                            const std::string& filename,
61
                            std::ostream& out,
62
                            Local<Value> error,
63
                            bool compact);
64
static void PrintVersionInformation(JSONWriter* writer);
65
static void PrintJavaScriptErrorStack(JSONWriter* writer,
66
                                      Isolate* isolate,
67
                                      Local<Value> error,
68
                                      const char* trigger);
69
static void PrintJavaScriptStack(JSONWriter* writer,
70
                                 Isolate* isolate,
71
                                 const char* trigger);
72
static void PrintJavaScriptErrorProperties(JSONWriter* writer,
73
                                           Isolate* isolate,
74
                                           Local<Value> error);
75
static void PrintNativeStack(JSONWriter* writer);
76
static void PrintResourceUsage(JSONWriter* writer);
77
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate);
78
static void PrintSystemInformation(JSONWriter* writer);
79
static void PrintLoadedLibraries(JSONWriter* writer);
80
static void PrintComponentVersions(JSONWriter* writer);
81
static void PrintRelease(JSONWriter* writer);
82
static void PrintCpuInfo(JSONWriter* writer);
83
static void PrintNetworkInterfaceInfo(JSONWriter* writer);
84
85
// Internal function to coordinate and write the various
86
// sections of the report to the supplied stream
87
35
static void WriteNodeReport(Isolate* isolate,
88
                            Environment* env,
89
                            const char* message,
90
                            const char* trigger,
91
                            const std::string& filename,
92
                            std::ostream& out,
93
                            Local<Value> error,
94
                            bool compact) {
95
  // Obtain the current time and the pid.
96
  TIME_TYPE tm_struct;
97
35
  DiagnosticFilename::LocalTime(&tm_struct);
98
35
  uv_pid_t pid = uv_os_getpid();
99
100
  // Save formatting for output stream.
101
70
  std::ios old_state(nullptr);
102
35
  old_state.copyfmt(out);
103
104
  // File stream opened OK, now start printing the report content:
105
  // the title and header information (event, filename, timestamp and pid)
106
107
35
  JSONWriter writer(out, compact);
108
35
  writer.json_start();
109
35
  writer.json_objectstart("header");
110
35
  writer.json_keyvalue("reportVersion", NODE_REPORT_VERSION);
111
35
  writer.json_keyvalue("event", message);
112
35
  writer.json_keyvalue("trigger", trigger);
113
35
  if (!filename.empty())
114
20
    writer.json_keyvalue("filename", filename);
115
  else
116
15
    writer.json_keyvalue("filename", JSONWriter::Null{});
117
118
  // Report dump event and module load date/time stamps
119
  char timebuf[64];
120
#ifdef _WIN32
121
  snprintf(timebuf,
122
           sizeof(timebuf),
123
           "%4d-%02d-%02dT%02d:%02d:%02dZ",
124
           tm_struct.wYear,
125
           tm_struct.wMonth,
126
           tm_struct.wDay,
127
           tm_struct.wHour,
128
           tm_struct.wMinute,
129
           tm_struct.wSecond);
130
  writer.json_keyvalue("dumpEventTime", timebuf);
131
#else  // UNIX, OSX
132
105
  snprintf(timebuf,
133
           sizeof(timebuf),
134
           "%4d-%02d-%02dT%02d:%02d:%02dZ",
135
35
           tm_struct.tm_year + 1900,
136
35
           tm_struct.tm_mon + 1,
137
           tm_struct.tm_mday,
138
           tm_struct.tm_hour,
139
           tm_struct.tm_min,
140
           tm_struct.tm_sec);
141
35
  writer.json_keyvalue("dumpEventTime", timebuf);
142
#endif
143
144
  uv_timeval64_t ts;
145
35
  if (uv_gettimeofday(&ts) == 0) {
146
35
    writer.json_keyvalue("dumpEventTimeStamp",
147
70
                         std::to_string(ts.tv_sec * 1000 + ts.tv_usec / 1000));
148
  }
149
150
  // Report native process ID
151
35
  writer.json_keyvalue("processId", pid);
152
35
  if (env != nullptr)
153
29
    writer.json_keyvalue("threadId", env->thread_id());
154
  else
155
6
    writer.json_keyvalue("threadId", JSONWriter::Null{});
156
157
  {
158
    // Report the process cwd.
159
    char buf[PATH_MAX_BYTES];
160
35
    size_t cwd_size = sizeof(buf);
161
35
    if (uv_cwd(buf, &cwd_size) == 0)
162
35
      writer.json_keyvalue("cwd", buf);
163
  }
164
165
  // Report out the command line.
166
35
  if (!per_process::cli_options->cmdline.empty()) {
167
35
    writer.json_arraystart("commandLine");
168
114
    for (const std::string& arg : per_process::cli_options->cmdline) {
169
79
      writer.json_element(arg);
170
    }
171
35
    writer.json_arrayend();
172
  }
173
174
  // Report Node.js and OS version information
175
35
  PrintVersionInformation(&writer);
176
35
  writer.json_objectend();
177
178
35
  if (isolate != nullptr) {
179
31
    writer.json_objectstart("javascriptStack");
180
    // Report summary JavaScript error stack backtrace
181
31
    PrintJavaScriptErrorStack(&writer, isolate, error, trigger);
182
183
31
    writer.json_objectend();  // the end of 'javascriptStack'
184
185
    // Report V8 Heap and Garbage Collector information
186
31
    PrintGCStatistics(&writer, isolate);
187
  }
188
189
  // Report native stack backtrace
190
35
  PrintNativeStack(&writer);
191
192
  // Report OS and current thread resource usage
193
35
  PrintResourceUsage(&writer);
194
195
35
  writer.json_arraystart("libuv");
196
35
  if (env != nullptr) {
197
29
    uv_walk(env->event_loop(), WalkHandle, static_cast<void*>(&writer));
198
199
29
    writer.json_start();
200
29
    writer.json_keyvalue("type", "loop");
201
29
    writer.json_keyvalue("is_active",
202
29
        static_cast<bool>(uv_loop_alive(env->event_loop())));
203
29
    writer.json_keyvalue("address",
204
58
        ValueToHexString(reinterpret_cast<int64_t>(env->event_loop())));
205
206
    // Report Event loop idle time
207
29
    uint64_t idle_time = uv_metrics_idle_time(env->event_loop());
208
29
    writer.json_keyvalue("loopIdleTimeSeconds", 1.0 * idle_time / 1e9);
209
29
    writer.json_end();
210
  }
211
212
35
  writer.json_arrayend();
213
214
35
  writer.json_arraystart("workers");
215
35
  if (env != nullptr) {
216
58
    Mutex workers_mutex;
217
58
    ConditionVariable notify;
218
58
    std::vector<std::string> worker_infos;
219
29
    size_t expected_results = 0;
220
221
29
    env->ForEachWorker([&](Worker* w) {
222
12
      expected_results += w->RequestInterrupt([&](Environment* env) {
223
4
        std::ostringstream os;
224
225
4
        GetNodeReport(
226
2
            env, "Worker thread subreport", trigger, Local<Value>(), os);
227
228
4
        Mutex::ScopedLock lock(workers_mutex);
229
2
        worker_infos.emplace_back(os.str());
230
4
        notify.Signal(lock);
231
2
      });
232
2
    });
233
234
58
    Mutex::ScopedLock lock(workers_mutex);
235
29
    worker_infos.reserve(expected_results);
236
31
    while (worker_infos.size() < expected_results)
237
2
      notify.Wait(lock);
238
31
    for (const std::string& worker_info : worker_infos)
239
2
      writer.json_element(JSONWriter::ForeignJSON { worker_info });
240
  }
241
35
  writer.json_arrayend();
242
243
  // Report operating system information
244
35
  PrintSystemInformation(&writer);
245
246
35
  writer.json_objectend();
247
248
  // Restore output stream formatting.
249
35
  out.copyfmt(old_state);
250
35
}
251
252
// Report Node.js version, OS version and machine information.
253
35
static void PrintVersionInformation(JSONWriter* writer) {
254
70
  std::ostringstream buf;
255
  // Report Node version
256
35
  buf << "v" << NODE_VERSION_STRING;
257
35
  writer->json_keyvalue("nodejsVersion", buf.str());
258
35
  buf.str("");
259
260
#ifndef _WIN32
261
  // Report compiler and runtime glibc versions where possible.
262
  const char* (*libc_version)();
263
70
  *(reinterpret_cast<void**>(&libc_version)) =
264
35
      dlsym(RTLD_DEFAULT, "gnu_get_libc_version");
265
35
  if (libc_version != nullptr)
266
35
    writer->json_keyvalue("glibcVersionRuntime", (*libc_version)());
267
#endif /* _WIN32 */
268
269
#ifdef __GLIBC__
270
35
  buf << __GLIBC__ << "." << __GLIBC_MINOR__;
271
35
  writer->json_keyvalue("glibcVersionCompiler", buf.str());
272
35
  buf.str("");
273
#endif
274
275
  // Report Process word size
276
35
  writer->json_keyvalue("wordSize", sizeof(void*) * 8);
277
35
  writer->json_keyvalue("arch", per_process::metadata.arch);
278
35
  writer->json_keyvalue("platform", per_process::metadata.platform);
279
280
  // Report deps component versions
281
35
  PrintComponentVersions(writer);
282
283
  // Report release metadata.
284
35
  PrintRelease(writer);
285
286
  // Report operating system and machine information
287
  uv_utsname_t os_info;
288
289
35
  if (uv_os_uname(&os_info) == 0) {
290
35
    writer->json_keyvalue("osName", os_info.sysname);
291
35
    writer->json_keyvalue("osRelease", os_info.release);
292
35
    writer->json_keyvalue("osVersion", os_info.version);
293
35
    writer->json_keyvalue("osMachine", os_info.machine);
294
  }
295
296
35
  PrintCpuInfo(writer);
297
35
  PrintNetworkInterfaceInfo(writer);
298
299
  char host[UV_MAXHOSTNAMESIZE];
300
35
  size_t host_size = sizeof(host);
301
302
35
  if (uv_os_gethostname(host, &host_size) == 0)
303
35
    writer->json_keyvalue("host", host);
304
35
}
305
306
// Report CPU info
307
35
static void PrintCpuInfo(JSONWriter* writer) {
308
  uv_cpu_info_t* cpu_info;
309
  int count;
310
35
  if (uv_cpu_info(&cpu_info, &count) == 0) {
311
35
    writer->json_arraystart("cpus");
312
3115
    for (int i = 0; i < count; i++) {
313
3080
      writer->json_start();
314
3080
      writer->json_keyvalue("model", cpu_info[i].model);
315
3080
      writer->json_keyvalue("speed", cpu_info[i].speed);
316
3080
      writer->json_keyvalue("user", cpu_info[i].cpu_times.user);
317
3080
      writer->json_keyvalue("nice", cpu_info[i].cpu_times.nice);
318
3080
      writer->json_keyvalue("sys", cpu_info[i].cpu_times.sys);
319
3080
      writer->json_keyvalue("idle", cpu_info[i].cpu_times.idle);
320
3080
      writer->json_keyvalue("irq", cpu_info[i].cpu_times.irq);
321
3080
      writer->json_end();
322
    }
323
35
    writer->json_arrayend();
324
35
    uv_free_cpu_info(cpu_info, count);
325
  }
326
35
}
327
328
35
static void PrintNetworkInterfaceInfo(JSONWriter* writer) {
329
  uv_interface_address_t* interfaces;
330
  char ip[INET6_ADDRSTRLEN];
331
  char netmask[INET6_ADDRSTRLEN];
332
  char mac[18];
333
  int count;
334
335
35
  if (uv_interface_addresses(&interfaces, &count) == 0) {
336
35
    writer->json_arraystart("networkInterfaces");
337
338
175
    for (int i = 0; i < count; i++) {
339
140
      writer->json_start();
340
140
      writer->json_keyvalue("name", interfaces[i].name);
341
140
      writer->json_keyvalue("internal", !!interfaces[i].is_internal);
342
840
      snprintf(mac,
343
               sizeof(mac),
344
               "%02x:%02x:%02x:%02x:%02x:%02x",
345
140
               static_cast<unsigned char>(interfaces[i].phys_addr[0]),
346
140
               static_cast<unsigned char>(interfaces[i].phys_addr[1]),
347
140
               static_cast<unsigned char>(interfaces[i].phys_addr[2]),
348
140
               static_cast<unsigned char>(interfaces[i].phys_addr[3]),
349
140
               static_cast<unsigned char>(interfaces[i].phys_addr[4]),
350
140
               static_cast<unsigned char>(interfaces[i].phys_addr[5]));
351
140
      writer->json_keyvalue("mac", mac);
352
353
140
      if (interfaces[i].address.address4.sin_family == AF_INET) {
354
70
        uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
355
70
        uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
356
70
        writer->json_keyvalue("address", ip);
357
70
        writer->json_keyvalue("netmask", netmask);
358
70
        writer->json_keyvalue("family", "IPv4");
359
70
      } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
360
70
        uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
361
70
        uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
362
70
        writer->json_keyvalue("address", ip);
363
70
        writer->json_keyvalue("netmask", netmask);
364
70
        writer->json_keyvalue("family", "IPv6");
365
70
        writer->json_keyvalue("scopeid",
366
70
                              interfaces[i].address.address6.sin6_scope_id);
367
      } else {
368
        writer->json_keyvalue("family", "unknown");
369
      }
370
371
140
      writer->json_end();
372
    }
373
374
35
    writer->json_arrayend();
375
35
    uv_free_interface_addresses(interfaces, count);
376
  }
377
35
}
378
379
25
static void PrintJavaScriptErrorProperties(JSONWriter* writer,
380
                                           Isolate* isolate,
381
                                           Local<Value> error) {
382
25
  writer->json_objectstart("errorProperties");
383

50
  if (!error.IsEmpty() && error->IsObject()) {
384
20
    TryCatch try_catch(isolate);
385
20
    Local<Object> error_obj = error.As<Object>();
386
20
    Local<Context> context = error_obj->GetIsolate()->GetCurrentContext();
387
    Local<Array> keys;
388
40
    if (!error_obj->GetOwnPropertyNames(context).ToLocal(&keys)) {
389
      return writer->json_objectend();  // the end of 'errorProperties'
390
    }
391
20
    uint32_t keys_length = keys->Length();
392
33
    for (uint32_t i = 0; i < keys_length; i++) {
393
      Local<Value> key;
394

52
      if (!keys->Get(context, i).ToLocal(&key) || !key->IsString()) {
395
        continue;
396
      }
397
      Local<Value> value;
398
      Local<String> value_string;
399
39
      if (!error_obj->Get(context, key).ToLocal(&value) ||
400

39
          !value->ToString(context).ToLocal(&value_string)) {
401
        continue;
402
      }
403
13
      String::Utf8Value k(isolate, key);
404

13
      if (!strcmp(*k, "stack") || !strcmp(*k, "message")) continue;
405
13
      String::Utf8Value v(isolate, value_string);
406
13
      writer->json_keyvalue(std::string(*k, k.length()),
407
26
                            std::string(*v, v.length()));
408
    }
409
  }
410
25
  writer->json_objectend();  // the end of 'errorProperties'
411
}
412
413
25
static Maybe<std::string> ErrorToString(Isolate* isolate,
414
                                        Local<Context> context,
415
                                        Local<Value> error) {
416
25
  if (error.IsEmpty()) {
417
    return Nothing<std::string>();
418
  }
419
420
  MaybeLocal<String> maybe_str;
421
  // `ToString` is not available to Symbols.
422
25
  if (error->IsSymbol()) {
423
1
    maybe_str = error.As<v8::Symbol>()->ToDetailString(context);
424
24
  } else if (!error->IsObject()) {
425
4
    maybe_str = error->ToString(context);
426
20
  } else if (error->IsObject()) {
427
20
    MaybeLocal<Value> stack = error.As<Object>()->Get(
428
40
        context, FIXED_ONE_BYTE_STRING(isolate, "stack"));
429

60
    if (!stack.IsEmpty() && stack.ToLocalChecked()->IsString()) {
430
40
      maybe_str = stack.ToLocalChecked().As<String>();
431
    }
432
  }
433
434
  Local<String> js_str;
435
25
  if (!maybe_str.ToLocal(&js_str)) {
436
    return Nothing<std::string>();
437
  }
438
25
  String::Utf8Value sv(isolate, js_str);
439
25
  return Just<>(std::string(*sv, sv.length()));
440
}
441
442
1
static void PrintEmptyJavaScriptStack(JSONWriter* writer) {
443
1
  writer->json_keyvalue("message", "No stack.");
444
1
  writer->json_arraystart("stack");
445
1
  writer->json_element("Unavailable.");
446
1
  writer->json_arrayend();
447
448
1
  writer->json_objectstart("errorProperties");
449
1
  writer->json_objectend();
450
1
}
451
452
// Do our best to report the JavaScript stack without calling into JavaScript.
453
6
static void PrintJavaScriptStack(JSONWriter* writer,
454
                                 Isolate* isolate,
455
                                 const char* trigger) {
456
  // Can not capture the stacktrace when the isolate is in a OOM state.
457
6
  if (!strcmp(trigger, "OOMError")) {
458
    PrintEmptyJavaScriptStack(writer);
459
1
    return;
460
  }
461
462
6
  HandleScope scope(isolate);
463
6
  RegisterState state;
464
6
  state.pc = nullptr;
465
6
  state.fp = &state;
466
6
  state.sp = &state;
467
468
  // in-out params
469
  SampleInfo info;
470
  void* samples[MAX_FRAME_COUNT];
471
6
  isolate->GetStackSample(state, samples, MAX_FRAME_COUNT, &info);
472
473
6
  constexpr StackTrace::StackTraceOptions stack_trace_options =
474
      static_cast<StackTrace::StackTraceOptions>(
475
          StackTrace::kDetailed |
476
          StackTrace::kExposeFramesAcrossSecurityOrigins);
477
  Local<StackTrace> stack = StackTrace::CurrentStackTrace(
478
6
      isolate, MAX_FRAME_COUNT, stack_trace_options);
479
480
6
  if (stack->GetFrameCount() == 0) {
481
1
    PrintEmptyJavaScriptStack(writer);
482
1
    return;
483
  }
484
485
5
  writer->json_keyvalue("message", trigger);
486
5
  writer->json_arraystart("stack");
487
94
  for (int i = 0; i < stack->GetFrameCount(); i++) {
488
42
    Local<StackFrame> frame = stack->GetFrame(isolate, i);
489
490
126
    Utf8Value function_name(isolate, frame->GetFunctionName());
491
126
    Utf8Value script_name(isolate, frame->GetScriptName());
492
42
    const int line_number = frame->GetLineNumber();
493
42
    const int column = frame->GetColumn();
494
495
    std::string stack_line = SPrintF(
496
84
        "at %s (%s:%d:%d)", *function_name, *script_name, line_number, column);
497
42
    writer->json_element(stack_line);
498
  }
499
5
  writer->json_arrayend();
500
5
  writer->json_objectstart("errorProperties");
501
5
  writer->json_objectend();
502
}
503
504
// Report the JavaScript stack.
505
31
static void PrintJavaScriptErrorStack(JSONWriter* writer,
506
                                      Isolate* isolate,
507
                                      Local<Value> error,
508
                                      const char* trigger) {
509
31
  if (error.IsEmpty()) {
510
6
    return PrintJavaScriptStack(writer, isolate, trigger);
511
  }
512
513
25
  TryCatch try_catch(isolate);
514
25
  HandleScope scope(isolate);
515
25
  Local<Context> context = isolate->GetCurrentContext();
516
25
  std::string ss = "";
517
50
  if (!ErrorToString(isolate, context, error).To(&ss)) {
518
    PrintEmptyJavaScriptStack(writer);
519
    return;
520
  }
521
522
25
  int line = ss.find('\n');
523
25
  if (line == -1) {
524
7
    writer->json_keyvalue("message", ss);
525
  } else {
526
36
    std::string l = ss.substr(0, line);
527
18
    writer->json_keyvalue("message", l);
528
18
    writer->json_arraystart("stack");
529
18
    ss = ss.substr(line + 1);
530
18
    line = ss.find('\n');
531
131
    while (line != -1) {
532
113
      l = ss.substr(0, line);
533
113
      l.erase(l.begin(), std::find_if(l.begin(), l.end(), [](int ch) {
534
565
                return !std::iswspace(ch);
535
226
              }));
536
113
      writer->json_element(l);
537
113
      ss = ss.substr(line + 1);
538
113
      line = ss.find('\n');
539
    }
540
18
    writer->json_arrayend();
541
  }
542
543
  // Report summary JavaScript error properties backtrace
544
25
  PrintJavaScriptErrorProperties(writer, isolate, error);
545
}
546
547
// Report a native stack backtrace
548
35
static void PrintNativeStack(JSONWriter* writer) {
549
70
  auto sym_ctx = NativeSymbolDebuggingContext::New();
550
  void* frames[256];
551
35
  const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
552
35
  writer->json_arraystart("nativeStack");
553
  int i;
554
404
  for (i = 1; i < size; i++) {
555
369
    void* frame = frames[i];
556
369
    writer->json_start();
557
369
    writer->json_keyvalue("pc",
558
738
                          ValueToHexString(reinterpret_cast<uintptr_t>(frame)));
559
369
    writer->json_keyvalue("symbol", sym_ctx->LookupSymbol(frame).Display());
560
369
    writer->json_end();
561
  }
562
35
  writer->json_arrayend();
563
35
}
564
565
// Report V8 JavaScript heap information.
566
// This uses the existing V8 HeapStatistics and HeapSpaceStatistics APIs.
567
// The isolate->GetGCStatistics(&heap_stats) internal V8 API could potentially
568
// provide some more useful information - the GC history and the handle counts
569
31
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate) {
570
31
  HeapStatistics v8_heap_stats;
571
31
  isolate->GetHeapStatistics(&v8_heap_stats);
572
31
  HeapSpaceStatistics v8_heap_space_stats;
573
574
31
  writer->json_objectstart("javascriptHeap");
575
31
  writer->json_keyvalue("totalMemory", v8_heap_stats.total_heap_size());
576
31
  writer->json_keyvalue("executableMemory",
577
31
                        v8_heap_stats.total_heap_size_executable());
578
31
  writer->json_keyvalue("totalCommittedMemory",
579
31
                        v8_heap_stats.total_physical_size());
580
31
  writer->json_keyvalue("availableMemory",
581
31
                        v8_heap_stats.total_available_size());
582
31
  writer->json_keyvalue("totalGlobalHandlesMemory",
583
31
                        v8_heap_stats.total_global_handles_size());
584
31
  writer->json_keyvalue("usedGlobalHandlesMemory",
585
31
                        v8_heap_stats.used_global_handles_size());
586
31
  writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
587
31
  writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
588
31
  writer->json_keyvalue("mallocedMemory", v8_heap_stats.malloced_memory());
589
31
  writer->json_keyvalue("externalMemory", v8_heap_stats.external_memory());
590
31
  writer->json_keyvalue("peakMallocedMemory",
591
31
                        v8_heap_stats.peak_malloced_memory());
592
31
  writer->json_keyvalue("nativeContextCount",
593
31
                        v8_heap_stats.number_of_native_contexts());
594
31
  writer->json_keyvalue("detachedContextCount",
595
31
                        v8_heap_stats.number_of_detached_contexts());
596
31
  writer->json_keyvalue("doesZapGarbage", v8_heap_stats.does_zap_garbage());
597
598
31
  writer->json_objectstart("heapSpaces");
599
  // Loop through heap spaces
600
279
  for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
601
248
    isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
602
248
    writer->json_objectstart(v8_heap_space_stats.space_name());
603
248
    writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
604
248
    writer->json_keyvalue(
605
        "committedMemory",
606
248
        v8_heap_space_stats.physical_space_size());
607
248
    writer->json_keyvalue(
608
        "capacity",
609
496
        v8_heap_space_stats.space_used_size() +
610
248
            v8_heap_space_stats.space_available_size());
611
248
    writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
612
248
    writer->json_keyvalue(
613
248
        "available", v8_heap_space_stats.space_available_size());
614
248
    writer->json_objectend();
615
  }
616
617
31
  writer->json_objectend();
618
31
  writer->json_objectend();
619
31
}
620
621
35
static void PrintResourceUsage(JSONWriter* writer) {
622
  // Get process uptime in seconds
623
  uint64_t uptime =
624
35
      (uv_hrtime() - per_process::node_start_time) / (NANOS_PER_SEC);
625
35
  if (uptime == 0) uptime = 1;  // avoid division by zero.
626
627
  // Process and current thread usage statistics
628
  uv_rusage_t rusage;
629
35
  writer->json_objectstart("resourceUsage");
630
631
35
  uint64_t free_memory = uv_get_free_memory();
632
35
  uint64_t total_memory = uv_get_total_memory();
633
634
35
  writer->json_keyvalue("free_memory", std::to_string(free_memory));
635
35
  writer->json_keyvalue("total_memory", std::to_string(total_memory));
636
637
  size_t rss;
638
35
  int err = uv_resident_set_memory(&rss);
639
35
  if (!err) {
640
35
    writer->json_keyvalue("rss", std::to_string(rss));
641
  }
642
643
35
  uint64_t constrained_memory = uv_get_constrained_memory();
644
35
  if (constrained_memory) {
645
35
    writer->json_keyvalue("constrained_memory",
646
70
                          std::to_string(constrained_memory));
647
  }
648
649
  // See GuessMemoryAvailableToTheProcess
650

35
  if (!err && constrained_memory && constrained_memory >= rss) {
651
35
    uint64_t available_memory = constrained_memory - rss;
652
35
    writer->json_keyvalue("available_memory", std::to_string(available_memory));
653
  } else {
654
    writer->json_keyvalue("available_memory", std::to_string(free_memory));
655
  }
656
657
35
  if (uv_getrusage(&rusage) == 0) {
658
35
    double user_cpu =
659
35
        rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
660
35
    double kernel_cpu =
661
35
        rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
662
35
    writer->json_keyvalue("userCpuSeconds", user_cpu);
663
35
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
664
35
    double cpu_abs = user_cpu + kernel_cpu;
665
35
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
666
35
    double user_cpu_percentage = (user_cpu / uptime) * 100.0;
667
35
    double kernel_cpu_percentage = (kernel_cpu / uptime) * 100.0;
668
35
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
669
35
    writer->json_keyvalue("userCpuConsumptionPercent", user_cpu_percentage);
670
35
    writer->json_keyvalue("kernelCpuConsumptionPercent", kernel_cpu_percentage);
671
35
    writer->json_keyvalue("maxRss", std::to_string(rusage.ru_maxrss * 1024));
672
35
    writer->json_objectstart("pageFaults");
673
35
    writer->json_keyvalue("IORequired", rusage.ru_majflt);
674
35
    writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
675
35
    writer->json_objectend();
676
35
    writer->json_objectstart("fsActivity");
677
35
    writer->json_keyvalue("reads", rusage.ru_inblock);
678
35
    writer->json_keyvalue("writes", rusage.ru_oublock);
679
35
    writer->json_objectend();
680
  }
681
35
  writer->json_objectend();
682
#ifdef RUSAGE_THREAD
683
  struct rusage stats;
684
35
  if (getrusage(RUSAGE_THREAD, &stats) == 0) {
685
35
    writer->json_objectstart("uvthreadResourceUsage");
686
35
    double user_cpu =
687
35
        stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
688
35
    double kernel_cpu =
689
35
        stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
690
35
    writer->json_keyvalue("userCpuSeconds", user_cpu);
691
35
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
692
35
    double cpu_abs = user_cpu + kernel_cpu;
693
35
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
694
35
    double user_cpu_percentage = (user_cpu / uptime) * 100.0;
695
35
    double kernel_cpu_percentage = (kernel_cpu / uptime) * 100.0;
696
35
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
697
35
    writer->json_keyvalue("userCpuConsumptionPercent", user_cpu_percentage);
698
35
    writer->json_keyvalue("kernelCpuConsumptionPercent", kernel_cpu_percentage);
699
35
    writer->json_objectstart("fsActivity");
700
35
    writer->json_keyvalue("reads", stats.ru_inblock);
701
35
    writer->json_keyvalue("writes", stats.ru_oublock);
702
35
    writer->json_objectend();
703
35
    writer->json_objectend();
704
  }
705
#endif  // RUSAGE_THREAD
706
35
}
707
708
// Report operating system information.
709
35
static void PrintSystemInformation(JSONWriter* writer) {
710
  uv_env_item_t* envitems;
711
  int envcount;
712
  int r;
713
714
35
  writer->json_objectstart("environmentVariables");
715
716
  {
717
70
    Mutex::ScopedLock lock(per_process::env_var_mutex);
718
35
    r = uv_os_environ(&envitems, &envcount);
719
  }
720
721
35
  if (r == 0) {
722
2675
    for (int i = 0; i < envcount; i++)
723
2640
      writer->json_keyvalue(envitems[i].name, envitems[i].value);
724
725
35
    uv_os_free_environ(envitems, envcount);
726
  }
727
728
35
  writer->json_objectend();
729
730
#ifndef _WIN32
731
  static struct {
732
    const char* description;
733
    int id;
734
  } rlimit_strings[] = {
735
    {"core_file_size_blocks", RLIMIT_CORE},
736
    {"data_seg_size_kbytes", RLIMIT_DATA},
737
    {"file_size_blocks", RLIMIT_FSIZE},
738
#if !(defined(_AIX) || defined(__sun))
739
    {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
740
#endif
741
#ifndef __sun
742
    {"max_memory_size_kbytes", RLIMIT_RSS},
743
#endif
744
    {"open_files", RLIMIT_NOFILE},
745
    {"stack_size_bytes", RLIMIT_STACK},
746
    {"cpu_time_seconds", RLIMIT_CPU},
747
#ifndef __sun
748
    {"max_user_processes", RLIMIT_NPROC},
749
#endif
750
#ifndef __OpenBSD__
751
    {"virtual_memory_kbytes", RLIMIT_AS}
752
#endif
753
  };
754
755
35
  writer->json_objectstart("userLimits");
756
  struct rlimit limit;
757
70
  std::string soft, hard;
758
759
385
  for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
760
350
    if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
761
350
      writer->json_objectstart(rlimit_strings[i].description);
762
763
350
      if (limit.rlim_cur == RLIM_INFINITY)
764
175
        writer->json_keyvalue("soft", "unlimited");
765
      else
766
175
        writer->json_keyvalue("soft", limit.rlim_cur);
767
768
350
      if (limit.rlim_max == RLIM_INFINITY)
769
245
        writer->json_keyvalue("hard", "unlimited");
770
      else
771
105
        writer->json_keyvalue("hard", limit.rlim_max);
772
773
350
      writer->json_objectend();
774
    }
775
  }
776
35
  writer->json_objectend();
777
#endif  // _WIN32
778
779
35
  PrintLoadedLibraries(writer);
780
35
}
781
782
// Report a list of loaded native libraries.
783
35
static void PrintLoadedLibraries(JSONWriter* writer) {
784
35
  writer->json_arraystart("sharedObjects");
785
  std::vector<std::string> modules =
786
70
      NativeSymbolDebuggingContext::GetLoadedLibraries();
787
325
  for (auto const& module_name : modules) writer->json_element(module_name);
788
35
  writer->json_arrayend();
789
35
}
790
791
// Obtain and report the node and subcomponent version strings.
792
35
static void PrintComponentVersions(JSONWriter* writer) {
793
70
  std::stringstream buf;
794
795
35
  writer->json_objectstart("componentVersions");
796
797
#define V(key) writer->json_keyvalue(#key, per_process::metadata.versions.key);
798
35
  NODE_VERSIONS_KEYS(V)
799
#undef V
800
801
35
  writer->json_objectend();
802
35
}
803
804
// Report runtime release information.
805
35
static void PrintRelease(JSONWriter* writer) {
806
35
  writer->json_objectstart("release");
807
35
  writer->json_keyvalue("name", per_process::metadata.release.name);
808
#if NODE_VERSION_IS_LTS
809
  writer->json_keyvalue("lts", per_process::metadata.release.lts);
810
#endif
811
812
#ifdef NODE_HAS_RELEASE_URLS
813
  writer->json_keyvalue("headersUrl",
814
                        per_process::metadata.release.headers_url);
815
  writer->json_keyvalue("sourceUrl", per_process::metadata.release.source_url);
816
#ifdef _WIN32
817
  writer->json_keyvalue("libUrl", per_process::metadata.release.lib_url);
818
#endif  // _WIN32
819
#endif  // NODE_HAS_RELEASE_URLS
820
821
35
  writer->json_objectend();
822
35
}
823
824
}  // namespace report
825
826
21
std::string TriggerNodeReport(Isolate* isolate,
827
                              Environment* env,
828
                              const char* message,
829
                              const char* trigger,
830
                              const std::string& name,
831
                              Local<Value> error) {
832
42
  std::string filename;
833
834
  // Determine the required report filename. In order of priority:
835
  //   1) supplied on API 2) configured on startup 3) default generated
836
21
  if (!name.empty()) {
837
    // Filename was specified as API parameter.
838
4
    filename = name;
839
  } else {
840
34
    std::string report_filename;
841
    {
842
34
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
843
17
      report_filename = per_process::cli_options->report_filename;
844
    }
845
17
    if (report_filename.length() > 0) {
846
      // File name was supplied via start-up option.
847
1
      filename = report_filename;
848
    } else {
849
44
      filename = *DiagnosticFilename(
850
28
          env != nullptr ? env->thread_id() : 0, "report", "json");
851
    }
852
  }
853
854
  // Open the report file stream for writing. Supports stdout/err,
855
  // user-specified or (default) generated name
856
42
  std::ofstream outfile;
857
  std::ostream* outstream;
858
21
  if (filename == "stdout") {
859
1
    outstream = &std::cout;
860
20
  } else if (filename == "stderr") {
861
1
    outstream = &std::cerr;
862
  } else {
863
19
    std::string report_directory;
864
    {
865
38
      Mutex::ScopedLock lock(per_process::cli_options_mutex);
866
19
      report_directory = per_process::cli_options->report_directory;
867
    }
868
    // Regular file. Append filename to directory path if one was specified
869
19
    if (report_directory.length() > 0) {
870
30
      std::string pathname = report_directory;
871
15
      pathname += kPathSeparator;
872
15
      pathname += filename;
873
15
      outfile.open(pathname, std::ios::out | std::ios::binary);
874
    } else {
875
4
      outfile.open(filename, std::ios::out | std::ios::binary);
876
    }
877
    // Check for errors on the file open
878
19
    if (!outfile.is_open()) {
879
1
      std::cerr << "\nFailed to open Node.js report file: " << filename;
880
881
1
      if (report_directory.length() > 0)
882
1
        std::cerr << " directory: " << report_directory;
883
884
1
      std::cerr << " (errno: " << errno << ")" << std::endl;
885
1
      return "";
886
    }
887
18
    outstream = &outfile;
888
18
    std::cerr << "\nWriting Node.js report to file: " << filename;
889
  }
890
891
  bool compact;
892
  {
893
20
    Mutex::ScopedLock lock(per_process::cli_options_mutex);
894
20
    compact = per_process::cli_options->report_compact;
895
  }
896
897
20
  report::WriteNodeReport(
898
      isolate, env, message, trigger, filename, *outstream, error, compact);
899
900
  // Do not close stdout/stderr, only close files we opened.
901
20
  if (outfile.is_open()) {
902
18
    outfile.close();
903
  }
904
905
  // Do not mix JSON and free-form text on stderr.
906
20
  if (filename != "stderr") {
907
19
    std::cerr << "\nNode.js report completed" << std::endl;
908
  }
909
20
  return filename;
910
}
911
912
// External function to trigger a report, writing to file.
913
4
std::string TriggerNodeReport(Isolate* isolate,
914
                              const char* message,
915
                              const char* trigger,
916
                              const std::string& name,
917
                              Local<Value> error) {
918
4
  Environment* env = nullptr;
919
4
  if (isolate != nullptr) {
920
3
    env = Environment::GetCurrent(isolate);
921
  }
922
4
  return TriggerNodeReport(isolate, env, message, trigger, name, error);
923
}
924
925
// External function to trigger a report, writing to file.
926
17
std::string TriggerNodeReport(Environment* env,
927
                              const char* message,
928
                              const char* trigger,
929
                              const std::string& name,
930
                              Local<Value> error) {
931
16
  return TriggerNodeReport(env != nullptr ? env->isolate() : nullptr,
932
                           env,
933
                           message,
934
                           trigger,
935
                           name,
936
33
                           error);
937
}
938
939
// External function to trigger a report, writing to a supplied stream.
940
2
void GetNodeReport(Isolate* isolate,
941
                   const char* message,
942
                   const char* trigger,
943
                   Local<Value> error,
944
                   std::ostream& out) {
945
2
  Environment* env = nullptr;
946
2
  if (isolate != nullptr) {
947
1
    env = Environment::GetCurrent(isolate);
948
  }
949
2
  report::WriteNodeReport(
950
      isolate, env, message, trigger, "", out, error, false);
951
2
}
952
953
// External function to trigger a report, writing to a supplied stream.
954
13
void GetNodeReport(Environment* env,
955
                   const char* message,
956
                   const char* trigger,
957
                   Local<Value> error,
958
                   std::ostream& out) {
959
13
  Isolate* isolate = nullptr;
960
13
  if (env != nullptr) {
961
12
    isolate = env->isolate();
962
  }
963
13
  report::WriteNodeReport(
964
      isolate, env, message, trigger, "", out, error, false);
965
13
}
966
967
}  // namespace node