1// Copyright 2011 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6//     * Redistributions of source code must retain the above copyright
7//       notice, this list of conditions and the following disclaimer.
8//     * Redistributions in binary form must reproduce the above
9//       copyright notice, this list of conditions and the following
10//       disclaimer in the documentation and/or other materials provided
11//       with the distribution.
12//     * Neither the name of Google Inc. nor the names of its
13//       contributors may be used to endorse or promote products derived
14//       from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "execution.h"
32#include "messages.h"
33#include "spaces-inl.h"
34
35namespace v8 {
36namespace internal {
37
38
39// If no message listeners have been registered this one is called
40// by default.
41void MessageHandler::DefaultMessageReport(const MessageLocation* loc,
42                                          Handle<Object> message_obj) {
43  SmartArrayPointer<char> str = GetLocalizedMessage(message_obj);
44  if (loc == NULL) {
45    PrintF("%s\n", *str);
46  } else {
47    HandleScope scope;
48    Handle<Object> data(loc->script()->name());
49    SmartArrayPointer<char> data_str;
50    if (data->IsString())
51      data_str = Handle<String>::cast(data)->ToCString(DISALLOW_NULLS);
52    PrintF("%s:%i: %s\n", *data_str ? *data_str : "<unknown>",
53           loc->start_pos(), *str);
54  }
55}
56
57
58Handle<JSMessageObject> MessageHandler::MakeMessageObject(
59    const char* type,
60    MessageLocation* loc,
61    Vector< Handle<Object> > args,
62    Handle<String> stack_trace,
63    Handle<JSArray> stack_frames) {
64  Handle<String> type_handle = FACTORY->LookupAsciiSymbol(type);
65  Handle<FixedArray> arguments_elements =
66      FACTORY->NewFixedArray(args.length());
67  for (int i = 0; i < args.length(); i++) {
68    arguments_elements->set(i, *args[i]);
69  }
70  Handle<JSArray> arguments_handle =
71      FACTORY->NewJSArrayWithElements(arguments_elements);
72
73  int start = 0;
74  int end = 0;
75  Handle<Object> script_handle = FACTORY->undefined_value();
76  if (loc) {
77    start = loc->start_pos();
78    end = loc->end_pos();
79    script_handle = GetScriptWrapper(loc->script());
80  }
81
82  Handle<Object> stack_trace_handle = stack_trace.is_null()
83      ? Handle<Object>::cast(FACTORY->undefined_value())
84      : Handle<Object>::cast(stack_trace);
85
86  Handle<Object> stack_frames_handle = stack_frames.is_null()
87      ? Handle<Object>::cast(FACTORY->undefined_value())
88      : Handle<Object>::cast(stack_frames);
89
90  Handle<JSMessageObject> message =
91      FACTORY->NewJSMessageObject(type_handle,
92                                  arguments_handle,
93                                  start,
94                                  end,
95                                  script_handle,
96                                  stack_trace_handle,
97                                  stack_frames_handle);
98
99  return message;
100}
101
102
103void MessageHandler::ReportMessage(Isolate* isolate,
104                                   MessageLocation* loc,
105                                   Handle<Object> message) {
106  // We are calling into embedder's code which can throw exceptions.
107  // Thus we need to save current exception state, reset it to the clean one
108  // and ignore scheduled exceptions callbacks can throw.
109  Isolate::ExceptionScope exception_scope(isolate);
110  isolate->clear_pending_exception();
111  isolate->set_external_caught_exception(false);
112
113  v8::Local<v8::Message> api_message_obj = v8::Utils::MessageToLocal(message);
114
115  v8::NeanderArray global_listeners(FACTORY->message_listeners());
116  int global_length = global_listeners.length();
117  if (global_length == 0) {
118    DefaultMessageReport(loc, message);
119    if (isolate->has_scheduled_exception()) {
120      isolate->clear_scheduled_exception();
121    }
122  } else {
123    for (int i = 0; i < global_length; i++) {
124      HandleScope scope;
125      if (global_listeners.get(i)->IsUndefined()) continue;
126      v8::NeanderObject listener(JSObject::cast(global_listeners.get(i)));
127      Handle<Foreign> callback_obj(Foreign::cast(listener.get(0)));
128      v8::MessageCallback callback =
129          FUNCTION_CAST<v8::MessageCallback>(callback_obj->foreign_address());
130      Handle<Object> callback_data(listener.get(1));
131      {
132        // Do not allow exceptions to propagate.
133        v8::TryCatch try_catch;
134        callback(api_message_obj, v8::Utils::ToLocal(callback_data));
135      }
136      if (isolate->has_scheduled_exception()) {
137        isolate->clear_scheduled_exception();
138      }
139    }
140  }
141}
142
143
144Handle<String> MessageHandler::GetMessage(Handle<Object> data) {
145  Handle<String> fmt_str = FACTORY->LookupAsciiSymbol("FormatMessage");
146  Handle<JSFunction> fun =
147      Handle<JSFunction>(
148          JSFunction::cast(
149              Isolate::Current()->js_builtins_object()->
150              GetPropertyNoExceptionThrown(*fmt_str)));
151  Handle<Object> argv[] = { data };
152
153  bool caught_exception;
154  Handle<Object> result =
155      Execution::TryCall(fun,
156                         Isolate::Current()->js_builtins_object(),
157                         ARRAY_SIZE(argv),
158                         argv,
159                         &caught_exception);
160
161  if (caught_exception || !result->IsString()) {
162    return FACTORY->LookupAsciiSymbol("<error>");
163  }
164  Handle<String> result_string = Handle<String>::cast(result);
165  // A string that has been obtained from JS code in this way is
166  // likely to be a complicated ConsString of some sort.  We flatten it
167  // here to improve the efficiency of converting it to a C string and
168  // other operations that are likely to take place (see GetLocalizedMessage
169  // for example).
170  FlattenString(result_string);
171  return result_string;
172}
173
174
175SmartArrayPointer<char> MessageHandler::GetLocalizedMessage(
176    Handle<Object> data) {
177  HandleScope scope;
178  return GetMessage(data)->ToCString(DISALLOW_NULLS);
179}
180
181
182} }  // namespace v8::internal
183