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