messages.cc 44 KB
Newer Older
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/messages.h"
6

7 8
#include <memory>

9 10
#include "src/api.h"
#include "src/execution.h"
11
#include "src/isolate-inl.h"
12
#include "src/keys.h"
13
#include "src/objects/frame-array-inl.h"
14
#include "src/string-builder.h"
15
#include "src/wasm/wasm-code-manager.h"
16
#include "src/wasm/wasm-objects.h"
17

18 19
namespace v8 {
namespace internal {
20

21 22 23 24
MessageLocation::MessageLocation(Handle<Script> script, int start_pos,
                                 int end_pos)
    : script_(script), start_pos_(start_pos), end_pos_(end_pos) {}
MessageLocation::MessageLocation(Handle<Script> script, int start_pos,
25
                                 int end_pos, Handle<SharedFunctionInfo> shared)
26 27 28
    : script_(script),
      start_pos_(start_pos),
      end_pos_(end_pos),
29
      shared_(shared) {}
30
MessageLocation::MessageLocation() : start_pos_(-1), end_pos_(-1) {}
31 32 33

// If no message listeners have been registered this one is called
// by default.
34 35
void MessageHandler::DefaultMessageReport(Isolate* isolate,
                                          const MessageLocation* loc,
36
                                          Handle<Object> message_obj) {
37
  std::unique_ptr<char[]> str = GetLocalizedMessage(isolate, message_obj);
38
  if (loc == nullptr) {
39
    PrintF("%s\n", str.get());
40
  } else {
41
    HandleScope scope(isolate);
42
    Handle<Object> data(loc->script()->name(), isolate);
43
    std::unique_ptr<char[]> data_str;
44 45
    if (data->IsString())
      data_str = Handle<String>::cast(data)->ToCString(DISALLOW_NULLS);
46 47
    PrintF("%s:%i: %s\n", data_str.get() ? data_str.get() : "<unknown>",
           loc->start_pos(), str.get());
48 49 50
  }
}

51
Handle<JSMessageObject> MessageHandler::MakeMessageObject(
52
    Isolate* isolate, MessageTemplate::Template message,
53
    const MessageLocation* location, Handle<Object> argument,
54
    Handle<FixedArray> stack_frames) {
55
  Factory* factory = isolate->factory();
56

57 58
  int start = -1;
  int end = -1;
59
  Handle<Object> script_handle = factory->undefined_value();
60
  if (location != nullptr) {
61 62 63 64 65
    start = location->start_pos();
    end = location->end_pos();
    script_handle = Script::GetWrapper(location->script());
  } else {
    script_handle = Script::GetWrapper(isolate->factory()->empty_script());
66
  }
67

68
  Handle<Object> stack_frames_handle = stack_frames.is_null()
69
      ? Handle<Object>::cast(factory->undefined_value())
70 71
      : Handle<Object>::cast(stack_frames);

72 73
  Handle<JSMessageObject> message_obj = factory->NewJSMessageObject(
      message, argument, start, end, script_handle, stack_frames_handle);
74

75
  return message_obj;
76 77
}

78
void MessageHandler::ReportMessage(Isolate* isolate, const MessageLocation* loc,
79
                                   Handle<JSMessageObject> message) {
80
  v8::Local<v8::Message> api_message_obj = v8::Utils::MessageToLocal(message);
81

82 83 84 85
  if (api_message_obj->ErrorLevel() == v8::Isolate::kMessageError) {
    // We are calling into embedder's code which can throw exceptions.
    // Thus we need to save current exception state, reset it to the clean one
    // and ignore scheduled exceptions callbacks can throw.
86

87 88 89 90
    // We pass the exception object into the message handler callback though.
    Object* exception_object = isolate->heap()->undefined_value();
    if (isolate->has_pending_exception()) {
      exception_object = isolate->pending_exception();
91
    }
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    Handle<Object> exception(exception_object, isolate);

    Isolate::ExceptionScope exception_scope(isolate);
    isolate->clear_pending_exception();
    isolate->set_external_caught_exception(false);

    // Turn the exception on the message into a string if it is an object.
    if (message->argument()->IsJSObject()) {
      HandleScope scope(isolate);
      Handle<Object> argument(message->argument(), isolate);

      MaybeHandle<Object> maybe_stringified;
      Handle<Object> stringified;
      // Make sure we don't leak uncaught internally generated Error objects.
      if (argument->IsJSError()) {
        maybe_stringified = Object::NoSideEffectsToString(isolate, argument);
      } else {
        v8::TryCatch catcher(reinterpret_cast<v8::Isolate*>(isolate));
        catcher.SetVerbose(false);
        catcher.SetCaptureMessage(false);

        maybe_stringified = Object::ToString(isolate, argument);
      }
115

116
      if (!maybe_stringified.ToHandle(&stringified)) {
117 118 119
        DCHECK(isolate->has_pending_exception());
        isolate->clear_pending_exception();
        isolate->set_external_caught_exception(false);
120 121 122 123
        stringified =
            isolate->factory()->NewStringFromAsciiChecked("exception");
      }
      message->set_argument(*stringified);
124
    }
125 126 127 128 129

    v8::Local<v8::Value> api_exception_obj = v8::Utils::ToLocal(exception);
    ReportMessageNoExceptions(isolate, loc, message, api_exception_obj);
  } else {
    ReportMessageNoExceptions(isolate, loc, message, v8::Local<v8::Value>());
130
  }
131
}
132

133 134 135
void MessageHandler::ReportMessageNoExceptions(
    Isolate* isolate, const MessageLocation* loc, Handle<Object> message,
    v8::Local<v8::Value> api_exception_obj) {
136
  v8::Local<v8::Message> api_message_obj = v8::Utils::MessageToLocal(message);
137
  int error_level = api_message_obj->ErrorLevel();
138

139 140 141
  Handle<TemplateList> global_listeners =
      isolate->factory()->message_listeners();
  int global_length = global_listeners->length();
142
  if (global_length == 0) {
143
    DefaultMessageReport(isolate, loc, message);
144 145 146
    if (isolate->has_scheduled_exception()) {
      isolate->clear_scheduled_exception();
    }
147 148
  } else {
    for (int i = 0; i < global_length; i++) {
149
      HandleScope scope(isolate);
150
      if (global_listeners->get(i)->IsUndefined(isolate)) continue;
cbruni's avatar
cbruni committed
151 152
      FixedArray* listener = FixedArray::cast(global_listeners->get(i));
      Foreign* callback_obj = Foreign::cast(listener->get(0));
153
      int32_t message_levels =
jgruber's avatar
jgruber committed
154
          static_cast<int32_t>(Smi::ToInt(listener->get(2)));
155 156 157
      if (!(message_levels & error_level)) {
        continue;
      }
158
      v8::MessageCallback callback =
159
          FUNCTION_CAST<v8::MessageCallback>(callback_obj->foreign_address());
cbruni's avatar
cbruni committed
160
      Handle<Object> callback_data(listener->get(1), isolate);
161 162
      {
        // Do not allow exceptions to propagate.
163
        v8::TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
164
        callback(api_message_obj, callback_data->IsUndefined(isolate)
165 166
                                      ? api_exception_obj
                                      : v8::Utils::ToLocal(callback_data));
167
      }
168 169 170
      if (isolate->has_scheduled_exception()) {
        isolate->clear_scheduled_exception();
      }
171 172 173 174 175
    }
  }
}


176 177
Handle<String> MessageHandler::GetMessage(Isolate* isolate,
                                          Handle<Object> data) {
178
  Handle<JSMessageObject> message = Handle<JSMessageObject>::cast(data);
179 180
  Handle<Object> arg = Handle<Object>(message->argument(), isolate);
  return MessageTemplate::FormatMessage(isolate, message->type(), arg);
181 182
}

183
std::unique_ptr<char[]> MessageHandler::GetLocalizedMessage(
rmcilroy's avatar
rmcilroy committed
184
    Isolate* isolate, Handle<Object> data) {
185
  HandleScope scope(isolate);
186
  return GetMessage(isolate, data)->ToCString(DISALLOW_NULLS);
187 188
}

189 190 191
namespace {

Object* EvalFromFunctionName(Isolate* isolate, Handle<Script> script) {
192
  if (!script->has_eval_from_shared())
193 194
    return isolate->heap()->undefined_value();

195
  Handle<SharedFunctionInfo> shared(script->eval_from_shared(), isolate);
196
  // Find the name of the function calling eval.
197
  if (shared->Name()->BooleanValue(isolate)) {
198
    return shared->Name();
199 200 201 202 203 204
  }

  return shared->inferred_name();
}

Object* EvalFromScript(Isolate* isolate, Handle<Script> script) {
205
  if (!script->has_eval_from_shared())
206 207
    return isolate->heap()->undefined_value();

208 209
  Handle<SharedFunctionInfo> eval_from_shared(script->eval_from_shared(),
                                              isolate);
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  return eval_from_shared->script()->IsScript()
             ? eval_from_shared->script()
             : isolate->heap()->undefined_value();
}

MaybeHandle<String> FormatEvalOrigin(Isolate* isolate, Handle<Script> script) {
  Handle<Object> sourceURL(script->GetNameOrSourceURL(), isolate);
  if (!sourceURL->IsUndefined(isolate)) {
    DCHECK(sourceURL->IsString());
    return Handle<String>::cast(sourceURL);
  }

  IncrementalStringBuilder builder(isolate);
  builder.AppendCString("eval at ");

  Handle<Object> eval_from_function_name =
      handle(EvalFromFunctionName(isolate, script), isolate);
227
  if (eval_from_function_name->BooleanValue(isolate)) {
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    Handle<String> str;
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, str, Object::ToString(isolate, eval_from_function_name),
        String);
    builder.AppendString(str);
  } else {
    builder.AppendCString("<anonymous>");
  }

