Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(199)

Side by Side Diff: Source/bindings/v8/V8DOMWindowShell.cpp

Issue 17031006: Rename DOMWindow interface to Window (Closed) Base URL: svn://svn.chromium.org/blink/trunk
Patch Set: Rebase on master Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « Source/bindings/v8/V8DOMWindowShell.h ('k') | Source/bindings/v8/V8DOMWrapper.cpp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * Copyright (C) 2008, 2009, 2011 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 are
6 * met:
7 *
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
13 * distribution.
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.
17 *
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.
29 */
30
31 #include "config.h"
32 #include "bindings/v8/V8DOMWindowShell.h"
33
34 #include <v8-debug.h>
35 #include <v8-i18n/include/extension.h>
36 #include <v8.h>
37 #include <algorithm>
38 #include <utility>
39 #include "RuntimeEnabledFeatures.h"
40 #include "V8DOMWindow.h"
41 #include "V8Document.h"
42 #include "V8HTMLCollection.h"
43 #include "V8HTMLDocument.h"
44 #include "bindings/v8/DOMWrapperWorld.h"
45 #include "bindings/v8/DateExtension.h"
46 #include "bindings/v8/ScriptController.h"
47 #include "bindings/v8/V8Binding.h"
48 #include "bindings/v8/V8GCForContextDispose.h"
49 #include "bindings/v8/V8HiddenPropertyName.h"
50 #include "bindings/v8/V8Initializer.h"
51 #include "bindings/v8/V8ObjectConstructor.h"
52 #include "bindings/v8/V8PerContextData.h"
53 #include "core/html/HTMLCollection.h"
54 #include "core/html/HTMLIFrameElement.h"
55 #include "core/inspector/InspectorInstrumentation.h"
56 #include "core/loader/DocumentLoader.h"
57 #include "core/loader/FrameLoader.h"
58 #include "core/loader/FrameLoaderClient.h"
59 #include "core/page/ContentSecurityPolicy.h"
60 #include "core/page/Frame.h"
61 #include "core/page/Page.h"
62 #include "core/platform/HistogramSupport.h"
63 #include "weborigin/SecurityOrigin.h"
64 #include "wtf/Assertions.h"
65 #include "wtf/OwnArrayPtr.h"
66 #include "wtf/StringExtras.h"
67 #include "wtf/text/CString.h"
68
69 namespace WebCore {
70
71 static void checkDocumentWrapper(v8::Handle<v8::Object> wrapper, Document* docum ent)
72 {
73 ASSERT(V8Document::toNative(wrapper) == document);
74 ASSERT(!document->isHTMLDocument() || (V8Document::toNative(v8::Handle<v8::O bject>::Cast(wrapper->GetPrototype())) == document));
75 }
76
77 static void setInjectedScriptContextDebugId(v8::Handle<v8::Context> targetContex t, int debugId)
78 {
79 V8PerContextDebugData::setContextDebugData(targetContext, "injected", debugI d);
80 }
81
82 PassOwnPtr<V8DOMWindowShell> V8DOMWindowShell::create(Frame* frame, PassRefPtr<D OMWrapperWorld> world, v8::Isolate* isolate)
83 {
84 return adoptPtr(new V8DOMWindowShell(frame, world, isolate));
85 }
86
87 V8DOMWindowShell::V8DOMWindowShell(Frame* frame, PassRefPtr<DOMWrapperWorld> wor ld, v8::Isolate* isolate)
88 : m_frame(frame)
89 , m_world(world)
90 , m_isolate(isolate)
91 {
92 }
93
94 void V8DOMWindowShell::disposeContext()
95 {
96 m_perContextData.clear();
97
98 if (m_context.isEmpty())
99 return;
100
101 v8::HandleScope handleScope(m_isolate);
102 m_frame->loader()->client()->willReleaseScriptContext(m_context.newLocal(m_i solate), m_world->worldId());
103
104 m_context.clear();
105
106 // It's likely that disposing the context has created a lot of
107 // garbage. Notify V8 about this so it'll have a chance of cleaning
108 // it up when idle.
109 bool isMainFrame = m_frame->page() && (m_frame->page()->mainFrame() == m_fra me);
110 V8GCForContextDispose::instance().notifyContextDisposed(isMainFrame);
111 }
112
113 void V8DOMWindowShell::clearForClose(bool destroyGlobal)
114 {
115 if (destroyGlobal)
116 m_global.clear();
117
118 if (m_context.isEmpty())
119 return;
120
121 m_document.clear();
122 disposeContext();
123 }
124
125 void V8DOMWindowShell::clearForNavigation()
126 {
127 if (m_context.isEmpty())
128 return;
129
130 v8::HandleScope handleScope(m_isolate);
131 m_document.clear();
132
133 v8::Handle<v8::Context> context = m_context.newLocal(m_isolate);
134 v8::Context::Scope contextScope(context);
135
136 // Clear the document wrapper cache before turning on access checks on
137 // the old DOMWindow wrapper. This way, access to the document wrapper
138 // will be protected by the security checks on the DOMWindow wrapper.
139 clearDocumentProperty();
140
141 v8::Handle<v8::Object> windowWrapper = m_global.newLocal(m_isolate)->FindIns tanceInPrototypeChain(V8DOMWindow::GetTemplate(m_isolate, worldTypeInMainThread( m_isolate)));
142 ASSERT(!windowWrapper.IsEmpty());
143 windowWrapper->TurnOnAccessCheck();
144 context->DetachGlobal();
145 disposeContext();
146 }
147
148 // Create a new environment and setup the global object.
149 //
150 // The global object corresponds to a DOMWindow instance. However, to
151 // allow properties of the JS DOMWindow instance to be shadowed, we
152 // use a shadow object as the global object and use the JS DOMWindow
153 // instance as the prototype for that shadow object. The JS DOMWindow
154 // instance is undetectable from JavaScript code because the __proto__
155 // accessors skip that object.
156 //
157 // The shadow object and the DOMWindow instance are seen as one object
158 // from JavaScript. The JavaScript object that corresponds to a
159 // DOMWindow instance is the shadow object. When mapping a DOMWindow
160 // instance to a V8 object, we return the shadow object.
161 //
162 // To implement split-window, see
163 // 1) https://bugs.webkit.org/show_bug.cgi?id=17249
164 // 2) https://wiki.mozilla.org/Gecko:SplitWindow
165 // 3) https://bugzilla.mozilla.org/show_bug.cgi?id=296639
166 // we need to split the shadow object further into two objects:
167 // an outer window and an inner window. The inner window is the hidden
168 // prototype of the outer window. The inner window is the default
169 // global object of the context. A variable declared in the global
170 // scope is a property of the inner window.
171 //
172 // The outer window sticks to a Frame, it is exposed to JavaScript
173 // via window.window, window.self, window.parent, etc. The outer window
174 // has a security token which is the domain. The outer window cannot
175 // have its own properties. window.foo = 'x' is delegated to the
176 // inner window.
177 //
178 // When a frame navigates to a new page, the inner window is cut off
179 // the outer window, and the outer window identify is preserved for
180 // the frame. However, a new inner window is created for the new page.
181 // If there are JS code holds a closure to the old inner window,
182 // it won't be able to reach the outer window via its global object.
183 bool V8DOMWindowShell::initializeIfNeeded()
184 {
185 if (!m_context.isEmpty())
186 return true;
187
188 v8::HandleScope handleScope(m_isolate);
189
190 V8Initializer::initializeMainThreadIfNeeded(m_isolate);
191
192 createContext();
193 if (m_context.isEmpty())
194 return false;
195
196 v8::Handle<v8::Context> context = m_context.newLocal(m_isolate);
197
198 m_world->setIsolatedWorldField(context);
199
200 bool isMainWorld = m_world->isMainWorld();
201
202 v8::Context::Scope contextScope(context);
203
204 if (m_global.isEmpty()) {
205 m_global.set(m_isolate, context->Global());
206 if (m_global.isEmpty()) {
207 disposeContext();
208 return false;
209 }
210 }
211
212 if (!isMainWorld) {
213 V8DOMWindowShell* mainWindow = m_frame->script()->existingWindowShell(ma inThreadNormalWorld());
214 if (mainWindow && !mainWindow->context().IsEmpty())
215 setInjectedScriptContextDebugId(context, m_frame->script()->contextD ebugId(mainWindow->context()));
216 }
217
218 m_perContextData = V8PerContextData::create(context);
219 if (!m_perContextData->init()) {
220 disposeContext();
221 return false;
222 }
223 m_perContextData->setActivityLogger(DOMWrapperWorld::activityLogger(m_world- >worldId()));
224 if (!installDOMWindow()) {
225 disposeContext();
226 return false;
227 }
228
229 if (isMainWorld) {
230 updateDocument();
231 setSecurityToken();
232 if (m_frame->document()) {
233 ContentSecurityPolicy* csp = m_frame->document()->contentSecurityPol icy();
234 context->AllowCodeGenerationFromStrings(csp->allowEval(0, ContentSec urityPolicy::SuppressReport));
235 context->SetErrorMessageForCodeGenerationFromStrings(v8String(csp->e valDisabledErrorMessage(), m_isolate));
236 }
237 } else {
238 // Using the default security token means that the canAccess is always
239 // called, which is slow.
240 // FIXME: Use tokens where possible. This will mean keeping track of all
241 // created contexts so that they can all be updated when the
242 // document domain
243 // changes.
244 context->UseDefaultSecurityToken();
245
246 SecurityOrigin* origin = m_world->isolatedWorldSecurityOrigin();
247 if (origin && InspectorInstrumentation::hasFrontends()) {
248 ScriptState* scriptState = ScriptState::forContext(v8::Local<v8::Con text>::New(context));
249 InspectorInstrumentation::didCreateIsolatedContext(m_frame, scriptSt ate, origin);
250 }
251 }
252 m_frame->loader()->client()->didCreateScriptContext(context, m_world->extens ionGroup(), m_world->worldId());
253 return true;
254 }
255
256 void V8DOMWindowShell::createContext()
257 {
258 // The activeDocumentLoader pointer could be 0 during frame shutdown.
259 // FIXME: Can we remove this check?
260 if (!m_frame->loader()->activeDocumentLoader())
261 return;
262
263 // Create a new environment using an empty template for the shadow
264 // object. Reuse the global object if one has been created earlier.
265 v8::Handle<v8::ObjectTemplate> globalTemplate = V8DOMWindow::GetShadowObject Template(m_isolate, m_world->isMainWorld() ? MainWorld : IsolatedWorld);
266 if (globalTemplate.IsEmpty())
267 return;
268
269 double contextCreationStartInSeconds = currentTime();
270
271 // Used to avoid sleep calls in unload handlers.
272 ScriptController::registerExtensionIfNeeded(DateExtension::get());
273
274 // Enables experimental i18n API in V8.
275 if (RuntimeEnabledFeatures::javaScriptI18NAPIEnabled())
276 ScriptController::registerExtensionIfNeeded(v8_i18n::Extension::get());
277
278 // Dynamically tell v8 about our extensions now.
279 const V8Extensions& extensions = ScriptController::registeredExtensions();
280 OwnArrayPtr<const char*> extensionNames = adoptArrayPtr(new const char*[exte nsions.size()]);
281 int index = 0;
282 int extensionGroup = m_world->extensionGroup();
283 int worldId = m_world->worldId();
284 for (size_t i = 0; i < extensions.size(); ++i) {
285 // Ensure our date extension is always allowed.
286 if (extensions[i] != DateExtension::get()
287 && !m_frame->loader()->client()->allowScriptExtension(extensions[i]- >name(), extensionGroup, worldId))
288 continue;
289
290 extensionNames[index++] = extensions[i]->name();
291 }
292 v8::ExtensionConfiguration extensionConfiguration(index, extensionNames.get( ));
293
294 v8::HandleScope handleScope(m_isolate);
295 m_context.set(m_isolate, v8::Context::New(m_isolate, &extensionConfiguration , globalTemplate, m_global.newLocal(m_isolate)));
296
297 double contextCreationDurationInMilliseconds = (currentTime() - contextCreat ionStartInSeconds) * 1000;
298 const char* histogramName = "WebCore.V8DOMWindowShell.createContext.MainWorl d";
299 if (!m_world->isMainWorld())
300 histogramName = "WebCore.V8DOMWindowShell.createContext.IsolatedWorld";
301 HistogramSupport::histogramCustomCounts(histogramName, contextCreationDurati onInMilliseconds, 0, 10000, 50);
302 }
303
304 bool V8DOMWindowShell::installDOMWindow()
305 {
306 DOMWrapperWorld::setInitializingWindow(true);
307 DOMWindow* window = m_frame->document()->domWindow();
308 v8::Local<v8::Object> windowWrapper = V8ObjectConstructor::newInstance(V8Per ContextData::from(m_context.get())->constructorForType(&V8DOMWindow::info));
309 if (windowWrapper.IsEmpty())
310 return false;
311
312 V8DOMWindow::installPerContextProperties(windowWrapper, window, m_isolate);
313
314 V8DOMWrapper::setNativeInfo(v8::Handle<v8::Object>::Cast(windowWrapper->GetP rototype()), &V8DOMWindow::info, window);
315
316 // Install the windowWrapper as the prototype of the innerGlobalObject.
317 // The full structure of the global object is as follows:
318 //
319 // outerGlobalObject (Empty object, remains after navigation)
320 // -- has prototype --> innerGlobalObject (Holds global variables, changes during navigation)
321 // -- has prototype --> DOMWindow instance
322 // -- has prototype --> Window.prototype
323 // -- has prototype --> Object.prototype
324 //
325 // Note: Much of this prototype structure is hidden from web content. The
326 // outer, inner, and DOMWindow instance all appear to be the same
327 // JavaScript object.
328 //
329 v8::Handle<v8::Object> innerGlobalObject = toInnerGlobalObject(m_context.new Local(m_isolate));
330 V8DOMWrapper::setNativeInfo(innerGlobalObject, &V8DOMWindow::info, window);
331 innerGlobalObject->SetPrototype(windowWrapper);
332 V8DOMWrapper::associateObjectWithWrapper(PassRefPtr<DOMWindow>(window), &V8D OMWindow::info, windowWrapper, m_isolate, WrapperConfiguration::Dependent);
333 DOMWrapperWorld::setInitializingWindow(false);
334 return true;
335 }
336
337 void V8DOMWindowShell::updateDocumentWrapper(v8::Handle<v8::Object> wrapper)
338 {
339 ASSERT(m_world->isMainWorld());
340 m_document.set(m_isolate, wrapper);
341 }
342
343 void V8DOMWindowShell::updateDocumentProperty()
344 {
345 if (!m_world->isMainWorld())
346 return;
347
348 v8::HandleScope handleScope(m_isolate);
349 v8::Handle<v8::Context> context = m_context.newLocal(m_isolate);
350 v8::Context::Scope contextScope(context);
351
352 v8::Handle<v8::Value> documentWrapper = toV8(m_frame->document(), v8::Handle <v8::Object>(), context->GetIsolate());
353 ASSERT(documentWrapper == m_document.newLocal(m_isolate) || m_document.isEmp ty());
354 if (m_document.isEmpty())
355 updateDocumentWrapper(v8::Handle<v8::Object>::Cast(documentWrapper));
356 checkDocumentWrapper(m_document.newLocal(m_isolate), m_frame->document());
357
358 // If instantiation of the document wrapper fails, clear the cache
359 // and let the DOMWindow accessor handle access to the document.
360 if (documentWrapper.IsEmpty()) {
361 clearDocumentProperty();
362 return;
363 }
364 ASSERT(documentWrapper->IsObject());
365 context->Global()->ForceSet(v8::String::NewSymbol("document"), documentWrapp er, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
366
367 // We also stash a reference to the document on the inner global object so t hat
368 // DOMWindow objects we obtain from JavaScript references are guaranteed to have
369 // live Document objects.
370 toInnerGlobalObject(context)->SetHiddenValue(V8HiddenPropertyName::document( ), documentWrapper);
371 }
372
373 void V8DOMWindowShell::clearDocumentProperty()
374 {
375 ASSERT(!m_context.isEmpty());
376 if (!m_world->isMainWorld())
377 return;
378 v8::HandleScope handleScope(m_isolate);
379 m_context.newLocal(m_isolate)->Global()->ForceDelete(v8::String::NewSymbol(" document"));
380 }
381
382 void V8DOMWindowShell::setSecurityToken()
383 {
384 ASSERT(m_world->isMainWorld());
385
386 Document* document = m_frame->document();
387
388 // Ask the document's SecurityOrigin to generate a security token.
389 // If two tokens are equal, then the SecurityOrigins canAccess each other.
390 // If two tokens are not equal, then we have to call canAccess.
391 // Note: we can't use the HTTPOrigin if it was set from the DOM.
392 SecurityOrigin* origin = document->securityOrigin();
393 String token;
394 // We stick with an empty token if document.domain was modified or if we
395 // are in the initial empty document, so that we can do a full canAccess
396 // check in those cases.
397 if (!origin->domainWasSetInDOM()
398 && !m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument( ))
399 token = document->securityOrigin()->toString();
400
401 // An empty or "null" token means we always have to call
402 // canAccess. The toString method on securityOrigins returns the
403 // string "null" for empty security origins and for security
404 // origins that should only allow access to themselves. In this
405 // case, we use the global object as the security token to avoid
406 // calling canAccess when a script accesses its own objects.
407 v8::HandleScope handleScope(m_isolate);
408 v8::Handle<v8::Context> context = m_context.newLocal(m_isolate);
409 if (token.isEmpty() || token == "null") {
410 context->UseDefaultSecurityToken();
411 return;
412 }
413
414 CString utf8Token = token.utf8();
415 // NOTE: V8 does identity comparison in fast path, must use a symbol
416 // as the security token.
417 context->SetSecurityToken(v8::String::NewSymbol(utf8Token.data(), utf8Token. length()));
418 }
419
420 void V8DOMWindowShell::updateDocument()
421 {
422 ASSERT(m_world->isMainWorld());
423 if (m_global.isEmpty())
424 return;
425 if (m_context.isEmpty())
426 return;
427 updateDocumentProperty();
428 updateSecurityOrigin();
429 }
430
431 static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
432 {
433 if (!htmlDocument->hasNamedItem(key.impl()) && !htmlDocument->hasExtraNamedI tem(key.impl()))
434 return v8Undefined();
435
436 RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
437 if (items->isEmpty())
438 return v8Undefined();
439
440 if (items->hasExactlyOneItem()) {
441 Node* node = items->item(0);
442 Frame* frame = 0;
443 if (node->hasTagName(HTMLNames::iframeTag) && (frame = static_cast<HTMLI FrameElement*>(node)->contentFrame()))
444 return toV8(frame->document()->domWindow(), creationContext, isolate );
445 return toV8(node, creationContext, isolate);
446 }
447 return toV8(items.release(), creationContext, isolate);
448 }
449
450 static void getter(v8::Local<v8::String> property, const v8::PropertyCallbackInf o<v8::Value>& info)
451 {
452 // FIXME: Consider passing AtomicStringImpl directly.
453 AtomicString name = toWebCoreAtomicString(property);
454 HTMLDocument* htmlDocument = V8HTMLDocument::toNative(info.Holder());
455 ASSERT(htmlDocument);
456 v8::Handle<v8::Value> result = getNamedProperty(htmlDocument, name, info.Hol der(), info.GetIsolate());
457 if (!result.IsEmpty()) {
458 v8SetReturnValue(info, result);
459 return;
460 }
461 v8::Handle<v8::Value> prototype = info.Holder()->GetPrototype();
462 if (prototype->IsObject()) {
463 v8SetReturnValue(info, prototype.As<v8::Object>()->Get(property));
464 return;
465 }
466 }
467
468 void V8DOMWindowShell::namedItemAdded(HTMLDocument* document, const AtomicString & name)
469 {
470 ASSERT(m_world->isMainWorld());
471
472 if (m_context.isEmpty())
473 return;
474
475 v8::HandleScope handleScope(m_isolate);
476 v8::Context::Scope contextScope(m_context.get());
477
478 ASSERT(!m_document.isEmpty());
479 v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
480 checkDocumentWrapper(documentHandle, document);
481 documentHandle->SetAccessor(v8String(name, m_isolate), getter);
482 }
483
484 void V8DOMWindowShell::namedItemRemoved(HTMLDocument* document, const AtomicStri ng& name)
485 {
486 ASSERT(m_world->isMainWorld());
487
488 if (m_context.isEmpty())
489 return;
490
491 if (document->hasNamedItem(name.impl()) || document->hasExtraNamedItem(name. impl()))
492 return;
493
494 v8::HandleScope handleScope(m_isolate);
495 v8::Context::Scope contextScope(m_context.get());
496
497 ASSERT(!m_document.isEmpty());
498 v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
499 checkDocumentWrapper(documentHandle, document);
500 documentHandle->Delete(v8String(name, m_isolate));
501 }
502
503 void V8DOMWindowShell::updateSecurityOrigin()
504 {
505 ASSERT(m_world->isMainWorld());
506 if (m_context.isEmpty())
507 return;
508 v8::HandleScope handleScope;
509 setSecurityToken();
510 }
511
512 } // WebCore
OLDNEW
« no previous file with comments | « Source/bindings/v8/V8DOMWindowShell.h ('k') | Source/bindings/v8/V8DOMWrapper.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698