GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_errors.cc Lines: 299 429 69.7 %
Date: 2021-08-24 04:12:49 Branches: 179 343 52.2 %

Line Branch Exec Source
1
#include <cerrno>
2
#include <cstdarg>
3
4
#include "debug_utils-inl.h"
5
#include "node_errors.h"
6
#include "node_external_reference.h"
7
#include "node_internals.h"
8
#include "node_process-inl.h"
9
#include "node_report.h"
10
#include "node_v8_platform-inl.h"
11
#include "util-inl.h"
12
13
namespace node {
14
15
using errors::TryCatchScope;
16
using v8::Boolean;
17
using v8::Context;
18
using v8::Exception;
19
using v8::Function;
20
using v8::FunctionCallbackInfo;
21
using v8::HandleScope;
22
using v8::Int32;
23
using v8::Isolate;
24
using v8::Just;
25
using v8::Local;
26
using v8::Maybe;
27
using v8::MaybeLocal;
28
using v8::Message;
29
using v8::Object;
30
using v8::ScriptOrigin;
31
using v8::StackFrame;
32
using v8::StackTrace;
33
using v8::String;
34
using v8::Undefined;
35
using v8::Value;
36
37
526
bool IsExceptionDecorated(Environment* env, Local<Value> er) {
38

1052
  if (!er.IsEmpty() && er->IsObject()) {
39
514
    Local<Object> err_obj = er.As<Object>();
40
    auto maybe_value =
41
514
        err_obj->GetPrivate(env->context(), env->decorated_private_symbol());
42
    Local<Value> decorated;
43

1028
    return maybe_value.ToLocal(&decorated) && decorated->IsTrue();
44
  }
45
12
  return false;
46
}
47
48
namespace per_process {
49
static Mutex tty_mutex;
50
}  // namespace per_process
51
52
870
static std::string GetErrorSource(Isolate* isolate,
53
                                  Local<Context> context,
54
                                  Local<Message> message,
55
                                  bool* added_exception_line) {
56
870
  MaybeLocal<String> source_line_maybe = message->GetSourceLine(context);
57
1740
  node::Utf8Value encoded_source(isolate, source_line_maybe.ToLocalChecked());
58
1740
  std::string sourceline(*encoded_source, encoded_source.length());
59
870
  *added_exception_line = false;
60
61
  // If source maps have been enabled, the exception line will instead be
62
  // added in the JavaScript context:
63
870
  Environment* env = Environment::GetCurrent(isolate);
64
  const bool has_source_map_url =
65
1740
      !message->GetScriptOrigin().SourceMapUrl().IsEmpty();
66


870
  if (has_source_map_url && env != nullptr && env->source_maps_enabled()) {
67
17
    return sourceline;
68
  }
69
70
853
  if (sourceline.find("node-do-not-add-exception-line") != std::string::npos) {
71
    return sourceline;
72
  }
73
74
  // Because of how node modules work, all scripts are wrapped with a
75
  // "function (module, exports, __filename, ...) {"
76
  // to provide script local variables.
77
  //
78
  // When reporting errors on the first line of a script, this wrapper
79
  // function is leaked to the user. There used to be a hack here to
80
  // truncate off the first 62 characters, but it caused numerous other
81
  // problems when vm.runIn*Context() methods were used for non-module
82
  // code.
83
  //
84
  // If we ever decide to re-instate such a hack, the following steps
85
  // must be taken:
86
  //
87
  // 1. Pass a flag around to say "this code was wrapped"
88
  // 2. Update the stack frame output so that it is also correct.
89
  //
90
  // It would probably be simpler to add a line rather than add some
91
  // number of characters to the first line, since V8 truncates the
92
  // sourceline to 78 characters, and we end up not providing very much
93
  // useful debugging info to the user if we remove 62 characters.
94
95
  // Print (filename):(line number): (message).
96
853
  ScriptOrigin origin = message->GetScriptOrigin();
97
1706
  node::Utf8Value filename(isolate, message->GetScriptResourceName());
98
853
  const char* filename_string = *filename;
99
853
  int linenum = message->GetLineNumber(context).FromJust();
100
101
853
  int script_start = (linenum - origin.LineOffset()) == 1
102
1007
                         ? origin.ColumnOffset()
103
853
                         : 0;
104
1706
  int start = message->GetStartColumn(context).FromMaybe(0);
105
853
  int end = message->GetEndColumn(context).FromMaybe(0);
106
853
  if (start >= script_start) {
107
852
    CHECK_GE(end, start);
108
852
    start -= script_start;
109
852
    end -= script_start;
110
  }
111
112
  std::string buf = SPrintF("%s:%i\n%s\n",
113
                            filename_string,
114
                            linenum,
115
1706
                            sourceline.c_str());
116
853
  CHECK_GT(buf.size(), 0);
117
853
  *added_exception_line = true;
118
119
2559
  if (start > end ||
120


1705
      start < 0 ||
121
852
      static_cast<size_t>(end) > sourceline.size()) {
122
18
    return buf;
123
  }
124
125
835
  constexpr int kUnderlineBufsize = 1020;
126
  char underline_buf[kUnderlineBufsize + 4];
127
835
  int off = 0;
128
  // Print wavy underline (GetUnderline is deprecated).
129
5000
  for (int i = 0; i < start; i++) {
130

4165
    if (sourceline[i] == '\0' || off >= kUnderlineBufsize) {
131
      break;
132
    }
133
4165
    CHECK_LT(off, kUnderlineBufsize);
134
4165
    underline_buf[off++] = (sourceline[i] == '\t') ? '\t' : ' ';
135
  }
136
3352
  for (int i = start; i < end; i++) {
137

2517
    if (sourceline[i] == '\0' || off >= kUnderlineBufsize) {
138
      break;
139
    }
140
2517
    CHECK_LT(off, kUnderlineBufsize);
141
2517
    underline_buf[off++] = '^';
142
  }
143
835
  CHECK_LE(off, kUnderlineBufsize);
144
835
  underline_buf[off++] = '\n';
145
146
835
  return buf + std::string(underline_buf, off);
147
}
148
149
6
void PrintStackTrace(Isolate* isolate, Local<StackTrace> stack) {
150
96
  for (int i = 0; i < stack->GetFrameCount(); i++) {
151
42
    Local<StackFrame> stack_frame = stack->GetFrame(isolate, i);
152
84
    node::Utf8Value fn_name_s(isolate, stack_frame->GetFunctionName());
153
84
    node::Utf8Value script_name(isolate, stack_frame->GetScriptName());
154
42
    const int line_number = stack_frame->GetLineNumber();
155
42
    const int column = stack_frame->GetColumn();
156
157
42
    if (stack_frame->IsEval()) {
158
      if (stack_frame->GetScriptId() == Message::kNoScriptIdInfo) {
159
        FPrintF(stderr, "    at [eval]:%i:%i\n", line_number, column);
160
      } else {
161
        FPrintF(stderr,
162
                "    at [eval] (%s:%i:%i)\n",
163
                *script_name,
164
                line_number,
165
                column);
166
      }
167
      break;
168
    }
169
170
42
    if (fn_name_s.length() == 0) {
171
11
      FPrintF(stderr, "    at %s:%i:%i\n", script_name, line_number, column);
172
    } else {
173
31
      FPrintF(stderr,
174
              "    at %s (%s:%i:%i)\n",
175
              fn_name_s,
176
              script_name,
177
              line_number,
178
              column);
179
    }
180
  }
181
6
  fflush(stderr);
182
6
}
183
184
394
void PrintException(Isolate* isolate,
185
                    Local<Context> context,
186
                    Local<Value> err,
187
                    Local<Message> message) {
188
  node::Utf8Value reason(isolate,
189
394
                         err->ToDetailString(context)
190
788
                             .FromMaybe(Local<String>()));
191
394
  bool added_exception_line = false;
192
  std::string source =
193
788
      GetErrorSource(isolate, context, message, &added_exception_line);
194
394
  FPrintF(stderr, "%s\n", source);
195
394
  FPrintF(stderr, "%s\n", reason);
196
197
394
  Local<v8::StackTrace> stack = message->GetStackTrace();
198
394
  if (!stack.IsEmpty()) PrintStackTrace(isolate, stack);
199
394
}
200
201
394
void PrintCaughtException(Isolate* isolate,
202
                          Local<Context> context,
203
                          const v8::TryCatch& try_catch) {
204
394
  CHECK(try_catch.HasCaught());
205
394
  PrintException(isolate, context, try_catch.Exception(), try_catch.Message());
206
394
}
207
208
543
void AppendExceptionLine(Environment* env,
209
                         Local<Value> er,
210
                         Local<Message> message,
211
                         enum ErrorHandlingMode mode) {
212
644
  if (message.IsEmpty()) return;
213
214
543
  HandleScope scope(env->isolate());
215
  Local<Object> err_obj;
216

1086
  if (!er.IsEmpty() && er->IsObject()) {
217
531
    err_obj = er.As<Object>();
218
    // If arrow_message is already set, skip.
219
    auto maybe_value = err_obj->GetPrivate(env->context(),
220
531
                                          env->arrow_message_private_symbol());
221
    Local<Value> lvalue;
222

1593
    if (!maybe_value.ToLocal(&lvalue) || lvalue->IsString())
223
67
      return;
224
  }
225
226
476
  bool added_exception_line = false;
227
  std::string source = GetErrorSource(
228
476
      env->isolate(), env->context(), message, &added_exception_line);
229
476
  if (!added_exception_line) {
230
17
    return;
231
  }
232
459
  MaybeLocal<Value> arrow_str = ToV8Value(env->context(), source);
233
234

918
  const bool can_set_arrow = !arrow_str.IsEmpty() && !err_obj.IsEmpty();
235
  // If allocating arrow_str failed, print it out. There's not much else to do.
236
  // If it's not an error, but something needs to be printed out because
237
  // it's a fatal exception, also print it out from here.
238
  // Otherwise, the arrow property will be attached to the object and handled
239
  // by the caller.
240


585
  if (!can_set_arrow || (mode == FATAL_ERROR && !err_obj->IsNativeError())) {
241
17
    if (env->printed_error()) return;
242
17
    Mutex::ScopedLock lock(per_process::tty_mutex);
243
17
    env->set_printed_error(true);
244
245
17
    ResetStdio();
246
17
    FPrintF(stderr, "\n%s", source);
247
17
    return;
248
  }
249
250

1326
  CHECK(err_obj
251
            ->SetPrivate(env->context(),
252
                         env->arrow_message_private_symbol(),
253
                         arrow_str.ToLocalChecked())
254
            .FromMaybe(false));
255
}
256
257
[[noreturn]] void Abort() {
258
  DumpBacktrace(stderr);
259
  fflush(stderr);
260
  ABORT_NO_BACKTRACE();
261
}
262
263
[[noreturn]] void Assert(const AssertionInfo& info) {
264
  std::string name = GetHumanReadableProcessName();
265
266
  fprintf(stderr,
267
          "%s: %s:%s%s Assertion `%s' failed.\n",
268
          name.c_str(),
269
          info.file_line,
270
          info.function,
271
          *info.function ? ":" : "",
272
          info.message);
273
  fflush(stderr);
274
275
  Abort();
276
}
277
278
enum class EnhanceFatalException { kEnhance, kDontEnhance };
279
280
/**
281
 * Report the exception to the inspector, then print it to stderr.
282
 * This should only be used when the Node.js instance is about to exit
283
 * (i.e. this should be followed by a env->Exit() or an Abort()).
284
 *
285
 * Use enhance_stack = EnhanceFatalException::kDontEnhance
286
 * when it's unsafe to call into JavaScript.
287
 */
288
220
static void ReportFatalException(Environment* env,
289
                                 Local<Value> error,
290
                                 Local<Message> message,
291
                                 EnhanceFatalException enhance_stack) {
292
220
  if (!env->can_call_into_js())
293
    enhance_stack = EnhanceFatalException::kDontEnhance;
294
295
220
  Isolate* isolate = env->isolate();
296
220
  CHECK(!error.IsEmpty());
297
220
  CHECK(!message.IsEmpty());
298
440
  HandleScope scope(isolate);
299
300
220
  AppendExceptionLine(env, error, message, FATAL_ERROR);
301
302
220
  auto report_to_inspector = [&]() {
303
#if HAVE_INSPECTOR
304
220
    env->inspector_agent()->ReportUncaughtException(error, message);
305
#endif
306
220
  };
307
308
  Local<Value> arrow;
309
  Local<Value> stack_trace;
310
220
  bool decorated = IsExceptionDecorated(env, error);
311
312
220
  if (!error->IsObject()) {  // We can only enhance actual errors.
313
12
    report_to_inspector();
314
24
    stack_trace = Undefined(isolate);
315
    // If error is not an object, AppendExceptionLine() has already print the
316
    // source line and the arrow to stderr.
317
    // TODO(joyeecheung): move that side effect out of AppendExceptionLine().
318
    // It is done just to preserve the source line as soon as possible.
319
  } else {
320
208
    Local<Object> err_obj = error.As<Object>();
321
322
412
    auto enhance_with = [&](Local<Function> enhancer) {
323
      Local<Value> enhanced;
324
412
      Local<Value> argv[] = {err_obj};
325
824
      if (!enhancer.IsEmpty() &&
326
          enhancer
327
1236
              ->Call(env->context(), Undefined(isolate), arraysize(argv), argv)
328
412
              .ToLocal(&enhanced)) {
329
408
        stack_trace = enhanced;
330
      }
331
620
    };
332
333
208
    switch (enhance_stack) {
334
206
      case EnhanceFatalException::kEnhance: {
335
206
        enhance_with(env->enhance_fatal_stack_before_inspector());
336
206
        report_to_inspector();
337
206
        enhance_with(env->enhance_fatal_stack_after_inspector());
338
206
        break;
339
      }
340
2
      case EnhanceFatalException::kDontEnhance: {
341
4
        USE(err_obj->Get(env->context(), env->stack_string())
342
2
                .ToLocal(&stack_trace));
343
2
        report_to_inspector();
344
2
        break;
345
      }
346
      default:
347
        UNREACHABLE();
348
    }
349
350
    arrow =
351
208
        err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol())
352
208
            .ToLocalChecked();
353
  }
354
355
440
  node::Utf8Value trace(env->isolate(), stack_trace);
356
357
  // range errors have a trace member set to undefined
358

656
  if (trace.length() > 0 && !stack_trace->IsUndefined()) {
359


618
    if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
360
78
      FPrintF(stderr, "%s\n", trace);
361
    } else {
362
256
      node::Utf8Value arrow_string(env->isolate(), arrow);
363
128
      FPrintF(stderr, "%s\n%s\n", arrow_string, trace);
364
    }
365
  } else {
366
    // this really only happens for RangeErrors, since they're the only
367
    // kind that won't have all this info in the trace, or when non-Error
368
    // objects are thrown manually.
369
    MaybeLocal<Value> message;
370
    MaybeLocal<Value> name;
371
372
14
    if (error->IsObject()) {
373
2
      Local<Object> err_obj = error.As<Object>();
374
4
      message = err_obj->Get(env->context(), env->message_string());
375
4
      name = err_obj->Get(env->context(), env->name_string());
376
    }
377
378
4
    if (message.IsEmpty() || message.ToLocalChecked()->IsUndefined() ||
379


16
        name.IsEmpty() || name.ToLocalChecked()->IsUndefined()) {
380
      // Not an error object. Just print as-is.
381
14
      node::Utf8Value message(env->isolate(), error);
382
383
14
      FPrintF(stderr, "%s\n",
384

28
              *message ? message.ToString() : "<toString() threw exception>");
385
    } else {
386
      node::Utf8Value name_string(env->isolate(), name.ToLocalChecked());
387
      node::Utf8Value message_string(env->isolate(), message.ToLocalChecked());
388
389
      if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
390
        FPrintF(stderr, "%s: %s\n", name_string, message_string);
391
      } else {
392
        node::Utf8Value arrow_string(env->isolate(), arrow);
393
        FPrintF(stderr,
394
            "%s\n%s: %s\n", arrow_string, name_string, message_string);
395
      }
396
    }
