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/core/v8/WindowProxy.h"
34 #include "bindings/core/v8/DOMWrapperWorld.h"
35 #include "bindings/core/v8/ScriptController.h"
36 #include "bindings/core/v8/V8Binding.h"
37 #include "bindings/core/v8/V8DOMActivityLogger.h"
38 #include "bindings/core/v8/V8Document.h"
39 #include "bindings/core/v8/V8GCForContextDispose.h"
40 #include "bindings/core/v8/V8HTMLCollection.h"
41 #include "bindings/core/v8/V8HTMLDocument.h"
42 #include "bindings/core/v8/V8HiddenValue.h"
43 #include "bindings/core/v8/V8Initializer.h"
44 #include "bindings/core/v8/V8ObjectConstructor.h"
45 #include "bindings/core/v8/V8Window.h"
46 #include "core/frame/LocalFrame.h"
47 #include "core/frame/csp/ContentSecurityPolicy.h"
48 #include "core/html/HTMLCollection.h"
49 #include "core/html/HTMLIFrameElement.h"
50 #include "core/inspector/InspectorInstrumentation.h"
51 #include "core/loader/DocumentLoader.h"
52 #include "core/loader/FrameLoader.h"
53 #include "core/loader/FrameLoaderClient.h"
54 #include "platform/RuntimeEnabledFeatures.h"
55 #include "platform/ScriptForbiddenScope.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 PassOwnPtr<WindowProxy> WindowProxy::create(LocalFrame* frame, DOMWrapperWorld& world, v8::Isolate* isolate)
79 return adoptPtr(new WindowProxy(frame, &world, isolate));
82 WindowProxy::WindowProxy(LocalFrame* frame, PassRefPtr<DOMWrapperWorld> world, v8::Isolate* isolate)
89 void WindowProxy::disposeContext(GlobalDetachmentBehavior behavior)
91 if (!isContextInitialized())
94 v8::HandleScope handleScope(m_isolate);
95 v8::Handle<v8::Context> context = m_scriptState->context();
96 m_frame->loader().client()->willReleaseScriptContext(context, m_world->worldId());
98 if (behavior == DetachGlobal)
99 context->DetachGlobal();
101 m_scriptState->disposePerContextData();
103 // It's likely that disposing the context has created a lot of
104 // garbage. Notify V8 about this so it'll have a chance of cleaning
106 V8GCForContextDispose::instanceTemplate().notifyContextDisposed(m_frame->isMainFrame());
109 void WindowProxy::clearForClose()
111 if (!isContextInitialized())
115 disposeContext(DoNotDetachGlobal);
118 void WindowProxy::clearForNavigation()
120 if (!isContextInitialized())
123 ScriptState::Scope scope(m_scriptState.get());
127 // Clear the document wrapper cache before turning on access checks on
128 // the old LocalDOMWindow wrapper. This way, access to the document wrapper
129 // will be protected by the security checks on the LocalDOMWindow wrapper.
130 clearDocumentProperty();
132 v8::Handle<v8::Object> windowWrapper = V8Window::findInstanceInPrototypeChain(m_global.newLocal(m_isolate), m_isolate);
133 ASSERT(!windowWrapper.IsEmpty());
134 windowWrapper->TurnOnAccessCheck();
135 disposeContext(DetachGlobal);
138 // Create a new environment and setup the global object.
140 // The global object corresponds to a LocalDOMWindow instance. However, to
141 // allow properties of the JS LocalDOMWindow instance to be shadowed, we
142 // use a shadow object as the global object and use the JS LocalDOMWindow
143 // instance as the prototype for that shadow object. The JS LocalDOMWindow
144 // instance is undetectable from JavaScript code because the __proto__
145 // accessors skip that object.
147 // The shadow object and the LocalDOMWindow instance are seen as one object
148 // from JavaScript. The JavaScript object that corresponds to a
149 // LocalDOMWindow instance is the shadow object. When mapping a LocalDOMWindow
150 // instance to a V8 object, we return the shadow object.
152 // To implement split-window, see
153 // 1) https://bugs.webkit.org/show_bug.cgi?id=17249
154 // 2) https://wiki.mozilla.org/Gecko:SplitWindow
155 // 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
156 // we need to split the shadow object further into two objects:
157 // an outer window and an inner window. The inner window is the hidden
158 // prototype of the outer window. The inner window is the default
159 // global object of the context. A variable declared in the global
160 // scope is a property of the inner window.
162 // The outer window sticks to a LocalFrame, it is exposed to JavaScript
163 // via window.window, window.self, window.parent, etc. The outer window
164 // has a security token which is the domain. The outer window cannot
165 // have its own properties. window.foo = 'x' is delegated to the
168 // When a frame navigates to a new page, the inner window is cut off
169 // the outer window, and the outer window identify is preserved for
170 // the frame. However, a new inner window is created for the new page.
171 // If there are JS code holds a closure to the old inner window,
172 // it won't be able to reach the outer window via its global object.
173 bool WindowProxy::initializeIfNeeded()
175 if (isContextInitialized())
178 DOMWrapperWorld::setWorldOfInitializingWindow(m_world.get());
179 bool result = initialize();
180 DOMWrapperWorld::setWorldOfInitializingWindow(0);
184 bool WindowProxy::initialize()
186 TRACE_EVENT0("v8", "WindowProxy::initialize");
187 TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "InitializeWindow");
189 ScriptForbiddenScope::AllowUserAgentScript allowScript;
191 v8::HandleScope handleScope(m_isolate);
195 if (!isContextInitialized())
198 ScriptState::Scope scope(m_scriptState.get());
199 v8::Handle<v8::Context> context = m_scriptState->context();
200 if (m_global.isEmpty()) {
201 m_global.set(m_isolate, context->Global());
202 if (m_global.isEmpty()) {
203 disposeContext(DoNotDetachGlobal);
208 if (!installDOMWindow()) {
209 disposeContext(DoNotDetachGlobal);
213 if (m_world->isMainWorld()) {
214 // ActivityLogger for main world is updated within updateDocument().
216 if (m_frame->document()) {
217 setSecurityToken(m_frame->document()->securityOrigin());
218 ContentSecurityPolicy* csp = m_frame->document()->contentSecurityPolicy();
219 context->AllowCodeGenerationFromStrings(csp->allowEval(0, ContentSecurityPolicy::SuppressReport));
220 context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, csp->evalDisabledErrorMessage()));
223 updateActivityLogger();
224 SecurityOrigin* origin = m_world->isolatedWorldSecurityOrigin();
225 setSecurityToken(origin);
226 if (origin && InspectorInstrumentation::hasFrontends()) {
227 InspectorInstrumentation::didCreateIsolatedContext(m_frame, m_scriptState.get(), origin);
230 m_frame->loader().client()->didCreateScriptContext(context, m_world->extensionGroup(), m_world->worldId());
234 void WindowProxy::createContext()
236 // The documentLoader pointer could be 0 during frame shutdown.
237 // FIXME: Can we remove this check?
238 if (!m_frame->loader().documentLoader())
241 // Create a new environment using an empty template for the shadow
242 // object. Reuse the global object if one has been created earlier.
243 v8::Handle<v8::ObjectTemplate> globalTemplate = V8Window::getShadowObjectTemplate(m_isolate);
244 if (globalTemplate.IsEmpty())
247 double contextCreationStartInSeconds = currentTime();
249 // Dynamically tell v8 about our extensions now.
250 const V8Extensions& extensions = ScriptController::registeredExtensions();
251 OwnPtr<const char*[]> extensionNames = adoptArrayPtr(new const char*[extensions.size()]);
253 int extensionGroup = m_world->extensionGroup();
254 int worldId = m_world->worldId();
255 for (size_t i = 0; i < extensions.size(); ++i) {
256 if (!m_frame->loader().client()->allowScriptExtension(extensions[i]->name(), extensionGroup, worldId))
259 extensionNames[index++] = extensions[i]->name();
261 v8::ExtensionConfiguration extensionConfiguration(index, extensionNames.get());
263 v8::Handle<v8::Context> context = v8::Context::New(m_isolate, &extensionConfiguration, globalTemplate, m_global.newLocal(m_isolate));
264 if (context.IsEmpty())
266 m_scriptState = ScriptState::create(context, m_world);
268 double contextCreationDurationInMilliseconds = (currentTime() - contextCreationStartInSeconds) * 1000;
269 const char* histogramName = "WebCore.WindowProxy.createContext.MainWorld";
270 if (!m_world->isMainWorld())
271 histogramName = "WebCore.WindowProxy.createContext.IsolatedWorld";
272 blink::Platform::current()->histogramCustomCounts(histogramName, contextCreationDurationInMilliseconds, 0, 10000, 50);
275 static v8::Handle<v8::Object> toInnerGlobalObject(v8::Handle<v8::Context> context)
277 return v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
280 bool WindowProxy::installDOMWindow()
282 LocalDOMWindow* window = m_frame->domWindow();
283 v8::Local<v8::Object> windowWrapper = V8ObjectConstructor::newInstance(m_isolate, m_scriptState->perContextData()->constructorForType(&V8Window::wrapperTypeInfo));
284 if (windowWrapper.IsEmpty())
287 V8DOMWrapper::setNativeInfoForHiddenWrapper(v8::Handle<v8::Object>::Cast(windowWrapper->GetPrototype()), &V8Window::wrapperTypeInfo, V8Window::toInternalPointer(window));
289 // Install the windowWrapper as the prototype of the innerGlobalObject.
290 // The full structure of the global object is as follows:
292 // outerGlobalObject (Empty object, remains after navigation)
293 // -- has prototype --> innerGlobalObject (Holds global variables, changes during navigation)
294 // -- has prototype --> LocalDOMWindow instance
295 // -- has prototype --> Window.prototype
296 // -- has prototype --> Object.prototype
298 // Note: Much of this prototype structure is hidden from web content. The
299 // outer, inner, and LocalDOMWindow instance all appear to be the same
300 // JavaScript object.
302 // Note: With Oilpan, the LocalDOMWindow object is garbage collected.
303 // Persistent references to this inner global object view of the LocalDOMWindow
304 // aren't kept, as that would prevent the global object from ever being released.
305 // It is safe not to do so, as the wrapper for the LocalDOMWindow being installed here
306 // already keeps a persistent reference, and it along with the inner global object
307 // views of the LocalDOMWindow will die together once that wrapper clears the persistent
309 v8::Handle<v8::Object> innerGlobalObject = toInnerGlobalObject(m_scriptState->context());
310 V8DOMWrapper::setNativeInfoForHiddenWrapper(innerGlobalObject, &V8Window::wrapperTypeInfo, V8Window::toInternalPointer(window));
311 innerGlobalObject->SetPrototype(windowWrapper);
312 V8DOMWrapper::associateObjectWithWrapper<V8Window>(PassRefPtrWillBeRawPtr<LocalDOMWindow>(window), &V8Window::wrapperTypeInfo, windowWrapper, m_isolate, WrapperConfiguration::Dependent);
313 V8Window::installConditionallyEnabledProperties(windowWrapper, m_isolate);
317 void WindowProxy::updateDocumentWrapper(v8::Handle<v8::Object> wrapper)
319 ASSERT(m_world->isMainWorld());
320 m_document.set(m_isolate, wrapper);
323 void WindowProxy::updateDocumentProperty()
325 if (!m_world->isMainWorld())
328 ScriptState::Scope scope(m_scriptState.get());
329 v8::Handle<v8::Context> context = m_scriptState->context();
330 v8::Handle<v8::Value> documentWrapper = toV8(m_frame->document(), context->Global(), context->GetIsolate());
331 ASSERT(documentWrapper == m_document.newLocal(m_isolate) || m_document.isEmpty());
332 if (m_document.isEmpty())
333 updateDocumentWrapper(v8::Handle<v8::Object>::Cast(documentWrapper));
334 checkDocumentWrapper(m_document.newLocal(m_isolate), m_frame->document());
336 // If instantiation of the document wrapper fails, clear the cache
337 // and let the LocalDOMWindow accessor handle access to the document.
338 if (documentWrapper.IsEmpty()) {
339 clearDocumentProperty();
342 ASSERT(documentWrapper->IsObject());
343 context->Global()->ForceSet(v8AtomicString(m_isolate, "document"), documentWrapper, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
345 // We also stash a reference to the document on the inner global object so that
346 // LocalDOMWindow objects we obtain from JavaScript references are guaranteed to have
347 // live Document objects.
348 V8HiddenValue::setHiddenValue(m_isolate, toInnerGlobalObject(context), V8HiddenValue::document(m_isolate), documentWrapper);
351 void WindowProxy::clearDocumentProperty()
353 ASSERT(isContextInitialized());
354 if (!m_world->isMainWorld())
356 v8::HandleScope handleScope(m_isolate);
357 m_scriptState->context()->Global()->ForceDelete(v8AtomicString(m_isolate, "document"));
360 void WindowProxy::updateActivityLogger()
362 m_scriptState->perContextData()->setActivityLogger(V8DOMActivityLogger::activityLogger(
363 m_world->worldId(), m_frame->document() ? m_frame->document()->baseURI() : KURL()));
366 void WindowProxy::setSecurityToken(SecurityOrigin* origin)
368 // If two tokens are equal, then the SecurityOrigins canAccess each other.
369 // If two tokens are not equal, then we have to call canAccess.
370 // Note: we can't use the HTTPOrigin if it was set from the DOM.
372 // We stick with an empty token if document.domain was modified or if we
373 // are in the initial empty document, so that we can do a full canAccess
374 // check in those cases.
375 bool delaySet = m_world->isMainWorld()
376 && (origin->domainWasSetInDOM()
377 || m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument());
378 if (origin && !delaySet)
379 token = origin->toString();
381 // An empty or "null" token means we always have to call
382 // canAccess. The toString method on securityOrigins returns the
383 // string "null" for empty security origins and for security
384 // origins that should only allow access to themselves. In this
385 // case, we use the global object as the security token to avoid
386 // calling canAccess when a script accesses its own objects.
387 v8::HandleScope handleScope(m_isolate);
388 v8::Handle<v8::Context> context = m_scriptState->context();
389 if (token.isEmpty() || token == "null") {
390 context->UseDefaultSecurityToken();
394 if (m_world->isPrivateScriptIsolatedWorld())
395 token = "private-script://" + token;
397 CString utf8Token = token.utf8();
398 // NOTE: V8 does identity comparison in fast path, must use a symbol
399 // as the security token.
400 context->SetSecurityToken(v8AtomicString(m_isolate, utf8Token.data(), utf8Token.length()));
403 void WindowProxy::updateDocument()
405 ASSERT(m_world->isMainWorld());
406 if (!isGlobalInitialized())
408 if (!isContextInitialized())
410 updateActivityLogger();
411 updateDocumentProperty();
412 updateSecurityOrigin(m_frame->document()->securityOrigin());
415 static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
417 if (!htmlDocument->hasNamedItem(key) && !htmlDocument->hasExtraNamedItem(key))
418 return v8Undefined();
420 RefPtrWillBeRawPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
421 if (items->isEmpty())
422 return v8Undefined();
424 if (items->hasExactlyOneItem()) {
425 Element* element = items->item(0);
427 Frame* frame = isHTMLIFrameElement(*element) ? toHTMLIFrameElement(*element).contentFrame() : 0;
429 return toV8(frame->domWindow(), creationContext, isolate);
430 return toV8(element, creationContext, isolate);
432 return toV8(items.release(), creationContext, isolate);
435 static void getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info)
437 // FIXME: Consider passing StringImpl directly.
438 AtomicString name = toCoreAtomicString(property);
439 HTMLDocument* htmlDocument = V8HTMLDocument::toNative(info.Holder());
440 ASSERT(htmlDocument);
441 v8::Handle<v8::Value> result = getNamedProperty(htmlDocument, name, info.Holder(), info.GetIsolate());
442 if (!result.IsEmpty()) {
443 v8SetReturnValue(info, result);
446 v8::Handle<v8::Value> prototype = info.Holder()->GetPrototype();
447 if (prototype->IsObject()) {
448 v8SetReturnValue(info, prototype.As<v8::Object>()->Get(property));
453 void WindowProxy::namedItemAdded(HTMLDocument* document, const AtomicString& name)
455 ASSERT(m_world->isMainWorld());
457 if (!isContextInitialized())
460 ScriptState::Scope scope(m_scriptState.get());
461 ASSERT(!m_document.isEmpty());
462 v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
463 checkDocumentWrapper(documentHandle, document);
464 documentHandle->SetAccessor(v8String(m_isolate, name), getter);
467 void WindowProxy::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
469 ASSERT(m_world->isMainWorld());
471 if (!isContextInitialized())
474 if (document->hasNamedItem(name) || document->hasExtraNamedItem(name))
477 ScriptState::Scope scope(m_scriptState.get());
478 ASSERT(!m_document.isEmpty());
479 v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
480 checkDocumentWrapper(documentHandle, document);
481 documentHandle->Delete(v8String(m_isolate, name));
484 void WindowProxy::updateSecurityOrigin(SecurityOrigin* origin)
486 ASSERT(m_world->isMainWorld());
487 if (!isContextInitialized())
489 setSecurityToken(origin);