  Handle<Object> eval_from_script_obj =
      handle(EvalFromScript(isolate, script), isolate);
  if (eval_from_script_obj->IsScript()) {
    Handle<Script> eval_from_script =
        Handle<Script>::cast(eval_from_script_obj);
    builder.AppendCString(" (");
    if (eval_from_script->compilation_type() == Script::COMPILATION_TYPE_EVAL) {
      // Eval script originated from another eval.
      Handle<String> str;
      ASSIGN_RETURN_ON_EXCEPTION(
          isolate, str, FormatEvalOrigin(isolate, eval_from_script), String);
      builder.AppendString(str);
    } else {
      DCHECK(eval_from_script->compilation_type() !=
             Script::COMPILATION_TYPE_EVAL);
      // eval script originated from "real" source.
      Handle<Object> name_obj = handle(eval_from_script->name(), isolate);
      if (eval_from_script->name()->IsString()) {
        builder.AppendString(Handle<String>::cast(name_obj));

        Script::PositionInfo info;
        if (Script::GetPositionInfo(eval_from_script, script->GetEvalPosition(),
                                    &info, Script::NO_OFFSET)) {
          builder.AppendCString(":");

          Handle<String> str = isolate->factory()->NumberToString(
              handle(Smi::FromInt(info.line + 1), isolate));
          builder.AppendString(str);

          builder.AppendCString(":");

          str = isolate->factory()->NumberToString(
              handle(Smi::FromInt(info.column + 1), isolate));
          builder.AppendString(str);
        }
      } else {
        DCHECK(!eval_from_script->name()->IsString());
        builder.AppendCString("unknown source");
      }
    }
    builder.AppendCString(")");
  }

