2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "bindings/v8/V8Initializer.h"
29 #include "V8DOMException.h"
30 #include "V8ErrorEvent.h"
31 #include "V8History.h"
32 #include "V8Location.h"
34 #include "bindings/v8/DOMWrapperWorld.h"
35 #include "bindings/v8/ScriptCallStackFactory.h"
36 #include "bindings/v8/ScriptController.h"
37 #include "bindings/v8/ScriptProfiler.h"
38 #include "bindings/v8/V8Binding.h"
39 #include "bindings/v8/V8ErrorHandler.h"
40 #include "bindings/v8/V8GCController.h"
41 #include "bindings/v8/V8PerContextData.h"
42 #include "core/dom/Document.h"
43 #include "core/dom/ExceptionCode.h"
44 #include "core/frame/ConsoleTypes.h"
45 #include "core/frame/DOMWindow.h"
46 #include "core/frame/LocalFrame.h"
47 #include "core/frame/csp/ContentSecurityPolicy.h"
48 #include "core/inspector/ScriptCallStack.h"
49 #include "platform/TraceEvent.h"
50 #include "public/platform/Platform.h"
51 #include "wtf/RefPtr.h"
52 #include "wtf/text/WTFString.h"
57 static LocalFrame* findFrame(v8::Local<v8::Object> host, v8::Local<v8::Value> data, v8::Isolate* isolate)
59 const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data);
61 if (V8Window::wrapperTypeInfo.equals(type)) {
62 v8::Handle<v8::Object> windowWrapper = V8Window::findInstanceInPrototypeChain(host, isolate);
63 if (windowWrapper.IsEmpty())
65 return V8Window::toNative(windowWrapper)->frame();
68 if (V8History::wrapperTypeInfo.equals(type))
69 return V8History::toNative(host)->frame();
71 if (V8Location::wrapperTypeInfo.equals(type))
72 return V8Location::toNative(host)->frame();
74 // This function can handle only those types listed above.
79 static void reportFatalErrorInMainThread(const char* location, const char* message)
81 int memoryUsageMB = blink::Platform::current()->actualMemoryUsageMB();
82 printf("V8 error: %s (%s). Current memory usage: %d MB\n", message, location, memoryUsageMB);
86 static void messageHandlerInMainThread(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
88 ASSERT(isMainThread());
89 // It's possible that messageHandlerInMainThread() is invoked while we're initializing a window.
90 // In that half-baked situation, we don't have a valid context nor a valid world,
91 // so just return immediately.
92 if (DOMWrapperWorld::windowIsBeingInitialized())
95 v8::Isolate* isolate = v8::Isolate::GetCurrent();
96 // If called during context initialization, there will be no entered window.
97 DOMWindow* enteredWindow = enteredDOMWindow(isolate);
98 if (!enteredWindow || !enteredWindow->isCurrentlyDisplayedInFrame())
101 String errorMessage = toCoreString(message->Get());
103 v8::Handle<v8::StackTrace> stackTrace = message->GetStackTrace();
104 RefPtr<ScriptCallStack> callStack;
105 // Currently stack trace is only collected when inspector is open.
106 if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
107 callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);
109 v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
110 bool shouldUseDocumentURL = resourceName.IsEmpty() || !resourceName->IsString();
111 String resource = shouldUseDocumentURL ? enteredWindow->document()->url() : toCoreString(resourceName.As<v8::String>());
112 AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
114 DOMWrapperWorld* world = DOMWrapperWorld::current(isolate);
115 RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, resource, message->GetLineNumber(), message->GetStartColumn() + 1, world);
116 if (V8DOMWrapper::isDOMWrapper(data)) {
117 v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(data);
118 const WrapperTypeInfo* type = toWrapperTypeInfo(obj);
119 if (V8DOMException::wrapperTypeInfo.isSubclass(type)) {
120 DOMException* exception = V8DOMException::toNative(obj);
121 if (exception && !exception->messageForConsole().isEmpty())
122 event->setUnsanitizedMessage("Uncaught " + exception->toStringForConsole());
126 // This method might be called while we're creating a new context. In this case, we
127 // avoid storing the exception object, as we can't create a wrapper during context creation.
128 // FIXME: Can we even get here during initialization now that we bail out when GetEntered returns an empty handle?
129 LocalFrame* frame = enteredWindow->document()->frame();
130 if (world && frame && frame->script().existingWindowShell(world))
131 V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, v8::Isolate::GetCurrent());
132 enteredWindow->document()->reportException(event.release(), callStack, corsStatus);
135 static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data)
137 v8::Isolate* isolate = v8::Isolate::GetCurrent();
138 LocalFrame* target = findFrame(host, data, isolate);
141 DOMWindow* targetWindow = target->domWindow();
143 // FIXME: We should modify V8 to pass in more contextual information (context, property, and object).
144 ExceptionState exceptionState(ExceptionState::UnknownContext, 0, 0, v8::Handle<v8::Object>(), isolate);
145 exceptionState.throwSecurityError(targetWindow->sanitizedCrossDomainAccessErrorMessage(callingDOMWindow(isolate)), targetWindow->crossDomainAccessErrorMessage(callingDOMWindow(isolate)));
146 exceptionState.throwIfNeeded();
149 static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context)
151 if (ExecutionContext* executionContext = toExecutionContext(context)) {
152 if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy())
153 return policy->allowEval(ScriptState::forContext(context));
158 static void timerTraceProfilerInMainThread(const char* name, int status)
161 TRACE_EVENT_BEGIN0("V8", name);
163 TRACE_EVENT_END0("V8", name);
167 static void initializeV8Common(v8::Isolate* isolate)
169 // FIXME: This is a temporary flags and should be removed soon.
170 const char promiseFlags[] = "--harmony-promises";
171 v8::ResourceConstraints constraints;
172 constraints.ConfigureDefaults(static_cast<uint64_t>(blink::Platform::current()->physicalMemoryMB()) << 20, static_cast<uint32_t>(blink::Platform::current()->numberOfProcessors()));
173 v8::SetResourceConstraints(isolate, &constraints);
175 v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue);
176 v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue);
177 v8::V8::SetFlagsFromString(promiseFlags, strlen(promiseFlags));
179 v8::Debug::SetLiveEditEnabled(false);
182 void V8Initializer::initializeMainThreadIfNeeded(v8::Isolate* isolate)
184 ASSERT(isMainThread());
186 static bool initialized = false;
191 initializeV8Common(isolate);
193 v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread);
194 V8PerIsolateData::ensureInitialized(isolate);
195 v8::V8::AddMessageListener(messageHandlerInMainThread);
196 v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread);
197 v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread);
199 isolate->SetEventLogger(timerTraceProfilerInMainThread);
201 ScriptProfiler::initialize();
204 static void reportFatalErrorInWorker(const char* location, const char* message)
206 // FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker.
210 static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
212 static bool isReportingException = false;
213 // Exceptions that occur in error handler should be ignored since in that case
214 // WorkerGlobalScope::reportException will send the exception to the worker object.
215 if (isReportingException)
217 isReportingException = true;
219 v8::Isolate* isolate = v8::Isolate::GetCurrent();
220 // During the frame teardown, there may not be a valid context.
221 if (ExecutionContext* context = currentExecutionContext(isolate)) {
222 String errorMessage = toCoreString(message->Get());
223 V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, sourceURL, message->GetScriptResourceName());
225 RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, DOMWrapperWorld::current(isolate));
226 AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
228 V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, isolate);
229 context->reportException(event.release(), nullptr, corsStatus);
232 isReportingException = false;
235 static const int kWorkerMaxStackSize = 500 * 1024;
237 void V8Initializer::initializeWorker(v8::Isolate* isolate)
239 initializeV8Common(isolate);
241 v8::V8::AddMessageListener(messageHandlerInWorker);
242 v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker);
244 v8::ResourceConstraints resourceConstraints;
246 resourceConstraints.set_stack_limit(&here - kWorkerMaxStackSize / sizeof(uint32_t*));
247 v8::SetResourceConstraints(isolate, &resourceConstraints);
250 } // namespace WebCore