Home | History | Annotate | Download | only in v8
      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/V8HiddenPropertyName.h"
     42 #include "bindings/v8/V8PerContextData.h"
     43 #include "core/dom/Document.h"
     44 #include "core/dom/ExceptionCode.h"
     45 #include "core/inspector/ScriptCallStack.h"
     46 #include "core/frame/ConsoleTypes.h"
     47 #include "core/frame/ContentSecurityPolicy.h"
     48 #include "core/frame/DOMWindow.h"
     49 #include "core/frame/Frame.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 Frame* 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 = host->FindInstanceInPrototypeChain(V8Window::domTemplate(isolate, worldTypeInMainThread(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     v8::Isolate* isolate = v8::Isolate::GetCurrent();
     89     // If called during context initialization, there will be no entered context.
     90     v8::Handle<v8::Context> enteredContext = isolate->GetEnteredContext();
     91     if (enteredContext.IsEmpty())
     92         return;
     93 
     94     DOMWindow* firstWindow = toDOMWindow(enteredContext);
     95     if (!firstWindow->isCurrentlyDisplayedInFrame())
     96         return;
     97 
     98     String errorMessage = toCoreString(message->Get());
     99 
    100     v8::Handle<v8::StackTrace> stackTrace = message->GetStackTrace();
    101     RefPtr<ScriptCallStack> callStack;
    102     // Currently stack trace is only collected when inspector is open.
    103     if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0)
    104         callStack = createScriptCallStack(stackTrace, ScriptCallStack::maxCallStackSizeToCapture, isolate);
    105 
    106     v8::Handle<v8::Value> resourceName = message->GetScriptResourceName();
    107     bool shouldUseDocumentURL = resourceName.IsEmpty() || !resourceName->IsString();
    108     String resource = shouldUseDocumentURL ? firstWindow->document()->url() : toCoreString(resourceName.As<v8::String>());
    109     AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
    110 
    111     RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, resource, message->GetLineNumber(), message->GetStartColumn() + 1, DOMWrapperWorld::current());
    112     if (V8DOMWrapper::isDOMWrapper(data)) {
    113         v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(data);
    114         const WrapperTypeInfo* type = toWrapperTypeInfo(obj);
    115         if (V8DOMException::wrapperTypeInfo.isSubclass(type)) {
    116             DOMException* exception = V8DOMException::toNative(obj);
    117             if (exception && !exception->messageForConsole().isEmpty())
    118                 event->setUnsanitizedMessage("Uncaught " + exception->toStringForConsole());
    119         }
    120     }
    121 
    122     // This method might be called while we're creating a new context. In this case, we
    123     // avoid storing the exception object, as we can't create a wrapper during context creation.
    124     // FIXME: Can we even get here during initialization now that we bail out when GetEntered returns an empty handle?
    125     DOMWrapperWorld* world = DOMWrapperWorld::current();
    126     Frame* frame = firstWindow->document()->frame();
    127     if (world && frame && frame->script().existingWindowShell(world))
    128         V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, v8::Isolate::GetCurrent());
    129     firstWindow->document()->reportException(event.release(), callStack, corsStatus);
    130 }
    131 
    132 static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data)
    133 {
    134     Frame* target = findFrame(host, data, v8::Isolate::GetCurrent());
    135     if (!target)
    136         return;
    137     DOMWindow* targetWindow = target->domWindow();
    138 
    139     ExceptionState exceptionState(v8::Handle<v8::Object>(), v8::Isolate::GetCurrent());
    140     exceptionState.throwSecurityError(targetWindow->sanitizedCrossDomainAccessErrorMessage(activeDOMWindow()), targetWindow->crossDomainAccessErrorMessage(activeDOMWindow()));
    141     exceptionState.throwIfNeeded();
    142 }
    143 
    144 static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context)
    145 {
    146     if (ExecutionContext* executionContext = toExecutionContext(context)) {
    147         if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy())
    148             return policy->allowEval(ScriptState::forContext(context));
    149     }
    150     return false;
    151 }
    152 
    153 static void initializeV8Common(v8::Isolate* isolate)
    154 {
    155     v8::ResourceConstraints constraints;
    156     constraints.ConfigureDefaults(static_cast<uint64_t>(blink::Platform::current()->physicalMemoryMB()) << 20, static_cast<uint32_t>(blink::Platform::current()->numberOfProcessors()));
    157     v8::SetResourceConstraints(isolate, &constraints);
    158 
    159     v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue);
    160     v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue);
    161     v8::V8::IgnoreOutOfMemoryException();
    162 
    163     v8::Debug::SetLiveEditEnabled(false);
    164 }
    165 
    166 void V8Initializer::initializeMainThreadIfNeeded(v8::Isolate* isolate)
    167 {
    168     ASSERT(isMainThread());
    169 
    170     static bool initialized = false;
    171     if (initialized)
    172         return;
    173     initialized = true;
    174 
    175     initializeV8Common(isolate);
    176 
    177     v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread);
    178     v8::V8::AddMessageListener(messageHandlerInMainThread);
    179     v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread);
    180     v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread);
    181     ScriptProfiler::initialize();
    182     V8PerIsolateData::ensureInitialized(isolate);
    183 }
    184 
    185 static void reportFatalErrorInWorker(const char* location, const char* message)
    186 {
    187     // FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker.
    188     CRASH();
    189 }
    190 
    191 static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data)
    192 {
    193     static bool isReportingException = false;
    194     // Exceptions that occur in error handler should be ignored since in that case
    195     // WorkerGlobalScope::reportException will send the exception to the worker object.
    196     if (isReportingException)
    197         return;
    198     isReportingException = true;
    199 
    200     // During the frame teardown, there may not be a valid context.
    201     if (ExecutionContext* context = getExecutionContext()) {
    202         String errorMessage = toCoreString(message->Get());
    203         V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, sourceURL, message->GetScriptResourceName());
    204 
    205         RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, DOMWrapperWorld::current());
    206         AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin;
    207 
    208         V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, v8::Isolate::GetCurrent());
    209         context->reportException(event.release(), 0, corsStatus);
    210     }
    211 
    212     isReportingException = false;
    213 }
    214 
    215 static const int kWorkerMaxStackSize = 500 * 1024;
    216 
    217 void V8Initializer::initializeWorker(v8::Isolate* isolate)
    218 {
    219     initializeV8Common(isolate);
    220 
    221     v8::V8::AddMessageListener(messageHandlerInWorker);
    222     v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker);
    223 
    224     v8::ResourceConstraints resourceConstraints;
    225     uint32_t here;
    226     resourceConstraints.set_stack_limit(&here - kWorkerMaxStackSize / sizeof(uint32_t*));
    227     v8::SetResourceConstraints(isolate, &resourceConstraints);
    228 }
    229 
    230 } // namespace WebCore
    231