397
398
14
    if (!env->options()->trace_uncaught) {
399
11
      std::string argv0;
400
11
      if (!env->argv().empty()) argv0 = env->argv()[0];
401
11
      if (argv0.empty()) argv0 = "node";
402
11
      FPrintF(stderr,
403
              "(Use `%s --trace-uncaught ...` to show where the exception "
404
              "was thrown)\n",
405
22
              fs::Basename(argv0, ".exe"));
406
    }
407
  }
408
409
220
  if (env->options()->trace_uncaught) {
410
3
    Local<StackTrace> trace = message->GetStackTrace();
411
3
    if (!trace.IsEmpty()) {
412
3
      FPrintF(stderr, "Thrown at:\n");
413
3
      PrintStackTrace(env->isolate(), trace);
414
    }
415
  }
416
417
220
  fflush(stderr);
418
220
}
419
420
[[noreturn]] void FatalError(const char* location, const char* message) {
421
  OnFatalError(location, message);
422
  // to suppress compiler warning
423
  ABORT();
424
}
425
426
void OnFatalError(const char* location, const char* message) {
427
  if (location) {
428
    FPrintF(stderr, "FATAL ERROR: %s %s\n", location, message);
429
  } else {
430
    FPrintF(stderr, "FATAL ERROR: %s\n", message);
431
  }
432
433
  Isolate* isolate = Isolate::GetCurrent();
434
  Environment* env = nullptr;
435
  if (isolate != nullptr) {
436
    env = Environment::GetCurrent(isolate);
437
  }
438
  bool report_on_fatalerror;
439
  {
440
    Mutex::ScopedLock lock(node::per_process::cli_options_mutex);
441
    report_on_fatalerror = per_process::cli_options->report_on_fatalerror;
442
  }
443
444
  if (report_on_fatalerror) {
445
    report::TriggerNodeReport(
446
        isolate, env, message, "FatalError", "", Local<Object>());
447
  }
448
449
  fflush(stderr);
450
  ABORT();
451
}
452
453
namespace errors {
454
455
850815
TryCatchScope::~TryCatchScope() {
456


850821
  if (HasCaught() && !HasTerminated() && mode_ == CatchMode::kFatal) {
457
6
    HandleScope scope(env_->isolate());
458
6
    Local<v8::Value> exception = Exception();
459
6
    Local<v8::Message> message = Message();
460
6
    EnhanceFatalException enhance = CanContinue() ?
461
6
        EnhanceFatalException::kEnhance : EnhanceFatalException::kDontEnhance;
462
6
    if (message.IsEmpty())
463
      message = Exception::CreateMessage(env_->isolate(), exception);
464
6
    ReportFatalException(env_, exception, message, enhance);
465
6
    env_->Exit(7);
466
  }
467
850815
}
468
469
8
const char* errno_string(int errorno) {
470
#define ERRNO_CASE(e)                                                          \
471
  case e:                                                                      \
472
    return #e;
473



















8
  switch (errorno) {
474
#ifdef EACCES
475
    ERRNO_CASE(EACCES);
476
#endif
477
478
#ifdef EADDRINUSE
479
    ERRNO_CASE(EADDRINUSE);
480
#endif
481
482
#ifdef EADDRNOTAVAIL
483
    ERRNO_CASE(EADDRNOTAVAIL);
484
#endif
485
486
#ifdef EAFNOSUPPORT
487
    ERRNO_CASE(EAFNOSUPPORT);
488
#endif
489
490
#ifdef EAGAIN
491
    ERRNO_CASE(EAGAIN);
492
#endif
493
494
#ifdef EWOULDBLOCK
495
#if EAGAIN != EWOULDBLOCK
496
    ERRNO_CASE(EWOULDBLOCK);
497
#endif
498
#endif
499
500
#ifdef EALREADY
501
    ERRNO_CASE(EALREADY);
502
#endif
503
504
#ifdef EBADF
505
    ERRNO_CASE(EBADF);
506
#endif
507
508
#ifdef EBADMSG
509
    ERRNO_CASE(EBADMSG);
510
#endif
511
512
#ifdef EBUSY
513
    ERRNO_CASE(EBUSY);
514
#endif
515
516
#ifdef ECANCELED
517
    ERRNO_CASE(ECANCELED);
518
#endif
519
520
#ifdef ECHILD
521
1
    ERRNO_CASE(ECHILD);
522
#endif
523
524
#ifdef ECONNABORTED
525
    ERRNO_CASE(ECONNABORTED);
526
#endif
527
528
#ifdef ECONNREFUSED
529
    ERRNO_CASE(ECONNREFUSED);
530
#endif
531
532
#ifdef ECONNRESET
533
    ERRNO_CASE(ECONNRESET);
534
#endif
535
536
#ifdef EDEADLK
537
    ERRNO_CASE(EDEADLK);
538
#endif
539
540
#ifdef EDESTADDRREQ
541
    ERRNO_CASE(EDESTADDRREQ);
542
#endif
543
544
#ifdef EDOM
545
    ERRNO_CASE(EDOM);
546
#endif
547
548
#ifdef EDQUOT
549
    ERRNO_CASE(EDQUOT);
550
#endif
551
552
#ifdef EEXIST
553
    ERRNO_CASE(EEXIST);
554
#endif
555
556
#ifdef EFAULT
557
    ERRNO_CASE(EFAULT);
558
#endif
559
560
#ifdef EFBIG
561
    ERRNO_CASE(EFBIG);
562
#endif
563
564
#ifdef EHOSTUNREACH
565
    ERRNO_CASE(EHOSTUNREACH);
566
#endif
567
568
#ifdef EIDRM
569
    ERRNO_CASE(EIDRM);
570
#endif
571
572
#ifdef EILSEQ
573
    ERRNO_CASE(EILSEQ);
574
#endif
575
576
#ifdef EINPROGRESS
577
    ERRNO_CASE(EINPROGRESS);
578
#endif
579
580
#ifdef EINTR
581
    ERRNO_CASE(EINTR);
582
#endif
583
584
#ifdef EINVAL
585
    ERRNO_CASE(EINVAL);
586
#endif
587
588
#ifdef EIO
589
    ERRNO_CASE(EIO);
590
#endif
591
592
#ifdef EISCONN
593
    ERRNO_CASE(EISCONN);
594
#endif
595
596
#ifdef EISDIR
597
    ERRNO_CASE(EISDIR);
598
#endif
599
600
#ifdef ELOOP
601
    ERRNO_CASE(ELOOP);
602
#endif
603
604
#ifdef EMFILE
605
    ERRNO_CASE(EMFILE);
606
#endif
607
608
#ifdef EMLINK
609
    ERRNO_CASE(EMLINK);
610
#endif
611
612
#ifdef EMSGSIZE
613
    ERRNO_CASE(EMSGSIZE);
614
#endif
615
616
#ifdef EMULTIHOP
617
    ERRNO_CASE(EMULTIHOP);
618
#endif
619
620
#ifdef ENAMETOOLONG
621
    ERRNO_CASE(ENAMETOOLONG);
622
#endif
623
624
#ifdef ENETDOWN
625
    ERRNO_CASE(ENETDOWN);
626
#endif
627
628
#ifdef ENETRESET
629
    ERRNO_CASE(ENETRESET);
630
#endif
631
632
#ifdef ENETUNREACH
633
    ERRNO_CASE(ENETUNREACH);
634
#endif
635
636
#ifdef ENFILE
637
    ERRNO_CASE(ENFILE);
638
#endif
639
640
#ifdef ENOBUFS
641
    ERRNO_CASE(ENOBUFS);
642
#endif
643
644
#ifdef ENODATA
645
    ERRNO_CASE(ENODATA);
646
#endif
647
648
#ifdef ENODEV
649
    ERRNO_CASE(ENODEV);
650
#endif
651
652
#ifdef ENOENT
653
    ERRNO_CASE(ENOENT);
654
#endif
655
656
#ifdef ENOEXEC
657
    ERRNO_CASE(ENOEXEC);
658
#endif
659
660
#ifdef ENOLINK
661
    ERRNO_CASE(ENOLINK);
662
#endif
663
664
#ifdef ENOLCK
665
#if ENOLINK != ENOLCK
666
    ERRNO_CASE(ENOLCK);
667
#endif
668
#endif
669
670
#ifdef ENOMEM
671
    ERRNO_CASE(ENOMEM);
672
#endif
673
674
#ifdef ENOMSG
675
    ERRNO_CASE(ENOMSG);
676
#endif
677
678
#ifdef ENOPROTOOPT
679
    ERRNO_CASE(ENOPROTOOPT);
680
#endif
681
682
#ifdef ENOSPC
683
    ERRNO_CASE(ENOSPC);
684
#endif
685
686
#ifdef ENOSR
687
    ERRNO_CASE(ENOSR);
688
#endif
689
690
#ifdef ENOSTR
691
    ERRNO_CASE(ENOSTR);
692
#endif
693
694
#ifdef ENOSYS
695
    ERRNO_CASE(ENOSYS);
696
#endif
697
698
#ifdef ENOTCONN
699
    ERRNO_CASE(ENOTCONN);
700
#endif
701
702
#ifdef ENOTDIR
703
    ERRNO_CASE(ENOTDIR);
704
#endif
705
706
#ifdef ENOTEMPTY
707
#if ENOTEMPTY != EEXIST
708
    ERRNO_CASE(ENOTEMPTY);
709
#endif
710
#endif
711
712
#ifdef ENOTSOCK
713
    ERRNO_CASE(ENOTSOCK);
714
#endif
715
716
#ifdef ENOTSUP
717
    ERRNO_CASE(ENOTSUP);
718
#else
719
#ifdef EOPNOTSUPP
720
    ERRNO_CASE(EOPNOTSUPP);
721
#endif
722
#endif
723
724
#ifdef ENOTTY
725
    ERRNO_CASE(ENOTTY);
726
#endif
727
728
#ifdef ENXIO
729
    ERRNO_CASE(ENXIO);
730
#endif
731
732
#ifdef EOVERFLOW
733
    ERRNO_CASE(EOVERFLOW);
734
#endif
735
736
#ifdef EPERM
737
6
    ERRNO_CASE(EPERM);
738
#endif
739
740
#ifdef EPIPE
741
    ERRNO_CASE(EPIPE);
742
#endif
743
744
#ifdef EPROTO
745
    ERRNO_CASE(EPROTO);
746
#endif
747
748
#ifdef EPROTONOSUPPORT
749
    ERRNO_CASE(EPROTONOSUPPORT);
750
#endif
751
752
#ifdef EPROTOTYPE
753
    ERRNO_CASE(EPROTOTYPE);
754
#endif
755
756
#ifdef ERANGE
757
    ERRNO_CASE(ERANGE);
758
#endif
759
760
#ifdef EROFS
761
    ERRNO_CASE(EROFS);
762
#endif
763
764
#ifdef ESPIPE
765
    ERRNO_CASE(ESPIPE);
766
#endif
767
768
#ifdef ESRCH
769
1
    ERRNO_CASE(ESRCH);
770
#endif
771
772
#ifdef ESTALE
773
    ERRNO_CASE(ESTALE);
774
#endif
775
776
#ifdef ETIME
777
    ERRNO_CASE(ETIME);
778
#endif
779
780
#ifdef ETIMEDOUT
781
    ERRNO_CASE(ETIMEDOUT);
782
#endif
783
784
#ifdef ETXTBSY
785
    ERRNO_CASE(ETXTBSY);
786
#endif
787
788
#ifdef EXDEV
789
    ERRNO_CASE(EXDEV);
790
#endif
791
792
    default:
793
      return "";
794
  }
795
}
796
797
1418
void PerIsolateMessageListener(Local<Message> message, Local<Value> error) {
798
1418
  Isolate* isolate = message->GetIsolate();
799
1418
  switch (message->ErrorLevel()) {
800
1
    case Isolate::MessageErrorLevel::kMessageWarning: {
801
1
      Environment* env = Environment::GetCurrent(isolate);
802
1
      if (!env) {
803
        break;
804
      }
805
3
      Utf8Value filename(isolate, message->GetScriptOrigin().ResourceName());
806
      // (filename):(line) (message)
807
2
      std::stringstream warning;
808
1
      warning << *filename;
809
1
      warning << ":";
810
2
      warning << message->GetLineNumber(env->context()).FromMaybe(-1);
811
1
      warning << " ";
812
3
      v8::String::Utf8Value msg(isolate, message->Get());
813
1
      warning << *msg;
814
1
      USE(ProcessEmitWarningGeneric(env, warning.str().c_str(), "V8"));
815
1
      break;
816
    }
817
1417
    case Isolate::MessageErrorLevel::kMessageError:
818
1417
      TriggerUncaughtException(isolate, error, message);
819
1235
      break;
820
  }
821
1236
}
822
823
638
void SetPrepareStackTraceCallback(const FunctionCallbackInfo<Value>& args) {
824
638
  Environment* env = Environment::GetCurrent(args);
825
638
  CHECK(args[0]->IsFunction());
826
1276
  env->set_prepare_stack_trace_callback(args[0].As<Function>());
827
638
}
828
829
5269
static void SetSourceMapsEnabled(const FunctionCallbackInfo<Value>& args) {
830
5269
  Environment* env = Environment::GetCurrent(args);
831
5269
  CHECK(args[0]->IsBoolean());
832
10538
  env->set_source_maps_enabled(args[0].As<Boolean>()->Value());
833
5269
}
834
835
615
static void SetEnhanceStackForFatalException(
836
    const FunctionCallbackInfo<Value>& args) {
837
615
  Environment* env = Environment::GetCurrent(args);
838
615
  CHECK(args[0]->IsFunction());
839
615
  CHECK(args[1]->IsFunction());
840
1230
  env->set_enhance_fatal_stack_before_inspector(args[0].As<Function>());
841
1230
  env->set_enhance_fatal_stack_after_inspector(args[1].As<Function>());
842
615
}
843
844
// Side effect-free stringification that will never throw exceptions.
845
9
static void NoSideEffectsToString(const FunctionCallbackInfo<Value>& args) {
846
9
  Local<Context> context = args.GetIsolate()->GetCurrentContext();
847
  Local<String> detail_string;
848
18
  if (args[0]->ToDetailString(context).ToLocal(&detail_string))
849
18
    args.GetReturnValue().Set(detail_string);
850
9
}
851
852
47
static void TriggerUncaughtException(const FunctionCallbackInfo<Value>& args) {
853
47
  Isolate* isolate = args.GetIsolate();
854
47
  Environment* env = Environment::GetCurrent(isolate);
855
47
  Local<Value> exception = args[0];
856
47
  Local<Message> message = Exception::CreateMessage(isolate, exception);
857

47
  if (env != nullptr && env->abort_on_uncaught_exception()) {
858
    ReportFatalException(
859
        env, exception, message, EnhanceFatalException::kEnhance);
860
    Abort();
861
  }
862
47
  bool from_promise = args[1]->IsTrue();
863
47
  errors::TriggerUncaughtException(isolate, exception, message, from_promise);
864
11
}
865
866
4833
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
867
4833
  registry->Register(SetPrepareStackTraceCallback);
868
4833
  registry->Register(SetSourceMapsEnabled);
869
4833
  registry->Register(SetEnhanceStackForFatalException);
870
4833
  registry->Register(NoSideEffectsToString);
871
4833
  registry->Register(TriggerUncaughtException);
872
4833
}
873
874
615
void Initialize(Local<Object> target,
875
                Local<Value> unused,
876
                Local<Context> context,
877
                void* priv) {
878
615
  Environment* env = Environment::GetCurrent(context);
879
615
  env->SetMethod(
880
      target, "setPrepareStackTraceCallback", SetPrepareStackTraceCallback);
881
615
  env->SetMethod(target, "setSourceMapsEnabled", SetSourceMapsEnabled);
882
615
  env->SetMethod(target,
883
                 "setEnhanceStackForFatalException",
884
                 SetEnhanceStackForFatalException);
885
615
  env->SetMethodNoSideEffect(
886
      target, "noSideEffectsToString", NoSideEffectsToString);
887
615
  env->SetMethod(target, "triggerUncaughtException", TriggerUncaughtException);
888
615
}
889
890
313
void DecorateErrorStack(Environment* env,
891
                        const errors::TryCatchScope& try_catch) {
892
313
  Local<Value> exception = try_catch.Exception();
893
894
318
  if (!exception->IsObject()) return;
895
896
306
  Local<Object> err_obj = exception.As<Object>();
897
898
306
  if (IsExceptionDecorated(env, err_obj)) return;
899
900
303
  AppendExceptionLine(env, exception, try_catch.Message(), CONTEXTIFY_ERROR);
901
303
  TryCatchScope try_catch_scope(env);  // Ignore exceptions below.
902
606
  MaybeLocal<Value> stack = err_obj->Get(env->context(), env->stack_string());
903
  MaybeLocal<Value> maybe_value =
904
303
      err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol());
