GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_report.cc Lines: 452 461 98.0 %
Date: 2022-09-19 04:21:54 Branches: 117 150 78.0 %

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