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 "V8DOMWindowShell.h"
34 #include "ContentSecurityPolicy.h"
35 #include "DOMWrapperWorld.h"
36 #include "DateExtension.h"
37 #include "DocumentLoader.h"
39 #include "FrameLoader.h"
40 #include "FrameLoaderClient.h"
41 #include "HTMLCollection.h"
42 #include "HTMLIFrameElement.h"
43 #include "InspectorInstrumentation.h"
45 #include "RuntimeEnabledFeatures.h"
46 #include "ScriptController.h"
47 #include "SecurityOrigin.h"
48 #include "V8Binding.h"
49 #include "V8DOMWindow.h"
50 #include "V8Document.h"
51 #include "V8GCForContextDispose.h"
52 #include "V8HTMLCollection.h"
53 #include "V8HTMLDocument.h"
54 #include "V8HiddenPropertyName.h"
55 #include "V8Initializer.h"
56 #include "V8ObjectConstructor.h"
57 #include "V8PerContextData.h"
62 #include <wtf/Assertions.h>
63 #include <wtf/OwnArrayPtr.h>
64 #include <wtf/StringExtras.h>
65 #include <wtf/text/CString.h>
67 #if ENABLE(JAVASCRIPT_I18N_API)
68 #include <v8-i18n/include/extension.h>
73 static void checkDocumentWrapper(v8::Handle<v8::Object> wrapper, Document* document)
75 ASSERT(V8Document::toNative(wrapper) == document);
76 ASSERT(!document->isHTMLDocument() || (V8Document::toNative(v8::Handle<v8::Object>::Cast(wrapper->GetPrototype())) == document));
79 static void setInjectedScriptContextDebugId(v8::Handle<v8::Context> targetContext, int debugId)
83 snprintf(buffer, sizeof(buffer), "injected");
85 snprintf(buffer, sizeof(buffer), "injected,%d", debugId);
86 targetContext->SetEmbedderData(0, v8::String::NewSymbol(buffer));
89 PassOwnPtr<V8DOMWindowShell> V8DOMWindowShell::create(Frame* frame, PassRefPtr<DOMWrapperWorld> world, v8::Isolate* isolate)
91 return adoptPtr(new V8DOMWindowShell(frame, world, isolate));
94 V8DOMWindowShell::V8DOMWindowShell(Frame* frame, PassRefPtr<DOMWrapperWorld> world, v8::Isolate* isolate)
101 void V8DOMWindowShell::destroyIsolatedShell()
103 ASSERT(m_world->isIsolatedWorld());
105 if (m_context.isEmpty())
108 v8::HandleScope handleScope;
109 m_world->makeContextWeak(m_context.get());
114 void V8DOMWindowShell::disposeContext()
116 m_perContextData.clear();
118 if (m_context.isEmpty())
121 m_frame->loader()->client()->willReleaseScriptContext(m_context.get(), m_world->worldId());
125 // It's likely that disposing the context has created a lot of
126 // garbage. Notify V8 about this so it'll have a chance of cleaning
128 bool isMainFrame = m_frame->page() && (m_frame->page()->mainFrame() == m_frame);
129 V8GCForContextDispose::instance().notifyContextDisposed(isMainFrame);
132 void V8DOMWindowShell::clearForClose(bool destroyGlobal)
137 if (m_context.isEmpty())
140 v8::HandleScope handleScope;
145 void V8DOMWindowShell::clearForNavigation()
147 if (m_context.isEmpty())
150 v8::HandleScope handleScope;
153 // FIXME: Should we create a new Local handle here?
154 v8::Context::Scope contextScope(m_context.get());
156 // Clear the document wrapper cache before turning on access checks on
157 // the old DOMWindow wrapper. This way, access to the document wrapper
158 // will be protected by the security checks on the DOMWindow wrapper.
159 clearDocumentProperty();
161 v8::Handle<v8::Object> windowWrapper = m_global->FindInstanceInPrototypeChain(V8DOMWindow::GetTemplate(m_isolate, worldTypeInMainThread(m_isolate)));
162 ASSERT(!windowWrapper.IsEmpty());
163 windowWrapper->TurnOnAccessCheck();
164 m_context->DetachGlobal();
168 // Create a new environment and setup the global object.
170 // The global object corresponds to a DOMWindow instance. However, to
171 // allow properties of the JS DOMWindow instance to be shadowed, we
172 // use a shadow object as the global object and use the JS DOMWindow
173 // instance as the prototype for that shadow object. The JS DOMWindow
174 // instance is undetectable from JavaScript code because the __proto__
175 // accessors skip that object.
177 // The shadow object and the DOMWindow instance are seen as one object
178 // from JavaScript. The JavaScript object that corresponds to a
179 // DOMWindow instance is the shadow object. When mapping a DOMWindow
180 // instance to a V8 object, we return the shadow object.
182 // To implement split-window, see
183 // 1) https://bugs.webkit.org/show_bug.cgi?id=17249
184 // 2) https://wiki.mozilla.org/Gecko:SplitWindow
185 // 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
186 // we need to split the shadow object further into two objects:
187 // an outer window and an inner window. The inner window is the hidden
188 // prototype of the outer window. The inner window is the default
189 // global object of the context. A variable declared in the global
190 // scope is a property of the inner window.
192 // The outer window sticks to a Frame, it is exposed to JavaScript
193 // via window.window, window.self, window.parent, etc. The outer window
194 // has a security token which is the domain. The outer window cannot
195 // have its own properties. window.foo = 'x' is delegated to the
198 // When a frame navigates to a new page, the inner window is cut off
199 // the outer window, and the outer window identify is preserved for
200 // the frame. However, a new inner window is created for the new page.
201 // If there are JS code holds a closure to the old inner window,
202 // it won't be able to reach the outer window via its global object.
203 bool V8DOMWindowShell::initializeIfNeeded()
205 if (!m_context.isEmpty())
208 v8::HandleScope handleScope;
210 V8Initializer::initializeMainThreadIfNeeded(m_isolate);
213 if (m_context.isEmpty())
216 m_world->setIsolatedWorldField(m_context.get());
218 bool isMainWorld = m_world->isMainWorld();
220 v8::Local<v8::Context> context = v8::Local<v8::Context>::New(m_context.get());
221 v8::Context::Scope contextScope(context);
223 if (m_global.isEmpty()) {
224 m_global.set(context->Global());
225 if (m_global.isEmpty()) {
232 V8DOMWindowShell* mainWindow = m_frame->script()->existingWindowShell(mainThreadNormalWorld());
233 if (mainWindow && !mainWindow->context().IsEmpty())
234 setInjectedScriptContextDebugId(m_context.get(), m_frame->script()->contextDebugId(mainWindow->context()));
237 m_perContextData = V8PerContextData::create(m_context.get());
238 if (!m_perContextData->init()) {
243 if (!installDOMWindow()) {
251 if (m_frame->document()) {
252 ContentSecurityPolicy* csp = m_frame->document()->contentSecurityPolicy();
253 context->AllowCodeGenerationFromStrings(csp->allowEval(0, ContentSecurityPolicy::SuppressReport));
254 context->SetErrorMessageForCodeGenerationFromStrings(v8String(csp->evalDisabledErrorMessage(), m_isolate));
257 // Using the default security token means that the canAccess is always
258 // called, which is slow.
259 // FIXME: Use tokens where possible. This will mean keeping track of all
260 // created contexts so that they can all be updated when the
263 m_context->UseDefaultSecurityToken();
265 SecurityOrigin* origin = m_world->isolatedWorldSecurityOrigin();
266 if (origin && InspectorInstrumentation::hasFrontends()) {
267 ScriptState* scriptState = ScriptState::forContext(v8::Local<v8::Context>::New(m_context.get()));
268 InspectorInstrumentation::didCreateIsolatedContext(m_frame, scriptState, origin);
271 m_frame->loader()->client()->didCreateScriptContext(m_context.get(), m_world->extensionGroup(), m_world->worldId());
275 void V8DOMWindowShell::createContext()
277 // The activeDocumentLoader pointer could be 0 during frame shutdown.
278 // FIXME: Can we remove this check?
279 if (!m_frame->loader()->activeDocumentLoader())
282 // Create a new environment using an empty template for the shadow
283 // object. Reuse the global object if one has been created earlier.
284 v8::Persistent<v8::ObjectTemplate> globalTemplate = V8DOMWindow::GetShadowObjectTemplate(m_isolate);
285 if (globalTemplate.IsEmpty())
288 // Used to avoid sleep calls in unload handlers.
289 ScriptController::registerExtensionIfNeeded(DateExtension::get());
291 #if ENABLE(JAVASCRIPT_I18N_API)
292 // Enables experimental i18n API in V8.
293 if (RuntimeEnabledFeatures::javaScriptI18NAPIEnabled())
294 ScriptController::registerExtensionIfNeeded(v8_i18n::Extension::get());
297 // Dynamically tell v8 about our extensions now.
298 const V8Extensions& extensions = ScriptController::registeredExtensions();
299 OwnArrayPtr<const char*> extensionNames = adoptArrayPtr(new const char*[extensions.size()]);
301 int extensionGroup = m_world->extensionGroup();
302 int worldId = m_world->worldId();
303 for (size_t i = 0; i < extensions.size(); ++i) {
304 // Ensure our date extension is always allowed.
305 if (extensions[i] != DateExtension::get()
306 && !m_frame->loader()->client()->allowScriptExtension(extensions[i]->name(), extensionGroup, worldId))
309 extensionNames[index++] = extensions[i]->name();
311 v8::ExtensionConfiguration extensionConfiguration(index, extensionNames.get());
313 m_context.adopt(v8::Context::New(&extensionConfiguration, globalTemplate, m_global.get()));
316 bool V8DOMWindowShell::installDOMWindow()
318 DOMWrapperWorld::setInitializingWindow(true);
319 DOMWindow* window = m_frame->document()->domWindow();
320 v8::Local<v8::Object> windowWrapper = V8ObjectConstructor::newInstance(V8PerContextData::from(m_context.get())->constructorForType(&V8DOMWindow::info));
321 if (windowWrapper.IsEmpty())
324 V8DOMWindow::installPerContextProperties(windowWrapper, window, m_isolate);
326 V8DOMWrapper::setNativeInfo(v8::Handle<v8::Object>::Cast(windowWrapper->GetPrototype()), &V8DOMWindow::info, window);
328 // Install the windowWrapper as the prototype of the innerGlobalObject.
329 // The full structure of the global object is as follows:
331 // outerGlobalObject (Empty object, remains after navigation)
332 // -- has prototype --> innerGlobalObject (Holds global variables, changes during navigation)
333 // -- has prototype --> DOMWindow instance
334 // -- has prototype --> Window.prototype
335 // -- has prototype --> Object.prototype
337 // Note: Much of this prototype structure is hidden from web content. The
338 // outer, inner, and DOMWindow instance all appear to be the same
339 // JavaScript object.
341 v8::Handle<v8::Object> innerGlobalObject = toInnerGlobalObject(m_context.get());
342 V8DOMWrapper::setNativeInfo(innerGlobalObject, &V8DOMWindow::info, window);
343 innerGlobalObject->SetPrototype(windowWrapper);
344 V8DOMWrapper::associateObjectWithWrapper(PassRefPtr<DOMWindow>(window), &V8DOMWindow::info, windowWrapper, m_isolate, WrapperConfiguration::Dependent);
345 DOMWrapperWorld::setInitializingWindow(false);
349 void V8DOMWindowShell::updateDocumentWrapper(v8::Handle<v8::Object> wrapper)
351 ASSERT(m_world->isMainWorld());
352 m_document.set(wrapper);
355 void V8DOMWindowShell::updateDocumentProperty()
357 if (!m_world->isMainWorld())
360 v8::HandleScope handleScope;
361 // FIXME: Should we use a new Local handle here?
362 v8::Context::Scope contextScope(m_context.get());
364 v8::Handle<v8::Value> documentWrapper = toV8(m_frame->document(), v8::Handle<v8::Object>(), m_context.get()->GetIsolate());
365 ASSERT(documentWrapper == m_document.get() || m_document.isEmpty());
366 if (m_document.isEmpty())
367 updateDocumentWrapper(v8::Handle<v8::Object>::Cast(documentWrapper));
368 checkDocumentWrapper(m_document.get(), m_frame->document());
370 // If instantiation of the document wrapper fails, clear the cache
371 // and let the DOMWindow accessor handle access to the document.
372 if (documentWrapper.IsEmpty()) {
373 clearDocumentProperty();
376 ASSERT(documentWrapper->IsObject());
377 m_context->Global()->ForceSet(v8::String::NewSymbol("document"), documentWrapper, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
379 // We also stash a reference to the document on the inner global object so that
380 // DOMWindow objects we obtain from JavaScript references are guaranteed to have
381 // live Document objects.
382 toInnerGlobalObject(m_context.get())->SetHiddenValue(V8HiddenPropertyName::document(), documentWrapper);
385 void V8DOMWindowShell::clearDocumentProperty()
387 ASSERT(!m_context.isEmpty());
388 if (!m_world->isMainWorld())
390 m_context->Global()->ForceDelete(v8::String::NewSymbol("document"));
393 void V8DOMWindowShell::setSecurityToken()
395 ASSERT(m_world->isMainWorld());
397 Document* document = m_frame->document();
399 // Ask the document's SecurityOrigin to generate a security token.
400 // If two tokens are equal, then the SecurityOrigins canAccess each other.
401 // If two tokens are not equal, then we have to call canAccess.
402 // Note: we can't use the HTTPOrigin if it was set from the DOM.
403 SecurityOrigin* origin = document->securityOrigin();
405 if (!origin->domainWasSetInDOM())
406 token = document->securityOrigin()->toString();
408 // An empty or "null" token means we always have to call
409 // canAccess. The toString method on securityOrigins returns the
410 // string "null" for empty security origins and for security
411 // origins that should only allow access to themselves. In this
412 // case, we use the global object as the security token to avoid
413 // calling canAccess when a script accesses its own objects.
414 if (token.isEmpty() || token == "null") {
415 m_context->UseDefaultSecurityToken();
419 CString utf8Token = token.utf8();
420 // NOTE: V8 does identity comparison in fast path, must use a symbol
421 // as the security token.
422 m_context->SetSecurityToken(v8::String::NewSymbol(utf8Token.data(), utf8Token.length()));
425 void V8DOMWindowShell::updateDocument()
427 ASSERT(m_world->isMainWorld());
428 if (m_global.isEmpty())
430 if (m_context.isEmpty())
432 updateDocumentProperty();
433 updateSecurityOrigin();
436 static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
438 if (!htmlDocument->hasNamedItem(key.impl()) && !htmlDocument->hasExtraNamedItem(key.impl()))
439 return v8Undefined();
441 RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
442 if (items->isEmpty())
443 return v8Undefined();
445 if (items->hasExactlyOneItem()) {
446 Node* node = items->item(0);
448 if (node->hasTagName(HTMLNames::iframeTag) && (frame = static_cast<HTMLIFrameElement*>(node)->contentFrame()))
449 return toV8(frame->document()->domWindow(), creationContext, isolate);
450 return toV8(node, creationContext, isolate);
452 return toV8(items.release(), creationContext, isolate);
455 static v8::Handle<v8::Value> getter(v8::Local<v8::String> property, const v8::AccessorInfo& info)
457 // FIXME: Consider passing AtomicStringImpl directly.
458 AtomicString name = toWebCoreAtomicString(property);
459 HTMLDocument* htmlDocument = V8HTMLDocument::toNative(info.Holder());
460 ASSERT(htmlDocument);
461 v8::Handle<v8::Value> result = getNamedProperty(htmlDocument, name, info.Holder(), info.GetIsolate());
462 if (!result.IsEmpty())
464 v8::Handle<v8::Value> prototype = info.Holder()->GetPrototype();
465 if (prototype->IsObject())
466 return prototype.As<v8::Object>()->Get(property);
467 return v8::Undefined();
470 void V8DOMWindowShell::namedItemAdded(HTMLDocument* document, const AtomicString& name)
472 ASSERT(m_world->isMainWorld());
474 if (m_context.isEmpty())
477 v8::HandleScope handleScope;
478 v8::Context::Scope contextScope(m_context.get());
480 ASSERT(!m_document.isEmpty());
481 checkDocumentWrapper(m_document.get(), document);
482 m_document->SetAccessor(v8String(name, m_isolate), getter);
485 void V8DOMWindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
487 ASSERT(m_world->isMainWorld());
489 if (m_context.isEmpty())
492 if (document->hasNamedItem(name.impl()) || document->hasExtraNamedItem(name.impl()))
495 v8::HandleScope handleScope;
496 v8::Context::Scope contextScope(m_context.get());
498 ASSERT(!m_document.isEmpty());
499 checkDocumentWrapper(m_document.get(), document);
500 m_document->Delete(v8String(name, m_isolate));
503 void V8DOMWindowShell::updateSecurityOrigin()
505 ASSERT(m_world->isMainWorld());
506 if (m_context.isEmpty())
508 v8::HandleScope handleScope;