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