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/core/v8/V8Initializer.h"
28
29#include "bindings/core/v8/DOMWrapperWorld.h"
30#include "bindings/core/v8/ScriptCallStackFactory.h"
31#include "bindings/core/v8/ScriptController.h"
32#include "bindings/core/v8/ScriptProfiler.h"
33#include "bindings/core/v8/V8Binding.h"
34#include "bindings/core/v8/V8DOMException.h"
35#include "bindings/core/v8/V8ErrorEvent.h"
36#include "bindings/core/v8/V8ErrorHandler.h"
37#include "bindings/core/v8/V8GCController.h"
38#include "bindings/core/v8/V8History.h"
39#include "bindings/core/v8/V8Location.h"
40#include "bindings/core/v8/V8PerContextData.h"
41#include "bindings/core/v8/V8Window.h"
42#include "core/dom/Document.h"
43#include "core/dom/ExceptionCode.h"
44#include "core/frame/ConsoleTypes.h"
45#include "core/frame/LocalDOMWindow.h"
46#include "core/frame/LocalFrame.h"
47#include "core/frame/csp/ContentSecurityPolicy.h"
48#include "core/inspector/ScriptCallStack.h"
49#include "platform/EventDispatchForbiddenScope.h"
50#include "platform/TraceEvent.h"
51#include "public/platform/Platform.h"
52#include "wtf/RefPtr.h"
53#include "wtf/text/WTFString.h"
54#include <v8-debug.h>
55
56namespace blink {
57
58static LocalFrame* findFrame(v8::Local<v8::Object> host, v8::Local<v8::Value> data, v8::Isolate* isolate)
59{
60    const WrapperTypeInfo* type = WrapperTypeInfo::unwrap(data);
61
62    if (V8Window::wrapperTypeInfo.equals(type)) {
63        v8::Handle<v8::Object> windowWrapper = V8Window::findInstanceInPrototypeChain(host, isolate);
64        if (windowWrapper.IsEmpty())
65            return 0;
66        return V8Window::toImpl(windowWrapper)->frame();
67    }
68
69    if (V8History::wrapperTypeInfo.equals(type))
70        return V8History::toImpl(host)->frame();
71
72    if (V8Location::wrapperTypeInfo.equals(type))
73        return V8Location::toImpl(host)->frame();
74
75    // This function can handle only those types listed above.
76    ASSERT_NOT_REACHED();
77    return 0;
78}
79
80static void reportFatalErrorInMainThread(const char* location, const char* message)
81{
82    int memoryUsageMB = blink::Platform::current()->actualMemoryUsageMB();
83    printf("V8 error: %s (%s).  Current memory usage: %d MB\n", message, location, memoryUsageMB);
84    CRASH();
85}
86
87static void messageHandlerInMainThread(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
88{
89    ASSERT(isMainThread());
90    // It's possible that messageHandlerInMainThread() is invoked while we're initializing a window.
91    // In that half-baked situation, we don't have a valid context nor a valid world,
92    // so just return immediately.
93    if (DOMWrapperWorld::windowIsBeingInitialized())
94        return;
95
96    v8::Isolate* isolate = v8::Isolate::GetCurrent();
97    // If called during context initialization, there will be no entered window.
98    LocalDOMWindow* enteredWindow = enteredDOMWindow(isolate);
99    if (!enteredWindow || !enteredWindow->isCurrentlyDisplayedInFrame())
100        return;
101
102    String errorMessage = toCoreString(message->Get());
103
104    v8::Handle<v8::StackTrace> stackTrace = message->GetStackTrace();
105    RefPtrWillBeRawPtr<ScriptCallStack> callStack = nullptr;
106    int scriptId = message->GetScriptOrigin().ScriptID()->Value();
107    // Currently stack trace is only collected when inspector is open.
108    if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0) {
109        callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);
110        bool success = false;
111        int topScriptId = callStack->at(0).scriptId().toInt(&success);
112        if (success && topScriptId == scriptId)
113            scriptId = 0;
114    } else {
115        Vector<ScriptCallFrame> callFrames;
116        callStack = ScriptCallStack::create(callFrames);
117    }
118
119    v8::Handle<v8::Value> resourceName = message->GetScriptOrigin().ResourceName();
120    bool shouldUseDocumentURL = resourceName.IsEmpty() || !resourceName->IsString();
121    String resource = shouldUseDocumentURL ? enteredWindow->document()->url() : toCoreString(resourceName.As<v8::String>());
122    AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
123
124    ScriptState* scriptState = ScriptState::current(isolate);
125    RefPtrWillBeRawPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, resource, message->GetLineNumber(), message->GetStartColumn() + 1, &scriptState->world());
126    if (V8DOMWrapper::isDOMWrapper(data)) {
127        v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(data);
128        const WrapperTypeInfo* type = toWrapperTypeInfo(obj);
129        if (V8DOMException::wrapperTypeInfo.isSubclass(type)) {
130            DOMException* exception = V8DOMException::toImpl(obj);
131            if (exception && !exception->messageForConsole().isEmpty())
132                event->setUnsanitizedMessage("Uncaught " + exception->toStringForConsole());
133        }
134    }
135
136    // This method might be called while we're creating a new context. In this case, we
137    // avoid storing the exception object, as we can't create a wrapper during context creation.
138    // FIXME: Can we even get here during initialization now that we bail out when GetEntered returns an empty handle?
139    LocalFrame* frame = enteredWindow->document()->frame();
140    if (frame && frame->script().existingWindowProxy(scriptState->world())) {
141        V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, scriptState->context()->Global(), isolate);
142    }
143
144    if (scriptState->world().isPrivateScriptIsolatedWorld()) {
145        // We allow a private script to dispatch error events even in a EventDispatchForbiddenScope scope.
146        // Without having this ability, it's hard to debug the private script because syntax errors
147        // in the private script are not reported to console (the private script just crashes silently).
148        // Allowing error events in private scripts is safe because error events don't propagate to
149        // other isolated worlds (which means that the error events won't fire any event listeners
150        // in user's scripts).
151        EventDispatchForbiddenScope::AllowUserAgentEvents allowUserAgentEvents;
152        enteredWindow->document()->reportException(event.release(), scriptId, callStack, corsStatus);
153    } else {
154        enteredWindow->document()->reportException(event.release(), scriptId, callStack, corsStatus);
155    }
156}
157
158static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data)
159{
160    v8::Isolate* isolate = v8::Isolate::GetCurrent();
161    LocalFrame* target = findFrame(host, data, isolate);
162    if (!target)
163        return;
164    LocalDOMWindow* targetWindow = target->domWindow();
165
166    // FIXME: We should modify V8 to pass in more contextual information (context, property, and object).
167    ExceptionState exceptionState(ExceptionState::UnknownContext, 0, 0, isolate->GetCurrentContext()->Global(), isolate);
168    exceptionState.throwSecurityError(targetWindow->sanitizedCrossDomainAccessErrorMessage(callingDOMWindow(isolate)), targetWindow->crossDomainAccessErrorMessage(callingDOMWindow(isolate)));
169    exceptionState.throwIfNeeded();
170}
171
172static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context)
173{
174    if (ExecutionContext* executionContext = toExecutionContext(context)) {
175        if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy())
176            return policy->allowEval(ScriptState::from(context));
177    }
178    return false;
179}
180
181static void timerTraceProfilerInMainThread(const char* name, int status)
182{
183    if (!status) {
184        TRACE_EVENT_BEGIN0("v8", name);
185    } else {
186        TRACE_EVENT_END0("v8", name);
187    }
188}
189
190static void initializeV8Common(v8::Isolate* isolate)
191{
192    v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue);
193    v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue);
194
195    v8::Debug::SetLiveEditEnabled(isolate, false);
196
197    isolate->SetAutorunMicrotasks(false);
198}
199
200void V8Initializer::initializeMainThreadIfNeeded()
201{
202    ASSERT(isMainThread());
203
204    static bool initialized = false;
205    if (initialized)
206        return;
207    initialized = true;
208
209    gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode, v8ArrayBufferAllocator());
210
211    v8::Isolate* isolate = V8PerIsolateData::initialize();
212
213    initializeV8Common(isolate);
214
215    v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread);
216    v8::V8::AddMessageListener(messageHandlerInMainThread);
217    v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread);
218    v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread);
219
220    isolate->SetEventLogger(timerTraceProfilerInMainThread);
221
222    ScriptProfiler::initialize();
223}
224
225static void reportFatalErrorInWorker(const char* location, const char* message)
226{
227    // FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker.
228    CRASH();
229}
230
231static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
232{
233    static bool isReportingException = false;
234    // Exceptions that occur in error handler should be ignored since in that case
235    // WorkerGlobalScope::reportException will send the exception to the worker object.
236    if (isReportingException)
237        return;
238    isReportingException = true;
239
240    v8::Isolate* isolate = v8::Isolate::GetCurrent();
241    ScriptState* scriptState = ScriptState::current(isolate);
242    // During the frame teardown, there may not be a valid context.
243    if (ExecutionContext* context = scriptState->executionContext()) {
244        String errorMessage = toCoreString(message->Get());
245        TOSTRING_VOID(V8StringResource<>, sourceURL, message->GetScriptOrigin().ResourceName());
246        int scriptId = message->GetScriptOrigin().ScriptID()->Value();
247
248        RefPtrWillBeRawPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, &DOMWrapperWorld::current(isolate));
249        AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
250
251        // If execution termination has been triggered as part of constructing
252        // the error event from the v8::Message, quietly leave.
253        if (!v8::V8::IsExecutionTerminating(isolate)) {
254            V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, scriptState->context()->Global(), isolate);
255            context->reportException(event.release(), scriptId, nullptr, corsStatus);
256        }
257    }
258
259    isReportingException = false;
260}
261
262static const int kWorkerMaxStackSize = 500 * 1024;
263
264void V8Initializer::initializeWorker(v8::Isolate* isolate)
265{
266    initializeV8Common(isolate);
267
268    v8::V8::AddMessageListener(messageHandlerInWorker);
269    v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker);
270
271    uint32_t here;
272    isolate->SetStackLimit(reinterpret_cast<uintptr_t>(&here - kWorkerMaxStackSize / sizeof(uint32_t*)));
273}
274
275} // namespace blink
276