  Handle<String> result;
  ASSIGN_RETURN_ON_EXCEPTION(isolate, result, builder.Finish(), String);
  return result;
}

}  // namespace

Handle<Object> StackFrameBase::GetEvalOrigin() {
  if (!HasScript()) return isolate_->factory()->undefined_value();
  return FormatEvalOrigin(isolate_, GetScript()).ToHandleChecked();
}

bool StackFrameBase::IsEval() {
  return HasScript() &&
         GetScript()->compilation_type() == Script::COMPILATION_TYPE_EVAL;
}

297 298 299 300 301 302 303 304 305 306
void JSStackFrame::FromFrameArray(Isolate* isolate, Handle<FrameArray> array,
                                  int frame_ix) {
  DCHECK(!array->IsWasmFrame(frame_ix));
  isolate_ = isolate;
  receiver_ = handle(array->Receiver(frame_ix), isolate);
  function_ = handle(array->Function(frame_ix), isolate);
  code_ = handle(array->Code(frame_ix), isolate);
  offset_ = array->Offset(frame_ix)->value();

  const int flags = array->Flags(frame_ix)->value();
307
  is_constructor_ = (flags & FrameArray::kIsConstructor) != 0;
308
  is_strict_ = (flags & FrameArray::kIsStrict) != 0;
309 310
}

311 312
JSStackFrame::JSStackFrame() {}

313 314 315
JSStackFrame::JSStackFrame(Isolate* isolate, Handle<Object> receiver,
                           Handle<JSFunction> function,
                           Handle<AbstractCode> code, int offset)
316
    : StackFrameBase(isolate),
317 318 319 320
      receiver_(receiver),
      function_(function),
      code_(code),
      offset_(offset),
321
      is_constructor_(false),
322 323 324 325
      is_strict_(false) {}

Handle<Object> JSStackFrame::GetFunction() const {
  return Handle<Object>::cast(function_);
326 327
}

328 329 330 331
Handle<Object> JSStackFrame::GetFileName() {
  if (!HasScript()) return isolate_->factory()->null_value();
  return handle(GetScript()->name(), isolate_);
}
332

333 334
Handle<Object> JSStackFrame::GetFunctionName() {
  Handle<String> result = JSFunction::GetName(function_);
335 336
  if (result->length() != 0) return result;

337 338
  if (HasScript() &&
      GetScript()->compilation_type() == Script::COMPILATION_TYPE_EVAL) {
339 340 341 342 343
    return isolate_->factory()->eval_string();
  }
  return isolate_->factory()->null_value();
}

344 345
namespace {

346 347
bool CheckMethodName(Isolate* isolate, Handle<JSReceiver> receiver,
                     Handle<Name> name, Handle<JSFunction> fun,
348 349
                     LookupIterator::Configuration config) {
  LookupIterator iter =
350
      LookupIterator::PropertyOrElement(isolate, receiver, name, config);
351 352 353 354 355 356 357 358 359 360 361 362
  if (iter.state() == LookupIterator::DATA) {
    return iter.GetDataValue().is_identical_to(fun);
  } else if (iter.state() == LookupIterator::ACCESSOR) {
    Handle<Object> accessors = iter.GetAccessors();
    if (accessors->IsAccessorPair()) {
      Handle<AccessorPair> pair = Handle<AccessorPair>::cast(accessors);
      return pair->getter() == *fun || pair->setter() == *fun;
    }
  }
  return false;
}

363 364 365 366 367 368
Handle<Object> ScriptNameOrSourceUrl(Handle<Script> script, Isolate* isolate) {
  Object* name_or_url = script->source_url();
  if (!name_or_url->IsString()) name_or_url = script->name();
  return handle(name_or_url, isolate);
}

369
}  // namespace
370

371 372 373 374 375
Handle<Object> JSStackFrame::GetScriptNameOrSourceUrl() {
  if (!HasScript()) return isolate_->factory()->null_value();
  return ScriptNameOrSourceUrl(GetScript(), isolate_);
}

376
Handle<Object> JSStackFrame::GetMethodName() {
377
  if (receiver_->IsNullOrUndefined(isolate_)) {
378 379
    return isolate_->factory()->null_value();
  }
380

381 382 383 384 385
  Handle<JSReceiver> receiver;
  if (!Object::ToObject(isolate_, receiver_).ToHandle(&receiver)) {
    DCHECK(isolate_->has_pending_exception());
    isolate_->clear_pending_exception();
    isolate_->set_external_caught_exception(false);
386 387 388
    return isolate_->factory()->null_value();
  }

389
  Handle<String> name(function_->shared()->Name(), isolate_);
390 391 392 393 394 395
  // ES2015 gives getters and setters name prefixes which must
  // be stripped to find the property name.
  if (name->IsUtf8EqualTo(CStrVector("get "), true) ||
      name->IsUtf8EqualTo(CStrVector("set "), true)) {
    name = isolate_->factory()->NewProperSubString(name, 4, name->length());
  }
396
  if (CheckMethodName(isolate_, receiver, name, function_,
397 398
                      LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR)) {
    return name;
399 400 401 402
  }

  HandleScope outer_scope(isolate_);
  Handle<Object> result;
403 404
  for (PrototypeIterator iter(isolate_, receiver, kStartAtReceiver);
       !iter.IsAtEnd(); iter.Advance()) {
405 406 407 408 409 410 411 412 413 414
    Handle<Object> current = PrototypeIterator::GetCurrent(iter);
    if (!current->IsJSObject()) break;
    Handle<JSObject> current_obj = Handle<JSObject>::cast(current);
    if (current_obj->IsAccessCheckNeeded()) break;
    Handle<FixedArray> keys =
        KeyAccumulator::GetOwnEnumPropertyKeys(isolate_, current_obj);
    for (int i = 0; i < keys->length(); i++) {
      HandleScope inner_scope(isolate_);
      if (!keys->get(i)->IsName()) continue;
      Handle<Name> name_key(Name::cast(keys->get(i)), isolate_);
415
      if (!CheckMethodName(isolate_, current_obj, name_key, function_,
416 417 418 419 420 421 422 423 424 425 426 427
                           LookupIterator::OWN_SKIP_INTERCEPTOR))
        continue;
      // Return null in case of duplicates to avoid confusion.
      if (!result.is_null()) return isolate_->factory()->null_value();
      result = inner_scope.CloseAndEscape(name_key);
    }
  }

  if (!result.is_null()) return outer_scope.CloseAndEscape(result);
  return isolate_->factory()->null_value();
}

428 429 430
Handle<Object> JSStackFrame::GetTypeName() {
  // TODO(jgruber): Check for strict/constructor here as in
  // CallSitePrototypeGetThis.
431

432
  if (receiver_->IsNullOrUndefined(isolate_)) {
433
    return isolate_->factory()->null_value();
434 435 436
  } else if (receiver_->IsJSProxy()) {
    return isolate_->factory()->Proxy_string();
  }
437

438 439 440 441 442 443 444
  Handle<JSReceiver> receiver;
  if (!Object::ToObject(isolate_, receiver_).ToHandle(&receiver)) {
    DCHECK(isolate_->has_pending_exception());
    isolate_->clear_pending_exception();
    isolate_->set_external_caught_exception(false);
    return isolate_->factory()->null_value();
  }
445

446
  return JSReceiver::GetConstructorName(receiver);
447 448
}

449 450 451 452 453
int JSStackFrame::GetLineNumber() {
  DCHECK_LE(0, GetPosition());
  if (HasScript()) return Script::GetLineNumber(GetScript(), GetPosition()) + 1;
  return -1;
}
454

455 456 457 458
int JSStackFrame::GetColumnNumber() {
  DCHECK_LE(0, GetPosition());
  if (HasScript()) {
    return Script::GetColumnNumber(GetScript(), GetPosition()) + 1;
459 460 461 462
  }
  return -1;
}

463 464
bool JSStackFrame::IsNative() {
  return HasScript() && GetScript()->type() == Script::TYPE_NATIVE;
465 466
}

467
bool JSStackFrame::IsToplevel() {
468
  return receiver_->IsJSGlobalProxy() || receiver_->IsNullOrUndefined(isolate_);
469 470 471 472
}

namespace {

473 474 475
bool IsNonEmptyString(Handle<Object> object) {
  return (object->IsString() && String::cast(*object)->length() > 0);
}
476

477
void AppendFileLocation(Isolate* isolate, StackFrameBase* call_site,
478 479 480 481 482
                        IncrementalStringBuilder* builder) {
  if (call_site->IsNative()) {
    builder->AppendCString("native");
    return;
  }
483

484 485 486 487 488 489 490
  Handle<Object> file_name = call_site->GetScriptNameOrSourceUrl();
  if (!file_name->IsString() && call_site->IsEval()) {
    Handle<Object> eval_origin = call_site->GetEvalOrigin();
    DCHECK(eval_origin->IsString());
    builder->AppendString(Handle<String>::cast(eval_origin));
    builder->AppendCString(", ");  // Expecting source position to follow.
  }
491

492 493 494 495 496 497 498 499
  if (IsNonEmptyString(file_name)) {
    builder->AppendString(Handle<String>::cast(file_name));
  } else {
    // Source code does not originate from a file and is not native, but we
    // can still get the source position inside the source string, e.g. in
    // an eval string.
    builder->AppendCString("<anonymous>");
  }
jgruber's avatar
jgruber committed
500

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  int line_number = call_site->GetLineNumber();
  if (line_number != -1) {
    builder->AppendCharacter(':');
    Handle<String> line_string = isolate->factory()->NumberToString(
        handle(Smi::FromInt(line_number), isolate), isolate);
    builder->AppendString(line_string);

    int column_number = call_site->GetColumnNumber();
    if (column_number != -1) {
      builder->AppendCharacter(':');
      Handle<String> column_string = isolate->factory()->NumberToString(
          handle(Smi::FromInt(column_number), isolate), isolate);
      builder->AppendString(column_string);
    }
  }
}
jgruber's avatar
jgruber committed
517

518 519 520 521 522 523 524 525 526 527 528
int StringIndexOf(Isolate* isolate, Handle<String> subject,
                  Handle<String> pattern) {
  if (pattern->length() > subject->length()) return -1;
  return String::IndexOf(isolate, subject, pattern, 0);
}

// Returns true iff
// 1. the subject ends with '.' + pattern, or
// 2. subject == pattern.
bool StringEndsWithMethodName(Isolate* isolate, Handle<String> subject,
                              Handle<String> pattern) {
529
  if (String::Equals(isolate, subject, pattern)) return true;
530

531 532
  FlatStringReader subject_reader(isolate, String::Flatten(isolate, subject));
  FlatStringReader pattern_reader(isolate, String::Flatten(isolate, pattern));
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569

  int pattern_index = pattern_reader.length() - 1;
  int subject_index = subject_reader.length() - 1;
  for (int i = 0; i <= pattern_reader.length(); i++) {  // Iterate over len + 1.
    if (subject_index < 0) {
      return false;
    }

    const uc32 subject_char = subject_reader.Get(subject_index);
    if (i == pattern_reader.length()) {
      if (subject_char != '.') return false;
    } else if (subject_char != pattern_reader.Get(pattern_index)) {
      return false;
    }

    pattern_index--;
    subject_index--;
  }

  return true;
}

void AppendMethodCall(Isolate* isolate, JSStackFrame* call_site,
                      IncrementalStringBuilder* builder) {
  Handle<Object> type_name = call_site->GetTypeName();
  Handle<Object> method_name = call_site->GetMethodName();
  Handle<Object> function_name = call_site->GetFunctionName();

  if (IsNonEmptyString(function_name)) {
    Handle<String> function_string = Handle<String>::cast(function_name);
    if (IsNonEmptyString(type_name)) {
      Handle<String> type_string = Handle<String>::cast(type_name);
      bool starts_with_type_name =
          (StringIndexOf(isolate, function_string, type_string) == 0);
      if (!starts_with_type_name) {
        builder->AppendString(type_string);
        builder->AppendCharacter('.');
jgruber's avatar
jgruber committed
570
      }
571 572
    }
    builder->AppendString(function_string);
jgruber's avatar
jgruber committed
573

574 575 576 577 578 579 580 581 582
    if (IsNonEmptyString(method_name)) {
      Handle<String> method_string = Handle<String>::cast(method_name);
      if (!StringEndsWithMethodName(isolate, function_string, method_string)) {
        builder->AppendCString(" [as ");
        builder->AppendString(method_string);
        builder->AppendCharacter(']');
      }
    }
  } else {
583 584 585 586
    if (IsNonEmptyString(type_name)) {
      builder->AppendString(Handle<String>::cast(type_name));
      builder->AppendCharacter('.');
    }
587 588 589 590 591 592 593 594 595 596 597 598
    if (IsNonEmptyString(method_name)) {
      builder->AppendString(Handle<String>::cast(method_name));
    } else {
      builder->AppendCString("<anonymous>");
    }
  }
}

}  // namespace

MaybeHandle<String> JSStackFrame::ToString() {
  IncrementalStringBuilder builder(isolate_);
jgruber's avatar
jgruber committed
599

600 601 602 603 604 605 606 607 608 609 610 611 612 613
  Handle<Object> function_name = GetFunctionName();

  const bool is_toplevel = IsToplevel();
  const bool is_constructor = IsConstructor();
  const bool is_method_call = !(is_toplevel || is_constructor);

  if (is_method_call) {
    AppendMethodCall(isolate_, this, &builder);
  } else if (is_constructor) {
    builder.AppendCString("new ");
    if (IsNonEmptyString(function_name)) {
      builder.AppendString(Handle<String>::cast(function_name));
    } else {
      builder.AppendCString("<anonymous>");
jgruber's avatar
jgruber committed
614
    }
615 616 617 618
  } else if (IsNonEmptyString(function_name)) {
    builder.AppendString(Handle<String>::cast(function_name));
  } else {
    AppendFileLocation(isolate_, this, &builder);
jgruber's avatar
jgruber committed
619
    return builder.Finish();
620 621 622 623 624 625
  }

  builder.AppendCString(" (");
  AppendFileLocation(isolate_, this, &builder);
  builder.AppendCString(")");

jgruber's avatar
jgruber committed
626
  return builder.Finish();
627 628 629 630 631 632 633 634 635 636 637 638
}

int JSStackFrame::GetPosition() const { return code_->SourcePosition(offset_); }

bool JSStackFrame::HasScript() const {
  return function_->shared()->script()->IsScript();
}

Handle<Script> JSStackFrame::GetScript() const {
  return handle(Script::cast(function_->shared()->script()), isolate_);
}

639 640
WasmStackFrame::WasmStackFrame() {}

641 642
void WasmStackFrame::FromFrameArray(Isolate* isolate, Handle<FrameArray> array,
                                    int frame_ix) {
643 644 645 646 647
  // This function is called for compiled and interpreted wasm frames, and for
  // asm.js->wasm frames.
  DCHECK(array->IsWasmFrame(frame_ix) ||
         array->IsWasmInterpretedFrame(frame_ix) ||
         array->IsAsmJsWasmFrame(frame_ix));
648
  isolate_ = isolate;
649
  wasm_instance_ = handle(array->WasmInstance(frame_ix), isolate);
650
  wasm_func_index_ = array->WasmFunctionIndex(frame_ix)->value();
651
  if (array->IsWasmInterpretedFrame(frame_ix)) {
652
    code_ = nullptr;
653
  } else {
654
    code_ = wasm_instance_->module_object()->native_module()->code(
655
        wasm_func_index_);
656
  }
657 658 659
  offset_ = array->Offset(frame_ix)->value();
}

660 661
Handle<Object> WasmStackFrame::GetReceiver() const { return wasm_instance_; }

662
Handle<Object> WasmStackFrame::GetFunction() const {
663
  return handle(Smi::FromInt(wasm_func_index_), isolate_);
664 665 666
}

Handle<Object> WasmStackFrame::GetFunctionName() {
667
  Handle<Object> name;
668 669 670 671
  Handle<WasmModuleObject> module_object(wasm_instance_->module_object(),
                                         isolate_);
  if (!WasmModuleObject::GetFunctionNameOrNull(isolate_, module_object,
                                               wasm_func_index_)
672 673 674 675
           .ToHandle(&name)) {
    name = isolate_->factory()->null_value();
  }
  return name;
676 677 678 679 680
}

MaybeHandle<String> WasmStackFrame::ToString() {
  IncrementalStringBuilder builder(isolate_);

681 682
  Handle<WasmModuleObject> module_object(wasm_instance_->module_object(),
                                         isolate_);
683
  MaybeHandle<String> module_name =
684 685 686
      WasmModuleObject::GetModuleNameOrNull(isolate_, module_object);
  MaybeHandle<String> function_name = WasmModuleObject::GetFunctionNameOrNull(
      isolate_, module_object, wasm_func_index_);
687 688 689 690 691 692 693 694 695 696 697
  bool has_name = !module_name.is_null() || !function_name.is_null();
  if (has_name) {
    if (module_name.is_null()) {
      builder.AppendString(function_name.ToHandleChecked());
    } else {
      builder.AppendString(module_name.ToHandleChecked());
      if (!function_name.is_null()) {
        builder.AppendCString(".");
        builder.AppendString(function_name.ToHandleChecked());
      }
    }
698
    builder.AppendCString(" (");
jgruber's avatar
jgruber committed
699 700
  }

701
  builder.AppendCString("wasm-function[");
702

703
  char buffer[16];
704
  SNPrintF(ArrayVector(buffer), "%u]", wasm_func_index_);
705
  builder.AppendCString(buffer);
706

707
  SNPrintF(ArrayVector(buffer), ":%d", GetPosition());
708
  builder.AppendCString(buffer);
709

710
  if (has_name) builder.AppendCString(")");
711 712 713 714 715

  return builder.Finish();
}

int WasmStackFrame::GetPosition() const {
716 717
  return IsInterpreted()
             ? offset_
718 719
             : FrameSummary::WasmCompiledFrameSummary::GetWasmSourcePosition(
                   code_, offset_);
720 721 722 723 724 725
}

Handle<Object> WasmStackFrame::Null() const {
  return isolate_->factory()->null_value();
}

726 727 728
bool WasmStackFrame::HasScript() const { return true; }

Handle<Script> WasmStackFrame::GetScript() const {
729
  return handle(wasm_instance_->module_object()->script(), isolate_);
730 731 732 733
}

AsmJsWasmStackFrame::AsmJsWasmStackFrame() {}

734 735 736 737 738 739 740 741 742
void AsmJsWasmStackFrame::FromFrameArray(Isolate* isolate,
                                         Handle<FrameArray> array,
                                         int frame_ix) {
  DCHECK(array->IsAsmJsWasmFrame(frame_ix));
  WasmStackFrame::FromFrameArray(isolate, array, frame_ix);
  is_at_number_conversion_ =
      array->Flags(frame_ix)->value() & FrameArray::kAsmJsAtNumberConversion;
}

743 744 745 746 747 748 749 750 751 752
Handle<Object> AsmJsWasmStackFrame::GetReceiver() const {
  return isolate_->global_proxy();
}

Handle<Object> AsmJsWasmStackFrame::GetFunction() const {
  // TODO(clemensh): Return lazily created JSFunction.
  return Null();
}

Handle<Object> AsmJsWasmStackFrame::GetFileName() {
753
  Handle<Script> script(wasm_instance_->module_object()->script(), isolate_);
754
  DCHECK(script->IsUserJavaScript());
755 756 757 758
  return handle(script->name(), isolate_);
}

Handle<Object> AsmJsWasmStackFrame::GetScriptNameOrSourceUrl() {
759
  Handle<Script> script(wasm_instance_->module_object()->script(), isolate_);
760
  DCHECK_EQ(Script::TYPE_NORMAL, script->type());
761 762 763 764 765
  return ScriptNameOrSourceUrl(script, isolate_);
}

int AsmJsWasmStackFrame::GetPosition() const {
  DCHECK_LE(0, offset_);
766
  int byte_offset =
767 768
      FrameSummary::WasmCompiledFrameSummary::GetWasmSourcePosition(code_,
                                                                    offset_);
769 770
  Handle<WasmModuleObject> module_object(wasm_instance_->module_object(),
                                         isolate_);
771
  DCHECK_LE(0, byte_offset);
772 773 774
  return WasmModuleObject::GetSourcePosition(module_object, wasm_func_index_,
                                             static_cast<uint32_t>(byte_offset),
                                             is_at_number_conversion_);
775 776 777 778
}

int AsmJsWasmStackFrame::GetLineNumber() {
  DCHECK_LE(0, GetPosition());
779
  Handle<Script> script(wasm_instance_->module_object()->script(), isolate_);
780
  DCHECK(script->IsUserJavaScript());
781 782 783 784 785
  return Script::GetLineNumber(script, GetPosition()) + 1;
}

int AsmJsWasmStackFrame::GetColumnNumber() {
  DCHECK_LE(0, GetPosition());
786
  Handle<Script> script(wasm_instance_->module_object()->script(), isolate_);
787
  DCHECK(script->IsUserJavaScript());
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
  return Script::GetColumnNumber(script, GetPosition()) + 1;
}

MaybeHandle<String> AsmJsWasmStackFrame::ToString() {
  // The string should look exactly as the respective javascript frame string.
  // Keep this method in line to JSStackFrame::ToString().

  IncrementalStringBuilder builder(isolate_);

  Handle<Object> function_name = GetFunctionName();

  if (IsNonEmptyString(function_name)) {
    builder.AppendString(Handle<String>::cast(function_name));
    builder.AppendCString(" (");
  }

  AppendFileLocation(isolate_, this, &builder);

  if (IsNonEmptyString(function_name)) builder.AppendCString(")");

jgruber's avatar
jgruber committed
808
  return builder.Finish();
809 810
}

811 812 813 814 815 816 817 818 819 820 821 822 823
FrameArrayIterator::FrameArrayIterator(Isolate* isolate,
                                       Handle<FrameArray> array, int frame_ix)
    : isolate_(isolate), array_(array), next_frame_ix_(frame_ix) {}

bool FrameArrayIterator::HasNext() const {
  return (next_frame_ix_ < array_->FrameCount());
}

void FrameArrayIterator::Next() { next_frame_ix_++; }

StackFrameBase* FrameArrayIterator::Frame() {
  DCHECK(HasNext());
  const int flags = array_->Flags(next_frame_ix_)->value();
824 825 826 827
  int flag_mask = FrameArray::kIsWasmFrame |
                  FrameArray::kIsWasmInterpretedFrame |
                  FrameArray::kIsAsmJsWasmFrame;
  switch (flags & flag_mask) {
828 829 830 831 832
    case 0:
      // JavaScript Frame.
      js_frame_.FromFrameArray(isolate_, array_, next_frame_ix_);
      return &js_frame_;
    case FrameArray::kIsWasmFrame:
833 834
    case FrameArray::kIsWasmInterpretedFrame:
      // Wasm Frame:
835 836 837 838 839 840 841 842
      wasm_frame_.FromFrameArray(isolate_, array_, next_frame_ix_);
      return &wasm_frame_;
    case FrameArray::kIsAsmJsWasmFrame:
      // Asm.js Wasm Frame:
      asm_wasm_frame_.FromFrameArray(isolate_, array_, next_frame_ix_);
      return &asm_wasm_frame_;
    default:
      UNREACHABLE();
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
  }
}

namespace {

MaybeHandle<Object> ConstructCallSite(Isolate* isolate,
                                      Handle<FrameArray> frame_array,
                                      int frame_index) {
  Handle<JSFunction> target =
      handle(isolate->native_context()->callsite_function(), isolate);

  Handle<JSObject> obj;
  ASSIGN_RETURN_ON_EXCEPTION(isolate, obj, JSObject::New(target, target),
                             Object);

  Handle<Symbol> key = isolate->factory()->call_site_frame_array_symbol();
  RETURN_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
                                   obj, key, frame_array, DONT_ENUM),
                      Object);

