GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_errors.cc Lines: 245 377 65.0 %
Date: 2019-07-28 22:34:34 Branches: 165 329 50.2 %

Line Branch Exec Source
1
#include <cerrno>
2
#include <cstdarg>
3
4
#include "node_errors.h"
5
#include "node_internals.h"
6
#ifdef NODE_REPORT
7
#include "node_report.h"
8
#endif
9
#include "node_process.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::Number;
30
using v8::Object;
31
using v8::ScriptOrigin;
32
using v8::StackFrame;
33
using v8::StackTrace;
34
using v8::String;
35
using v8::Undefined;
36
using v8::Value;
37
38
449
bool IsExceptionDecorated(Environment* env, Local<Value> er) {
39

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

886
    return maybe_value.ToLocal(&decorated) && decorated->IsTrue();
45
  }
46
6
  return false;
47
}
48
49
namespace per_process {
50
4828
static Mutex tty_mutex;
51
}  // namespace per_process
52
53
static const int kMaxErrorSourceLength = 1024;
54
55
455
static std::string GetErrorSource(Isolate* isolate,
56
                                  Local<Context> context,
57
                                  Local<Message> message,
58
                                  bool* added_exception_line) {
59
455
  MaybeLocal<String> source_line_maybe = message->GetSourceLine(context);
60
455
  node::Utf8Value encoded_source(isolate, source_line_maybe.ToLocalChecked());
61
910
  std::string sourceline(*encoded_source, encoded_source.length());
62
63
455
  if (sourceline.find("node-do-not-add-exception-line") != std::string::npos) {
64
8
    *added_exception_line = false;
65
8
    return sourceline;
66
  }
67
68
  // Because of how node modules work, all scripts are wrapped with a
69
  // "function (module, exports, __filename, ...) {"
70
  // to provide script local variables.
71
  //
72
  // When reporting errors on the first line of a script, this wrapper
73
  // function is leaked to the user. There used to be a hack here to
74
  // truncate off the first 62 characters, but it caused numerous other
75
  // problems when vm.runIn*Context() methods were used for non-module
76
  // code.
77
  //
78
  // If we ever decide to re-instate such a hack, the following steps
79
  // must be taken:
80
  //
81
  // 1. Pass a flag around to say "this code was wrapped"
82
  // 2. Update the stack frame output so that it is also correct.
83
  //
84
  // It would probably be simpler to add a line rather than add some
85
  // number of characters to the first line, since V8 truncates the
86
  // sourceline to 78 characters, and we end up not providing very much
87
  // useful debugging info to the user if we remove 62 characters.
88
89
  // Print (filename):(line number): (message).
90
447
  ScriptOrigin origin = message->GetScriptOrigin();
91
894
  node::Utf8Value filename(isolate, message->GetScriptResourceName());
92
447
  const char* filename_string = *filename;
93
894
  int linenum = message->GetLineNumber(context).FromJust();
94
95
1788
  int script_start = (linenum - origin.ResourceLineOffset()->Value()) == 1
96
717
                         ? origin.ResourceColumnOffset()->Value()
97
717
                         : 0;
98
1341
  int start = message->GetStartColumn(context).FromMaybe(0);
99
1341
  int end = message->GetEndColumn(context).FromMaybe(0);
100
447
  if (start >= script_start) {
101
447
    CHECK_GE(end, start);
102
447
    start -= script_start;
103
447
    end -= script_start;
104
  }
105
106
447
  int max_off = kMaxErrorSourceLength - 2;
107
108
  char buf[kMaxErrorSourceLength];
109
  int off = snprintf(buf,
110
                     kMaxErrorSourceLength,
111
                     "%s:%i\n%s\n",
112
                     filename_string,
113
                     linenum,
114
447
                     sourceline.c_str());
115
447
  CHECK_GE(off, 0);
116
447
  if (off > max_off) {
117
2
    off = max_off;
118
  }
119
120
  // Print wavy underline (GetUnderline is deprecated).
121
2554
  for (int i = 0; i < start; i++) {
122

2107
    if (sourceline[i] == '\0' || off >= max_off) {
123
      break;
124
    }
125
2107
    CHECK_LT(off, max_off);
126
2107
    buf[off++] = (sourceline[i] == '\t') ? '\t' : ' ';
127
  }
128
1831
  for (int i = start; i < end; i++) {
129

1407
    if (sourceline[i] == '\0' || off >= max_off) {
130
23
      break;
131
    }
132
1384
    CHECK_LT(off, max_off);
133
1384
    buf[off++] = '^';
134
  }
135
447
  CHECK_LE(off, max_off);
136
447
  buf[off] = '\n';
137
447
  buf[off + 1] = '\0';
138
139
447
  *added_exception_line = true;
140
902
  return std::string(buf);
141
}
142
143
32
void PrintStackTrace(Isolate* isolate, Local<StackTrace> stack) {
144
512
  for (int i = 0; i < stack->GetFrameCount() - 1; i++) {
145
448
    Local<StackFrame> stack_frame = stack->GetFrame(isolate, i);
146
448
    node::Utf8Value fn_name_s(isolate, stack_frame->GetFunctionName());
147
672
    node::Utf8Value script_name(isolate, stack_frame->GetScriptName());
148
224
    const int line_number = stack_frame->GetLineNumber();
149
224
    const int column = stack_frame->GetColumn();
150
151
224
    if (stack_frame->IsEval()) {
152
      if (stack_frame->GetScriptId() == Message::kNoScriptIdInfo) {
153
        fprintf(stderr, "    at [eval]:%i:%i\n", line_number, column);
154
      } else {
155
        fprintf(stderr,
156
                "    at [eval] (%s:%i:%i)\n",
157
                *script_name,
158
                line_number,
159
                column);
160
      }
161
      break;
162
    }
163
164
224
    if (fn_name_s.length() == 0) {
165
18
      fprintf(stderr, "    at %s:%i:%i\n", *script_name, line_number, column);
166
    } else {
167
      fprintf(stderr,
168
              "    at %s (%s:%i:%i)\n",
169
              *fn_name_s,
170
              *script_name,
171
              line_number,
172
206
              column);
173
    }
174
224
  }
175
32
  fflush(stderr);
176
32
}
177
178
void PrintException(Isolate* isolate,
179
                    Local<Context> context,
180
                    Local<Value> err,
181
                    Local<Message> message) {
182
  node::Utf8Value reason(isolate,
183
                         err->ToDetailString(context)
184
                             .FromMaybe(Local<String>()));
185
  bool added_exception_line = false;
186
  std::string source =
187
      GetErrorSource(isolate, context, message, &added_exception_line);
188
  fprintf(stderr, "%s\n", source.c_str());
189
  fprintf(stderr, "%s\n", *reason);
190
191
  Local<v8::StackTrace> stack = message->GetStackTrace();
192
  if (!stack.IsEmpty()) PrintStackTrace(isolate, stack);
193
}
194
195
void PrintCaughtException(Isolate* isolate,
196
                          Local<Context> context,
197
                          const v8::TryCatch& try_catch) {
198
  CHECK(try_catch.HasCaught());
199
  PrintException(isolate, context, try_catch.Exception(), try_catch.Message());
200
}
201
202
455
void AppendExceptionLine(Environment* env,
203
                         Local<Value> er,
204
                         Local<Message> message,
205
                         enum ErrorHandlingMode mode) {
206
475
  if (message.IsEmpty()) return;
207
208
455
  HandleScope scope(env->isolate());
209
  Local<Object> err_obj;
210

910
  if (!er.IsEmpty() && er->IsObject()) {
211
449
    err_obj = er.As<Object>();
212
  }
213
214
455
  bool added_exception_line = false;
215
  std::string source = GetErrorSource(
216
890
      env->isolate(), env->context(), message, &added_exception_line);
217
455
  if (!added_exception_line) {
218
8
    return;
219
  }
220
447
  MaybeLocal<Value> arrow_str = ToV8Value(env->context(), source);
221
222

894
  const bool can_set_arrow = !arrow_str.IsEmpty() && !err_obj.IsEmpty();
223
  // If allocating arrow_str failed, print it out. There's not much else to do.
224
  // If it's not an error, but something needs to be printed out because
225
  // it's a fatal exception, also print it out from here.
226
  // Otherwise, the arrow property will be attached to the object and handled
227
  // by the caller.
228


604
  if (!can_set_arrow || (mode == FATAL_ERROR && !err_obj->IsNativeError())) {
229
12
    if (env->printed_error()) return;
230
12
    Mutex::ScopedLock lock(per_process::tty_mutex);
231
12
    env->set_printed_error(true);
232
233
12
    ResetStdio();
234
12
    PrintErrorString("\n%s", source.c_str());
235
12
    return;
236
  }
237
238

1740
  CHECK(err_obj
239
            ->SetPrivate(env->context(),
240
                         env->arrow_message_private_symbol(),
241
                         arrow_str.ToLocalChecked())
242
435
            .FromMaybe(false));
243
}
244
245
[[noreturn]] void Abort() {
246
  DumpBacktrace(stderr);
247
  fflush(stderr);
248
  ABORT_NO_BACKTRACE();
249
}
250
251
[[noreturn]] void Assert(const AssertionInfo& info) {
252
  char name[1024];
253
  GetHumanReadableProcessName(&name);
254
255
  fprintf(stderr,
256
          "%s: %s:%s%s Assertion `%s' failed.\n",
257
          name,
258
          info.file_line,
259
          info.function,
260
          *info.function ? ":" : "",
261
          info.message);
262
  fflush(stderr);
263
264
  Abort();
265
}
266
267
enum class EnhanceFatalException { kEnhance, kDontEnhance };
268
269
/**
270
 * Report the exception to the inspector, then print it to stderr.
271
 * This should only be used when the Node.js instance is about to exit
272
 * (i.e. this should be followed by a env->Exit() or an Abort()).
273
 *
274
 * Use enhance_stack = EnhanceFatalException::kDontEnhance
275
 * when it's unsafe to call into JavaScript.
276
 */
