GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_errors.cc Lines: 344 476 72.3 %
Date: 2022-08-12 04:19:25 Branches: 197 365 54.0 %

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
554
bool IsExceptionDecorated(Environment* env, Local<Value> er) {
38

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

1082
    return maybe_value.ToLocal(&decorated) && decorated->IsTrue();
44
  }
45
13
  return false;
46
}
47
48
namespace per_process {
49
static Mutex tty_mutex;
50
}  // namespace per_process
51
52
17
static std::string GetSourceMapErrorSource(Isolate* isolate,
53
                                           Local<Context> context,
54
                                           Local<Message> message,
55
                                           bool* added_exception_line) {
56
34
  v8::TryCatch try_catch(isolate);
57
34
  HandleScope handle_scope(isolate);
58
17
  Environment* env = Environment::GetCurrent(context);
59
60
  // The ScriptResourceName of the message may be different from the one we use
61
  // to compile the script. V8 replaces it when it detects magic comments in
62
  // the source texts.
63
17
  Local<Value> script_resource_name = message->GetScriptResourceName();
64
34
  int linenum = message->GetLineNumber(context).FromJust();
65
17
  int columnum = message->GetStartColumn(context).FromJust();
66
67
  Local<Value> argv[] = {script_resource_name,
68
                         v8::Int32::New(isolate, linenum),
69
34
                         v8::Int32::New(isolate, columnum)};
70
17
  MaybeLocal<Value> maybe_ret = env->get_source_map_error_source()->Call(
71
34
      context, Undefined(isolate), arraysize(argv), argv);
72
  Local<Value> ret;
73
17
  if (!maybe_ret.ToLocal(&ret)) {
74
    // Ignore the caught exceptions.
75
    DCHECK(try_catch.HasCaught());
76
    return std::string();
77
  }
78
34
  if (!ret->IsString()) {
79
1
    return std::string();
80
  }
81
16
  *added_exception_line = true;
82
16
  node::Utf8Value error_source_utf8(isolate, ret.As<String>());
83
16
  return *error_source_utf8;
84
}
85
86
929
static std::string GetErrorSource(Isolate* isolate,
87
                                  Local<Context> context,
88
                                  Local<Message> message,
89
                                  bool* added_exception_line) {
90
929
  MaybeLocal<String> source_line_maybe = message->GetSourceLine(context);
91
1858
  node::Utf8Value encoded_source(isolate, source_line_maybe.ToLocalChecked());
92
1858
  std::string sourceline(*encoded_source, encoded_source.length());
93
929
  *added_exception_line = false;
94
95
929
  if (sourceline.find("node-do-not-add-exception-line") != std::string::npos) {
96
    return sourceline;
97
  }
98
99
  // If source maps have been enabled, the exception line will instead be
100
  // added in the JavaScript context:
101
929
  Environment* env = Environment::GetCurrent(isolate);
102
  const bool has_source_map_url =
103
2787
      !message->GetScriptOrigin().SourceMapUrl().IsEmpty() &&
104
2787
      !message->GetScriptOrigin().SourceMapUrl()->IsUndefined();
105


929
  if (has_source_map_url && env != nullptr && env->source_maps_enabled()) {
106
    std::string source = GetSourceMapErrorSource(
107
17
        isolate, context, message, added_exception_line);
108
17
    if (*added_exception_line) {
109
16
      return source;
110
    }
111
  }
112
113
  // Because of how node modules work, all scripts are wrapped with a
114
  // "function (module, exports, __filename, ...) {"
115
  // to provide script local variables.
116
  //
117
  // When reporting errors on the first line of a script, this wrapper
118
  // function is leaked to the user. There used to be a hack here to
119
  // truncate off the first 62 characters, but it caused numerous other
120
  // problems when vm.runIn*Context() methods were used for non-module
121
  // code.
122
  //
123
  // If we ever decide to re-instate such a hack, the following steps
124
  // must be taken:
125
  //
126
  // 1. Pass a flag around to say "this code was wrapped"
127
  // 2. Update the stack frame output so that it is also correct.
128
  //
129
  // It would probably be simpler to add a line rather than add some
130
  // number of characters to the first line, since V8 truncates the
131
  // sourceline to 78 characters, and we end up not providing very much
132
  // useful debugging info to the user if we remove 62 characters.
133
134
  // Print (filename):(line number): (message).
135
913
  ScriptOrigin origin = message->GetScriptOrigin();
136
1826
  node::Utf8Value filename(isolate, message->GetScriptResourceName());
137
913
  const char* filename_string = *filename;
138
913
  int linenum = message->GetLineNumber(context).FromJust();
139
140
913
  int script_start = (linenum - origin.LineOffset()) == 1
141
1072
                         ? origin.ColumnOffset()
142
913
                         : 0;
143
1826
  int start = message->GetStartColumn(context).FromMaybe(0);
144
913
  int end = message->GetEndColumn(context).FromMaybe(0);
145
913
  if (start >= script_start) {
146
912
    CHECK_GE(end, start);
147
912
    start -= script_start;
148
912
    end -= script_start;
149
  }
150
151
  std::string buf = SPrintF("%s:%i\n%s\n",
152
                            filename_string,
153
                            linenum,
154
1826
                            sourceline.c_str());
155
913
  CHECK_GT(buf.size(), 0);
156
913
  *added_exception_line = true;
157
158
2739
  if (start > end ||
159


1825
      start < 0 ||
160
912
      static_cast<size_t>(end) > sourceline.size()) {
161
18
    return buf;
162
  }
163
164
895
  constexpr int kUnderlineBufsize = 1020;
165
  char underline_buf[kUnderlineBufsize + 4];
166
895
  int off = 0;
167
  // Print wavy underline (GetUnderline is deprecated).
168
5217
  for (int i = 0; i < start; i++) {
169

4322
    if (sourceline[i] == '\0' || off >= kUnderlineBufsize) {
170
      break;
171
    }
172
4322
    CHECK_LT(off, kUnderlineBufsize);
173
4322
    underline_buf[off++] = (sourceline[i] == '\t') ? '\t' : ' ';
174
  }
175
3477
  for (int i = start; i < end; i++) {
176

2582
    if (sourceline[i] == '\0' || off >= kUnderlineBufsize) {
177
      break;
178
    }
179
2582
    CHECK_LT(off, kUnderlineBufsize);
180
2582
    underline_buf[off++] = '^';
181
  }
182
895
  CHECK_LE(off, kUnderlineBufsize);
183
895
  underline_buf[off++] = '\n';
184
185
895
  return buf + std::string(underline_buf, off);
186
}
187
188
7
void PrintStackTrace(Isolate* isolate, Local<StackTrace> stack) {
189
104
  for (int i = 0; i < stack->GetFrameCount(); i++) {
190
45
    Local<StackFrame> stack_frame = stack->GetFrame(isolate, i);
191
90
    node::Utf8Value fn_name_s(isolate, stack_frame->GetFunctionName());
192
90
    node::Utf8Value script_name(isolate, stack_frame->GetScriptName());
193
45
    const int line_number = stack_frame->GetLineNumber();
194
45
    const int column = stack_frame->GetColumn();
195
196
45
    if (stack_frame->IsEval()) {
197
      if (stack_frame->GetScriptId() == Message::kNoScriptIdInfo) {
198
        FPrintF(stderr, "    at [eval]:%i:%i\n", line_number, column);
199
      } else {
200
        FPrintF(stderr,
201
                "    at [eval] (%s:%i:%i)\n",
202
                *script_name,
203
                line_number,
204
                column);
205
      }
206
      break;
207
    }
208
209
45
    if (fn_name_s.length() == 0) {
210
13
      FPrintF(stderr, "    at %s:%i:%i\n", script_name, line_number, column);
211
    } else {
212
32
      FPrintF(stderr,
213
              "    at %s (%s:%i:%i)\n",
214
              fn_name_s,
215
              script_name,
216
              line_number,
217
              column);
218
    }
219
  }
220
7
  fflush(stderr);
221
7
}
222
223
424
void PrintException(Isolate* isolate,
224
                    Local<Context> context,
225
                    Local<Value> err,
226
                    Local<Message> message) {
227
  node::Utf8Value reason(isolate,
228
424
                         err->ToDetailString(context)
229
848
                             .FromMaybe(Local<String>()));
230
424
  bool added_exception_line = false;
231
  std::string source =
232
848
      GetErrorSource(isolate, context, message, &added_exception_line);
233
424
  FPrintF(stderr, "%s\n", source);
234
424
  FPrintF(stderr, "%s\n", reason);
235
236
424
  Local<v8::StackTrace> stack = message->GetStackTrace();
237
424
  if (!stack.IsEmpty()) PrintStackTrace(isolate, stack);
238
424
}
239
240
424
void PrintCaughtException(Isolate* isolate,
241
                          Local<Context> context,
242
                          const v8::TryCatch& try_catch) {
243
424
  CHECK(try_catch.HasCaught());
244
424
  PrintException(isolate, context, try_catch.Exception(), try_catch.Message());
245
424
}
246
247
572
void AppendExceptionLine(Environment* env,
248
                         Local<Value> er,
249
                         Local<Message> message,
250
                         enum ErrorHandlingMode mode) {
251
660
  if (message.IsEmpty()) return;
252
253
572
  HandleScope scope(env->isolate());
254
  Local<Object> err_obj;
255

1144
  if (!er.IsEmpty() && er->IsObject()) {
256
559
    err_obj = er.As<Object>();
257
    // If arrow_message is already set, skip.
258
    auto maybe_value = err_obj->GetPrivate(env->context(),
259
559
                                          env->arrow_message_private_symbol());
260
    Local<Value> lvalue;
261

1677
    if (!maybe_value.ToLocal(&lvalue) || lvalue->IsString())
262
67
      return;
263
  }
264
265
505
  bool added_exception_line = false;
266
  std::string source = GetErrorSource(
267
505
      env->isolate(), env->context(), message, &added_exception_line);
268
505
  if (!added_exception_line) {
269
    return;
270
  }
271
505
  MaybeLocal<Value> arrow_str = ToV8Value(env->context(), source);
272
273

1010
  const bool can_set_arrow = !arrow_str.IsEmpty() && !err_obj.IsEmpty();
274
  // If allocating arrow_str failed, print it out. There's not much else to do.
275
  // If it's not an error, but something needs to be printed out because
276
  // it's a fatal exception, also print it out from here.
277
  // Otherwise, the arrow property will be attached to the object and handled
278
  // by the caller.
279


681
  if (!can_set_arrow || (mode == FATAL_ERROR && !err_obj->IsNativeError())) {
280
21
    if (env->printed_error()) return;
281
21
    Mutex::ScopedLock lock(per_process::tty_mutex);
282
21
    env->set_printed_error(true);
283
284
21
    ResetStdio();
285
21
    FPrintF(stderr, "\n%s", source);
286
21
    return;
287
  }
288
289

1452
  CHECK(err_obj
290
            ->SetPrivate(env->context(),
291
                         env->arrow_message_private_symbol(),
292
                         arrow_str.ToLocalChecked())
293
            .FromMaybe(false));
294
}
295
296
[[noreturn]] void Abort() {
297
  DumpBacktrace(stderr);
298
  fflush(stderr);
299
  ABORT_NO_BACKTRACE();
300
}
301
302
[[noreturn]] void Assert(const AssertionInfo& info) {
303
  std::string name = GetHumanReadableProcessName();
304
305
  fprintf(stderr,
306
          "%s: %s:%s%s Assertion `%s' failed.\n",
307
          name.c_str(),
308
          info.file_line,
309
          info.function,
310
          *info.function ? ":" : "",
311
          info.message);
312
  fflush(stderr);
313
314
  Abort();
315
}
316
317
enum class EnhanceFatalException { kEnhance, kDontEnhance };
318
319
/**
320
 * Report the exception to the inspector, then print it to stderr.
321
 * This should only be used when the Node.js instance is about to exit
322
 * (i.e. this should be followed by a env->Exit() or an Abort()).
323
 *
324
 * Use enhance_stack = EnhanceFatalException::kDontEnhance
325
 * when it's unsafe to call into JavaScript.
326
 */