  key = isolate->factory()->call_site_frame_index_symbol();
  Handle<Object> value(Smi::FromInt(frame_index), isolate);
  RETURN_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
                                   obj, key, value, DONT_ENUM),
                      Object);

  return obj;
}

// Convert the raw frames as written by Isolate::CaptureSimpleStackTrace into
// a JSArray of JSCallSite objects.
MaybeHandle<JSArray> GetStackFrames(Isolate* isolate,
                                    Handle<FrameArray> elems) {
  const int frame_count = elems->FrameCount();

  Handle<FixedArray> frames = isolate->factory()->NewFixedArray(frame_count);
  for (int i = 0; i < frame_count; i++) {
    Handle<Object> site;
    ASSIGN_RETURN_ON_EXCEPTION(isolate, site,
                               ConstructCallSite(isolate, elems, i), JSArray);
    frames->set(i, *site);
  }

  return isolate->factory()->NewJSArrayWithElements(frames);
jgruber's avatar
jgruber committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900
}

MaybeHandle<Object> AppendErrorString(Isolate* isolate, Handle<Object> error,
                                      IncrementalStringBuilder* builder) {
  MaybeHandle<String> err_str =
      ErrorUtils::ToString(isolate, Handle<Object>::cast(error));
  if (err_str.is_null()) {
    // Error.toString threw. Try to return a string representation of the thrown
    // exception instead.

    DCHECK(isolate->has_pending_exception());
    Handle<Object> pending_exception =
        handle(isolate->pending_exception(), isolate);
    isolate->clear_pending_exception();
901
    isolate->set_external_caught_exception(false);
jgruber's avatar
jgruber committed
902 903 904 905 906 907

    err_str = ErrorUtils::ToString(isolate, pending_exception);
    if (err_str.is_null()) {
      // Formatting the thrown exception threw again, give up.
      DCHECK(isolate->has_pending_exception());
      isolate->clear_pending_exception();
908
      isolate->set_external_caught_exception(false);
jgruber's avatar
jgruber committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
      builder->AppendCString("<error>");
    } else {
      // Formatted thrown exception successfully, append it.
      builder->AppendCString("<error: ");
      builder->AppendString(err_str.ToHandleChecked());
      builder->AppendCharacter('>');
    }
  } else {
    builder->AppendString(err_str.ToHandleChecked());
  }

  return error;
}