277
171
static void ReportFatalException(Environment* env,
278
                                 Local<Value> error,
279
                                 Local<Message> message,
280
                                 EnhanceFatalException enhance_stack) {
281
171
  Isolate* isolate = env->isolate();
282
171
  CHECK(!error.IsEmpty());
283
171
  CHECK(!message.IsEmpty());
284
171
  HandleScope scope(isolate);
285
286
171
  AppendExceptionLine(env, error, message, FATAL_ERROR);
287
288
171
  auto report_to_inspector = [&]() {
289
#if HAVE_INSPECTOR
290
171
    env->inspector_agent()->ReportUncaughtException(error, message);
291
#endif
292
342
  };
293
294
  Local<Value> arrow;
295
  Local<Value> stack_trace;
296
171
  bool decorated = IsExceptionDecorated(env, error);
297
298
171
  if (!error->IsObject()) {  // We can only enhance actual errors.
299
6
    report_to_inspector();
300
12
    stack_trace = Undefined(isolate);
301
    // If error is not an object, AppendExceptionLine() has already print the
302
    // source line and the arrow to stderr.
303
    // TODO(joyeecheung): move that side effect out of AppendExceptionLine().
304
    // It is done just to preserve the source line as soon as possible.
305
  } else {
306
165
    Local<Object> err_obj = error.As<Object>();
307
308
330
    auto enhance_with = [&](Local<Function> enhancer) {
309
      Local<Value> enhanced;
310
660
      Local<Value> argv[] = {err_obj};
311

1650
      if (!enhancer.IsEmpty() &&
312
          enhancer
313
1650
              ->Call(env->context(), Undefined(isolate), arraysize(argv), argv)
314
1320
              .ToLocal(&enhanced)) {
315
328
        stack_trace = enhanced;
316
      }
317
495
    };
318
319
165
    switch (enhance_stack) {
320
      case EnhanceFatalException::kEnhance: {
321
165
        enhance_with(env->enhance_fatal_stack_before_inspector());
322
165
        report_to_inspector();
323
165
        enhance_with(env->enhance_fatal_stack_after_inspector());
324
165
        break;
325
      }
326
      case EnhanceFatalException::kDontEnhance: {
327
        report_to_inspector();
328
        break;
329
      }
330
      default:
331
        UNREACHABLE();
332
    }
333
334
    arrow =
335
330
        err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol())
336
330
            .ToLocalChecked();
337
  }