905
906
  Local<Value> arrow;
907

909
  if (!(maybe_value.ToLocal(&arrow) && arrow->IsString())) {
908
    return;
909
  }
910
911

909
  if (stack.IsEmpty() || !stack.ToLocalChecked()->IsString()) {
912
2
    return;
913
  }
914
915
  Local<String> decorated_stack = String::Concat(
916
      env->isolate(),
917
      String::Concat(env->isolate(),
918
                     arrow.As<String>(),
919
                     FIXED_ONE_BYTE_STRING(env->isolate(), "\n")),
920
903
      stack.ToLocalChecked().As<String>());
921
602
  USE(err_obj->Set(env->context(), env->stack_string(), decorated_stack));
922
  err_obj->SetPrivate(
923
602
      env->context(), env->decorated_private_symbol(), True(env->isolate()));
924
}
925
926
1473
void TriggerUncaughtException(Isolate* isolate,
927
                              Local<Value> error,
928
                              Local<Message> message,
929
                              bool from_promise) {
930
1473
  CHECK(!error.IsEmpty());
931
1473
  HandleScope scope(isolate);
932
933
1473
  if (message.IsEmpty()) message = Exception::CreateMessage(isolate, error);
934
935
1473
  CHECK(isolate->InContext());
936
1473
  Local<Context> context = isolate->GetCurrentContext();
937
1473
  Environment* env = Environment::GetCurrent(context);
938
1473
  if (env == nullptr) {
939
    // This means that the exception happens before Environment is assigned
940
    // to the context e.g. when there is a SyntaxError in a per-context
941
    // script - which usually indicates that there is a bug because no JS
942
    // error is supposed to be thrown at this point.
943
    // Since we don't have access to Environment here, there is not
944
    // much we can do, so we just print whatever is useful and crash.
945
    PrintException(isolate, context, error, message);
946
    Abort();
947
  }
948
949
  // Invoke process._fatalException() to give user a chance to handle it.
950
  // We have to grab it from the process object since this has been
951
  // monkey-patchable.
952
1473
  Local<Object> process_object = env->process_object();
953
1473
  Local<String> fatal_exception_string = env->fatal_exception_string();
954
  Local<Value> fatal_exception_function =
955
1473
      process_object->Get(env->context(),
956
2946
                          fatal_exception_string).ToLocalChecked();
957
  // If the exception happens before process._fatalException is attached
958
  // during bootstrap, or if the user has patched it incorrectly, exit
959
  // the current Node.js instance.
960
1473
  if (!fatal_exception_function->IsFunction()) {
961
2
    ReportFatalException(
962
        env, error, message, EnhanceFatalException::kDontEnhance);
963
2
    env->Exit(6);
964
1
    return;
965
  }
966
967
  MaybeLocal<Value> maybe_handled;
968
1471
  if (env->can_call_into_js()) {
969
    // We do not expect the global uncaught exception itself to throw any more
970
    // exceptions. If it does, exit the current Node.js instance.
971
    errors::TryCatchScope try_catch(env,
972
1465
                                    errors::TryCatchScope::CatchMode::kFatal);
973
    // Explicitly disable verbose exception reporting -
974
    // if process._fatalException() throws an error, we don't want it to
975
    // trigger the per-isolate message listener which will call this
976
    // function and recurse.
977
1465
    try_catch.SetVerbose(false);
978
    Local<Value> argv[2] = { error,
979
2930
                             Boolean::New(env->isolate(), from_promise) };
980
981
1465
    maybe_handled = fatal_exception_function.As<Function>()->Call(
982
1465
        env->context(), process_object, arraysize(argv), argv);
983
  }
984
985
  // If process._fatalException() throws, we are now exiting the Node.js
986
  // instance so return to continue the exit routine.
987
  // TODO(joyeecheung): return a Maybe here to prevent the caller from
988
  // stepping on the exit.
989
  Local<Value> handled;
990
1461
  if (!maybe_handled.ToLocal(&handled)) {
991
7
    return;
992
  }
993
994
  // The global uncaught exception handler returns true if the user handles it
995
  // by e.g. listening to `uncaughtException`. In that case, continue program
996
  // execution.
997
  // TODO(joyeecheung): This has been only checking that the return value is
998
  // exactly false. Investigate whether this can be turned to an "if true"
999
  // similar to how the worker global uncaught exception handler handles it.
1000
1454
  if (!handled->IsFalse()) {
1001
1242
    return;
1002
  }
1003
1004
  // Now we are certain that the exception is fatal.
1005
212
  ReportFatalException(env, error, message, EnhanceFatalException::kEnhance);
1006
212
  RunAtExit(env);
1007
1008
  // If the global uncaught exception handler sets process.exitCode,
1009
  // exit with that code. Otherwise, exit with 1.
1010
212
  Local<String> exit_code = env->exit_code_string();
1011
  Local<Value> code;
1012

636
  if (process_object->Get(env->context(), exit_code).ToLocal(&code) &&
1013
212
      code->IsInt32()) {
1014
211
    env->Exit(code.As<Int32>()->Value());
1015
  } else {
1016
1
    env->Exit(1);
1017
  }
1018
}
1019
1020
6
void TriggerUncaughtException(Isolate* isolate, const v8::TryCatch& try_catch) {
1021
  // If the try_catch is verbose, the per-isolate message listener is going to
1022
  // handle it (which is going to call into another overload of
1023
  // TriggerUncaughtException()).
1024
6
  if (try_catch.IsVerbose()) {
1025
    return;
1026
  }
1027
1028
  // If the user calls TryCatch::TerminateExecution() on this TryCatch
1029
  // they must call CancelTerminateExecution() again before invoking
1030
  // TriggerUncaughtException() because it will invoke
1031
  // process._fatalException() in the JS land.
1032
6
  CHECK(!try_catch.HasTerminated());
1033
6
  CHECK(try_catch.HasCaught());
1034
9
  HandleScope scope(isolate);
1035
6
  TriggerUncaughtException(isolate,
1036
                           try_catch.Exception(),
1037
                           try_catch.Message(),
1038
                           false /* from_promise */);
1039
}
1040
1041
}  // namespace errors
1042
1043
}  // namespace node
1044
1045
4906
NODE_MODULE_CONTEXT_AWARE_INTERNAL(errors, node::errors::Initialize)
1046
4833
NODE_MODULE_EXTERNAL_REFERENCE(errors, node::errors::RegisterExternalReferences)