class PrepareStackTraceScope {
 public:
  explicit PrepareStackTraceScope(Isolate* isolate) : isolate_(isolate) {
    DCHECK(!isolate_->formatting_stack_trace());
    isolate_->set_formatting_stack_trace(true);
  }

  ~PrepareStackTraceScope() { isolate_->set_formatting_stack_trace(false); }

 private:
  Isolate* isolate_;

  DISALLOW_COPY_AND_ASSIGN(PrepareStackTraceScope);
};

}  // namespace

940 941 942 943
// static
MaybeHandle<Object> ErrorUtils::FormatStackTrace(Isolate* isolate,
                                                 Handle<JSObject> error,
                                                 Handle<Object> raw_stack) {
944 945
  DCHECK(raw_stack->IsJSArray());
  Handle<JSArray> raw_stack_array = Handle<JSArray>::cast(raw_stack);
jgruber's avatar
jgruber committed
946

947
  DCHECK(raw_stack_array->elements()->IsFixedArray());
948 949
  Handle<FrameArray> elems(FrameArray::cast(raw_stack_array->elements()),
                           isolate);
950

jgruber's avatar
jgruber committed
951 952
  // If there's a user-specified "prepareStackFrames" function, call it on the
  // frames and use its result.
953

jgruber's avatar
jgruber committed
954 955
  Handle<JSFunction> global_error = isolate->error_function();
  Handle<Object> prepare_stack_trace;
956
  ASSIGN_RETURN_ON_EXCEPTION(
jgruber's avatar
jgruber committed
957 958 959 960 961 962 963
      isolate, prepare_stack_trace,
      JSFunction::GetProperty(isolate, global_error, "prepareStackTrace"),
      Object);

  const bool in_recursion = isolate->formatting_stack_trace();
  if (prepare_stack_trace->IsJSFunction() && !in_recursion) {
    PrepareStackTraceScope scope(isolate);
964

965 966
    isolate->CountUsage(v8::Isolate::kErrorPrepareStackTrace);

967 968 969
    Handle<JSArray> sites;
    ASSIGN_RETURN_ON_EXCEPTION(isolate, sites, GetStackFrames(isolate, elems),
                               Object);
jgruber's avatar
jgruber committed
970 971 972

    const int argc = 2;
    ScopedVector<Handle<Object>> argv(argc);
973

jgruber's avatar
jgruber committed
974
    argv[0] = error;
975
    argv[1] = sites;
jgruber's avatar
jgruber committed
976 977 978 979 980 981 982 983

    Handle<Object> result;
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, result, Execution::Call(isolate, prepare_stack_trace,
                                         global_error, argc, argv.start()),
        Object);

    return result;
984
  }
