GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_report.cc Lines: 433 443 97.7 %
Date: 2022-08-21 04:19:51 Branches: 103 142 72.5 %

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

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

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

39
          !value->ToString(context).ToLocal(&value_string)) {
502
        continue;
503
      }
504
13
      String::Utf8Value k(isolate, key);
505

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

60
    if (!stack.IsEmpty() && stack.ToLocalChecked()->IsString()) {
531
40
      maybe_str = stack.ToLocalChecked().As<String>();
532
    }
533
  }
534
535
  Local<String> js_str;
536
23
  if (!maybe_str.ToLocal(&js_str)) {
537
    return Nothing<std::string>();
538
  }
539
23
  String::Utf8Value sv(isolate, js_str);
540
23
  return Just<>(std::string(*sv, sv.length()));
541
}
542
543
1
static void PrintEmptyJavaScriptStack(JSONWriter* writer) {
544
1
  writer->json_keyvalue("message", "No stack.");
545
1
  writer->json_arraystart("stack");
546
1
  writer->json_element("Unavailable.");
547
1
  writer->json_arrayend();
548
549
1
  writer->json_objectstart("errorProperties");
550
1
  writer->json_objectend();
551
1
}
552
553
// Do our best to report the JavaScript stack without calling into JavaScript.
554
2
static void PrintJavaScriptStack(JSONWriter* writer,
555
                                 Isolate* isolate,
556
                                 const char* trigger) {
557
  // Can not capture the stacktrace when the isolate is in a OOM state.
558
2
  if (!strcmp(trigger, "OOMError")) {
559
    PrintEmptyJavaScriptStack(writer);
560
1
    return;
561
  }
562
563
2
  HandleScope scope(isolate);
564
2
  RegisterState state;
565
2
  state.pc = nullptr;
566
2
  state.fp = &state;
567
2
  state.sp = &state;
568
569
  // in-out params
570
  SampleInfo info;
571
  void* samples[MAX_FRAME_COUNT];
572
2
  isolate->GetStackSample(state, samples, MAX_FRAME_COUNT, &info);
573
574
  Local<StackTrace> stack = StackTrace::CurrentStackTrace(
575
2
      isolate, MAX_FRAME_COUNT, StackTrace::kDetailed);
576
577
2
  if (stack->GetFrameCount() == 0) {
578
1
    PrintEmptyJavaScriptStack(writer);
579
1
    return;
580
  }
581
582
1
  writer->json_keyvalue("message", trigger);
583
1
  writer->json_arraystart("stack");
584
22
  for (int i = 0; i < stack->GetFrameCount(); i++) {
585
10
    Local<StackFrame> frame = stack->GetFrame(isolate, i);
586
587
30
    Utf8Value function_name(isolate, frame->GetFunctionName());
588
30
    Utf8Value script_name(isolate, frame->GetScriptName());
589
10
    const int line_number = frame->GetLineNumber();
590
10
    const int column = frame->GetColumn();
591
592
    std::string stack_line = SPrintF(
593
20
        "at %s (%s:%d:%d)", *function_name, *script_name, line_number, column);
594
10
    writer->json_element(stack_line);
595
  }
596
1
  writer->json_arrayend();
597
1
  writer->json_objectstart("errorProperties");
598
1
  writer->json_objectend();
599
}
600
601
// Report the JavaScript stack.
602
25
static void PrintJavaScriptErrorStack(JSONWriter* writer,
603
                                      Isolate* isolate,
604
                                      Local<Value> error,
605
                                      const char* trigger) {
606
25
  if (error.IsEmpty()) {
607
2
    return PrintJavaScriptStack(writer, isolate, trigger);
608
  }
609
610
23
  TryCatch try_catch(isolate);
611
23
  HandleScope scope(isolate);
612
23
  Local<Context> context = isolate->GetCurrentContext();
613
23
  std::string ss = "";
614
46
  if (!ErrorToString(isolate, context, error).To(&ss)) {
615
    PrintEmptyJavaScriptStack(writer);
616
    return;
617
  }
618
619
23
  int line = ss.find('\n');
620
23
  if (line == -1) {
621
5
    writer->json_keyvalue("message", ss);
622
  } else {
623
36
    std::string l = ss.substr(0, line);
624
18
    writer->json_keyvalue("message", l);
625
18
    writer->json_arraystart("stack");
626
18
    ss = ss.substr(line + 1);
627
18
    line = ss.find('\n');
628
131
    while (line != -1) {
629
113
      l = ss.substr(0, line);
630
113
      l.erase(l.begin(), std::find_if(l.begin(), l.end(), [](int ch) {
631
565
                return !std::iswspace(ch);
632
226
              }));
633
113
      writer->json_element(l);
634
113
      ss = ss.substr(line + 1);
635
113
      line = ss.find('\n');
636
    }
637
18
    writer->json_arrayend();
638
  }
639
640
  // Report summary JavaScript error properties backtrace
641
23
  PrintJavaScriptErrorProperties(writer, isolate, error);
642
}
643
644
// Report a native stack backtrace
645
25
static void PrintNativeStack(JSONWriter* writer) {
646
50
  auto sym_ctx = NativeSymbolDebuggingContext::New();
647
  void* frames[256];
648
25
  const int size = sym_ctx->GetStackTrace(frames, arraysize(frames));
649
25
  writer->json_arraystart("nativeStack");
650
  int i;
651
280
  for (i = 1; i < size; i++) {
652
255
    void* frame = frames[i];
653
255
    writer->json_start();
654
255
    writer->json_keyvalue("pc",
655
510
                          ValueToHexString(reinterpret_cast<uintptr_t>(frame)));
656
255
    writer->json_keyvalue("symbol", sym_ctx->LookupSymbol(frame).Display());
657
255
    writer->json_end();
658
  }
659
25
  writer->json_arrayend();
660
25
}
661
662
// Report V8 JavaScript heap information.
663
// This uses the existing V8 HeapStatistics and HeapSpaceStatistics APIs.
664
// The isolate->GetGCStatistics(&heap_stats) internal V8 API could potentially
665
// provide some more useful information - the GC history and the handle counts
666
25
static void PrintGCStatistics(JSONWriter* writer, Isolate* isolate) {
667
25
  HeapStatistics v8_heap_stats;
668
25
  isolate->GetHeapStatistics(&v8_heap_stats);
669
25
  HeapSpaceStatistics v8_heap_space_stats;
670
671
25
  writer->json_objectstart("javascriptHeap");
672
25
  writer->json_keyvalue("totalMemory", v8_heap_stats.total_heap_size());
673
25
  writer->json_keyvalue("executableMemory",
674
25
                        v8_heap_stats.total_heap_size_executable());
675
25
  writer->json_keyvalue("totalCommittedMemory",
676
25
                        v8_heap_stats.total_physical_size());
677
25
  writer->json_keyvalue("availableMemory",
678
25
                        v8_heap_stats.total_available_size());
679
25
  writer->json_keyvalue("totalGlobalHandlesMemory",
680
25
                        v8_heap_stats.total_global_handles_size());
681
25
  writer->json_keyvalue("usedGlobalHandlesMemory",
682
25
                        v8_heap_stats.used_global_handles_size());
683
25
  writer->json_keyvalue("usedMemory", v8_heap_stats.used_heap_size());
684
25
  writer->json_keyvalue("memoryLimit", v8_heap_stats.heap_size_limit());
685
25
  writer->json_keyvalue("mallocedMemory", v8_heap_stats.malloced_memory());
686
25
  writer->json_keyvalue("externalMemory", v8_heap_stats.external_memory());
687
25
  writer->json_keyvalue("peakMallocedMemory",
688
25
                        v8_heap_stats.peak_malloced_memory());
689
25
  writer->json_keyvalue("nativeContextCount",
690
25
                        v8_heap_stats.number_of_native_contexts());
691
25
  writer->json_keyvalue("detachedContextCount",
692
25
                        v8_heap_stats.number_of_detached_contexts());
693
25
  writer->json_keyvalue("doesZapGarbage", v8_heap_stats.does_zap_garbage());
694
695
25
  writer->json_objectstart("heapSpaces");
696
  // Loop through heap spaces
697
225
  for (size_t i = 0; i < isolate->NumberOfHeapSpaces(); i++) {
698
200
    isolate->GetHeapSpaceStatistics(&v8_heap_space_stats, i);
699
200
    writer->json_objectstart(v8_heap_space_stats.space_name());
700
200
    writer->json_keyvalue("memorySize", v8_heap_space_stats.space_size());
701
200
    writer->json_keyvalue(
702
        "committedMemory",
703
200
        v8_heap_space_stats.physical_space_size());
704
200
    writer->json_keyvalue(
705
        "capacity",
706
400
        v8_heap_space_stats.space_used_size() +
707
200
            v8_heap_space_stats.space_available_size());
708
200
    writer->json_keyvalue("used", v8_heap_space_stats.space_used_size());
709
200
    writer->json_keyvalue(
710
200
        "available", v8_heap_space_stats.space_available_size());
711
200
    writer->json_objectend();
712
  }
713
714
25
  writer->json_objectend();
715
25
  writer->json_objectend();
716
25
}
717
718
25
static void PrintResourceUsage(JSONWriter* writer) {
719
  // Get process uptime in seconds
720
  uint64_t uptime =
721
25
      (uv_hrtime() - per_process::node_start_time) / (NANOS_PER_SEC);
722
25
  if (uptime == 0) uptime = 1;  // avoid division by zero.
723
724
  // Process and current thread usage statistics
725
  uv_rusage_t rusage;
726
25
  writer->json_objectstart("resourceUsage");
727
25
  if (uv_getrusage(&rusage) == 0) {
728
25
    double user_cpu =
729
25
        rusage.ru_utime.tv_sec + SEC_PER_MICROS * rusage.ru_utime.tv_usec;
730
25
    double kernel_cpu =
731
25
        rusage.ru_stime.tv_sec + SEC_PER_MICROS * rusage.ru_stime.tv_usec;
732
25
    writer->json_keyvalue("userCpuSeconds", user_cpu);
733
25
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
734
25
    double cpu_abs = user_cpu + kernel_cpu;
735
25
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
736
25
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
737
25
    writer->json_keyvalue("maxRss", rusage.ru_maxrss * 1024);
738
25
    writer->json_objectstart("pageFaults");
739
25
    writer->json_keyvalue("IORequired", rusage.ru_majflt);
740
25
    writer->json_keyvalue("IONotRequired", rusage.ru_minflt);
741
25
    writer->json_objectend();
742
25
    writer->json_objectstart("fsActivity");
743
25
    writer->json_keyvalue("reads", rusage.ru_inblock);
744
25
    writer->json_keyvalue("writes", rusage.ru_oublock);
745
25
    writer->json_objectend();
746
  }
747
25
  writer->json_objectend();
748
#ifdef RUSAGE_THREAD
749
  struct rusage stats;
750
25
  if (getrusage(RUSAGE_THREAD, &stats) == 0) {
751
25
    writer->json_objectstart("uvthreadResourceUsage");
752
25
    double user_cpu =
753
25
        stats.ru_utime.tv_sec + SEC_PER_MICROS * stats.ru_utime.tv_usec;
754
25
    double kernel_cpu =
755
25
        stats.ru_stime.tv_sec + SEC_PER_MICROS * stats.ru_stime.tv_usec;
756
25
    writer->json_keyvalue("userCpuSeconds", user_cpu);
757
25
    writer->json_keyvalue("kernelCpuSeconds", kernel_cpu);
758
25
    double cpu_abs = user_cpu + kernel_cpu;
759
25
    double cpu_percentage = (cpu_abs / uptime) * 100.0;
760
25
    writer->json_keyvalue("cpuConsumptionPercent", cpu_percentage);
761
25
    writer->json_objectstart("fsActivity");
762
25
    writer->json_keyvalue("reads", stats.ru_inblock);
763
25
    writer->json_keyvalue("writes", stats.ru_oublock);
764
25
    writer->json_objectend();
765
25
    writer->json_objectend();
766
  }
767
#endif  // RUSAGE_THREAD
768
25
}
769
770
// Report operating system information.
771
25
static void PrintSystemInformation(JSONWriter* writer) {
772
  uv_env_item_t* envitems;
773
  int envcount;
774
  int r;
775
776
25
  writer->json_objectstart("environmentVariables");
777
778
  {
779
50
    Mutex::ScopedLock lock(per_process::env_var_mutex);
780
25
    r = uv_os_environ(&envitems, &envcount);
781
  }
782
783
25
  if (r == 0) {
784
1825
    for (int i = 0; i < envcount; i++)
785
1800
      writer->json_keyvalue(envitems[i].name, envitems[i].value);
786
787
25
    uv_os_free_environ(envitems, envcount);
788
  }
789
790
25
  writer->json_objectend();
791
792
#ifndef _WIN32
793
  static struct {
794
    const char* description;
795
    int id;
796
  } rlimit_strings[] = {
797
    {"core_file_size_blocks", RLIMIT_CORE},
798
    {"data_seg_size_kbytes", RLIMIT_DATA},
799
    {"file_size_blocks", RLIMIT_FSIZE},
800
#if !(defined(_AIX) || defined(__sun))
801
    {"max_locked_memory_bytes", RLIMIT_MEMLOCK},
802
#endif
803
#ifndef __sun
804
    {"max_memory_size_kbytes", RLIMIT_RSS},
805
#endif
806
    {"open_files", RLIMIT_NOFILE},
807
    {"stack_size_bytes", RLIMIT_STACK},
808
    {"cpu_time_seconds", RLIMIT_CPU},
809
#ifndef __sun
810
    {"max_user_processes", RLIMIT_NPROC},
811
#endif
812
#ifndef __OpenBSD__
813
    {"virtual_memory_kbytes", RLIMIT_AS}
814
#endif
815
  };
816
817
25
  writer->json_objectstart("userLimits");
818
  struct rlimit limit;
819
50
  std::string soft, hard;
820
821
275
  for (size_t i = 0; i < arraysize(rlimit_strings); i++) {
822
250
    if (getrlimit(rlimit_strings[i].id, &limit) == 0) {
823
250
      writer->json_objectstart(rlimit_strings[i].description);
824
825
250
      if (limit.rlim_cur == RLIM_INFINITY)
826
125
        writer->json_keyvalue("soft", "unlimited");
827
      else
828
125
        writer->json_keyvalue("soft", limit.rlim_cur);
829
830
250
      if (limit.rlim_max == RLIM_INFINITY)
831
175
        writer->json_keyvalue("hard", "unlimited");
832
      else
833
75
        writer->json_keyvalue("hard", limit.rlim_max);
834
835
250
      writer->json_objectend();
836
    }
837
  }
838
25
  writer->json_objectend();
839
#endif  // _WIN32
840
841
25
  PrintLoadedLibraries(writer);
842
25
}
843
844
// Report a list of loaded native libraries.
845
25
static void PrintLoadedLibraries(JSONWriter* writer) {
846
25
  writer->json_arraystart("sharedObjects");
847
  std::vector<std::string> modules =
848
50
      NativeSymbolDebuggingContext::GetLoadedLibraries();
849
204
  for (auto const& module_name : modules) writer->json_element(module_name);
850
25
  writer->json_arrayend();
851
25
}
852
853
// Obtain and report the node and subcomponent version strings.
854
25
static void PrintComponentVersions(JSONWriter* writer) {
855
50
  std::stringstream buf;
856
857
25
  writer->json_objectstart("componentVersions");
858
859
#define V(key) writer->json_keyvalue(#key, per_process::metadata.versions.key);
860
25
  NODE_VERSIONS_KEYS(V)
861
#undef V
862
863
25
  writer->json_objectend();
864
25
}
865
866
// Report runtime release information.
867
25
static void PrintRelease(JSONWriter* writer) {
868
25
  writer->json_objectstart("release");
869
25
  writer->json_keyvalue("name", per_process::metadata.release.name);
870
#if NODE_VERSION_IS_LTS
871
  writer->json_keyvalue("lts", per_process::metadata.release.lts);
872
#endif
873
874
#ifdef NODE_HAS_RELEASE_URLS
875
  writer->json_keyvalue("headersUrl",
876
                        per_process::metadata.release.headers_url);
877
  writer->json_keyvalue("sourceUrl", per_process::metadata.release.source_url);
878
#ifdef _WIN32
879
  writer->json_keyvalue("libUrl", per_process::metadata.release.lib_url);
880
#endif  // _WIN32
881
#endif  // NODE_HAS_RELEASE_URLS
882
883
25
  writer->json_objectend();
884
25
}
885
886
}  // namespace report
887
}  // namespace node