338
339
171
  node::Utf8Value trace(env->isolate(), stack_trace);
340
341
  // range errors have a trace member set to undefined
342

511
  if (trace.length() > 0 && !stack_trace->IsUndefined()) {
343


492
    if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
344
55
      PrintErrorString("%s\n", *trace);
345
    } else {
346
109
      node::Utf8Value arrow_string(env->isolate(), arrow);
347
109
      PrintErrorString("%s\n%s\n", *arrow_string, *trace);
348
    }
349
  } else {
350
    // this really only happens for RangeErrors, since they're the only
351
    // kind that won't have all this info in the trace, or when non-Error
352
    // objects are thrown manually.
353
    MaybeLocal<Value> message;
354
    MaybeLocal<Value> name;
355
356
7
    if (error->IsObject()) {
357
1
      Local<Object> err_obj = error.As<Object>();
358
3
      message = err_obj->Get(env->context(), env->message_string());
359
3
      name = err_obj->Get(env->context(), env->name_string());
360
    }
361
362


24
    if (message.IsEmpty() || message.ToLocalChecked()->IsUndefined() ||
363

21
        name.IsEmpty() || name.ToLocalChecked()->IsUndefined()) {
364
      // Not an error object. Just print as-is.
365
7
      String::Utf8Value message(env->isolate(), error);
366
367
      PrintErrorString("%s\n",
368
7
                       *message ? *message : "<toString() threw exception>");
369
    } else {
370
      node::Utf8Value name_string(env->isolate(), name.ToLocalChecked());
371
      node::Utf8Value message_string(env->isolate(), message.ToLocalChecked());
372
373
      if (arrow.IsEmpty() || !arrow->IsString() || decorated) {
374
        PrintErrorString("%s: %s\n", *name_string, *message_string);
375
      } else {
376
        node::Utf8Value arrow_string(env->isolate(), arrow);
377
        PrintErrorString(
378
            "%s\n%s: %s\n", *arrow_string, *name_string, *message_string);
379
      }
380
    }
381
  }