985

986 987
  // Otherwise, run our internal formatting logic.

988
  IncrementalStringBuilder builder(isolate);
jgruber's avatar
jgruber committed
989

990 991
  RETURN_ON_EXCEPTION(isolate, AppendErrorString(isolate, error, &builder),
                      Object);
jgruber's avatar
jgruber committed
992

993
  for (FrameArrayIterator it(isolate, elems); it.HasNext(); it.Next()) {
994
    builder.AppendCString("\n    at ");
jgruber's avatar
jgruber committed
995

996 997
    StackFrameBase* frame = it.Frame();
    MaybeHandle<String> maybe_frame_string = frame->ToString();
998 999 1000 1001 1002 1003 1004 1005
    if (maybe_frame_string.is_null()) {
      // CallSite.toString threw. Try to return a string representation of the
      // thrown exception instead.

      DCHECK(isolate->has_pending_exception());
      Handle<Object> pending_exception =
          handle(isolate->pending_exception(), isolate);
      isolate->clear_pending_exception();
1006
      isolate->set_external_caught_exception(false);
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

      maybe_frame_string = ErrorUtils::ToString(isolate, pending_exception);
      if (maybe_frame_string.is_null()) {
        // Formatting the thrown exception threw again, give up.

        builder.AppendCString("<error>");
      } else {
        // Formatted thrown exception successfully, append it.
        builder.AppendCString("<error: ");
        builder.AppendString(maybe_frame_string.ToHandleChecked());
        builder.AppendCString("<error>");
      }
    } else {
      // CallSite.toString completed without throwing.
      builder.AppendString(maybe_frame_string.ToHandleChecked());
    }
1023
  }