327
256
static void ReportFatalException(Environment* env,
328
                                 Local<Value> error,
329
                                 Local<Message> message,
330
                                 EnhanceFatalException enhance_stack) {
331
256
  if (!env->can_call_into_js())
332
    enhance_stack = EnhanceFatalException::kDontEnhance;
333
334
256
  Isolate* isolate = env->isolate();
335
256
  CHECK(!error.IsEmpty());
336
256
  CHECK(!message.IsEmpty());
337
512
  HandleScope scope(isolate);
338
339
256
  AppendExceptionLine(env, error, message, FATAL_ERROR);
340
341
256
  auto report_to_inspector = [&]() {
342
#if HAVE_INSPECTOR
343
256
    env->inspector_agent()->ReportUncaughtException(error, message);
344
#endif
345
256
  };
346
347
  Local<Value> arrow;
348
  Local<Value> stack_trace;
349
256
  bool decorated = IsExceptionDecorated(env, error);
350
351
256
  if (!error->IsObject()) {  // We can only enhance actual errors.
352
13
    report_to_inspector();
353
26
    stack_trace = Undefined(isolate);
354
    // If error is not an object, AppendExceptionLine() has already print the
355
    // source line and the arrow to stderr.
356
    // TODO(joyeecheung): move that side effect out of AppendExceptionLine().
357
    // It is done just to preserve the source line as soon as possible.
358
  } else {
359
243
    Local<Object> err_obj = error.As<Object>();
360
361
482
    auto enhance_with = [&](Local<Function> enhancer) {
362
      Local<Value> enhanced;
363
482
      Local<Value> argv[] = {err_obj};
364
964
      if (!enhancer.IsEmpty() &&
365
          enhancer
366
1446
              ->Call(env->context(), Undefined(isolate), arraysize(argv), argv)
367
482
              .ToLocal(&enhanced)) {
368
478
        stack_trace = enhanced;
369
      }
370
725
    };
371
372
243
    switch (enhance_stack) {
373
241
      case EnhanceFatalException::kEnhance: {
374
241
        enhance_with(env->enhance_fatal_stack_before_inspector());
375
241
        report_to_inspector();
376
241
        enhance_with(env->enhance_fatal_stack_after_inspector());
377
241
        break;
378
      }
379
2
      case EnhanceFatalException::kDontEnhance: {
380
4
        USE(err_obj->Get(env->context(), env->stack_string())
381
2
                .ToLocal(&stack_trace));
382
2
        report_to_inspector();
383
2
        break;
384
      }
385
      default:
386
        UNREACHABLE();
387
    }
388
389
    arrow =
390
243
        err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol())
391
243
            .ToLocalChecked();
392
  }
