messages.cc 17.2 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 "src/api.h"
#include "src/execution.h"
9
#include "src/isolate-inl.h"
10
#include "src/string-builder.h"
11

12 13
namespace v8 {
namespace internal {
14 15 16 17


// If no message listeners have been registered this one is called
// by default.
18 19
void MessageHandler::DefaultMessageReport(Isolate* isolate,
                                          const MessageLocation* loc,
20
                                          Handle<Object> message_obj) {
rmcilroy's avatar
rmcilroy committed
21
  base::SmartArrayPointer<char> str = GetLocalizedMessage(isolate, message_obj);
22
  if (loc == NULL) {
23
    PrintF("%s\n", str.get());
24
  } else {
25
    HandleScope scope(isolate);
26
    Handle<Object> data(loc->script()->name(), isolate);
rmcilroy's avatar
rmcilroy committed
27
    base::SmartArrayPointer<char> data_str;
28 29
    if (data->IsString())
      data_str = Handle<String>::cast(data)->ToCString(DISALLOW_NULLS);
30 31
    PrintF("%s:%i: %s\n", data_str.get() ? data_str.get() : "<unknown>",
           loc->start_pos(), str.get());
32 33 34 35
  }
}


36
Handle<JSMessageObject> MessageHandler::MakeMessageObject(
37 38 39
    Isolate* isolate, MessageTemplate::Template message,
    MessageLocation* location, Handle<Object> argument,
    Handle<JSArray> stack_frames) {
40
  Factory* factory = isolate->factory();
41

42 43
  int start = -1;
  int end = -1;
44
  Handle<Object> script_handle = factory->undefined_value();
45 46 47 48 49 50
  if (location != NULL) {
    start = location->start_pos();
    end = location->end_pos();
    script_handle = Script::GetWrapper(location->script());
  } else {
    script_handle = Script::GetWrapper(isolate->factory()->empty_script());
51
  }
52

53
  Handle<Object> stack_frames_handle = stack_frames.is_null()
54
      ? Handle<Object>::cast(factory->undefined_value())
55 56
      : Handle<Object>::cast(stack_frames);

57 58
  Handle<JSMessageObject> message_obj = factory->NewJSMessageObject(
      message, argument, start, end, script_handle, stack_frames_handle);
59

60
  return message_obj;
61 62
}

63

64 65
void MessageHandler::ReportMessage(Isolate* isolate, MessageLocation* loc,
                                   Handle<JSMessageObject> message) {
66 67 68
  // 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.
69 70 71 72

  // We pass the exception object into the message handler callback though.
  Object* exception_object = isolate->heap()->undefined_value();
  if (isolate->has_pending_exception()) {
73
    exception_object = isolate->pending_exception();
74
  }
75
  Handle<Object> exception(exception_object, isolate);
76

77 78 79 80
  Isolate::ExceptionScope exception_scope(isolate);
  isolate->clear_pending_exception();
  isolate->set_external_caught_exception(false);

81 82 83 84 85 86
  // 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);
    Handle<Object> args[] = {argument};
    MaybeHandle<Object> maybe_stringified = Execution::TryCall(
87
        isolate->to_detail_string_fun(), isolate->factory()->undefined_value(),
88 89 90 91 92 93 94 95
        arraysize(args), args);
    Handle<Object> stringified;
    if (!maybe_stringified.ToHandle(&stringified)) {
      stringified = isolate->factory()->NewStringFromAsciiChecked("exception");
    }
    message->set_argument(*stringified);
  }

96
  v8::Local<v8::Message> api_message_obj = v8::Utils::MessageToLocal(message);
97
  v8::Local<v8::Value> api_exception_obj = v8::Utils::ToLocal(exception);
98

99
  v8::NeanderArray global_listeners(isolate->factory()->message_listeners());
100 101
  int global_length = global_listeners.length();
  if (global_length == 0) {
102
    DefaultMessageReport(isolate, loc, message);
103 104 105
    if (isolate->has_scheduled_exception()) {
      isolate->clear_scheduled_exception();
    }
106 107
  } else {
    for (int i = 0; i < global_length; i++) {
108
      HandleScope scope(isolate);
109
      if (global_listeners.get(i)->IsUndefined()) continue;
110 111
      v8::NeanderObject listener(JSObject::cast(global_listeners.get(i)));
      Handle<Foreign> callback_obj(Foreign::cast(listener.get(0)));
112
      v8::MessageCallback callback =
113
          FUNCTION_CAST<v8::MessageCallback>(callback_obj->foreign_address());
114
      Handle<Object> callback_data(listener.get(1), isolate);
115 116
      {
        // Do not allow exceptions to propagate.
117
        v8::TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
118 119 120
        callback(api_message_obj, callback_data->IsUndefined()
                                      ? api_exception_obj
                                      : v8::Utils::ToLocal(callback_data));
121
      }
122 123 124
      if (isolate->has_scheduled_exception()) {
        isolate->clear_scheduled_exception();
      }
125 126 127 128 129
    }
  }
}


130 131
Handle<String> MessageHandler::GetMessage(Isolate* isolate,
                                          Handle<Object> data) {
132
  Handle<JSMessageObject> message = Handle<JSMessageObject>::cast(data);
133 134
  Handle<Object> arg = Handle<Object>(message->argument(), isolate);
  return MessageTemplate::FormatMessage(isolate, message->type(), arg);
135 136 137
}


rmcilroy's avatar
rmcilroy committed
138 139
base::SmartArrayPointer<char> MessageHandler::GetLocalizedMessage(
    Isolate* isolate, Handle<Object> data) {
140
  HandleScope scope(isolate);
141
  return GetMessage(isolate, data)->ToCString(DISALLOW_NULLS);
142 143 144
}


145 146
CallSite::CallSite(Isolate* isolate, Handle<JSObject> call_site_obj)
    : isolate_(isolate) {
147 148 149 150 151
  Handle<Object> maybe_function = JSObject::GetDataProperty(
      call_site_obj, isolate->factory()->call_site_function_symbol());
  if (!maybe_function->IsJSFunction()) return;

  fun_ = Handle<JSFunction>::cast(maybe_function);
152 153 154 155 156 157 158 159 160 161 162
  receiver_ = JSObject::GetDataProperty(
      call_site_obj, isolate->factory()->call_site_receiver_symbol());
  pos_ = Handle<Smi>::cast(JSObject::GetDataProperty(
                               call_site_obj,
                               isolate->factory()->call_site_position_symbol()))
             ->value();
}


Handle<Object> CallSite::GetFileName() {
  Handle<Object> script(fun_->shared()->script(), isolate_);
163
  if (script->IsScript()) {
164
    return Handle<Object>(Handle<Script>::cast(script)->name(), isolate_);
165
  }
166
  return isolate_->factory()->null_value();
167 168 169
}


170
Handle<Object> CallSite::GetFunctionName() {
171 172
  Handle<String> result = JSFunction::GetDebugName(fun_);
  if (result->length() != 0) return result;
173
  Handle<Object> script(fun_->shared()->script(), isolate_);
174 175 176
  if (script->IsScript() &&
      Handle<Script>::cast(script)->compilation_type() ==
          Script::COMPILATION_TYPE_EVAL) {
177
    return isolate_->factory()->eval_string();
178
  }
179
  return isolate_->factory()->null_value();
180 181 182
}


183 184
Handle<Object> CallSite::GetScriptNameOrSourceUrl() {
  Handle<Object> script_obj(fun_->shared()->script(), isolate_);
185 186 187
  if (script_obj->IsScript()) {
    Handle<Script> script = Handle<Script>::cast(script_obj);
    Object* source_url = script->source_url();
188 189
    if (source_url->IsString()) return Handle<Object>(source_url, isolate_);
    return Handle<Object>(script->name(), isolate_);
190
  }
191
  return isolate_->factory()->null_value();
192 193 194
}


195
bool CheckMethodName(Isolate* isolate, Handle<JSObject> obj, Handle<Name> name,
196 197
                     Handle<JSFunction> fun,
                     LookupIterator::Configuration config) {
198 199
  LookupIterator iter =
      LookupIterator::PropertyOrElement(isolate, obj, name, config);
200 201 202 203 204 205 206 207 208 209 210 211 212
  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;
}


213 214
Handle<Object> CallSite::GetMethodName() {
  MaybeHandle<JSReceiver> maybe = Object::ToObject(isolate_, receiver_);
215 216
  Handle<JSReceiver> receiver;
  if (!maybe.ToHandle(&receiver) || !receiver->IsJSObject()) {
217
    return isolate_->factory()->null_value();
218 219 220
  }

  Handle<JSObject> obj = Handle<JSObject>::cast(receiver);
221
  Handle<Object> function_name(fun_->shared()->name(), isolate_);
222 223
  if (function_name->IsName()) {
    Handle<Name> name = Handle<Name>::cast(function_name);
224
    if (CheckMethodName(isolate_, obj, name, fun_,
225 226 227 228
                        LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR))
      return name;
  }

229
  HandleScope outer_scope(isolate_);
230
  Handle<Object> result;
231
  for (PrototypeIterator iter(isolate_, obj,
232 233 234 235 236 237 238 239
                              PrototypeIterator::START_AT_RECEIVER);
       !iter.IsAtEnd(); iter.Advance()) {
    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 = JSObject::GetEnumPropertyKeys(current_obj, false);
    for (int i = 0; i < keys->length(); i++) {
240
      HandleScope inner_scope(isolate_);
241
      if (!keys->get(i)->IsName()) continue;
242 243
      Handle<Name> name_key(Name::cast(keys->get(i)), isolate_);
      if (!CheckMethodName(isolate_, current_obj, name_key, fun_,
244 245 246
                           LookupIterator::OWN_SKIP_INTERCEPTOR))
        continue;
      // Return null in case of duplicates to avoid confusion.
247
      if (!result.is_null()) return isolate_->factory()->null_value();
248 249 250 251 252
      result = inner_scope.CloseAndEscape(name_key);
    }
  }

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


257
int CallSite::GetLineNumber() {
258
  if (pos_ >= 0) {
259
    Handle<Object> script_obj(fun_->shared()->script(), isolate_);
260 261 262 263 264 265 266 267 268
    if (script_obj->IsScript()) {
      Handle<Script> script = Handle<Script>::cast(script_obj);
      return Script::GetLineNumber(script, pos_) + 1;
    }
  }
  return -1;
}


269
int CallSite::GetColumnNumber() {
270
  if (pos_ >= 0) {
271
    Handle<Object> script_obj(fun_->shared()->script(), isolate_);
272 273 274 275 276 277 278 279 280
    if (script_obj->IsScript()) {
      Handle<Script> script = Handle<Script>::cast(script_obj);
      return Script::GetColumnNumber(script, pos_) + 1;
    }
  }
  return -1;
}


281 282
bool CallSite::IsNative() {
  Handle<Object> script(fun_->shared()->script(), isolate_);
283
  return script->IsScript() &&
284
         Handle<Script>::cast(script)->type() == Script::TYPE_NATIVE;
285 286 287
}


288
bool CallSite::IsToplevel() {
289 290 291 292 293
  return receiver_->IsJSGlobalProxy() || receiver_->IsNull() ||
         receiver_->IsUndefined();
}


294 295
bool CallSite::IsEval() {
  Handle<Object> script(fun_->shared()->script(), isolate_);
296 297 298 299 300 301
  return script->IsScript() &&
         Handle<Script>::cast(script)->compilation_type() ==
             Script::COMPILATION_TYPE_EVAL;
}


302
bool CallSite::IsConstructor() {
303 304
  if (!receiver_->IsJSObject()) return false;
  Handle<Object> constructor =
305
      JSReceiver::GetDataProperty(Handle<JSObject>::cast(receiver_),
306
                                  isolate_->factory()->constructor_string());
307 308 309 310
  return constructor.is_identical_to(fun_);
}


311 312 313 314
Handle<String> MessageTemplate::FormatMessage(Isolate* isolate,
                                              int template_index,
                                              Handle<Object> arg) {
  Factory* factory = isolate->factory();
315 316 317 318
  Handle<String> result_string;
  if (arg->IsString()) {
    result_string = Handle<String>::cast(arg);
  } else {
319
    Handle<JSFunction> fun = isolate->no_side_effect_to_string_fun();
320 321

    MaybeHandle<Object> maybe_result =
322
        Execution::TryCall(fun, factory->undefined_value(), 1, &arg);
323 324 325 326 327
    Handle<Object> result;
    if (!maybe_result.ToHandle(&result) || !result->IsString()) {
      return factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("<error>"));
    }
    result_string = Handle<String>::cast(result);
328 329
  }
  MaybeHandle<String> maybe_result_string = MessageTemplate::FormatMessage(
330
      template_index, result_string, factory->empty_string(),
331 332 333 334 335 336 337 338 339 340 341 342 343
      factory->empty_string());
  if (!maybe_result_string.ToHandle(&result_string)) {
    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).
  return String::Flatten(result_string);
}


344
const char* MessageTemplate::TemplateString(int template_index) {
345
  switch (template_index) {
346 347 348
#define CASE(NAME, STRING) \
  case k##NAME:            \
    return STRING;
349 350 351 352
    MESSAGE_TEMPLATES(CASE)
#undef CASE
    case kLastMessage:
    default:
353 354 355 356 357 358 359 360 361 362 363 364 365 366
      return NULL;
  }
}


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);
  if (template_string == NULL) {
    isolate->ThrowIllegalOperation();
    return MaybeHandle<String>();
367 368 369 370
  }

  IncrementalStringBuilder builder(isolate);