1024

jgruber's avatar
jgruber committed
1025
  return builder.Finish();
1026
}
1027

1028 1029 1030 1031
Handle<String> MessageTemplate::FormatMessage(Isolate* isolate,
                                              int template_index,
                                              Handle<Object> arg) {
  Factory* factory = isolate->factory();
1032
  Handle<String> result_string = Object::NoSideEffectsToString(isolate, arg);
1033
  MaybeHandle<String> maybe_result_string = MessageTemplate::FormatMessage(
1034
      template_index, result_string, factory->empty_string(),
1035 1036
      factory->empty_string());
  if (!maybe_result_string.ToHandle(&result_string)) {
1037 1038
    DCHECK(isolate->has_pending_exception());
    isolate->clear_pending_exception();
1039 1040 1041 1042 1043 1044 1045
    return factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("<error>"));
  }
  // A string that has been obtained from JS code in this way is
  // likely to be a complicated ConsString of some sort.  We flatten it
  // here to improve the efficiency of converting it to a C string and
  // other operations that are likely to take place (see GetLocalizedMessage
  // for example).
1046
  return String::Flatten(isolate, result_string);
1047 1048 1049
}


1050
const char* MessageTemplate::TemplateString(int template_index) {
1051
  switch (template_index) {
1052 1053 1054
#define CASE(NAME, STRING) \
  case k##NAME:            \
    return STRING;
1055 1056 1057 1058
    MESSAGE_TEMPLATES(CASE)
#undef CASE
    case kLastMessage:
    default:
1059
      return nullptr;
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  }
}


MaybeHandle<String> MessageTemplate::FormatMessage(int template_index,
                                                   Handle<String> arg0,
                                                   Handle<String> arg1,
                                                   Handle<String> arg2) {
  Isolate* isolate = arg0->GetIsolate();
  const char* template_string = TemplateString(template_index);
1070
  if (template_string == nullptr) {
1071 1072
    isolate->ThrowIllegalOperation();
    return MaybeHandle<String>();
1073 1074 1075 1076
  }

  IncrementalStringBuilder builder(isolate);

1077
  unsigned int i = 0;
1078 1079 1080
  Handle<String> args[] = {arg0, arg1, arg2};
  for (const char* c = template_string; *c != '\0'; c++) {
    if (*c == '%') {
1081 1082 1083 1084 1085 1086
      // %% results in verbatim %.
      if (*(c + 1) == '%') {
        c++;
        builder.AppendCharacter('%');
      } else {
        DCHECK(i < arraysize(args));
1087
        Handle<String> arg = args[i++];
1088
        builder.AppendString(arg);
1089
      }
1090 1091 1092 1093 1094 1095 1096
    } else {
      builder.AppendCharacter(*c);
    }
  }

  return builder.Finish();
}
1097