382
383
171
  fflush(stderr);
384
171
}
385
386
195
void PrintErrorString(const char* format, ...) {
387
  va_list ap;
388
195
  va_start(ap, format);
389
#ifdef _WIN32
390
  HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
391
392
  // Check if stderr is something other than a tty/console
393
  if (stderr_handle == INVALID_HANDLE_VALUE || stderr_handle == nullptr ||
394
      uv_guess_handle(_fileno(stderr)) != UV_TTY) {
395
    vfprintf(stderr, format, ap);
396
    va_end(ap);
397
    return;
398
  }
399
400
  // Fill in any placeholders
401
  int n = _vscprintf(format, ap);
402
  std::vector<char> out(n + 1);
403
  vsprintf(out.data(), format, ap);
404
405
  // Get required wide buffer size
406
  n = MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, nullptr, 0);
407
408
  std::vector<wchar_t> wbuf(n);
409
  MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, wbuf.data(), n);
410
411
  // Don't include the null character in the output
412
  CHECK_GT(n, 0);
413
  WriteConsoleW(stderr_handle, wbuf.data(), n - 1, nullptr, nullptr);
414
#else
415
195
  vfprintf(stderr, format, ap);
416
#endif
417
195
  va_end(ap);
418
195
}
419
420
[[noreturn]] void FatalError(const char* location, const char* message) {
421
  OnFatalError(location, message);
422
  // to suppress compiler warning
423
  ABORT();
424
}
425
426
void OnFatalError(const char* location, const char* message) {
427
  if (location) {
428
    PrintErrorString("FATAL ERROR: %s %s\n", location, message);
429
  } else {
430
    PrintErrorString("FATAL ERROR: %s\n", message);
431
  }
432
#ifdef NODE_REPORT
433
  Isolate* isolate = Isolate::GetCurrent();
434
  Environment* env = Environment::GetCurrent(isolate);
435
  if (env == nullptr || env->isolate_data()->options()->report_on_fatalerror) {
436
    report::TriggerNodeReport(
437
        isolate, env, message, "FatalError", "", Local<String>());
438
  }
439
#endif  // NODE_REPORT
440
  fflush(stderr);
441
  ABORT();
442
}
443
444
namespace errors {
445
446
452036
TryCatchScope::~TryCatchScope() {
447


226020
  if (HasCaught() && !HasTerminated() && mode_ == CatchMode::kFatal) {
448
4
    HandleScope scope(env_->isolate());
449
4
    Local<v8::Value> exception = Exception();
450
4
    Local<v8::Message> message = Message();
451
4
    EnhanceFatalException enhance = CanContinue() ?
452
4
        EnhanceFatalException::kEnhance : EnhanceFatalException::kDontEnhance;
453
4
    if (message.IsEmpty())
454
      message = Exception::CreateMessage(env_->isolate(), exception);
455
4
    ReportFatalException(env_, exception, message, enhance);
456
4
    env_->Exit(7);
457
  }
458
226016
}
459
460
4
const char* errno_string(int errorno) {
461
#define ERRNO_CASE(e)                                                          \
462
  case e:                                                                      \
463
    return #e;
464



















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

21
  if (env != nullptr && env->abort_on_uncaught_exception()) {
843
    ReportFatalException(
844
        env, exception, message, EnhanceFatalException::kEnhance);
845
    Abort();
846
  }
847
42
  bool from_promise = args[1]->IsTrue();
848
21
  errors::TriggerUncaughtException(isolate, exception, message, from_promise);
849
5
}
850
851
4962
void Initialize(Local<Object> target,
852
                Local<Value> unused,
853
                Local<Context> context,
854
                void* priv) {
855
4962
  Environment* env = Environment::GetCurrent(context);
856
  env->SetMethod(
857
4962
      target, "setPrepareStackTraceCallback", SetPrepareStackTraceCallback);
858
  env->SetMethod(target,
859
                 "setEnhanceStackForFatalException",
860
4962
                 SetEnhanceStackForFatalException);
861
  env->SetMethodNoSideEffect(
862
4962
      target, "noSideEffectsToString", NoSideEffectsToString);
863
4962
  env->SetMethod(target, "triggerUncaughtException", TriggerUncaughtException);
864
4962
}
865
866
284
void DecorateErrorStack(Environment* env,
867
                        const errors::TryCatchScope& try_catch) {
868
284
  Local<Value> exception = try_catch.Exception();
869
870
295
  if (!exception->IsObject()) return;
871
872
278
  Local<Object> err_obj = exception.As<Object>();
873
874
278
  if (IsExceptionDecorated(env, err_obj)) return;
875
876
275
  AppendExceptionLine(env, exception, try_catch.Message(), CONTEXTIFY_ERROR);
877
275
  TryCatchScope try_catch_scope(env);  // Ignore exceptions below.
878
825
  MaybeLocal<Value> stack = err_obj->Get(env->context(), env->stack_string());
879
  MaybeLocal<Value> maybe_value =
880
550
      err_obj->GetPrivate(env->context(), env->arrow_message_private_symbol());
881
882
  Local<Value> arrow;
883

825
  if (!(maybe_value.ToLocal(&arrow) && arrow->IsString())) {
884
    return;
885
  }
886
887


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


835
  if (process_object->Get(env->context(), exit_code).ToLocal(&code) &&
987
167
      code->IsInt32()) {
988
332
    env->Exit(code.As<Int32>()->Value());
989
  } else {
990
1
    env->Exit(1);
991
  }
992
}
993
994
4
void TriggerUncaughtException(Isolate* isolate, const v8::TryCatch& try_catch) {
995
  // If the try_catch is verbose, the per-isolate message listener is going to
996
  // handle it (which is going to call into another overload of
997
  // TriggerUncaughtException()).
998
4
  if (try_catch.IsVerbose()) {
999
3
    return;
1000
  }
1001
1002
  // If the user calls TryCatch::TerminateExecution() on this TryCatch
1003
  // they must call CancelTerminateExecution() again before invoking
1004
  // TriggerUncaughtException() because it will invoke
1005
  // process._fatalException() in the JS land.
1006
4
  CHECK(!try_catch.HasTerminated());
1007
4
  CHECK(try_catch.HasCaught());
1008
4
  HandleScope scope(isolate);
1009
  TriggerUncaughtException(isolate,
1010
                           try_catch.Exception(),
1011
                           try_catch.Message(),
1012
4
                           false /* from_promise */);
1013
}
1014
1015
}  // namespace errors
1016
1017
}  // namespace node
1018
1019

19311
NODE_MODULE_CONTEXT_AWARE_INTERNAL(errors, node::errors::Initialize)