GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_errors.cc Lines: 347 496 70.0 %
Date: 2022-08-21 04:19:51 Branches: 200 375 53.3 %

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

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

1092
    return maybe_value.ToLocal(&decorated) && decorated->IsTrue();
44
  }
45
15
  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
935
static std::string GetErrorSource(Isolate* isolate,
87
                                  Local<Context> context,
88
                                  Local<Message> message,
89
                                  bool* added_exception_line) {
90
935
  MaybeLocal<String> source_line_maybe = message->GetSourceLine(context);
91
1870
  node::Utf8Value encoded_source(isolate, source_line_maybe.ToLocalChecked());
92
1870
  std::string sourceline(*encoded_source, encoded_source.length());
93
935
  *added_exception_line = false;
94
95
935
  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
935
  Environment* env = Environment::GetCurrent(isolate);
102
  const bool has_source_map_url =
103
2805
      !message->GetScriptOrigin().SourceMapUrl().IsEmpty() &&
104
2805
      !message->GetScriptOrigin().SourceMapUrl()->IsUndefined();
105


935
  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
919
  ScriptOrigin origin = message->GetScriptOrigin();
136
1838
  node::Utf8Value filename(isolate, message->GetScriptResourceName());
137
919
  const char* filename_string = *filename;
138
919
  int linenum = message->GetLineNumber(context).FromJust();
139
140
919
  int script_start = (linenum - origin.LineOffset()) == 1
141
1081
                         ? origin.ColumnOffset()
142
919
                         : 0;
143
1838
  int start = message->GetStartColumn(context).FromMaybe(0);
144
919
  int end = message->GetEndColumn(context).FromMaybe(0);
145
919
  if (start >= script_start) {
146
918
    CHECK_GE(end, start);
147
918
    start -= script_start;
148
918
    end -= script_start;
149
  }
150
151
  std::string buf = SPrintF("%s:%i\n%s\n",
152
                            filename_string,
153
                            linenum,
154
1838
                            sourceline.c_str());
155
919
  CHECK_GT(buf.size(), 0);
156
919
  *added_exception_line = true;
157
158
2757
  if (start > end ||
159


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

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

2588
    if (sourceline[i] == '\0' || off >= kUnderlineBufsize) {
177
      break;
178
    }
179
2588
    CHECK_LT(off, kUnderlineBufsize);
180
2588
    underline_buf[off++] = '^';
181
  }
182
901
  CHECK_LE(off, kUnderlineBufsize);
183
901
  underline_buf[off++] = '\n';
184
185
901
  return buf + std::string(underline_buf, off);
186
}
187
188
7
void PrintStackTrace(Isolate* isolate, Local<StackTrace> stack) {
189
110
  for (int i = 0; i < stack->GetFrameCount(); i++) {
190
48
    Local<StackFrame> stack_frame = stack->GetFrame(isolate, i);
191
96
    node::Utf8Value fn_name_s(isolate, stack_frame->GetFunctionName());
192
96
    node::Utf8Value script_name(isolate, stack_frame->GetScriptName());
193
48
    const int line_number = stack_frame->GetLineNumber();
194
48
    const int column = stack_frame->GetColumn();
195
196
48
    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
48
    if (fn_name_s.length() == 0) {
210
19
      FPrintF(stderr, "    at %s:%i:%i\n", script_name, line_number, column);
211
    } else {
212
29
      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
579
void AppendExceptionLine(Environment* env,
248
                         Local<Value> er,
249
                         Local<Message> message,
250
                         enum ErrorHandlingMode mode) {
251
669
  if (message.IsEmpty()) return;
252
253
579
  HandleScope scope(env->isolate());
254
  Local<Object> err_obj;
255

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

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

1022
  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


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

1467
  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
262
static void ReportFatalException(Environment* env,
328
                                 Local<Value> error,
329
                                 Local<Message> message,
330
                                 EnhanceFatalException enhance_stack) {
331
262
  if (!env->can_call_into_js())
332
    enhance_stack = EnhanceFatalException::kDontEnhance;
333
334
262
  Isolate* isolate = env->isolate();
335
262
  CHECK(!error.IsEmpty());
336
262
  CHECK(!message.IsEmpty());
337
524
  HandleScope scope(isolate);
338
339
262
  AppendExceptionLine(env, error, message, FATAL_ERROR);
340
341
262
  auto report_to_inspector = [&]() {
342
#if HAVE_INSPECTOR
343
262
    env->inspector_agent()->ReportUncaughtException(error, message);
344
#endif
345
262
  };
346
347
  Local<Value> arrow;
348
  Local<Value> stack_trace;
349
262
  bool decorated = IsExceptionDecorated(env, error);
350
351
262
  if (!error->IsObject()) {  // We can only enhance actual errors.
352
15
    report_to_inspector();
353
30
    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
247
    Local<Object> err_obj = error.As<Object>();
360
361
490
    auto enhance_with = [&](Local<Function> enhancer) {
362
      Local<Value> enhanced;
363
490
      Local<Value> argv[] = {err_obj};
364
980
      if (!enhancer.IsEmpty() &&
365
          enhancer
366
1470
              ->Call(env->context(), Undefined(isolate), arraysize(argv), argv)
367
490
              .ToLocal(&enhanced)) {
368
486
        stack_trace = enhanced;
369
      }
370
737
    };
371
372
247
    switch (enhance_stack) {
373
245
      case EnhanceFatalException::kEnhance: {
374
245
        enhance_with(env->enhance_fatal_stack_before_inspector());
375
245
        report_to_inspector();
376
245
        enhance_with(env->enhance_fatal_stack_after_inspector());
377
245
        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
247
        err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol())
391
247
            .ToLocalChecked();
392
  }
393
394
524
  node::Utf8Value trace(env->isolate(), stack_trace);
395
524
  std::string report_message = "Exception";
396
397
  // range errors have a trace member set to undefined
398

782
  if (trace.length() > 0 && !stack_trace->IsUndefined()) {
399


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


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

34
              *message ? message.ToString() : "<toString() threw exception>");
425
    } else {
426
      node::Utf8Value name_string(env->isolate(), name.ToLocalChecked());
427
      node::Utf8Value message_string(env->isolate(), message.ToLocalChecked());
428
      // Update the report message if it is an object has message property.
429
      report_message = message_string.ToString();
430
431
      if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
432
        FPrintF(stderr, "%s: %s\n", name_string, message_string);
433
      } else {
434
        node::Utf8Value arrow_string(env->isolate(), arrow);
435
        FPrintF(stderr,
436
            "%s\n%s: %s\n", arrow_string, name_string, message_string);
437
      }
438
    }
439
440
17
    if (!env->options()->trace_uncaught) {
441
14
      std::string argv0;
442
14
      if (!env->argv().empty()) argv0 = env->argv()[0];
443
14
      if (argv0.empty()) argv0 = "node";
444
14
      FPrintF(stderr,
445
              "(Use `%s --trace-uncaught ...` to show where the exception "
446
              "was thrown)\n",
447
28
              fs::Basename(argv0, ".exe"));
448
    }
449
  }
450
451
262
  if (env->isolate_data()->options()->report_uncaught_exception) {
452
4
    report::TriggerNodeReport(
453
        isolate, env, report_message.c_str(), "Exception", "", error);
454
  }
455
456
262
  if (env->options()->trace_uncaught) {
457
3
    Local<StackTrace> trace = message->GetStackTrace();
458
3
    if (!trace.IsEmpty()) {
459
3
      FPrintF(stderr, "Thrown at:\n");
460
3
      PrintStackTrace(env->isolate(), trace);
461
    }
462
  }
463
464
262
  if (env->options()->extra_info_on_fatal_exception) {
465
261
    FPrintF(stderr, "\nNode.js %s\n", NODE_VERSION);
466
  }
467
468
262
  fflush(stderr);
469
262
}
470
471
[[noreturn]] void FatalError(const char* location, const char* message) {
472
  OnFatalError(location, message);
473
  // to suppress compiler warning
474
  ABORT();
475
}
476
477
void OnFatalError(const char* location, const char* message) {
478
  if (location) {
479
    FPrintF(stderr, "FATAL ERROR: %s %s\n", location, message);
480
  } else {
481
    FPrintF(stderr, "FATAL ERROR: %s\n", message);
482
  }
483
484
  Isolate* isolate = Isolate::TryGetCurrent();
485
  Environment* env = nullptr;
486
  if (isolate != nullptr) {
487
    env = Environment::GetCurrent(isolate);
488
  }
489
  bool report_on_fatalerror;
490
  {
491
    Mutex::ScopedLock lock(node::per_process::cli_options_mutex);
492
    report_on_fatalerror = per_process::cli_options->report_on_fatalerror;
493
  }
494
495
  if (report_on_fatalerror) {
496
    report::TriggerNodeReport(
497
        isolate, env, message, "FatalError", "", Local<Object>());
498
  }
499
500
  fflush(stderr);
501
  ABORT();
502
}
503
504
void OOMErrorHandler(const char* location, bool is_heap_oom) {
505
  const char* message =
506
      is_heap_oom ? "Allocation failed - JavaScript heap out of memory"
507
                  : "Allocation failed - process out of memory";
508
  if (location) {
509
    FPrintF(stderr, "FATAL ERROR: %s %s\n", location, message);
510
  } else {
511
    FPrintF(stderr, "FATAL ERROR: %s\n", message);
512
  }
513
514
  Isolate* isolate = Isolate::TryGetCurrent();
515
  Environment* env = nullptr;
516
  if (isolate != nullptr) {
517
    env = Environment::GetCurrent(isolate);
518
  }
519
  bool report_on_fatalerror;
520
  {
521
    Mutex::ScopedLock lock(node::per_process::cli_options_mutex);
522
    report_on_fatalerror = per_process::cli_options->report_on_fatalerror;
523
  }
524
525
  if (report_on_fatalerror) {
526
    report::TriggerNodeReport(
527
        isolate, env, message, "OOMError", "", Local<Object>());
528
  }
529
530
  fflush(stderr);
531
  ABORT();
532
}
533
534
2985
v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings(
535
    v8::Local<v8::Context> context,
536
    v8::Local<v8::Value> source,
537
    bool is_code_like) {
538
5970
  HandleScope scope(context->GetIsolate());
539
540
2985
  Environment* env = Environment::GetCurrent(context);
541
2985
  if (env->source_maps_enabled()) {
542
    // We do not expect the maybe_cache_generated_source_map to throw any more
543
    // exceptions. If it does, just ignore it.
544
4
    errors::TryCatchScope try_catch(env);
545
    Local<Function> maybe_cache_source_map =
546
2
        env->maybe_cache_generated_source_map();
547
2
    Local<Value> argv[1] = {source};
548
549
    MaybeLocal<Value> maybe_cached = maybe_cache_source_map->Call(
550
4
        context, context->Global(), arraysize(argv), argv);
551
2
    if (maybe_cached.IsEmpty()) {
552
      DCHECK(try_catch.HasCaught());
553
    }
554
  }
555
556
  Local<Value> allow_code_gen = context->GetEmbedderData(
557
5970
      ContextEmbedderIndex::kAllowCodeGenerationFromStrings);
558
  bool codegen_allowed =
559

8955
      allow_code_gen->IsUndefined() || allow_code_gen->IsTrue();
560
  return {
561
      codegen_allowed,
562
      {},
563
2985
  };
564
}
565
566
namespace errors {
567
568
1092357
TryCatchScope::~TryCatchScope() {
569


1092363
  if (HasCaught() && !HasTerminated() && mode_ == CatchMode::kFatal) {
570
6
    HandleScope scope(env_->isolate());
571
6
    Local<v8::Value> exception = Exception();
572
6
    Local<v8::Message> message = Message();
573
6
    EnhanceFatalException enhance = CanContinue() ?
574
6
        EnhanceFatalException::kEnhance : EnhanceFatalException::kDontEnhance;
575
6
    if (message.IsEmpty())
576
      message = Exception::CreateMessage(env_->isolate(), exception);
577
6
    ReportFatalException(env_, exception, message, enhance);
578
6
    env_->Exit(7);
579
  }
580
1092357
}
581
582
8
const char* errno_string(int errorno) {
583
#define ERRNO_CASE(e)                                                          \
584
  case e:                                                                      \
585
    return #e;
586



















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

87
  if (env != nullptr && env->abort_on_uncaught_exception()) {
985
    ReportFatalException(
986
        env, exception, message, EnhanceFatalException::kEnhance);
987
    Abort();
988
  }
989
87
  bool from_promise = args[1]->IsTrue();
990
87
  errors::TriggerUncaughtException(isolate, exception, message, from_promise);
991
13
}
992
993
5357
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
994
5357
  registry->Register(SetPrepareStackTraceCallback);
995
5357
  registry->Register(SetGetSourceMapErrorSource);
996
5357
  registry->Register(SetSourceMapsEnabled);
997
5357
  registry->Register(SetMaybeCacheGeneratedSourceMap);
998
5357
  registry->Register(SetEnhanceStackForFatalException);
999
5357
  registry->Register(NoSideEffectsToString);
1000
5357
  registry->Register(TriggerUncaughtException);
1001
5357
}
1002
1003
775
void Initialize(Local<Object> target,
1004
                Local<Value> unused,
1005
                Local<Context> context,
1006
                void* priv) {
1007
775
  SetMethod(context,
1008
            target,
1009
            "setPrepareStackTraceCallback",
1010
            SetPrepareStackTraceCallback);
1011
775
  SetMethod(context,
1012
            target,
1013
            "setGetSourceMapErrorSource",
1014
            SetGetSourceMapErrorSource);
1015
775
  SetMethod(context, target, "setSourceMapsEnabled", SetSourceMapsEnabled);
1016
775
  SetMethod(context,
1017
            target,
1018
            "setMaybeCacheGeneratedSourceMap",
1019
            SetMaybeCacheGeneratedSourceMap);
1020
775
  SetMethod(context,
1021
            target,
1022
            "setEnhanceStackForFatalException",
1023
            SetEnhanceStackForFatalException);
1024
775
  SetMethodNoSideEffect(
1025
      context, target, "noSideEffectsToString", NoSideEffectsToString);
1026
775
  SetMethod(
1027
      context, target, "triggerUncaughtException", TriggerUncaughtException);
1028
775
}
1029
1030
308
void DecorateErrorStack(Environment* env,
1031
                        const errors::TryCatchScope& try_catch) {
1032
308
  Local<Value> exception = try_catch.Exception();
1033
1034
314
  if (!exception->IsObject()) return;
1035
1036
299
  Local<Object> err_obj = exception.As<Object>();
1037
1038
299
  if (IsExceptionDecorated(env, err_obj)) return;
1039
1040
296
  AppendExceptionLine(env, exception, try_catch.Message(), CONTEXTIFY_ERROR);
1041
296
  TryCatchScope try_catch_scope(env);  // Ignore exceptions below.
1042
592
  MaybeLocal<Value> stack = err_obj->Get(env->context(), env->stack_string());
1043
  MaybeLocal<Value> maybe_value =
1044
296
      err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol());
1045
1046
  Local<Value> arrow;
1047

888
  if (!(maybe_value.ToLocal(&arrow) && arrow->IsString())) {
1048
    return;
1049
  }
1050
1051

886
  if (stack.IsEmpty() || !stack.ToLocalChecked()->IsString()) {
1052
3
    return;
1053
  }
1054
1055
  Local<String> decorated_stack = String::Concat(
1056
      env->isolate(),
1057
      String::Concat(env->isolate(),
1058
                     arrow.As<String>(),
1059
                     FIXED_ONE_BYTE_STRING(env->isolate(), "\n")),
1060
879
      stack.ToLocalChecked().As<String>());
1061
586
  USE(err_obj->Set(env->context(), env->stack_string(), decorated_stack));
1062
  err_obj->SetPrivate(
1063
586
      env->context(), env->decorated_private_symbol(), True(env->isolate()));
1064
}
1065
1066
1533
void TriggerUncaughtException(Isolate* isolate,
1067
                              Local<Value> error,
1068
                              Local<Message> message,
1069
                              bool from_promise) {
1070
1533
  CHECK(!error.IsEmpty());
1071
1533
  HandleScope scope(isolate);
1072
1073
1533
  if (message.IsEmpty()) message = Exception::CreateMessage(isolate, error);
1074
1075
1533
  CHECK(isolate->InContext());
1076
1533
  Local<Context> context = isolate->GetCurrentContext();
1077
1533
  Environment* env = Environment::GetCurrent(context);
1078
1533
  if (env == nullptr) {
1079
    // This means that the exception happens before Environment is assigned
1080
    // to the context e.g. when there is a SyntaxError in a per-context
1081
    // script - which usually indicates that there is a bug because no JS
1082
    // error is supposed to be thrown at this point.
1083
    // Since we don't have access to Environment here, there is not
1084
    // much we can do, so we just print whatever is useful and crash.
1085
    PrintException(isolate, context, error, message);
1086
    Abort();
1087
  }
1088
1089
  // Invoke process._fatalException() to give user a chance to handle it.
1090
  // We have to grab it from the process object since this has been
1091
  // monkey-patchable.
1092
1533
  Local<Object> process_object = env->process_object();
1093
1533
  Local<String> fatal_exception_string = env->fatal_exception_string();
1094
  Local<Value> fatal_exception_function =
1095
1533
      process_object->Get(env->context(),
1096
3066
                          fatal_exception_string).ToLocalChecked();
1097
  // If the exception happens before process._fatalException is attached
1098
  // during bootstrap, or if the user has patched it incorrectly, exit
1099
  // the current Node.js instance.
1100
1533
  if (!fatal_exception_function->IsFunction()) {
1101
2
    ReportFatalException(
1102
        env, error, message, EnhanceFatalException::kDontEnhance);
1103
2
    env->Exit(6);
1104
1
    return;
1105
  }
1106
1107
  MaybeLocal<Value> maybe_handled;
1108
1531
  if (env->can_call_into_js()) {
1109
    // We do not expect the global uncaught exception itself to throw any more
1110
    // exceptions. If it does, exit the current Node.js instance.
1111
    errors::TryCatchScope try_catch(env,
1112
1525
                                    errors::TryCatchScope::CatchMode::kFatal);
1113
    // Explicitly disable verbose exception reporting -
1114
    // if process._fatalException() throws an error, we don't want it to
1115
    // trigger the per-isolate message listener which will call this
1116
    // function and recurse.
1117
1525
    try_catch.SetVerbose(false);
1118
    Local<Value> argv[2] = { error,
1119
3050
                             Boolean::New(env->isolate(), from_promise) };
1120
1121
1525
    maybe_handled = fatal_exception_function.As<Function>()->Call(
1122
1525
        env->context(), process_object, arraysize(argv), argv);
1123
  }
1124
1125
  // If process._fatalException() throws, we are now exiting the Node.js
1126
  // instance so return to continue the exit routine.
1127
  // TODO(joyeecheung): return a Maybe here to prevent the caller from
1128
  // stepping on the exit.
1129
  Local<Value> handled;
1130
1517
  if (!maybe_handled.ToLocal(&handled)) {
1131
9
    return;
1132
  }
1133
1134
  // The global uncaught exception handler returns true if the user handles it
1135
  // by e.g. listening to `uncaughtException`. In that case, continue program
1136
  // execution.
1137
  // TODO(joyeecheung): This has been only checking that the return value is
1138
  // exactly false. Investigate whether this can be turned to an "if true"
1139
  // similar to how the worker global uncaught exception handler handles it.
1140
1508
  if (!handled->IsFalse()) {
1141
1254
    return;
1142
  }
1143
1144
  // Now we are certain that the exception is fatal.
1145
254
  ReportFatalException(env, error, message, EnhanceFatalException::kEnhance);
1146
254
  RunAtExit(env);
1147
1148
  // If the global uncaught exception handler sets process.exitCode,
1149
  // exit with that code. Otherwise, exit with 1.
1150
254
  Local<String> exit_code = env->exit_code_string();
1151
  Local<Value> code;
1152

762
  if (process_object->Get(env->context(), exit_code).ToLocal(&code) &&
1153
254
      code->IsInt32()) {
1154
253
    env->Exit(code.As<Int32>()->Value());
1155
  } else {
1156
1
    env->Exit(1);
1157
  }
1158
}
1159
1160
5
void TriggerUncaughtException(Isolate* isolate, const v8::TryCatch& try_catch) {
1161
  // If the try_catch is verbose, the per-isolate message listener is going to
1162
  // handle it (which is going to call into another overload of
1163
  // TriggerUncaughtException()).
1164
5
  if (try_catch.IsVerbose()) {
1165
    return;
1166
  }
1167
1168
  // If the user calls TryCatch::TerminateExecution() on this TryCatch
1169
  // they must call CancelTerminateExecution() again before invoking
1170
  // TriggerUncaughtException() because it will invoke
1171
  // process._fatalException() in the JS land.
1172
5
  CHECK(!try_catch.HasTerminated());
1173
5
  CHECK(try_catch.HasCaught());
1174
8
  HandleScope scope(isolate);
1175
5
  TriggerUncaughtException(isolate,
1176
                           try_catch.Exception(),
1177
                           try_catch.Message(),
1178
                           false /* from_promise */);
1179
}
1180
1181
}  // namespace errors
1182
1183
}  // namespace node
1184
1185
5429
NODE_MODULE_CONTEXT_AWARE_INTERNAL(errors, node::errors::Initialize)
1186
5357
NODE_MODULE_EXTERNAL_REFERENCE(errors, node::errors::RegisterExternalReferences)