393
394
512
  node::Utf8Value trace(env->isolate(), stack_trace);
395
396
  // range errors have a trace member set to undefined
397

764
  if (trace.length() > 0 && !stack_trace->IsUndefined()) {
398


723
    if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
399
66
      FPrintF(stderr, "%s\n", trace);
400
    } else {
401
350
      node::Utf8Value arrow_string(env->isolate(), arrow);
402
175
      FPrintF(stderr, "%s\n%s\n", arrow_string, trace);
403
    }
404
  } else {
405
    // this really only happens for RangeErrors, since they're the only
406
    // kind that won't have all this info in the trace, or when non-Error
407
    // objects are thrown manually.
408
    MaybeLocal<Value> message;
409
    MaybeLocal<Value> name;
410
411
15
    if (error->IsObject()) {
412
2
      Local<Object> err_obj = error.As<Object>();
413
4
      message = err_obj->Get(env->context(), env->message_string());
414
4
      name = err_obj->Get(env->context(), env->name_string());
415
    }
416
417
4
    if (message.IsEmpty() || message.ToLocalChecked()->IsUndefined() ||
418


17
        name.IsEmpty() || name.ToLocalChecked()->IsUndefined()) {
419
      // Not an error object. Just print as-is.
420
15
      node::Utf8Value message(env->isolate(), error);
421
422
15
      FPrintF(stderr, "%s\n",
423

30
              *message ? message.ToString() : "<toString() threw exception>");
424
    } else {
425
      node::Utf8Value name_string(env->isolate(), name.ToLocalChecked());
426
      node::Utf8Value message_string(env->isolate(), message.ToLocalChecked());
427
428
      if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
429
        FPrintF(stderr, "%s: %s\n", name_string, message_string);
430
      } else {
431
        node::Utf8Value arrow_string(env->isolate(), arrow);
432
        FPrintF(stderr,
433
            "%s\n%s: %s\n", arrow_string, name_string, message_string);
434
      }
435
    }
