messages.cc 12.9 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/v8.h"
6

7 8
#include "src/api.h"
#include "src/execution.h"
9
#include "src/heap/spaces-inl.h"
10
#include "src/messages.h"
11
#include "src/string-builder.h"
12

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


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


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

  int start = 0;
  int end = 0;
44
  Handle<Object> script_handle = factory->undefined_value();
45 46 47
  if (loc) {
    start = loc->start_pos();
    end = loc->end_pos();
48
    script_handle = Script::GetWrapper(loc->script());
49
  }
50

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

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

58
  return message_obj;
59 60
}

61

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

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

75 76 77 78
  Isolate::ExceptionScope exception_scope(isolate);
  isolate->clear_pending_exception();
  isolate->set_external_caught_exception(false);

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  // 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(
        isolate->to_detail_string_fun(), isolate->js_builtins_object(),
        arraysize(args), args);
    Handle<Object> stringified;
    if (!maybe_stringified.ToHandle(&stringified)) {
      stringified = isolate->factory()->NewStringFromAsciiChecked("exception");
    }
    message->set_argument(*stringified);
  }

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

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


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


136
SmartArrayPointer<char> MessageHandler::GetLocalizedMessage(
137
    Isolate* isolate,
138
    Handle<Object> data) {
139
  HandleScope scope(isolate);
140
  return GetMessage(isolate, data)->ToCString(DISALLOW_NULLS);
141 142 143
}


144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
Handle<Object> CallSite::GetFileName(Isolate* isolate) {
  Handle<Object> script(fun_->shared()->script(), isolate);
  if (script->IsScript()) {
    return Handle<Object>(Handle<Script>::cast(script)->name(), isolate);
  }
  return isolate->factory()->null_value();
}


Handle<Object> CallSite::GetFunctionName(Isolate* isolate) {
  Handle<String> result = JSFunction::GetDebugName(fun_);
  if (result->length() != 0) return result;
  Handle<Object> script(fun_->shared()->script(), isolate);
  if (script->IsScript() &&
      Handle<Script>::cast(script)->compilation_type() ==
          Script::COMPILATION_TYPE_EVAL) {
    return isolate->factory()->eval_string();
  }
  return isolate->factory()->null_value();
}


Handle<Object> CallSite::GetScriptNameOrSourceUrl(Isolate* isolate) {
  Handle<Object> script_obj(fun_->shared()->script(), isolate);
  if (script_obj->IsScript()) {
    Handle<Script> script = Handle<Script>::cast(script_obj);
    Object* source_url = script->source_url();
    if (source_url->IsString()) return Handle<Object>(source_url, isolate);
    return Handle<Object>(script->name(), isolate);
  }
  return isolate->factory()->null_value();
}


178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
bool CheckMethodName(Handle<JSObject> obj, Handle<Name> name,
                     Handle<JSFunction> fun,
                     LookupIterator::Configuration config) {
  LookupIterator iter(obj, name, config);
  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;
}


