messages.cc 16.1 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/keys.h"
11
#include "src/string-builder.h"
12
#include "src/wasm/wasm-module.h"
13

14 15
namespace v8 {
namespace internal {
16

17 18 19 20 21 22 23 24 25 26
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,
                                 int end_pos, Handle<JSFunction> function)
    : script_(script),
      start_pos_(start_pos),
      end_pos_(end_pos),
      function_(function) {}
MessageLocation::MessageLocation() : start_pos_(-1), end_pos_(-1) {}
27 28 29

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


48
Handle<JSMessageObject> MessageHandler::MakeMessageObject(
49 50 51
    Isolate* isolate, MessageTemplate::Template message,
    MessageLocation* location, Handle<Object> argument,
    Handle<JSArray> stack_frames) {
52
  Factory* factory = isolate->factory();
53

54 55
  int start = -1;
  int end = -1;
56
  Handle<Object> script_handle = factory->undefined_value();
57 58 59 60 61 62
  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());
63
  }
64

65
  Handle<Object> stack_frames_handle = stack_frames.is_null()
66
      ? Handle<Object>::cast(factory->undefined_value())
67 68
      : Handle<Object>::cast(stack_frames);

69 70
  Handle<JSMessageObject> message_obj = factory->NewJSMessageObject(
      message, argument, start, end, script_handle, stack_frames_handle);
71

72
  return message_obj;
73 74
}

75

76 77
void MessageHandler::ReportMessage(Isolate* isolate, MessageLocation* loc,
                                   Handle<JSMessageObject> message) {
78 79 80
  // 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.
81 82 83 84

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

89 90 91 92
  Isolate::ExceptionScope exception_scope(isolate);
  isolate->clear_pending_exception();
  isolate->set_external_caught_exception(false);

93 94 95 96
  // 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);
97 98

    MaybeHandle<Object> maybe_stringified;
99
    Handle<Object> stringified;
100 101 102 103 104 105 106 107 108 109 110 111 112 113
    // Make sure we don't leak uncaught internally generated Error objects.
    if (Object::IsErrorObject(isolate, argument)) {
      Handle<Object> args[] = {argument};
      maybe_stringified = Execution::TryCall(
          isolate, isolate->no_side_effects_to_string_fun(),
          isolate->factory()->undefined_value(), arraysize(args), args);
    } else {
      v8::TryCatch catcher(reinterpret_cast<v8::Isolate*>(isolate));
      catcher.SetVerbose(false);
      catcher.SetCaptureMessage(false);

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

114 115 116 117 118 119
    if (!maybe_stringified.ToHandle(&stringified)) {
      stringified = isolate->factory()->NewStringFromAsciiChecked("exception");
    }
    message->set_argument(*stringified);
  }

120
  v8::Local<v8::Message> api_message_obj = v8::Utils::MessageToLocal(message);
121
  v8::Local<v8::Value> api_exception_obj = v8::Utils::ToLocal(exception);
122

123
  v8::NeanderArray global_listeners(isolate->factory()->message_listeners());
124 125
  int global_length = global_listeners.length();
  if (global_length == 0) {
126
    DefaultMessageReport(isolate, loc, message);
127 128 129
    if (isolate->has_scheduled_exception()) {
      isolate->clear_scheduled_exception();
    }
130 131
  } else {
    for (int i = 0; i < global_length; i++) {
132
      HandleScope scope(isolate);
133
      if (global_listeners.get(i)->IsUndefined(isolate)) continue;
134 135
      v8::NeanderObject listener(JSObject::cast(global_listeners.get(i)));
      Handle<Foreign> callback_obj(Foreign::cast(listener.get(0)));
136
      v8::MessageCallback callback =
137
          FUNCTION_CAST<v8::MessageCallback>(callback_obj->foreign_address());
138
      Handle<Object> callback_data(listener.get(1), isolate);
139 140
      {
        // Do not allow exceptions to propagate.
141
        v8::TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
142
        callback(api_message_obj, callback_data->IsUndefined(isolate)
143 144
                                      ? api_exception_obj
                                      : v8::Utils::ToLocal(callback_data));
145
      }
146 147 148
      if (isolate->has_scheduled_exception()) {
        isolate->clear_scheduled_exception();
      }
149 150 151 152 153
    }
  }
}


154 155
Handle<String> MessageHandler::GetMessage(Isolate* isolate,
                                          Handle<Object> data) {
156
  Handle<JSMessageObject> message = Handle<JSMessageObject>::cast(data);
157 158
  Handle<Object> arg = Handle<Object>(message->argument(), isolate);
  return MessageTemplate::FormatMessage(isolate, message->type(), arg);
159 160 161
}


rmcilroy's avatar
rmcilroy committed
162 163
base::SmartArrayPointer<char> MessageHandler::GetLocalizedMessage(
    Isolate* isolate, Handle<Object> data) {
164
  HandleScope scope(isolate);
165
  return GetMessage(isolate, data)->ToCString(DISALLOW_NULLS);
166 167 168
}


