GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_report.cc Lines: 463 472 98.1 %
Date: 2022-10-31 03:21:21 Branches: 118 152 77.6 %

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