Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / v8 / V8Initializer.cpp
1 /*
2  * Copyright (C) 2009 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25
26 #include "config.h"
27 #include "bindings/v8/V8Initializer.h"
28
29 #include "V8DOMException.h"
30 #include "V8ErrorEvent.h"
31 #include "V8History.h"
32 #include "V8Location.h"
33 #include "V8Window.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"
53 #include <v8-debug.h>
54
55 namespace WebCore {
56
57 static LocalFrame* findFrame(v8::Local<v8::Object> host, v8::Local<v8::Value> data, v8::Isolate* isolate)
58 {
59     const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data);
60
61     if (V8Window::wrapperTypeInfo.equals(type)) {
62         v8::Handle<v8::Object> windowWrapper = V8Window::findInstanceInPrototypeChain(host, isolate);
63         if (windowWrapper.IsEmpty())
64             return 0;
65         return V8Window::toNative(windowWrapper)->frame();
66     }
67
68     if (V8History::wrapperTypeInfo.equals(type))
69         return V8History::toNative(host)->frame();
70
71     if (V8Location::wrapperTypeInfo.equals(type))
72         return V8Location::toNative(host)->frame();
73
74     // This function can handle only those types listed above.
75     ASSERT_NOT_REACHED();
76     return 0;
77 }
78
79 static void reportFatalErrorInMainThread(const char* location, const char* message)
80 {
81     int memoryUsageMB = blink::Platform::current()->actualMemoryUsageMB();
82     printf("V8 error: %s (%s).  Current memory usage: %d MB\n", message, location, memoryUsageMB);
83     CRASH();
84 }
85
86 static void messageHandlerInMainThread(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
87 {
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())
93         return;
94
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())
99         return;
100
101     String errorMessage = toCoreString(message->Get());
102
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);
108
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;
113
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());
123         }
124     }
125
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);
133 }
134
135 static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data)
136 {
137     v8::Isolate* isolate = v8::Isolate::GetCurrent();
138     LocalFrame* target = findFrame(host, data, isolate);
139     if (!target)
140         return;
141     DOMWindow* targetWindow = target->domWindow();
142
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();
147 }
148
149 static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context)
150 {
151     if (ExecutionContext* executionContext = toExecutionContext(context)) {
152         if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy())
153             return policy->allowEval(ScriptState::forContext(context));
154     }
155     return false;
156 }
157
158 static void timerTraceProfilerInMainThread(const char* name, int status)
159 {
160     if (!status) {
161         TRACE_EVENT_BEGIN0("V8", name);
162     } else {
163         TRACE_EVENT_END0("V8", name);
164     }
165 }
166
167 static void initializeV8Common(v8::Isolate* isolate)
168 {
169     v8::ResourceConstraints constraints;
170     constraints.ConfigureDefaults(static_cast<uint64_t>(blink::Platform::current()->physicalMemoryMB()) << 20, static_cast<uint32_t>(blink::Platform::current()->numberOfProcessors()));
171     v8::SetResourceConstraints(isolate, &constraints);
172
173     v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue);
174     v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue);
175
176     v8::Debug::SetLiveEditEnabled(false);
177 }
178
179 void V8Initializer::initializeMainThreadIfNeeded(v8::Isolate* isolate)
180 {
181     ASSERT(isMainThread());
182
183     static bool initialized = false;
184     if (initialized)
185         return;
186     initialized = true;
187
188     initializeV8Common(isolate);
189
190     v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread);
191     V8PerIsolateData::ensureInitialized(isolate);
192     v8::V8::AddMessageListener(messageHandlerInMainThread);
193     v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread);
194     v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread);
195
196     isolate->SetEventLogger(timerTraceProfilerInMainThread);
197
198     ScriptProfiler::initialize();
199 }
200
201 static void reportFatalErrorInWorker(const char* location, const char* message)
202 {
203     // FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker.
204     CRASH();
205 }
206
207 static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
208 {
209     static bool isReportingException = false;
210     // Exceptions that occur in error handler should be ignored since in that case
211     // WorkerGlobalScope::reportException will send the exception to the worker object.
212     if (isReportingException)
213         return;
214     isReportingException = true;
215
216     v8::Isolate* isolate = v8::Isolate::GetCurrent();
217     // During the frame teardown, there may not be a valid context.
218     if (ExecutionContext* context = currentExecutionContext(isolate)) {
219         String errorMessage = toCoreString(message->Get());
220         V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, sourceURL, message->GetScriptResourceName());
221
222         RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, DOMWrapperWorld::current(isolate));
223         AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
224
225         V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, isolate);
226         context->reportException(event.release(), nullptr, corsStatus);
227     }
228
229     isReportingException = false;
230 }
231
232 static const int kWorkerMaxStackSize = 500 * 1024;
233
234 void V8Initializer::initializeWorker(v8::Isolate* isolate)
235 {
236     initializeV8Common(isolate);
237
238     v8::V8::AddMessageListener(messageHandlerInWorker);
239     v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker);
240
241     v8::ResourceConstraints resourceConstraints;
242     uint32_t here;
243     resourceConstraints.set_stack_limit(&here - kWorkerMaxStackSize / sizeof(uint32_t*));
244     v8::SetResourceConstraints(isolate, &resourceConstraints);
245 }
246
247 } // namespace WebCore