2 * Copyright (C) 2008, 2009, 2011 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 are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "bindings/v8/V8WindowShell.h"
34 #include "RuntimeEnabledFeatures.h"
35 #include "V8Document.h"
36 #include "V8HTMLCollection.h"
37 #include "V8HTMLDocument.h"
39 #include "bindings/v8/DOMWrapperWorld.h"
40 #include "bindings/v8/ScriptController.h"
41 #include "bindings/v8/V8Binding.h"
42 #include "bindings/v8/V8DOMActivityLogger.h"
43 #include "bindings/v8/V8GCForContextDispose.h"
44 #include "bindings/v8/V8HiddenValue.h"
45 #include "bindings/v8/V8Initializer.h"
46 #include "bindings/v8/V8ObjectConstructor.h"
47 #include "core/dom/ScriptForbiddenScope.h"
48 #include "core/frame/LocalFrame.h"
49 #include "core/frame/csp/ContentSecurityPolicy.h"
50 #include "core/html/HTMLCollection.h"
51 #include "core/html/HTMLIFrameElement.h"
52 #include "core/inspector/InspectorInstrumentation.h"
53 #include "core/loader/DocumentLoader.h"
54 #include "core/loader/FrameLoader.h"
55 #include "core/loader/FrameLoaderClient.h"
56 #include "platform/TraceEvent.h"
57 #include "platform/heap/Handle.h"
58 #include "platform/weborigin/SecurityOrigin.h"
59 #include "public/platform/Platform.h"
60 #include "wtf/Assertions.h"
61 #include "wtf/OwnPtr.h"
62 #include "wtf/StringExtras.h"
63 #include "wtf/text/CString.h"
71 static void checkDocumentWrapper(v8::Handle<v8::Object> wrapper, Document* document)
73 ASSERT(V8Document::toNative(wrapper) == document);
74 ASSERT(!document->isHTMLDocument() || (V8Document::toNative(v8::Handle<v8::Object>::Cast(wrapper->GetPrototype())) == document));
77 static void setInjectedScriptContextDebugId(v8::Handle<v8::Context> targetContext, int debugId)
79 V8PerContextDebugData::setContextDebugData(targetContext, "injected", debugId);
82 PassOwnPtr<V8WindowShell> V8WindowShell::create(LocalFrame* frame, DOMWrapperWorld& world, v8::Isolate* isolate)
84 return adoptPtr(new V8WindowShell(frame, &world, isolate));
87 V8WindowShell::V8WindowShell(LocalFrame* frame, PassRefPtr<DOMWrapperWorld> world, v8::Isolate* isolate)
94 void V8WindowShell::disposeContext(GlobalDetachmentBehavior behavior)
96 if (!isContextInitialized())
99 v8::HandleScope handleScope(m_isolate);
100 v8::Handle<v8::Context> context = m_scriptState->context();
101 m_frame->loader().client()->willReleaseScriptContext(context, m_world->worldId());
103 if (behavior == DetachGlobal)
104 context->DetachGlobal();
106 m_scriptState->disposePerContextData();
108 // It's likely that disposing the context has created a lot of
109 // garbage. Notify V8 about this so it'll have a chance of cleaning
111 V8GCForContextDispose::instanceTemplate().notifyContextDisposed(m_frame->isMainFrame());
114 void V8WindowShell::clearForClose()
116 if (!isContextInitialized())
120 disposeContext(DoNotDetachGlobal);
123 void V8WindowShell::clearForNavigation()
125 if (!isContextInitialized())
128 ScriptState::Scope scope(m_scriptState.get());
132 // Clear the document wrapper cache before turning on access checks on
133 // the old DOMWindow wrapper. This way, access to the document wrapper
134 // will be protected by the security checks on the DOMWindow wrapper.
135 clearDocumentProperty();
137 v8::Handle<v8::Object> windowWrapper = V8Window::findInstanceInPrototypeChain(m_global.newLocal(m_isolate), m_isolate);
138 ASSERT(!windowWrapper.IsEmpty());
139 windowWrapper->TurnOnAccessCheck();
140 disposeContext(DetachGlobal);
143 // Create a new environment and setup the global object.
145 // The global object corresponds to a DOMWindow instance. However, to
146 // allow properties of the JS DOMWindow instance to be shadowed, we
147 // use a shadow object as the global object and use the JS DOMWindow
148 // instance as the prototype for that shadow object. The JS DOMWindow
149 // instance is undetectable from JavaScript code because the __proto__
150 // accessors skip that object.
152 // The shadow object and the DOMWindow instance are seen as one object
153 // from JavaScript. The JavaScript object that corresponds to a
154 // DOMWindow instance is the shadow object. When mapping a DOMWindow
155 // instance to a V8 object, we return the shadow object.
157 // To implement split-window, see
158 // 1) https://bugs.webkit.org/show_bug.cgi?id=17249
159 // 2) https://wiki.mozilla.org/Gecko:SplitWindow
160 // 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
161 // we need to split the shadow object further into two objects:
162 // an outer window and an inner window. The inner window is the hidden
163 // prototype of the outer window. The inner window is the default
164 // global object of the context. A variable declared in the global
165 // scope is a property of the inner window.
167 // The outer window sticks to a LocalFrame, it is exposed to JavaScript
168 // via window.window, window.self, window.parent, etc. The outer window
169 // has a security token which is the domain. The outer window cannot
170 // have its own properties. window.foo = 'x' is delegated to the
173 // When a frame navigates to a new page, the inner window is cut off
174 // the outer window, and the outer window identify is preserved for
175 // the frame. However, a new inner window is created for the new page.
176 // If there are JS code holds a closure to the old inner window,
177 // it won't be able to reach the outer window via its global object.
178 bool V8WindowShell::initializeIfNeeded()
180 if (isContextInitialized())
183 DOMWrapperWorld::setWorldOfInitializingWindow(m_world.get());
184 bool result = initialize();
185 DOMWrapperWorld::setWorldOfInitializingWindow(0);
189 bool V8WindowShell::initialize()
191 TRACE_EVENT0("v8", "V8WindowShell::initialize");
192 TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "InitializeWindow");
194 ScriptForbiddenScope::AllowUserAgentScript allowScript;
196 v8::HandleScope handleScope(m_isolate);
200 if (!isContextInitialized())
203 ScriptState::Scope scope(m_scriptState.get());
204 v8::Handle<v8::Context> context = m_scriptState->context();
205 if (m_global.isEmpty()) {
206 m_global.set(m_isolate, context->Global());
207 if (m_global.isEmpty()) {
208 disposeContext(DoNotDetachGlobal);
213 if (!m_world->isMainWorld()) {
214 V8WindowShell* mainWindow = m_frame->script().existingWindowShell(DOMWrapperWorld::mainWorld());
215 if (mainWindow && !mainWindow->context().IsEmpty())
216 setInjectedScriptContextDebugId(context, m_frame->script().contextDebugId(mainWindow->context()));
219 m_scriptState->world().setActivityLogger(V8DOMActivityLogger::activityLogger(m_world->worldId()));
220 if (!installDOMWindow()) {
221 disposeContext(DoNotDetachGlobal);
225 if (m_world->isMainWorld()) {
227 if (m_frame->document()) {
228 setSecurityToken(m_frame->document()->securityOrigin());
229 ContentSecurityPolicy* csp = m_frame->document()->contentSecurityPolicy();
230 context->AllowCodeGenerationFromStrings(csp->allowEval(0, ContentSecurityPolicy::SuppressReport));
231 context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, csp->evalDisabledErrorMessage()));
234 SecurityOrigin* origin = m_world->isolatedWorldSecurityOrigin();
235 setSecurityToken(origin);
236 if (origin && InspectorInstrumentation::hasFrontends()) {
237 InspectorInstrumentation::didCreateIsolatedContext(m_frame, ScriptState::current(m_isolate), origin);
240 m_frame->loader().client()->didCreateScriptContext(context, m_world->extensionGroup(), m_world->worldId());
244 void V8WindowShell::createContext()
246 // The documentLoader pointer could be 0 during frame shutdown.
247 // FIXME: Can we remove this check?
248 if (!m_frame->loader().documentLoader())
251 // Create a new environment using an empty template for the shadow
252 // object. Reuse the global object if one has been created earlier.
253 v8::Handle<v8::ObjectTemplate> globalTemplate = V8Window::getShadowObjectTemplate(m_isolate);
254 if (globalTemplate.IsEmpty())
257 double contextCreationStartInSeconds = currentTime();
259 // Dynamically tell v8 about our extensions now.
260 const V8Extensions& extensions = ScriptController::registeredExtensions();
261 OwnPtr<const char*[]> extensionNames = adoptArrayPtr(new const char*[extensions.size()]);
263 int extensionGroup = m_world->extensionGroup();
264 int worldId = m_world->worldId();
265 for (size_t i = 0; i < extensions.size(); ++i) {
266 if (!m_frame->loader().client()->allowScriptExtension(extensions[i]->name(), extensionGroup, worldId))
269 extensionNames[index++] = extensions[i]->name();
271 v8::ExtensionConfiguration extensionConfiguration(index, extensionNames.get());
273 v8::Handle<v8::Context> context = v8::Context::New(m_isolate, &extensionConfiguration, globalTemplate, m_global.newLocal(m_isolate));
274 if (context.IsEmpty())
276 m_scriptState = ScriptState::create(context, m_world);
278 double contextCreationDurationInMilliseconds = (currentTime() - contextCreationStartInSeconds) * 1000;
279 const char* histogramName = "WebCore.V8WindowShell.createContext.MainWorld";
280 if (!m_world->isMainWorld())
281 histogramName = "WebCore.V8WindowShell.createContext.IsolatedWorld";
282 blink::Platform::current()->histogramCustomCounts(histogramName, contextCreationDurationInMilliseconds, 0, 10000, 50);
285 static v8::Handle<v8::Object> toInnerGlobalObject(v8::Handle<v8::Context> context)
287 return v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
290 bool V8WindowShell::installDOMWindow()
292 DOMWindow* window = m_frame->domWindow();
293 v8::Local<v8::Object> windowWrapper = V8ObjectConstructor::newInstance(m_isolate, m_scriptState->perContextData()->constructorForType(&V8Window::wrapperTypeInfo));
294 if (windowWrapper.IsEmpty())
297 V8Window::installPerContextEnabledProperties(windowWrapper, window, m_isolate);
299 V8DOMWrapper::setNativeInfoForHiddenWrapper(v8::Handle<v8::Object>::Cast(windowWrapper->GetPrototype()), &V8Window::wrapperTypeInfo, window);
301 // Install the windowWrapper as the prototype of the innerGlobalObject.
302 // The full structure of the global object is as follows:
304 // outerGlobalObject (Empty object, remains after navigation)
305 // -- has prototype --> innerGlobalObject (Holds global variables, changes during navigation)
306 // -- has prototype --> DOMWindow instance
307 // -- has prototype --> Window.prototype
308 // -- has prototype --> Object.prototype
310 // Note: Much of this prototype structure is hidden from web content. The
311 // outer, inner, and DOMWindow instance all appear to be the same
312 // JavaScript object.
314 // Note: With Oilpan, the DOMWindow object is garbage collected.
315 // Persistent references to this inner global object view of the DOMWindow
316 // aren't kept, as that would prevent the global object from ever being released.
317 // It is safe not to do so, as the wrapper for the DOMWindow being installed here
318 // already keeps a persistent reference, and it along with the inner global object
319 // views of the DOMWindow will die together once that wrapper clears the persistent
321 v8::Handle<v8::Object> innerGlobalObject = toInnerGlobalObject(m_scriptState->context());
322 V8DOMWrapper::setNativeInfoForHiddenWrapper(innerGlobalObject, &V8Window::wrapperTypeInfo, window);
323 innerGlobalObject->SetPrototype(windowWrapper);
324 V8DOMWrapper::associateObjectWithWrapper<V8Window>(PassRefPtrWillBeRawPtr<DOMWindow>(window), &V8Window::wrapperTypeInfo, windowWrapper, m_isolate, WrapperConfiguration::Dependent);
328 void V8WindowShell::updateDocumentWrapper(v8::Handle<v8::Object> wrapper)
330 ASSERT(m_world->isMainWorld());
331 m_document.set(m_isolate, wrapper);
334 void V8WindowShell::updateDocumentProperty()
336 if (!m_world->isMainWorld())
339 ScriptState::Scope scope(m_scriptState.get());
340 v8::Handle<v8::Context> context = m_scriptState->context();
341 v8::Handle<v8::Value> documentWrapper = toV8(m_frame->document(), v8::Handle<v8::Object>(), context->GetIsolate());
342 ASSERT(documentWrapper == m_document.newLocal(m_isolate) || m_document.isEmpty());
343 if (m_document.isEmpty())
344 updateDocumentWrapper(v8::Handle<v8::Object>::Cast(documentWrapper));
345 checkDocumentWrapper(m_document.newLocal(m_isolate), m_frame->document());
347 // If instantiation of the document wrapper fails, clear the cache
348 // and let the DOMWindow accessor handle access to the document.
349 if (documentWrapper.IsEmpty()) {
350 clearDocumentProperty();
353 ASSERT(documentWrapper->IsObject());
354 context->Global()->ForceSet(v8AtomicString(m_isolate, "document"), documentWrapper, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
356 // We also stash a reference to the document on the inner global object so that
357 // DOMWindow objects we obtain from JavaScript references are guaranteed to have
358 // live Document objects.
359 V8HiddenValue::setHiddenValue(m_isolate, toInnerGlobalObject(context), V8HiddenValue::document(m_isolate), documentWrapper);
362 void V8WindowShell::clearDocumentProperty()
364 ASSERT(isContextInitialized());
365 if (!m_world->isMainWorld())
367 v8::HandleScope handleScope(m_isolate);
368 m_scriptState->context()->Global()->ForceDelete(v8AtomicString(m_isolate, "document"));
371 void V8WindowShell::setSecurityToken(SecurityOrigin* origin)
373 // If two tokens are equal, then the SecurityOrigins canAccess each other.
374 // If two tokens are not equal, then we have to call canAccess.
375 // Note: we can't use the HTTPOrigin if it was set from the DOM.
377 // We stick with an empty token if document.domain was modified or if we
378 // are in the initial empty document, so that we can do a full canAccess
379 // check in those cases.
380 bool delaySet = m_world->isMainWorld()
381 && (origin->domainWasSetInDOM()
382 || m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument());
383 if (origin && !delaySet)
384 token = origin->toString();
386 // An empty or "null" token means we always have to call
387 // canAccess. The toString method on securityOrigins returns the
388 // string "null" for empty security origins and for security
389 // origins that should only allow access to themselves. In this
390 // case, we use the global object as the security token to avoid
391 // calling canAccess when a script accesses its own objects.
392 v8::HandleScope handleScope(m_isolate);
393 v8::Handle<v8::Context> context = m_scriptState->context();
394 if (token.isEmpty() || token == "null") {
395 context->UseDefaultSecurityToken();
399 CString utf8Token = token.utf8();
400 // NOTE: V8 does identity comparison in fast path, must use a symbol
401 // as the security token.
402 context->SetSecurityToken(v8AtomicString(m_isolate, utf8Token.data(), utf8Token.length()));
405 void V8WindowShell::updateDocument()
407 ASSERT(m_world->isMainWorld());
408 if (!isGlobalInitialized())
410 if (!isContextInitialized())
412 updateDocumentProperty();
413 updateSecurityOrigin(m_frame->document()->securityOrigin());
416 static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
418 if (!htmlDocument->hasNamedItem(key) && !htmlDocument->hasExtraNamedItem(key))
419 return v8Undefined();
421 RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
422 if (items->isEmpty())
423 return v8Undefined();
425 if (items->hasExactlyOneItem()) {
426 Element* element = items->item(0);
429 if (isHTMLIFrameElement(*element) && (frame = toHTMLIFrameElement(*element).contentFrame()))
430 return toV8(frame->domWindow(), creationContext, isolate);
431 return toV8(element, creationContext, isolate);
433 return toV8(items.release(), creationContext, isolate);
436 static void getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info)
438 // FIXME: Consider passing StringImpl directly.
439 AtomicString name = toCoreAtomicString(property);
440 HTMLDocument* htmlDocument = V8HTMLDocument::toNative(info.Holder());
441 ASSERT(htmlDocument);
442 v8::Handle<v8::Value> result = getNamedProperty(htmlDocument, name, info.Holder(), info.GetIsolate());
443 if (!result.IsEmpty()) {
444 v8SetReturnValue(info, result);
447 v8::Handle<v8::Value> prototype = info.Holder()->GetPrototype();
448 if (prototype->IsObject()) {
449 v8SetReturnValue(info, prototype.As<v8::Object>()->Get(property));
454 void V8WindowShell::namedItemAdded(HTMLDocument* document, const AtomicString& name)
456 ASSERT(m_world->isMainWorld());
458 if (!isContextInitialized())
461 ScriptState::Scope scope(m_scriptState.get());
462 ASSERT(!m_document.isEmpty());
463 v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
464 checkDocumentWrapper(documentHandle, document);
465 documentHandle->SetAccessor(v8String(m_isolate, name), getter);
468 void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
470 ASSERT(m_world->isMainWorld());
472 if (!isContextInitialized())
475 if (document->hasNamedItem(name) || document->hasExtraNamedItem(name))
478 ScriptState::Scope scope(m_scriptState.get());
479 ASSERT(!m_document.isEmpty());
480 v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
481 checkDocumentWrapper(documentHandle, document);
482 documentHandle->Delete(v8String(m_isolate, name));
485 void V8WindowShell::updateSecurityOrigin(SecurityOrigin* origin)
487 ASSERT(m_world->isMainWorld());
488 if (!isContextInitialized())
490 setSecurityToken(origin);