169 170
CallSite::CallSite(Isolate* isolate, Handle<JSObject> call_site_obj)
    : isolate_(isolate) {
171 172
  Handle<Object> maybe_function = JSObject::GetDataProperty(
      call_site_obj, isolate->factory()->call_site_function_symbol());
173 174 175 176 177 178 179 180 181 182 183 184 185
  if (maybe_function->IsJSFunction()) {
    // javascript
    fun_ = Handle<JSFunction>::cast(maybe_function);
    receiver_ = JSObject::GetDataProperty(
        call_site_obj, isolate->factory()->call_site_receiver_symbol());
  } else {
    Handle<Object> maybe_wasm_func_index = JSObject::GetDataProperty(
        call_site_obj, isolate->factory()->call_site_wasm_func_index_symbol());
    if (!maybe_wasm_func_index->IsSmi()) {
      // invalid: neither javascript nor wasm
      return;
    }
    // wasm
186 187
    wasm_obj_ = Handle<JSObject>::cast(JSObject::GetDataProperty(
        call_site_obj, isolate->factory()->call_site_wasm_obj_symbol()));
188 189 190
    wasm_func_index_ = Smi::cast(*maybe_wasm_func_index)->value();
    DCHECK(static_cast<int>(wasm_func_index_) >= 0);
  }
191

192 193 194
  CHECK(JSObject::GetDataProperty(
            call_site_obj, isolate->factory()->call_site_position_symbol())
            ->ToInt32(&pos_));
195 196 197 198
}


Handle<Object> CallSite::GetFileName() {
199 200 201 202
  if (!IsJavaScript()) return isolate_->factory()->null_value();
  Object* script = fun_->shared()->script();
  if (!script->IsScript()) return isolate_->factory()->null_value();
  return Handle<Object>(Script::cast(script)->name(), isolate_);
203 204 205
}


206
Handle<Object> CallSite::GetFunctionName() {
207
  if (IsWasm()) {
208 209
    MaybeHandle<String> name =
        wasm::GetWasmFunctionName(wasm_obj_, wasm_func_index_);
210 211
    if (name.is_null()) return isolate_->factory()->null_value();
    return name.ToHandleChecked();
212
  }
213
  Handle<String> result = JSFunction::GetName(fun_);
214
  if (result->length() != 0) return result;
215

216
  Handle<Object> script(fun_->shared()->script(), isolate_);
217 218 219
  if (script->IsScript() &&
      Handle<Script>::cast(script)->compilation_type() ==
          Script::COMPILATION_TYPE_EVAL) {
220
    return isolate_->factory()->eval_string();
221
  }
222
  return isolate_->factory()->null_value();
223 224
}

225
Handle<Object> CallSite::GetScriptNameOrSourceUrl() {
226 227 228 229 230 231 232
  if (!IsJavaScript()) return isolate_->factory()->null_value();
  Object* script_obj = fun_->shared()->script();
  if (!script_obj->IsScript()) return isolate_->factory()->null_value();
  Handle<Script> script(Script::cast(script_obj), isolate_);
  Object* source_url = script->source_url();
  if (source_url->IsString()) return Handle<Object>(source_url, isolate_);
  return Handle<Object>(script->name(), isolate_);
233 234
}

235
bool CheckMethodName(Isolate* isolate, Handle<JSObject> obj, Handle<Name> name,
236 237
                     Handle<JSFunction> fun,
                     LookupIterator::Configuration config) {
238 239
  LookupIterator iter =
      LookupIterator::PropertyOrElement(isolate, obj, name, config);
240 241 242 243 244 245 246 247 248 249 250 251 252
  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;
}


