Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / core / v8 / WindowProxy.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/core/v8/WindowProxy.h"
33
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"
64 #include <algorithm>
65 #include <utility>
66 #include <v8-debug.h>
67 #include <v8.h>
68
69 namespace blink {
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 PassOwnPtr<WindowProxy> WindowProxy::create(LocalFrame* frame, DOMWrapperWorld& world, v8::Isolate* isolate)
78 {
79     return adoptPtr(new WindowProxy(frame, &world, isolate));
80 }
81
82 WindowProxy::WindowProxy(LocalFrame* frame, PassRefPtr<DOMWrapperWorld> world, v8::Isolate* isolate)
83     : m_frame(frame)
84     , m_isolate(isolate)
85     , m_world(world)
86 {
87 }
88
89 void WindowProxy::disposeContext(GlobalDetachmentBehavior behavior)
90 {
91     if (!isContextInitialized())
92         return;
93
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());
97
98     if (behavior == DetachGlobal)
99         context->DetachGlobal();
100
101     m_scriptState->disposePerContextData();
102
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
105     // it up when idle.
106     V8GCForContextDispose::instanceTemplate().notifyContextDisposed(m_frame->isMainFrame());
107 }
108
109 void WindowProxy::clearForClose()
110 {
111     if (!isContextInitialized())
112         return;
113
114     m_document.clear();
115     disposeContext(DoNotDetachGlobal);
116 }
117
118 void WindowProxy::clearForNavigation()
119 {
120     if (!isContextInitialized())
121         return;
122
123     ScriptState::Scope scope(m_scriptState.get());
124
125     m_document.clear();
126
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();
131
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);
136 }
137
138 // Create a new environment and setup the global object.
139 //
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.
146 //
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.
151 //
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.
161 //
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
166 // inner window.
167 //
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()
174 {
175     if (isContextInitialized())
176         return true;
177
178     DOMWrapperWorld::setWorldOfInitializingWindow(m_world.get());
179     bool result = initialize();
180     DOMWrapperWorld::setWorldOfInitializingWindow(0);
181     return result;
182 }
183
184 bool WindowProxy::initialize()
185 {
186     TRACE_EVENT0("v8", "WindowProxy::initialize");
187     TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "InitializeWindow");
188
189     ScriptForbiddenScope::AllowUserAgentScript allowScript;
190
191     v8::HandleScope handleScope(m_isolate);
192
193     createContext();
194
195     if (!isContextInitialized())
196         return false;
197
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);
204             return false;
205         }
206     }
207
208     if (!installDOMWindow()) {
209         disposeContext(DoNotDetachGlobal);
210         return false;
211     }
212
213     if (m_world->isMainWorld()) {
214         // ActivityLogger for main world is updated within updateDocument().
215         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()));
221         }
222     } else {
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);
228         }
229     }
230     m_frame->loader().client()->didCreateScriptContext(context, m_world->extensionGroup(), m_world->worldId());
231     return true;
232 }
233
234 void WindowProxy::createContext()
235 {
236     // The documentLoader pointer could be 0 during frame shutdown.
237     // FIXME: Can we remove this check?
238     if (!m_frame->loader().documentLoader())
239         return;
240
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())
245         return;
246
247     double contextCreationStartInSeconds = currentTime();
248
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()]);
252     int index = 0;
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))
257             continue;
258
259         extensionNames[index++] = extensions[i]->name();
260     }
261     v8::ExtensionConfiguration extensionConfiguration(index, extensionNames.get());
262
263     v8::Handle<v8::Context> context = v8::Context::New(m_isolate, &extensionConfiguration, globalTemplate, m_global.newLocal(m_isolate));
264     if (context.IsEmpty())
265         return;
266     m_scriptState = ScriptState::create(context, m_world);
267
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);
273 }
274
275 static v8::Handle<v8::Object> toInnerGlobalObject(v8::Handle<v8::Context> context)
276 {
277     return v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
278 }
279
280 bool WindowProxy::installDOMWindow()
281 {
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())
285         return false;
286
287     V8DOMWrapper::setNativeInfoForHiddenWrapper(v8::Handle<v8::Object>::Cast(windowWrapper->GetPrototype()), &V8Window::wrapperTypeInfo, V8Window::toInternalPointer(window));
288
289     // Install the windowWrapper as the prototype of the innerGlobalObject.
290     // The full structure of the global object is as follows:
291     //
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
297     //
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.
301     //
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
308     //       reference.
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);
314     return true;
315 }
316
317 void WindowProxy::updateDocumentWrapper(v8::Handle<v8::Object> wrapper)
318 {
319     ASSERT(m_world->isMainWorld());
320     m_document.set(m_isolate, wrapper);
321 }
322
323 void WindowProxy::updateDocumentProperty()
324 {
325     if (!m_world->isMainWorld())
326         return;
327
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());
335
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();
340         return;
341     }
342     ASSERT(documentWrapper->IsObject());
343     context->Global()->ForceSet(v8AtomicString(m_isolate, "document"), documentWrapper, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete));
344
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);
349 }
350
351 void WindowProxy::clearDocumentProperty()
352 {
353     ASSERT(isContextInitialized());
354     if (!m_world->isMainWorld())
355         return;
356     v8::HandleScope handleScope(m_isolate);
357     m_scriptState->context()->Global()->ForceDelete(v8AtomicString(m_isolate, "document"));
358 }
359
360 void WindowProxy::updateActivityLogger()
361 {
362     m_scriptState->perContextData()->setActivityLogger(V8DOMActivityLogger::activityLogger(
363         m_world->worldId(), m_frame->document() ? m_frame->document()->baseURI() : KURL()));
364 }
365
366 void WindowProxy::setSecurityToken(SecurityOrigin* origin)
367 {
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.
371     String token;
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();
380
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();
391         return;
392     }
393
394     if (m_world->isPrivateScriptIsolatedWorld())
395         token = "private-script://" + token;
396
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()));
401 }
402
403 void WindowProxy::updateDocument()
404 {
405     ASSERT(m_world->isMainWorld());
406     if (!isGlobalInitialized())
407         return;
408     if (!isContextInitialized())
409         return;
410     updateActivityLogger();
411     updateDocumentProperty();
412     updateSecurityOrigin(m_frame->document()->securityOrigin());
413 }
414
415 static v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
416 {
417     if (!htmlDocument->hasNamedItem(key) && !htmlDocument->hasExtraNamedItem(key))
418         return v8Undefined();
419
420     RefPtrWillBeRawPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
421     if (items->isEmpty())
422         return v8Undefined();
423
424     if (items->hasExactlyOneItem()) {
425         Element* element = items->item(0);
426         ASSERT(element);
427         Frame* frame = isHTMLIFrameElement(*element) ? toHTMLIFrameElement(*element).contentFrame() : 0;
428         if (frame)
429             return toV8(frame->domWindow(), creationContext, isolate);
430         return toV8(element, creationContext, isolate);
431     }
432     return toV8(items.release(), creationContext, isolate);
433 }
434
435 static void getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info)
436 {
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);
444         return;
445     }
446     v8::Handle<v8::Value> prototype = info.Holder()->GetPrototype();
447     if (prototype->IsObject()) {
448         v8SetReturnValue(info, prototype.As<v8::Object>()->Get(property));
449         return;
450     }
451 }
452
453 void WindowProxy::namedItemAdded(HTMLDocument* document, const AtomicString& name)
454 {
455     ASSERT(m_world->isMainWorld());
456
457     if (!isContextInitialized())
458         return;
459
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);
465 }
466
467 void WindowProxy::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
468 {
469     ASSERT(m_world->isMainWorld());
470
471     if (!isContextInitialized())
472         return;
473
474     if (document->hasNamedItem(name) || document->hasExtraNamedItem(name))
475         return;
476
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));
482 }
483
484 void WindowProxy::updateSecurityOrigin(SecurityOrigin* origin)
485 {
486     ASSERT(m_world->isMainWorld());
487     if (!isContextInitialized())
488         return;
489     setSecurityToken(origin);
490 }
491
492 } // namespace blink