jgruber's avatar
jgruber committed
1098 1099
MaybeHandle<Object> ErrorUtils::Construct(
    Isolate* isolate, Handle<JSFunction> target, Handle<Object> new_target,
1100 1101
    Handle<Object> message, FrameSkipMode mode, Handle<Object> caller,
    bool suppress_detailed_trace) {
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  // 1. If NewTarget is undefined, let newTarget be the active function object,
  // else let newTarget be NewTarget.

  Handle<JSReceiver> new_target_recv =
      new_target->IsJSReceiver() ? Handle<JSReceiver>::cast(new_target)
                                 : Handle<JSReceiver>::cast(target);

  // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%ErrorPrototype%",
  //    « [[ErrorData]] »).
  Handle<JSObject> err;
  ASSIGN_RETURN_ON_EXCEPTION(isolate, err,
                             JSObject::New(target, new_target_recv), Object);

  // 3. If message is not undefined, then
  //  a. Let msg be ? ToString(message).
  //  b. Let msgDesc be the PropertyDescriptor{[[Value]]: msg, [[Writable]]:
  //     true, [[Enumerable]]: false, [[Configurable]]: true}.
  //  c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc).
  // 4. Return O.

  if (!message->IsUndefined(isolate)) {
    Handle<String> msg_string;
    ASSIGN_RETURN_ON_EXCEPTION(isolate, msg_string,
                               Object::ToString(isolate, message), Object);
    RETURN_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
                                     err, isolate->factory()->message_string(),
                                     msg_string, DONT_ENUM),
                        Object);
  }

  // Optionally capture a more detailed stack trace for the message.
  if (!suppress_detailed_trace) {
    RETURN_ON_EXCEPTION(isolate, isolate->CaptureAndSetDetailedStackTrace(err),
                        Object);
  }
1137

1138
  // Capture a simple stack trace for the stack property.
1139 1140
  RETURN_ON_EXCEPTION(isolate,
                      isolate->CaptureAndSetSimpleStackTrace(err, mode, caller),
1141 1142 1143 1144
                      Object);

  return err;
}
1145

jgruber's avatar
jgruber committed
1146 1147 1148 1149 1150 1151 1152
namespace {

MaybeHandle<String> GetStringPropertyOrDefault(Isolate* isolate,
                                               Handle<JSReceiver> recv,
                                               Handle<String> key,
                                               Handle<String> default_str) {
  Handle<Object> obj;
1153 1154
  ASSIGN_RETURN_ON_EXCEPTION(isolate, obj,
                             JSObject::GetProperty(isolate, recv, key), String);
jgruber's avatar
jgruber committed
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

  Handle<String> str;
  if (obj->IsUndefined(isolate)) {
    str = default_str;
  } else {
    ASSIGN_RETURN_ON_EXCEPTION(isolate, str, Object::ToString(isolate, obj),
                               String);
  }

  return str;
}

}  // namespace

// ES6 section 19.5.3.4 Error.prototype.toString ( )
MaybeHandle<String> ErrorUtils::ToString(Isolate* isolate,
                                         Handle<Object> receiver) {
  // 1. Let O be the this value.
  // 2. If Type(O) is not Object, throw a TypeError exception.
  if (!receiver->IsJSReceiver()) {
    return isolate->Throw<String>(isolate->factory()->NewTypeError(
        MessageTemplate::kIncompatibleMethodReceiver,
        isolate->factory()->NewStringFromAsciiChecked(
            "Error.prototype.toString"),
        receiver));
  }
  Handle<JSReceiver> recv = Handle<JSReceiver>::cast(receiver);

  // 3. Let name be ? Get(O, "name").
  // 4. If name is undefined, let name be "Error"; otherwise let name be
  // ? ToString(name).
  Handle<String> name_key = isolate->factory()->name_string();
  Handle<String> name_default = isolate->factory()->Error_string();
  Handle<String> name;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, name,
      GetStringPropertyOrDefault(isolate, recv, name_key, name_default),
      String);

  // 5. Let msg be ? Get(O, "message").
  // 6. If msg is undefined, let msg be the empty String; otherwise let msg be
  // ? ToString(msg).
  Handle<String> msg_key = isolate->factory()->message_string();
  Handle<String> msg_default = isolate->factory()->empty_string();
  Handle<String> msg;
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, msg,
      GetStringPropertyOrDefault(isolate, recv, msg_key, msg_default), String);

  // 7. If name is the empty String, return msg.
  // 8. If msg is the empty String, return name.
  if (name->length() == 0) return msg;
  if (msg->length() == 0) return name;

  // 9. Return the result of concatenating name, the code unit 0x003A (COLON),
  // the code unit 0x0020 (SPACE), and msg.
  IncrementalStringBuilder builder(isolate);
  builder.AppendString(name);
  builder.AppendCString(": ");
  builder.AppendString(msg);

  Handle<String> result;
  ASSIGN_RETURN_ON_EXCEPTION(isolate, result, builder.Finish(), String);
  return result;
}

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
namespace {

Handle<String> FormatMessage(Isolate* isolate, int template_index,
                             Handle<Object> arg0, Handle<Object> arg1,
                             Handle<Object> arg2) {
  Handle<String> arg0_str = Object::NoSideEffectsToString(isolate, arg0);
  Handle<String> arg1_str = Object::NoSideEffectsToString(isolate, arg1);
  Handle<String> arg2_str = Object::NoSideEffectsToString(isolate, arg2);

  isolate->native_context()->IncrementErrorsThrown();

  Handle<String> msg;
  if (!MessageTemplate::FormatMessage(template_index, arg0_str, arg1_str,
                                      arg2_str)
           .ToHandle(&msg)) {
    DCHECK(isolate->has_pending_exception());
    isolate->clear_pending_exception();
1238
    isolate->set_external_caught_exception(false);
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    return isolate->factory()->NewStringFromAsciiChecked("<error>");
  }

  return msg;
}

}  // namespace

// static
MaybeHandle<Object> ErrorUtils::MakeGenericError(
    Isolate* isolate, Handle<JSFunction> constructor, int template_index,
    Handle<Object> arg0, Handle<Object> arg1, Handle<Object> arg2,
    FrameSkipMode mode) {
1252 1253 1254 1255 1256 1257 1258
  if (FLAG_clear_exceptions_on_js_entry) {
    // This function used to be implemented in JavaScript, and JSEntryStub
    // clears
    // any pending exceptions - so whenever we'd call this from C++, pending
    // exceptions would be cleared. Preserve this behavior.
    isolate->clear_pending_exception();
  }
1259 1260 1261 1262 1263 1264 1265 1266 1267

  DCHECK(mode != SKIP_UNTIL_SEEN);

  Handle<Object> no_caller;
  Handle<String> msg = FormatMessage(isolate, template_index, arg0, arg1, arg2);
  return ErrorUtils::Construct(isolate, constructor, constructor, msg, mode,
                               no_caller, false);
}

1268 1269
}  // namespace internal
}  // namespace v8