253
Handle<Object> CallSite::GetMethodName() {
254 255
  if (!IsJavaScript() || receiver_->IsNull() ||
      receiver_->IsUndefined(isolate_)) {
256 257 258 259 260
    return isolate_->factory()->null_value();
  }
  Handle<JSReceiver> receiver =
      Object::ToObject(isolate_, receiver_).ToHandleChecked();
  if (!receiver->IsJSObject()) {
261
    return isolate_->factory()->null_value();
262 263 264
  }

  Handle<JSObject> obj = Handle<JSObject>::cast(receiver);
265
  Handle<Object> function_name(fun_->shared()->name(), isolate_);
266 267
  if (function_name->IsName()) {
    Handle<Name> name = Handle<Name>::cast(function_name);
268 269 270 271 272 273 274 275 276 277
    // ES2015 gives getters and setters name prefixes which must
    // be stripped to find the property name.
    if (name->IsString() && FLAG_harmony_function_name) {
      Handle<String> name_string = Handle<String>::cast(name);
      if (name_string->IsUtf8EqualTo(CStrVector("get "), true) ||
          name_string->IsUtf8EqualTo(CStrVector("set "), true)) {
        name = isolate_->factory()->NewProperSubString(name_string, 4,
                                                       name_string->length());
      }
    }
278
    if (CheckMethodName(isolate_, obj, name, fun_,
279
                        LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR)) {
280
      return name;
281
    }
282 283
  }

284
  HandleScope outer_scope(isolate_);
285
  Handle<Object> result;
286
  for (PrototypeIterator iter(isolate_, obj,
287 288 289 290 291 292
                              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;
293 294
    Handle<FixedArray> keys =
        KeyAccumulator::GetEnumPropertyKeys(isolate_, current_obj);
295
    for (int i = 0; i < keys->length(); i++) {
296
      HandleScope inner_scope(isolate_);
297
      if (!keys->get(i)->IsName()) continue;
298 299
      Handle<Name> name_key(Name::cast(keys->get(i)), isolate_);
      if (!CheckMethodName(isolate_, current_obj, name_key, fun_,
300 301 302
                           LookupIterator::OWN_SKIP_INTERCEPTOR))
        continue;
      // Return null in case of duplicates to avoid confusion.
303
      if (!result.is_null()) return isolate_->factory()->null_value();
304 305 306 307 308
      result = inner_scope.CloseAndEscape(name_key);
    }
  }

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


313
int CallSite::GetLineNumber() {
314
  if (pos_ >= 0 && IsJavaScript()) {
315
    Handle<Object> script_obj(fun_->shared()->script(), isolate_);
316 317 318 319 320 321 322 323 324
    if (script_obj->IsScript()) {
      Handle<Script> script = Handle<Script>::cast(script_obj);
      return Script::GetLineNumber(script, pos_) + 1;
    }
  }
  return -1;
}


325
int CallSite::GetColumnNumber() {
326
  if (pos_ >= 0 && IsJavaScript()) {
327
    Handle<Object> script_obj(fun_->shared()->script(), isolate_);
328 329 330 331 332 333 334 335 336
    if (script_obj->IsScript()) {
      Handle<Script> script = Handle<Script>::cast(script_obj);
      return Script::GetColumnNumber(script, pos_) + 1;
    }
  }
  return -1;
}


337
bool CallSite::IsNative() {
338
  if (!IsJavaScript()) return false;
339
  Handle<Object> script(fun_->shared()->script(), isolate_);
340
  return script->IsScript() &&
341
         Handle<Script>::cast(script)->type() == Script::TYPE_NATIVE;
342 343 344
}


345
bool CallSite::IsToplevel() {
346
  if (IsWasm()) return false;
347
  return receiver_->IsJSGlobalProxy() || receiver_->IsNull() ||
348
         receiver_->IsUndefined(isolate_);
349 350 351
}


352
bool CallSite::IsEval() {
353
  if (!IsJavaScript()) return false;
354
  Handle<Object> script(fun_->shared()->script(), isolate_);
355 356 357 358 359 360
  return script->IsScript() &&
         Handle<Script>::cast(script)->compilation_type() ==
             Script::COMPILATION_TYPE_EVAL;
}


361
bool CallSite::IsConstructor() {
362
  if (!IsJavaScript() || !receiver_->IsJSObject()) return false;
363
  Handle<Object> constructor =
364
      JSReceiver::GetDataProperty(Handle<JSObject>::cast(receiver_),
365
                                  isolate_->factory()->constructor_string());
366 367 368 369
  return constructor.is_identical_to(fun_);
}


370 371 372 373
Handle<String> MessageTemplate::FormatMessage(Isolate* isolate,
                                              int template_index,
                                              Handle<Object> arg) {
  Factory* factory = isolate->factory();
374 375 376 377
  Handle<String> result_string;
  if (arg->IsString()) {
    result_string = Handle<String>::cast(arg);
  } else {
378
    Handle<JSFunction> fun = isolate->no_side_effects_to_string_fun();
379 380

    MaybeHandle<Object> maybe_result =
381
        Execution::TryCall(isolate, fun, factory->undefined_value(), 1, &arg);
382 383 384 385 386
    Handle<Object> result;
    if (!maybe_result.ToHandle(&result) || !result->IsString()) {
      return factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("<error>"));
    }
    result_string = Handle<String>::cast(result);
387 388
  }
  MaybeHandle<String> maybe_result_string = MessageTemplate::FormatMessage(
389
      template_index, result_string, factory->empty_string(),
390 391 392 393 394 395 396 397 398 399 400 401 402
      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);
}


403
const char* MessageTemplate::TemplateString(int template_index) {
404
  switch (template_index) {
405 406 407
#define CASE(NAME, STRING) \
  case k##NAME:            \
    return STRING;
408 409 410 411
    MESSAGE_TEMPLATES(CASE)
#undef CASE
    case kLastMessage:
    default:
412 413 414 415 416 417 418 419 420 421 422 423 424 425
      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>();
426 427 428 429
  }

  IncrementalStringBuilder builder(isolate);

430
  unsigned int i = 0;
431 432 433
  Handle<String> args[] = {arg0, arg1, arg2};
  for (const char* c = template_string; *c != '\0'; c++) {
    if (*c == '%') {
434 435 436 437 438 439
      // %% results in verbatim %.
      if (*(c + 1) == '%') {
        c++;
        builder.AppendCharacter('%');
      } else {
        DCHECK(i < arraysize(args));
440
        Handle<String> arg = args[i++];
441
        builder.AppendString(arg);
442
      }
443 444 445 446 447 448 449
    } else {
      builder.AppendCharacter(*c);
    }
  }

  return builder.Finish();
}
450 451


452 453
}  // namespace internal
}  // namespace v8