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 "bindings/core/v8/V8DOMException.h" 30 #include "bindings/core/v8/V8ErrorEvent.h" 31 #include "bindings/core/v8/V8History.h" 32 #include "bindings/core/v8/V8Location.h" 33 #include "bindings/core/v8/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/LocalDOMWindow.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 LocalDOMWindow* 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 RefPtrWillBeRawPtr<ScriptCallStack> callStack = nullptr; 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 ScriptState* scriptState = ScriptState::current(isolate); 115 RefPtrWillBeRawPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, resource, message->GetLineNumber(), message->GetStartColumn() + 1, &scriptState->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 (frame && frame->script().existingWindowShell(scriptState->world())) { 131 V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, scriptState->context()->Global(), isolate); 132 } 133 enteredWindow->document()->reportException(event.release(), callStack, corsStatus); 134 } 135 136 static void failedAccessCheckCallbackInMainThread(v8::Local<v8::Object> host, v8::AccessType type, v8::Local<v8::Value> data) 137 { 138 v8::Isolate* isolate = v8::Isolate::GetCurrent(); 139 LocalFrame* target = findFrame(host, data, isolate); 140 if (!target) 141 return; 142 LocalDOMWindow* targetWindow = target->domWindow(); 143 144 // FIXME: We should modify V8 to pass in more contextual information (context, property, and object). 145 ExceptionState exceptionState(ExceptionState::UnknownContext, 0, 0, isolate->GetCurrentContext()->Global(), isolate); 146 exceptionState.throwSecurityError(targetWindow->sanitizedCrossDomainAccessErrorMessage(callingDOMWindow(isolate)), targetWindow->crossDomainAccessErrorMessage(callingDOMWindow(isolate))); 147 exceptionState.throwIfNeeded(); 148 } 149 150 static bool codeGenerationCheckCallbackInMainThread(v8::Local<v8::Context> context) 151 { 152 if (ExecutionContext* executionContext = toExecutionContext(context)) { 153 if (ContentSecurityPolicy* policy = toDocument(executionContext)->contentSecurityPolicy()) 154 return policy->allowEval(ScriptState::from(context)); 155 } 156 return false; 157 } 158 159 static void timerTraceProfilerInMainThread(const char* name, int status) 160 { 161 if (!status) { 162 TRACE_EVENT_BEGIN0("V8", name); 163 } else { 164 TRACE_EVENT_END0("V8", name); 165 } 166 } 167 168 static void initializeV8Common(v8::Isolate* isolate) 169 { 170 v8::ResourceConstraints constraints; 171 constraints.ConfigureDefaults(static_cast<uint64_t>(blink::Platform::current()->physicalMemoryMB()) << 20, static_cast<uint32_t>(blink::Platform::current()->virtualMemoryLimitMB()) << 20, static_cast<uint32_t>(blink::Platform::current()->numberOfProcessors())); 172 v8::SetResourceConstraints(isolate, &constraints); 173 174 v8::V8::AddGCPrologueCallback(V8GCController::gcPrologue); 175 v8::V8::AddGCEpilogueCallback(V8GCController::gcEpilogue); 176 177 v8::Debug::SetLiveEditEnabled(isolate, false); 178 179 isolate->SetAutorunMicrotasks(false); 180 } 181 182 void V8Initializer::initializeMainThreadIfNeeded(v8::Isolate* isolate) 183 { 184 ASSERT(isMainThread()); 185 186 static bool initialized = false; 187 if (initialized) 188 return; 189 initialized = true; 190 191 initializeV8Common(isolate); 192 193 v8::V8::SetFatalErrorHandler(reportFatalErrorInMainThread); 194 V8PerIsolateData::ensureInitialized(isolate); 195 v8::V8::AddMessageListener(messageHandlerInMainThread); 196 v8::V8::SetFailedAccessCheckCallbackFunction(failedAccessCheckCallbackInMainThread); 197 v8::V8::SetAllowCodeGenerationFromStringsCallback(codeGenerationCheckCallbackInMainThread); 198 199 isolate->SetEventLogger(timerTraceProfilerInMainThread); 200 201 ScriptProfiler::initialize(); 202 } 203 204 static void reportFatalErrorInWorker(const char* location, const char* message) 205 { 206 // FIXME: We temporarily deal with V8 internal error situations such as out-of-memory by crashing the worker. 207 CRASH(); 208 } 209 210 static void messageHandlerInWorker(v8::Handle<v8::Message> message, v8::Handle<v8::Value> data) 211 { 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) 216 return; 217 isReportingException = true; 218 219 v8::Isolate* isolate = v8::Isolate::GetCurrent(); 220 ScriptState* scriptState = ScriptState::current(isolate); 221 // During the frame teardown, there may not be a valid context. 222 if (ExecutionContext* context = scriptState->executionContext()) { 223 String errorMessage = toCoreString(message->Get()); 224 TOSTRING_VOID(V8StringResource<>, sourceURL, message->GetScriptResourceName()); 225 226 RefPtrWillBeRawPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, message->GetLineNumber(), message->GetStartColumn() + 1, &DOMWrapperWorld::current(isolate)); 227 AccessControlStatus corsStatus = message->IsSharedCrossOrigin() ? SharableCrossOrigin : NotSharableCrossOrigin; 228 229 V8ErrorHandler::storeExceptionOnErrorEventWrapper(event.get(), data, scriptState->context()->Global(), isolate); 230 context->reportException(event.release(), nullptr, corsStatus); 231 } 232 233 isReportingException = false; 234 } 235 236 static const int kWorkerMaxStackSize = 500 * 1024; 237 238 void V8Initializer::initializeWorker(v8::Isolate* isolate) 239 { 240 initializeV8Common(isolate); 241 242 v8::V8::AddMessageListener(messageHandlerInWorker); 243 v8::V8::SetFatalErrorHandler(reportFatalErrorInWorker); 244 245 v8::ResourceConstraints resourceConstraints; 246 uint32_t here; 247 resourceConstraints.set_stack_limit(&here - kWorkerMaxStackSize / sizeof(uint32_t*)); 248 v8::SetResourceConstraints(isolate, &resourceConstraints); 249 } 250 251 } // namespace WebCore 252