Upstream version 7.36.149.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/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"
64 #include <algorithm>
65 #include <utility>
66 #include <v8-debug.h>
67 #include <v8.h>
68
69 namespace WebCore {
70
71 static void checkDocumentWrapper(v8::Handle<v8::Object> wrapper, Document* document)
72 {
73     ASSERT(V8Document::toNative(wrapper) == document);
74     ASSERT(!document->isHTMLDocument() || (V8Document::toNative(v8::Handle<v8::Object>::Cast(wrapper->GetPrototype())) == document));
75 }
76
77 static void setInjectedScriptContextDebugId(v8::Handle<v8::Context> targetContext, int debugId)
78 {
79     V8PerContextDebugData::setContextDebugData(targetContext, "injected", debugId);
80 }
81
82 PassOwnPtr<V8WindowShell> V8WindowShell::create(LocalFrame* frame, DOMWrapperWorld& world, v8::Isolate* isolate)
83 {
84     return adoptPtr(new V8WindowShell(frame, &world, isolate));
85 }
86
87 V8WindowShell::V8WindowShell(LocalFrame* frame, PassRefPtr<DOMWrapperWorld> world, v8::Isolate* isolate)
88     : m_frame(frame)
89     , m_isolate(isolate)
90     , m_world(world)
91 {
92 }
93
94 void V8WindowShell::disposeContext(GlobalDetachmentBehavior behavior)
95 {
96     if (!isContextInitialized())
97         return;
98
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());
102
103     if (behavior == DetachGlobal)
104         context->DetachGlobal();
105
106     m_scriptState->disposePerContextData();
107
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
110     // it up when idle.
111     V8GCForContextDispose::instanceTemplate().notifyContextDisposed(m_frame->isMainFrame());
112 }
113
114 void V8WindowShell::clearForClose()
115 {
116     if (!isContextInitialized())
117         return;
118
119     m_document.clear();
120     disposeContext(DoNotDetachGlobal);
121 }
122
123 void V8WindowShell::clearForNavigation()
124 {
125     if (!isContextInitialized())
126         return;
127
128     ScriptState::Scope scope(m_scriptState.get());
129
130     m_document.clear();
131
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();
136
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);
141 }
142
143 // Create a new environment and setup the global object.
144 //
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.
151 //
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.
156 //
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.
166 //
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
171 // inner window.
172 //
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()
179 {
180     if (isContextInitialized())
181         return true;
182
183     DOMWrapperWorld::setWorldOfInitializingWindow(m_world.get());
184     bool result = initialize();
185     DOMWrapperWorld::setWorldOfInitializingWindow(0);
186     return result;
187 }
188
189 bool V8WindowShell::initialize()
190 {
191     TRACE_EVENT0("v8", "V8WindowShell::initialize");
192     TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "InitializeWindow");
193
194     ScriptForbiddenScope::AllowUserAgentScript allowScript;
195
196     v8::HandleScope handleScope(m_isolate);
197
198     createContext();
199
200     if (!isContextInitialized())
201         return false;
202
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);
209             return false;
210         }
211     }
212
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()));
217     }
218
219     m_scriptState->world().setActivityLogger(V8DOMActivityLogger::activityLogger(m_world->worldId()));
220     if (!installDOMWindow()) {
221         disposeContext(DoNotDetachGlobal);
222         return false;
223     }
224
225     if (m_world->isMainWorld()) {
226         updateDocument();
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()));
232         }
233     } else {
234         SecurityOrigin* origin = m_world->isolatedWorldSecurityOrigin();
235         setSecurityToken(origin);
236         if (origin && InspectorInstrumentation::hasFrontends()) {
237             InspectorInstrumentation::didCreateIsolatedContext(m_frame, ScriptState::current(m_isolate), origin);
238         }
239     }
240     m_frame->loader().client()->didCreateScriptContext(context, m_world->extensionGroup(), m_world->worldId());
241     return true;
242 }
243
244 void V8WindowShell::createContext()
245 {
246     // The documentLoader pointer could be 0 during frame shutdown.
247     // FIXME: Can we remove this check?
248     if (!m_frame->loader().documentLoader())
249         return;
250
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())
255         return;
256
257     double contextCreationStartInSeconds = currentTime();
258
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()]);
262     int index = 0;
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))
267             continue;
268
269         extensionNames[index++] = extensions[i]->name();
270     }
271     v8::ExtensionConfiguration extensionConfiguration(index, extensionNames.get());
272
273     v8::Handle<v8::Context> context = v8::Context::New(m_isolate, &extensionConfiguration, globalTemplate, m_global.newLocal(m_isolate));
274     if (context.IsEmpty())
275         return;
276     m_scriptState = ScriptState::create(context, m_world);
277
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);
283 }
284
285 static v8::Handle<v8::Object> toInnerGlobalObject(v8::Handle<v8::Context> context)
286 {
287     return v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
288 }
289
290 bool V8WindowShell::installDOMWindow()
291 {
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())
295         return false;
296
297     V8Window::installPerContextEnabledProperties(windowWrapper, window, m_isolate);
298
299     V8DOMWrapper::setNativeInfoForHiddenWrapper(v8::Handle<v8::Object>::Cast(windowWrapper->GetPrototype()), &V8Window::wrapperTypeInfo, window);
300
301     // Install the windowWrapper as the prototype of the innerGlobalObject.
302     // The full structure of the global object is as follows:
303     //
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
309     //
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.
313     //
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
320     //       reference.
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);
325     return true;
326 }
327
328 void V8WindowShell::updateDocumentWrapper(v8::Handle<v8::Object> wrapper)
329 {
330     ASSERT(m_world->isMainWorld());
331     m_document.set(m_isolate, wrapper);
332 }
333
334 void V8WindowShell::updateDocumentProperty()
335 {
336     if (!m_world->isMainWorld())
337         return;
338
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());
346
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();
351         return;
352     }
353     ASSERT(documentWrapper->IsObject());
354     context->Global()->ForceSet(v8AtomicString(m_isolate, "document"), documentWrapper, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
355
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);
360 }
361
362 void V8WindowShell::clearDocumentProperty()
363 {
364     ASSERT(isContextInitialized());
365     if (!m_world->isMainWorld())
366         return;
367     v8::HandleScope handleScope(m_isolate);
368     m_scriptState->context()->Global()->ForceDelete(v8AtomicString(m_isolate, "document"));
369 }
370
371 void V8WindowShell::setSecurityToken(SecurityOrigin* origin)
372 {
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.
376     String token;
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();
385
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();
396         return;
397     }
398
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()));
403 }
404
405 void V8WindowShell::updateDocument()
406 {
407     ASSERT(m_world->isMainWorld());
408     if (!isGlobalInitialized())
409         return;
410     if (!isContextInitialized())
411         return;
412     updateDocumentProperty();
413     updateSecurityOrigin(m_frame->document()->securityOrigin());
414 }
415
416 static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
417 {
418     if (!htmlDocument->hasNamedItem(key) && !htmlDocument->hasExtraNamedItem(key))
419         return v8Undefined();
420
421     RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
422     if (items->isEmpty())
423         return v8Undefined();
424
425     if (items->hasExactlyOneItem()) {
426         Element* element = items->item(0);
427         ASSERT(element);
428         Frame* frame = 0;
429         if (isHTMLIFrameElement(*element) && (frame = toHTMLIFrameElement(*element).contentFrame()))
430             return toV8(frame->domWindow(), creationContext, isolate);
431         return toV8(element, creationContext, isolate);
432     }
433     return toV8(items.release(), creationContext, isolate);
434 }
435
436 static void getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info)
437 {
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);
445         return;
446     }
447     v8::Handle<v8::Value> prototype = info.Holder()->GetPrototype();
448     if (prototype->IsObject()) {
449         v8SetReturnValue(info, prototype.As<v8::Object>()->Get(property));
450         return;
451     }
452 }
453
454 void V8WindowShell::namedItemAdded(HTMLDocument* document, const AtomicString& name)
455 {
456     ASSERT(m_world->isMainWorld());
457
458     if (!isContextInitialized())
459         return;
460
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);
466 }
467
468 void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
469 {
470     ASSERT(m_world->isMainWorld());
471
472     if (!isContextInitialized())
473         return;
474
475     if (document->hasNamedItem(name) || document->hasExtraNamedItem(name))
476         return;
477
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));
483 }
484
485 void V8WindowShell::updateSecurityOrigin(SecurityOrigin* origin)
486 {
487     ASSERT(m_world->isMainWorld());
488     if (!isContextInitialized())
489         return;
490     setSecurityToken(origin);
491 }
492
493 } // WebCore