436
437
15
    if (!env->options()->trace_uncaught) {
438
12
      std::string argv0;
439
12
      if (!env->argv().empty()) argv0 = env->argv()[0];
440
12
      if (argv0.empty()) argv0 = "node";
441
12
      FPrintF(stderr,
442
              "(Use `%s --trace-uncaught ...` to show where the exception "
443
              "was thrown)\n",
444
24
              fs::Basename(argv0, ".exe"));
445
    }
446
  }
447
448
256
  if (env->options()->trace_uncaught) {
449
3
    Local<StackTrace> trace = message->GetStackTrace();
450
3
    if (!trace.IsEmpty()) {
451
3
      FPrintF(stderr, "Thrown at:\n");
452
3
      PrintStackTrace(env->isolate(), trace);
453
    }
454
  }
455
456
256
  if (env->options()->extra_info_on_fatal_exception) {
457
255
    FPrintF(stderr, "\nNode.js %s\n", NODE_VERSION);
458
  }
459
460
256
  fflush(stderr);
461
256
}
462
463
[[noreturn]] void FatalError(const char* location, const char* message) {
464
  OnFatalError(location, message);
465
  // to suppress compiler warning
466
  ABORT();
467
}
468
469
void OnFatalError(const char* location, const char* message) {
470
  if (location) {
471
    FPrintF(stderr, "FATAL ERROR: %s %s\n", location, message);
472
  } else {
473
    FPrintF(stderr, "FATAL ERROR: %s\n", message);
474
  }
475
476
  Isolate* isolate = Isolate::TryGetCurrent();
477
  Environment* env = nullptr;
478
  if (isolate != nullptr) {
479
    env = Environment::GetCurrent(isolate);
480
  }
481
  bool report_on_fatalerror;
482
  {
483
    Mutex::ScopedLock lock(node::per_process::cli_options_mutex);
484
    report_on_fatalerror = per_process::cli_options->report_on_fatalerror;
485
  }
486
487
  if (report_on_fatalerror) {
488
    report::TriggerNodeReport(
489
        isolate, env, message, "FatalError", "", Local<Object>());
490
  }
491
492
  fflush(stderr);
493
  ABORT();
494
}
495
496
1480
v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings(
497
    v8::Local<v8::Context> context,
498
    v8::Local<v8::Value> source,
499
    bool is_code_like) {
500
2960
  HandleScope scope(context->GetIsolate());
501
502
1480
  Environment* env = Environment::GetCurrent(context);
503
1480
  if (env->source_maps_enabled()) {
504
    // We do not expect the maybe_cache_generated_source_map to throw any more
505
    // exceptions. If it does, just ignore it.
506
4
    errors::TryCatchScope try_catch(env);
507
    Local<Function> maybe_cache_source_map =
508
2
        env->maybe_cache_generated_source_map();
509
2
    Local<Value> argv[1] = {source};
510
511
    MaybeLocal<Value> maybe_cached = maybe_cache_source_map->Call(
512
4
        context, context->Global(), arraysize(argv), argv);
513
2
    if (maybe_cached.IsEmpty()) {
514
      DCHECK(try_catch.HasCaught());
515
    }
516
  }
517
518
  Local<Value> allow_code_gen = context->GetEmbedderData(
519
2960
      ContextEmbedderIndex::kAllowCodeGenerationFromStrings);
520
  bool codegen_allowed =
521

4440
      allow_code_gen->IsUndefined() || allow_code_gen->IsTrue();
522
  return {
523
      codegen_allowed,
524
      {},
525
1480
  };
526
}
527
528
namespace errors {
529
530
1076044
TryCatchScope::~TryCatchScope() {
531


1076050
  if (HasCaught() && !HasTerminated() && mode_ == CatchMode::kFatal) {
532
6
    HandleScope scope(env_->isolate());
533
6
    Local<v8::Value> exception = Exception();
534
6
    Local<v8::Message> message = Message();
535
6
    EnhanceFatalException enhance = CanContinue() ?
536
6
        EnhanceFatalException::kEnhance : EnhanceFatalException::kDontEnhance;
537
6
    if (message.IsEmpty())
538
      message = Exception::CreateMessage(env_->isolate(), exception);
539
6
    ReportFatalException(env_, exception, message, enhance);
540
6
    env_->Exit(7);
541
  }
542
1076044
}
543
544
8
const char* errno_string(int errorno) {
545
#define ERRNO_CASE(e)                                                          \
546
  case e:                                                                      \
547
    return #e;
548



















8
  switch (errorno) {
549
#ifdef EACCES
550
    ERRNO_CASE(EACCES);
551
#endif
552
553
#ifdef EADDRINUSE
554
    ERRNO_CASE(EADDRINUSE);
555
#endif
556
557
#ifdef EADDRNOTAVAIL
558
    ERRNO_CASE(EADDRNOTAVAIL);
559
#endif
560
561
#ifdef EAFNOSUPPORT
562
    ERRNO_CASE(EAFNOSUPPORT);
563
#endif
564
565
#ifdef EAGAIN
566
    ERRNO_CASE(EAGAIN);
567
#endif
568
569
#ifdef EWOULDBLOCK
570
#if EAGAIN != EWOULDBLOCK
571
    ERRNO_CASE(EWOULDBLOCK);
572
#endif
573
#endif
574
575
#ifdef EALREADY
576
    ERRNO_CASE(EALREADY);
577
#endif
578
579
#ifdef EBADF
580
    ERRNO_CASE(EBADF);
581
#endif
582
583
#ifdef EBADMSG
584
    ERRNO_CASE(EBADMSG);
585
#endif
586
587
#ifdef EBUSY
588
    ERRNO_CASE(EBUSY);
589
#endif
590
591
#ifdef ECANCELED
592
    ERRNO_CASE(ECANCELED);
593
#endif
594
595
#ifdef ECHILD
596
1
    ERRNO_CASE(ECHILD);
597
#endif
598
599
#ifdef ECONNABORTED
600
    ERRNO_CASE(ECONNABORTED);
601
#endif
602
603
#ifdef ECONNREFUSED
604
    ERRNO_CASE(ECONNREFUSED);
605
#endif
606
607
#ifdef ECONNRESET
608
    ERRNO_CASE(ECONNRESET);
609
#endif
610
611
#ifdef EDEADLK
612
    ERRNO_CASE(EDEADLK);
613
#endif
614
615
#ifdef EDESTADDRREQ
616
    ERRNO_CASE(EDESTADDRREQ);
617
#endif
618
619
#ifdef EDOM
620
    ERRNO_CASE(EDOM);
621
#endif
622
623
#ifdef EDQUOT
624
    ERRNO_CASE(EDQUOT);
625
#endif
626
627
#ifdef EEXIST
628
    ERRNO_CASE(EEXIST);
629
#endif
630
631
#ifdef EFAULT
632
    ERRNO_CASE(EFAULT);
633
#endif
634
635
#ifdef EFBIG
636
    ERRNO_CASE(EFBIG);
637
#endif
638
639
#ifdef EHOSTUNREACH
640
    ERRNO_CASE(EHOSTUNREACH);
641
#endif
642
643
#ifdef EIDRM
644
    ERRNO_CASE(EIDRM);
645
#endif
646
647
#ifdef EILSEQ
648
    ERRNO_CASE(EILSEQ);
649
#endif
650
651
#ifdef EINPROGRESS
652
    ERRNO_CASE(EINPROGRESS);
653
#endif
654
655
#ifdef EINTR
656
    ERRNO_CASE(EINTR);
657
#endif
658
659
#ifdef EINVAL
660
    ERRNO_CASE(EINVAL);
661
#endif
662
663
#ifdef EIO
664
    ERRNO_CASE(EIO);
665
#endif
666
667
#ifdef EISCONN
668
    ERRNO_CASE(EISCONN);
669
#endif
670
671
#ifdef EISDIR
672
    ERRNO_CASE(EISDIR);
673
#endif
674
675
#ifdef ELOOP
676
    ERRNO_CASE(ELOOP);
677
#endif
678
679
#ifdef EMFILE
680
    ERRNO_CASE(EMFILE);
681
#endif
682
683
#ifdef EMLINK
684
    ERRNO_CASE(EMLINK);
685
#endif
686
687
#ifdef EMSGSIZE
688
    ERRNO_CASE(EMSGSIZE);
689
#endif
690
691
#ifdef EMULTIHOP
692
    ERRNO_CASE(EMULTIHOP);
693
#endif
694
695
#ifdef ENAMETOOLONG
696
    ERRNO_CASE(ENAMETOOLONG);
697
#endif
698
699
#ifdef ENETDOWN
700
    ERRNO_CASE(ENETDOWN);
701
#endif
702
703
#ifdef ENETRESET
704
    ERRNO_CASE(ENETRESET);
705
#endif
706
707
#ifdef ENETUNREACH
708
    ERRNO_CASE(ENETUNREACH);
709
#endif
710
711
#ifdef ENFILE
712
    ERRNO_CASE(ENFILE);
713
#endif
714
715
#ifdef ENOBUFS
716
    ERRNO_CASE(ENOBUFS);
717
#endif
718
719
#ifdef ENODATA
720
    ERRNO_CASE(ENODATA);
721
#endif
722
723
#ifdef ENODEV
724
    ERRNO_CASE(ENODEV);
725
#endif
726
727
#ifdef ENOENT
728
    ERRNO_CASE(ENOENT);
729
#endif
730
731
#ifdef ENOEXEC
732
    ERRNO_CASE(ENOEXEC);
733
#endif
734
735
#ifdef ENOLINK
736
    ERRNO_CASE(ENOLINK);
737
#endif
738
739
#ifdef ENOLCK
740
#if ENOLINK != ENOLCK
741
    ERRNO_CASE(ENOLCK);
742
#endif
743
#endif
744
745
#ifdef ENOMEM
746
    ERRNO_CASE(ENOMEM);
747
#endif
748
749
#ifdef ENOMSG
750
    ERRNO_CASE(ENOMSG);
751
#endif
752
753
#ifdef ENOPROTOOPT
754
    ERRNO_CASE(ENOPROTOOPT);
755
#endif
756
757
#ifdef ENOSPC
758
    ERRNO_CASE(ENOSPC);
759
#endif
760
761
#ifdef ENOSR
762
    ERRNO_CASE(ENOSR);
763
#endif
764
765
#ifdef ENOSTR
766
    ERRNO_CASE(ENOSTR);
767
#endif
768
769
#ifdef ENOSYS
770
    ERRNO_CASE(ENOSYS);
771
#endif
772
773
#ifdef ENOTCONN
774
    ERRNO_CASE(ENOTCONN);
775
#endif
776
777
#ifdef ENOTDIR
778
    ERRNO_CASE(ENOTDIR);
779
#endif
780
781
#ifdef ENOTEMPTY
782
#if ENOTEMPTY != EEXIST
783
    ERRNO_CASE(ENOTEMPTY);
784
#endif
785
#endif
786
787
#ifdef ENOTSOCK
788
    ERRNO_CASE(ENOTSOCK);
789
#endif
790
791
#ifdef ENOTSUP
792
    ERRNO_CASE(ENOTSUP);
793
#else
794
#ifdef EOPNOTSUPP
795
    ERRNO_CASE(EOPNOTSUPP);
796
#endif
797
#endif
798
799
#ifdef ENOTTY
800
    ERRNO_CASE(ENOTTY);
801
#endif
802
803
#ifdef ENXIO
804
    ERRNO_CASE(ENXIO);
805
#endif
806
807
#ifdef EOVERFLOW
808
    ERRNO_CASE(EOVERFLOW);
809
#endif
810
811
#ifdef EPERM
812
6
    ERRNO_CASE(EPERM);
813
#endif
814
815
#ifdef EPIPE
816
    ERRNO_CASE(EPIPE);
817
#endif
818
819
#ifdef EPROTO
820
    ERRNO_CASE(EPROTO);
821
#endif
822
823
#ifdef EPROTONOSUPPORT
824
    ERRNO_CASE(EPROTONOSUPPORT);
825
#endif
826
827
#ifdef EPROTOTYPE
828
    ERRNO_CASE(EPROTOTYPE);
829
#endif
830
831
#ifdef ERANGE
832
    ERRNO_CASE(ERANGE);
833
#endif
834
835
#ifdef EROFS
836
    ERRNO_CASE(EROFS);
837
#endif
838
839
#ifdef ESPIPE
840
    ERRNO_CASE(ESPIPE);
841
#endif
842
843
#ifdef ESRCH
844
1
    ERRNO_CASE(ESRCH);
845
#endif
846
847
#ifdef ESTALE
848
    ERRNO_CASE(ESTALE);
849
#endif
850
851
#ifdef ETIME
852
    ERRNO_CASE(ETIME);
853
#endif
854
855
#ifdef ETIMEDOUT
856
    ERRNO_CASE(ETIMEDOUT);
857
#endif
858
859
#ifdef ETXTBSY
860
    ERRNO_CASE(ETXTBSY);
861
#endif
862
863
#ifdef EXDEV
864
    ERRNO_CASE(EXDEV);
865
#endif
866
867
    default:
868
      return "";
869
  }
870
}
871
872
1426
void PerIsolateMessageListener(Local<Message> message, Local<Value> error) {
873
1426
  Isolate* isolate = message->GetIsolate();
874
1426
  switch (message->ErrorLevel()) {
875
1
    case Isolate::MessageErrorLevel::kMessageWarning: {
876
1
      Environment* env = Environment::GetCurrent(isolate);
877
1
      if (!env) {
878
        break;
879
      }
880
3
      Utf8Value filename(isolate, message->GetScriptOrigin().ResourceName());
881
      // (filename):(line) (message)
882
2
      std::stringstream warning;
883
1
      warning << *filename;
884
1
      warning << ":";
885
2
      warning << message->GetLineNumber(env->context()).FromMaybe(-1);
886
1
      warning << " ";
887
3
      v8::String::Utf8Value msg(isolate, message->Get());
888
1
      warning << *msg;
889
1
      USE(ProcessEmitWarningGeneric(env, warning.str().c_str(), "V8"));
890
1
      break;
891
    }
892
1425
    case Isolate::MessageErrorLevel::kMessageError:
893
1425
      TriggerUncaughtException(isolate, error, message);
894
1245
      break;
895
  }
896
1246
}
897
898
798
void SetPrepareStackTraceCallback(const FunctionCallbackInfo<Value>& args) {
899
798
  Environment* env = Environment::GetCurrent(args);
900
798
  CHECK(args[0]->IsFunction());
901
1596
  env->set_prepare_stack_trace_callback(args[0].As<Function>());
902
798
}
903
904
5899
static void SetSourceMapsEnabled(const FunctionCallbackInfo<Value>& args) {
905
5899
  Environment* env = Environment::GetCurrent(args);
906
5899
  CHECK(args[0]->IsBoolean());
907
11798
  env->set_source_maps_enabled(args[0].As<Boolean>()->Value());
908
5899
}
909
910
25
static void SetGetSourceMapErrorSource(
911
    const FunctionCallbackInfo<Value>& args) {
912
25
  Environment* env = Environment::GetCurrent(args);
913
25
  CHECK(args[0]->IsFunction());
914
50
  env->set_get_source_map_error_source(args[0].As<Function>());
915
25
}
916
917
6065
static void SetMaybeCacheGeneratedSourceMap(
918
    const FunctionCallbackInfo<Value>& args) {
919
6065
  Environment* env = Environment::GetCurrent(args);
920
6065
  CHECK(args[0]->IsFunction());
921
12130
  env->set_maybe_cache_generated_source_map(args[0].As<Function>());
922
6065
}
923
924
771
static void SetEnhanceStackForFatalException(
925
    const FunctionCallbackInfo<Value>& args) {
926
771
  Environment* env = Environment::GetCurrent(args);
927
771
  CHECK(args[0]->IsFunction());
928
771
  CHECK(args[1]->IsFunction());
929
1542
  env->set_enhance_fatal_stack_before_inspector(args[0].As<Function>());
930
1542
  env->set_enhance_fatal_stack_after_inspector(args[1].As<Function>());
931
771
}
932
933
// Side effect-free stringification that will never throw exceptions.
934
9
static void NoSideEffectsToString(const FunctionCallbackInfo<Value>& args) {
935
9
  Local<Context> context = args.GetIsolate()->GetCurrentContext();
936
  Local<String> detail_string;
937
18
  if (args[0]->ToDetailString(context).ToLocal(&detail_string))
938
18
    args.GetReturnValue().Set(detail_string);
939
9
}
940
941
87
static void TriggerUncaughtException(const FunctionCallbackInfo<Value>& args) {
942
87
  Isolate* isolate = args.GetIsolate();
943
87
  Environment* env = Environment::GetCurrent(isolate);
944
87
  Local<Value> exception = args[0];
945
87
  Local<Message> message = Exception::CreateMessage(isolate, exception);
946

87
  if (env != nullptr && env->abort_on_uncaught_exception()) {
947
    ReportFatalException(
948
        env, exception, message, EnhanceFatalException::kEnhance);
949
    Abort();
950
  }
951
87
  bool from_promise = args[1]->IsTrue();
952
87
  errors::TriggerUncaughtException(isolate, exception, message, from_promise);
953
13
}
954
955
5337
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
956
5337
  registry->Register(SetPrepareStackTraceCallback);
957
5337
  registry->Register(SetGetSourceMapErrorSource);
958
5337
  registry->Register(SetSourceMapsEnabled);
959
5337
  registry->Register(SetMaybeCacheGeneratedSourceMap);
960
5337
  registry->Register(SetEnhanceStackForFatalException);
961
5337
  registry->Register(NoSideEffectsToString);
962
5337
  registry->Register(TriggerUncaughtException);
963
5337
}
964
965
771
void Initialize(Local<Object> target,
966
                Local<Value> unused,
967
                Local<Context> context,
968
                void* priv) {
969
771
  SetMethod(context,
970
            target,
971
            "setPrepareStackTraceCallback",
972
            SetPrepareStackTraceCallback);
973
771
  SetMethod(context,
974
            target,
975
            "setGetSourceMapErrorSource",
976
            SetGetSourceMapErrorSource);
977
771
  SetMethod(context, target, "setSourceMapsEnabled", SetSourceMapsEnabled);
978
771
  SetMethod(context,
979
            target,
980
            "setMaybeCacheGeneratedSourceMap",
981
            SetMaybeCacheGeneratedSourceMap);
982
771
  SetMethod(context,
983
            target,
984
            "setEnhanceStackForFatalException",
985
            SetEnhanceStackForFatalException);
986
771
  SetMethodNoSideEffect(
987
      context, target, "noSideEffectsToString", NoSideEffectsToString);
988
771
  SetMethod(
989
      context, target, "triggerUncaughtException", TriggerUncaughtException);
990
771
}
991
992
305
void DecorateErrorStack(Environment* env,
993
                        const errors::TryCatchScope& try_catch) {
994
305
  Local<Value> exception = try_catch.Exception();
995
996
310
  if (!exception->IsObject()) return;
997
998
298
  Local<Object> err_obj = exception.As<Object>();
999
1000
298
  if (IsExceptionDecorated(env, err_obj)) return;
1001
1002
295
  AppendExceptionLine(env, exception, try_catch.Message(), CONTEXTIFY_ERROR);
1003
295
  TryCatchScope try_catch_scope(env);  // Ignore exceptions below.
1004
590
  MaybeLocal<Value> stack = err_obj->Get(env->context(), env->stack_string());
1005
  MaybeLocal<Value> maybe_value =
1006
295
      err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol());
