GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_errors.cc Lines: 347 480 72.3 %
Date: 2022-08-17 04:19:55 Branches: 200 367 54.5 %

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

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

1088
    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
933
static std::string GetErrorSource(Isolate* isolate,
87
                                  Local<Context> context,
88
                                  Local<Message> message,
89
                                  bool* added_exception_line) {
90
933
  MaybeLocal<String> source_line_maybe = message->GetSourceLine(context);
91
1866
  node::Utf8Value encoded_source(isolate, source_line_maybe.ToLocalChecked());
92
1866
  std::string sourceline(*encoded_source, encoded_source.length());
93
933
  *added_exception_line = false;
94
95
933
  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
933
  Environment* env = Environment::GetCurrent(isolate);
102
  const bool has_source_map_url =
103
2799
      !message->GetScriptOrigin().SourceMapUrl().IsEmpty() &&
104
2799
      !message->GetScriptOrigin().SourceMapUrl()->IsUndefined();
105


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


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

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

2586
    if (sourceline[i] == '\0' || off >= kUnderlineBufsize) {
177
      break;
178
    }
179
2586
    CHECK_LT(off, kUnderlineBufsize);
180
2586
    underline_buf[off++] = '^';
181
  }
182
899
  CHECK_LE(off, kUnderlineBufsize);
183
899
  underline_buf[off++] = '\n';
184
185
899
  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
577
void AppendExceptionLine(Environment* env,
248
                         Local<Value> er,
249
                         Local<Message> message,
250
                         enum ErrorHandlingMode mode) {
251
667
  if (message.IsEmpty()) return;
252
253
577
  HandleScope scope(env->isolate());
254
  Local<Object> err_obj;
255

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

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

1018
  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


686
  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

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

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


729
    if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
400
66
      FPrintF(stderr, "%s\n", trace);
401
    } else {
402
354
      node::Utf8Value arrow_string(env->isolate(), arrow);
403
177
      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
260
  if (env->isolate_data()->options()->report_uncaught_exception) {
452
4
    report::TriggerNodeReport(
453
        isolate, env, report_message.c_str(), "Exception", "", error);
454
  }
455
456
260
  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
260
  if (env->options()->extra_info_on_fatal_exception) {
465
259
    FPrintF(stderr, "\nNode.js %s\n", NODE_VERSION);
466
  }
467
468
260
  fflush(stderr);
469
260
}
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
1405
v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings(
505
    v8::Local<v8::Context> context,
506
    v8::Local<v8::Value> source,
507
    bool is_code_like) {
508
2810
  HandleScope scope(context->GetIsolate());
509
510
1405
  Environment* env = Environment::GetCurrent(context);
511
1405
  if (env->source_maps_enabled()) {
512
    // We do not expect the maybe_cache_generated_source_map to throw any more
513
    // exceptions. If it does, just ignore it.
514
4
    errors::TryCatchScope try_catch(env);
515
    Local<Function> maybe_cache_source_map =
516
2
        env->maybe_cache_generated_source_map();
517
2
    Local<Value> argv[1] = {source};
518
519
    MaybeLocal<Value> maybe_cached = maybe_cache_source_map->Call(
520
4
        context, context->Global(), arraysize(argv), argv);
521
2
    if (maybe_cached.IsEmpty()) {
522
      DCHECK(try_catch.HasCaught());
523
    }
524
  }
525
526
  Local<Value> allow_code_gen = context->GetEmbedderData(
527
2810
      ContextEmbedderIndex::kAllowCodeGenerationFromStrings);
528
  bool codegen_allowed =
529

4215
      allow_code_gen->IsUndefined() || allow_code_gen->IsTrue();
530
  return {
531
      codegen_allowed,
532
      {},
533
1405
  };
534
}
535
536
namespace errors {
537
538
1083537
TryCatchScope::~TryCatchScope() {
539


1083543
  if (HasCaught() && !HasTerminated() && mode_ == CatchMode::kFatal) {
540
6
    HandleScope scope(env_->isolate());
541
6
    Local<v8::Value> exception = Exception();
542
6
    Local<v8::Message> message = Message();
543
6
    EnhanceFatalException enhance = CanContinue() ?
544
6
        EnhanceFatalException::kEnhance : EnhanceFatalException::kDontEnhance;
545
6
    if (message.IsEmpty())
546
      message = Exception::CreateMessage(env_->isolate(), exception);
547
6
    ReportFatalException(env_, exception, message, enhance);
548
6
    env_->Exit(7);
549
  }
550
1083537
}
551
552
8
const char* errno_string(int errorno) {
553
#define ERRNO_CASE(e)                                                          \
554
  case e:                                                                      \
555
    return #e;
556



















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

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

888
  if (!(maybe_value.ToLocal(&arrow) && arrow->IsString())) {
1018
    return;
1019
  }
1020
1021

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

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