371
  unsigned int i = 0;
372 373 374
  Handle<String> args[] = {arg0, arg1, arg2};
  for (const char* c = template_string; *c != '\0'; c++) {
    if (*c == '%') {
375 376 377 378 379 380
      // %% results in verbatim %.
      if (*(c + 1) == '%') {
        c++;
        builder.AppendCharacter('%');
      } else {
        DCHECK(i < arraysize(args));
381
        Handle<String> arg = args[i++];
382
        builder.AppendString(arg);
383
      }
384 385 386 387 388 389 390
    } else {
      builder.AppendCharacter(*c);
    }
  }

  return builder.Finish();
}
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413


MaybeHandle<String> ErrorToStringHelper::Stringify(Isolate* isolate,
                                                   Handle<JSObject> error) {
  VisitedScope scope(this, error);
  if (scope.has_visited()) return isolate->factory()->empty_string();

  Handle<String> name;
  Handle<String> message;
  Handle<Name> internal_key = isolate->factory()->internal_error_symbol();
  Handle<String> message_string =
      isolate->factory()->NewStringFromStaticChars("message");
  Handle<String> name_string = isolate->factory()->name_string();
  LookupIterator internal_error_lookup(
      error, internal_key, LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);

  // Find out whether an internally created error object is on the prototype
  // chain. If the name property is found on a holder prior to the internally
  // created error object, use that name property. Otherwise just use the
  // constructor name to avoid triggering possible side effects.
  // Similar for the message property. If the message property shadows the
  // internally created error object, use that message property. Otherwise
  // use empty string as message.
414 415 416 417 418 419 420
  LookupIterator name_lookup(error, name_string,
                             LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
  if (internal_error_lookup.IsFound() &&
      !ShadowsInternalError(isolate, &name_lookup, &internal_error_lookup)) {
    Handle<JSObject> holder = internal_error_lookup.GetHolder<JSObject>();
    name = Handle<String>(holder->constructor_name());
  } else {
421 422 423 424 425 426
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, name,
        GetStringifiedProperty(isolate, &name_lookup,
                               isolate->factory()->Error_string()),
        String);
  }
427 428 429 430 431 432 433

  LookupIterator message_lookup(
      error, message_string, LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
  if (internal_error_lookup.IsFound() &&
      !ShadowsInternalError(isolate, &message_lookup, &internal_error_lookup)) {
    message = isolate->factory()->empty_string();
  } else {
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, message,
        GetStringifiedProperty(isolate, &message_lookup,
                               isolate->factory()->empty_string()),
        String);
  }

  if (name->length() == 0) return message;
  if (message->length() == 0) return name;
  IncrementalStringBuilder builder(isolate);
  builder.AppendString(name);
  builder.AppendCString(": ");
  builder.AppendString(message);
  return builder.Finish();
}