Handle<Object> CallSite::GetMethodName(Isolate* isolate) {
  MaybeHandle<JSReceiver> maybe = Object::ToObject(isolate, receiver_);
  Handle<JSReceiver> receiver;
  if (!maybe.ToHandle(&receiver) || !receiver->IsJSObject()) {
    return isolate->factory()->null_value();
  }

  Handle<JSObject> obj = Handle<JSObject>::cast(receiver);
  Handle<Object> function_name(fun_->shared()->name(), isolate);
  if (function_name->IsName()) {
    Handle<Name> name = Handle<Name>::cast(function_name);
    if (CheckMethodName(obj, name, fun_,
                        LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR))
      return name;
  }

  HandleScope outer_scope(isolate);
  Handle<Object> result;
  for (PrototypeIterator iter(isolate, obj,
                              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++) {
      HandleScope inner_scope(isolate);
      if (!keys->get(i)->IsName()) continue;
      Handle<Name> name_key(Name::cast(keys->get(i)), isolate);
      if (!CheckMethodName(current_obj, name_key, fun_,
                           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();
}


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
int CallSite::GetLineNumber(Isolate* isolate) {
  if (pos_ >= 0) {
    Handle<Object> script_obj(fun_->shared()->script(), isolate);
    if (script_obj->IsScript()) {
      Handle<Script> script = Handle<Script>::cast(script_obj);
      return Script::GetLineNumber(script, pos_) + 1;
    }
  }
  return -1;
}


int CallSite::GetColumnNumber(Isolate* isolate) {
  if (pos_ >= 0) {
    Handle<Object> script_obj(fun_->shared()->script(), isolate);
    if (script_obj->IsScript()) {
      Handle<Script> script = Handle<Script>::cast(script_obj);
      return Script::GetColumnNumber(script, pos_) + 1;
    }
  }
  return -1;
}


bool CallSite::IsNative(Isolate* isolate) {
  Handle<Object> script(fun_->shared()->script(), isolate);
  return script->IsScript() &&
         Handle<Script>::cast(script)->type()->value() == Script::TYPE_NATIVE;
}


bool CallSite::IsToplevel(Isolate* isolate) {
  return receiver_->IsJSGlobalProxy() || receiver_->IsNull() ||
         receiver_->IsUndefined();
}


bool CallSite::IsEval(Isolate* isolate) {
  Handle<Object> script(fun_->shared()->script(), isolate);
  return script->IsScript() &&
         Handle<Script>::cast(script)->compilation_type() ==
             Script::COMPILATION_TYPE_EVAL;
}


284 285 286
bool CallSite::IsConstructor(Isolate* isolate) {
  if (!receiver_->IsJSObject()) return false;
  Handle<Object> constructor =
287 288
      JSReceiver::GetDataProperty(Handle<JSObject>::cast(receiver_),
                                  isolate->factory()->constructor_string());
289 290 291 292
  return constructor.is_identical_to(fun_);
}


293 294 295 296
Handle<String> MessageTemplate::FormatMessage(Isolate* isolate,
                                              int template_index,
                                              Handle<Object> arg) {
  Factory* factory = isolate->factory();
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  Handle<String> result_string;
  if (arg->IsString()) {
    result_string = Handle<String>::cast(arg);
  } else {
    Handle<String> fmt_str = factory->InternalizeOneByteString(
        STATIC_CHAR_VECTOR("$noSideEffectToString"));
    Handle<JSFunction> fun = Handle<JSFunction>::cast(
        Object::GetProperty(isolate->js_builtins_object(), fmt_str)
            .ToHandleChecked());

    MaybeHandle<Object> maybe_result =
        Execution::TryCall(fun, isolate->js_builtins_object(), 1, &arg);
    Handle<Object> result;
    if (!maybe_result.ToHandle(&result) || !result->IsString()) {
      return factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("<error>"));
    }
    result_string = Handle<String>::cast(result);
314 315
  }
  MaybeHandle<String> maybe_result_string = MessageTemplate::FormatMessage(
316
      template_index, result_string, factory->empty_string(),
317 318 319 320 321 322 323 324 325 326 327 328 329
      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);
}


330 331 332 333
MaybeHandle<String> MessageTemplate::FormatMessage(int template_index,
                                                   Handle<String> arg0,
                                                   Handle<String> arg1,
                                                   Handle<String> arg2) {
334
  Isolate* isolate = arg0->GetIsolate();
335 336 337 338 339 340 341 342 343 344
  const char* template_string;
  switch (template_index) {
#define CASE(NAME, STRING)    \
  case k##NAME:               \
    template_string = STRING; \
    break;
    MESSAGE_TEMPLATES(CASE)
#undef CASE
    case kLastMessage:
    default:
345 346
      isolate->ThrowIllegalOperation();
      return MaybeHandle<String>();
347 348 349 350
  }

  IncrementalStringBuilder builder(isolate);

351
  unsigned int i = 0;
352 353 354
  Handle<String> args[] = {arg0, arg1, arg2};
  for (const char* c = template_string; *c != '\0'; c++) {
    if (*c == '%') {
355 356 357 358 359 360 361 362
      // %% results in verbatim %.
      if (*(c + 1) == '%') {
        c++;
        builder.AppendCharacter('%');
      } else {
        DCHECK(i < arraysize(args));
        builder.AppendString(args[i++]);
      }
363 364 365 366 367 368 369
    } else {
      builder.AppendCharacter(*c);
    }
  }

  return builder.Finish();
}
370 371
}  // namespace internal
}  // namespace v8