1007
1008
  Local<Value> arrow;
1009

885
  if (!(maybe_value.ToLocal(&arrow) && arrow->IsString())) {
1010
    return;
1011
  }
1012
1013

885
  if (stack.IsEmpty() || !stack.ToLocalChecked()->IsString()) {
1014
2
    return;
1015
  }
1016
1017
  Local<String> decorated_stack = String::Concat(
1018
      env->isolate(),
1019
      String::Concat(env->isolate(),
1020
                     arrow.As<String>(),
1021
                     FIXED_ONE_BYTE_STRING(env->isolate(), "\n")),
1022
879
      stack.ToLocalChecked().As<String>());
1023
586
  USE(err_obj->Set(env->context(), env->stack_string(), decorated_stack));
1024
  err_obj->SetPrivate(
1025
586
      env->context(), env->decorated_private_symbol(), True(env->isolate()));
1026
}
1027
1028
1525
void TriggerUncaughtException(Isolate* isolate,
1029
                              Local<Value> error,
1030
                              Local<Message> message,
1031
                              bool from_promise) {
1032
1525
  CHECK(!error.IsEmpty());
1033
1525
  HandleScope scope(isolate);
1034
1035
1525
  if (message.IsEmpty()) message = Exception::CreateMessage(isolate, error);
1036
1037
1525
  CHECK(isolate->InContext());
1038
1525
  Local<Context> context = isolate->GetCurrentContext();
1039
1525
  Environment* env = Environment::GetCurrent(context);
1040
1525
  if (env == nullptr) {
1041
    // This means that the exception happens before Environment is assigned
1042
    // to the context e.g. when there is a SyntaxError in a per-context
1043
    // script - which usually indicates that there is a bug because no JS
1044
    // error is supposed to be thrown at this point.
1045
    // Since we don't have access to Environment here, there is not
1046
    // much we can do, so we just print whatever is useful and crash.
1047
    PrintException(isolate, context, error, message);
1048
    Abort();
1049
  }
1050
1051
  // Invoke process._fatalException() to give user a chance to handle it.
1052
  // We have to grab it from the process object since this has been
1053
  // monkey-patchable.
1054
1525
  Local<Object> process_object = env->process_object();
1055
1525
  Local<String> fatal_exception_string = env->fatal_exception_string();
1056
  Local<Value> fatal_exception_function =
1057
1525
      process_object->Get(env->context(),
1058
3050
                          fatal_exception_string).ToLocalChecked();
1059
  // If the exception happens before process._fatalException is attached
1060
  // during bootstrap, or if the user has patched it incorrectly, exit
1061
  // the current Node.js instance.
1062
1525
  if (!fatal_exception_function->IsFunction()) {
1063
2
    ReportFatalException(
1064
        env, error, message, EnhanceFatalException::kDontEnhance);
1065
2
    env->Exit(6);
1066
1
    return;
1067
  }
1068
1069
  MaybeLocal<Value> maybe_handled;
1070
1523
  if (env->can_call_into_js()) {
1071
    // We do not expect the global uncaught exception itself to throw any more
1072
    // exceptions. If it does, exit the current Node.js instance.
1073
    errors::TryCatchScope try_catch(env,
1074
1517
                                    errors::TryCatchScope::CatchMode::kFatal);
1075
    // Explicitly disable verbose exception reporting -
1076
    // if process._fatalException() throws an error, we don't want it to
1077
    // trigger the per-isolate message listener which will call this
1078
    // function and recurse.
1079
1517
    try_catch.SetVerbose(false);
1080
    Local<Value> argv[2] = { error,
1081
3034
                             Boolean::New(env->isolate(), from_promise) };
1082
1083
1517
    maybe_handled = fatal_exception_function.As<Function>()->Call(
1084
1517
        env->context(), process_object, arraysize(argv), argv);
1085
  }
1086
1087
  // If process._fatalException() throws, we are now exiting the Node.js
1088
  // instance so return to continue the exit routine.
1089
  // TODO(joyeecheung): return a Maybe here to prevent the caller from
1090
  // stepping on the exit.
1091
  Local<Value> handled;
1092
1513
  if (!maybe_handled.ToLocal(&handled)) {
1093
8
    return;
1094
  }
1095
1096
  // The global uncaught exception handler returns true if the user handles it
1097
  // by e.g. listening to `uncaughtException`. In that case, continue program
1098
  // execution.
1099
  // TODO(joyeecheung): This has been only checking that the return value is
1100
  // exactly false. Investigate whether this can be turned to an "if true"
1101
  // similar to how the worker global uncaught exception handler handles it.
1102
1505
  if (!handled->IsFalse()) {
1103
1257
    return;
1104
  }
1105
1106
  // Now we are certain that the exception is fatal.
1107
248
  ReportFatalException(env, error, message, EnhanceFatalException::kEnhance);
1108
248
  RunAtExit(env);
1109
1110
  // If the global uncaught exception handler sets process.exitCode,
1111
  // exit with that code. Otherwise, exit with 1.
1112
248
  Local<String> exit_code = env->exit_code_string();
1113
  Local<Value> code;
1114

744
  if (process_object->Get(env->context(), exit_code).ToLocal(&code) &&
1115
248
      code->IsInt32()) {
1116
247
    env->Exit(code.As<Int32>()->Value());
1117
  } else {
1118
1
    env->Exit(1);
1119
  }
1120
}
1121
1122
5
void TriggerUncaughtException(Isolate* isolate, const v8::TryCatch& try_catch) {
1123
  // If the try_catch is verbose, the per-isolate message listener is going to
1124
  // handle it (which is going to call into another overload of
1125
  // TriggerUncaughtException()).
1126
5
  if (try_catch.IsVerbose()) {
1127
    return;
1128
  }
1129
1130
  // If the user calls TryCatch::TerminateExecution() on this TryCatch
1131
  // they must call CancelTerminateExecution() again before invoking
1132
  // TriggerUncaughtException() because it will invoke
1133
  // process._fatalException() in the JS land.
1134
5
  CHECK(!try_catch.HasTerminated());
1135
5
  CHECK(try_catch.HasCaught());
1136
8
  HandleScope scope(isolate);
1137
5
  TriggerUncaughtException(isolate,
1138
                           try_catch.Exception(),
1139
                           try_catch.Message(),
1140
                           false /* from_promise */);
1141
}
1142
1143
}  // namespace errors
1144
1145
}  // namespace node
1146
1147
5409
NODE_MODULE_CONTEXT_AWARE_INTERNAL(errors, node::errors::Initialize)
1148
5337
NODE_MODULE_EXTERNAL_REFERENCE(errors, node::errors::RegisterExternalReferences)