bool ErrorToStringHelper::ShadowsInternalError(
    Isolate* isolate, LookupIterator* property_lookup,
    LookupIterator* internal_error_lookup) {
454
  if (!property_lookup->IsFound()) return false;
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  Handle<JSObject> holder = property_lookup->GetHolder<JSObject>();
  // It's fine if the property is defined on the error itself.
  if (holder.is_identical_to(property_lookup->GetReceiver())) return true;
  PrototypeIterator it(isolate, holder, PrototypeIterator::START_AT_RECEIVER);
  while (true) {
    if (it.IsAtEnd()) return false;
    if (it.IsAtEnd(internal_error_lookup->GetHolder<JSObject>())) return true;
    it.AdvanceIgnoringProxies();
  }
}


MaybeHandle<String> ErrorToStringHelper::GetStringifiedProperty(
    Isolate* isolate, LookupIterator* property_lookup,
    Handle<String> default_value) {
  if (!property_lookup->IsFound()) return default_value;
  Handle<Object> obj;
  ASSIGN_RETURN_ON_EXCEPTION(isolate, obj, Object::GetProperty(property_lookup),
                             String);
  if (obj->IsUndefined()) return default_value;
  if (!obj->IsString()) {
476
    ASSIGN_RETURN_ON_EXCEPTION(isolate, obj, Object::ToString(isolate, obj),
477 478 479 480 481
                               String);
  }
  return Handle<String>::cast(obj);
}

482 483
}  // namespace internal
}  // namespace v8