Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / v8 / ScriptController.cpp
1 /*
2  * Copyright (C) 2008, 2009 Google Inc. All rights reserved.
3  * Copyright (C) 2009 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include "config.h"
33 #include "bindings/v8/ScriptController.h"
34
35 #include "V8Event.h"
36 #include "V8HTMLElement.h"
37 #include "V8Window.h"
38 #include "bindings/v8/BindingSecurity.h"
39 #include "bindings/v8/NPV8Object.h"
40 #include "bindings/v8/ScriptCallStackFactory.h"
41 #include "bindings/v8/ScriptSourceCode.h"
42 #include "bindings/v8/ScriptValue.h"
43 #include "bindings/v8/V8Binding.h"
44 #include "bindings/v8/V8GCController.h"
45 #include "bindings/v8/V8NPObject.h"
46 #include "bindings/v8/V8PerContextData.h"
47 #include "bindings/v8/V8ScriptRunner.h"
48 #include "bindings/v8/V8WindowShell.h"
49 #include "bindings/v8/npruntime_impl.h"
50 #include "bindings/v8/npruntime_priv.h"
51 #include "core/dom/Document.h"
52 #include "core/dom/Node.h"
53 #include "core/dom/ScriptableDocumentParser.h"
54 #include "core/events/Event.h"
55 #include "core/events/EventListener.h"
56 #include "core/events/ThreadLocalEventNames.h"
57 #include "core/html/HTMLPlugInElement.h"
58 #include "core/inspector/InspectorInstrumentation.h"
59 #include "core/inspector/ScriptCallStack.h"
60 #include "core/loader/DocumentLoader.h"
61 #include "core/loader/FrameLoader.h"
62 #include "core/loader/FrameLoaderClient.h"
63 #include "core/frame/ContentSecurityPolicy.h"
64 #include "core/frame/DOMWindow.h"
65 #include "core/frame/Frame.h"
66 #include "core/frame/Settings.h"
67 #include "core/plugins/PluginView.h"
68 #include "platform/NotImplemented.h"
69 #include "platform/TraceEvent.h"
70 #include "platform/UserGestureIndicator.h"
71 #include "platform/Widget.h"
72 #include "platform/weborigin/SecurityOrigin.h"
73 #include "public/platform/Platform.h"
74 #include "wtf/CurrentTime.h"
75 #include "wtf/StdLibExtras.h"
76 #include "wtf/StringExtras.h"
77 #include "wtf/text/CString.h"
78 #include "wtf/text/StringBuilder.h"
79 #include "wtf/text/TextPosition.h"
80
81 namespace WebCore {
82
83 bool ScriptController::canAccessFromCurrentOrigin(Frame *frame)
84 {
85     if (!frame)
86         return false;
87     v8::Isolate* isolate = toIsolate(frame);
88     return !isolate->InContext() || BindingSecurity::shouldAllowAccessToFrame(isolate, frame);
89 }
90
91 ScriptController::ScriptController(Frame* frame)
92     : m_frame(frame)
93     , m_sourceURL(0)
94     , m_isolate(v8::Isolate::GetCurrent())
95     , m_windowShell(V8WindowShell::create(frame, DOMWrapperWorld::mainWorld(), m_isolate))
96     , m_windowScriptNPObject(0)
97 {
98 }
99
100 ScriptController::~ScriptController()
101 {
102     // V8WindowShell::clearForClose() must be invoked before destruction starts.
103     ASSERT(!m_windowShell->isContextInitialized());
104 }
105
106 void ScriptController::clearScriptObjects()
107 {
108     PluginObjectMap::iterator it = m_pluginObjects.begin();
109     for (; it != m_pluginObjects.end(); ++it) {
110         _NPN_UnregisterObject(it->value);
111         _NPN_ReleaseObject(it->value);
112     }
113     m_pluginObjects.clear();
114
115     if (m_windowScriptNPObject) {
116         // Dispose of the underlying V8 object before releasing our reference
117         // to it, so that if a plugin fails to release it properly we will
118         // only leak the NPObject wrapper, not the object, its document, or
119         // anything else they reference.
120         disposeUnderlyingV8Object(m_windowScriptNPObject, m_isolate);
121         _NPN_ReleaseObject(m_windowScriptNPObject);
122         m_windowScriptNPObject = 0;
123     }
124 }
125
126 void ScriptController::clearForOutOfMemory()
127 {
128     clearForClose(true);
129 }
130
131 void ScriptController::clearForClose(bool destroyGlobal)
132 {
133     m_windowShell->clearForClose(destroyGlobal);
134     for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
135         iter->value->clearForClose(destroyGlobal);
136     V8GCController::hintForCollectGarbage();
137 }
138
139 void ScriptController::clearForClose()
140 {
141     double start = currentTime();
142     clearForClose(false);
143     blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearForClose", (currentTime() - start) * 1000, 0, 10000, 50);
144 }
145
146 void ScriptController::updateSecurityOrigin(SecurityOrigin* origin)
147 {
148     m_windowShell->updateSecurityOrigin(origin);
149 }
150
151 v8::Local<v8::Value> ScriptController::callFunction(v8::Handle<v8::Function> function, v8::Handle<v8::Object> receiver, int argc, v8::Handle<v8::Value> info[])
152 {
153     // Keep Frame (and therefore ScriptController) alive.
154     RefPtr<Frame> protect(m_frame);
155     return ScriptController::callFunction(m_frame->document(), function, receiver, argc, info, m_isolate);
156 }
157
158 static bool resourceInfo(const v8::Handle<v8::Function> function, String& resourceName, int& lineNumber)
159 {
160     v8::ScriptOrigin origin = function->GetScriptOrigin();
161     if (origin.ResourceName().IsEmpty()) {
162         resourceName = "undefined";
163         lineNumber = 1;
164     } else {
165         V8TRYCATCH_FOR_V8STRINGRESOURCE_RETURN(V8StringResource<>, stringResourceName, origin.ResourceName(), false);
166         resourceName = stringResourceName;
167         lineNumber = function->GetScriptLineNumber() + 1;
168     }
169     return true;
170 }
171
172 v8::Local<v8::Value> ScriptController::callFunction(ExecutionContext* context, v8::Handle<v8::Function> function, v8::Handle<v8::Object> receiver, int argc, v8::Handle<v8::Value> info[], v8::Isolate* isolate)
173 {
174     InspectorInstrumentationCookie cookie;
175     if (InspectorInstrumentation::timelineAgentEnabled(context)) {
176         String resourceName;
177         int lineNumber;
178         if (!resourceInfo(getBoundFunction(function), resourceName, lineNumber))
179             return v8::Local<v8::Value>();
180         cookie = InspectorInstrumentation::willCallFunction(context, resourceName, lineNumber);
181     }
182
183     v8::Local<v8::Value> result = V8ScriptRunner::callFunction(function, context, receiver, argc, info, isolate);
184
185     InspectorInstrumentation::didCallFunction(cookie);
186     return result;
187 }
188
189 v8::Local<v8::Value> ScriptController::executeScriptAndReturnValue(v8::Handle<v8::Context> context, const ScriptSourceCode& source, AccessControlStatus corsStatus)
190 {
191     v8::Context::Scope scope(context);
192
193     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willEvaluateScript(m_frame, source.url().isNull() ? String() : source.url().string(), source.startLine());
194
195     v8::Local<v8::Value> result;
196     {
197         // Isolate exceptions that occur when compiling and executing
198         // the code. These exceptions should not interfere with
199         // javascript code we might evaluate from C++ when returning
200         // from here.
201         v8::TryCatch tryCatch;
202         tryCatch.SetVerbose(true);
203
204         v8::Handle<v8::String> code = v8String(m_isolate, source.source());
205         OwnPtr<v8::ScriptData> scriptData = V8ScriptRunner::precompileScript(code, source.resource());
206
207         // NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at
208         // 1, whereas v8 starts at 0.
209         v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(code, source.url(), source.startPosition(), scriptData.get(), m_isolate, corsStatus);
210
211         // Keep Frame (and therefore ScriptController) alive.
212         RefPtr<Frame> protect(m_frame);
213         result = V8ScriptRunner::runCompiledScript(script, m_frame->document(), m_isolate);
214         ASSERT(!tryCatch.HasCaught() || result.IsEmpty());
215     }
216
217     InspectorInstrumentation::didEvaluateScript(cookie);
218
219     return result;
220 }
221
222 bool ScriptController::initializeMainWorld()
223 {
224     if (m_windowShell->isContextInitialized())
225         return false;
226     return windowShell(DOMWrapperWorld::mainWorld())->isContextInitialized();
227 }
228
229 V8WindowShell* ScriptController::existingWindowShell(DOMWrapperWorld* world)
230 {
231     ASSERT(world);
232
233     if (world->isMainWorld())
234         return m_windowShell->isContextInitialized() ? m_windowShell.get() : 0;
235
236     IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world->worldId());
237     if (iter == m_isolatedWorlds.end())
238         return 0;
239     return iter->value->isContextInitialized() ? iter->value.get() : 0;
240 }
241
242 V8WindowShell* ScriptController::windowShell(DOMWrapperWorld* world)
243 {
244     ASSERT(world);
245
246     V8WindowShell* shell = 0;
247     if (world->isMainWorld())
248         shell = m_windowShell.get();
249     else {
250         IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world->worldId());
251         if (iter != m_isolatedWorlds.end())
252             shell = iter->value.get();
253         else {
254             OwnPtr<V8WindowShell> isolatedWorldShell = V8WindowShell::create(m_frame, world, m_isolate);
255             shell = isolatedWorldShell.get();
256             m_isolatedWorlds.set(world->worldId(), isolatedWorldShell.release());
257         }
258     }
259     if (!shell->isContextInitialized() && shell->initializeIfNeeded())
260         m_frame->loader().dispatchDidClearWindowObjectInWorld(world);
261     return shell;
262 }
263
264 bool ScriptController::shouldBypassMainWorldContentSecurityPolicy()
265 {
266     DOMWrapperWorld* world = DOMWrapperWorld::current(m_isolate);
267     if (world && world->isIsolatedWorld())
268         return world->isolatedWorldHasContentSecurityPolicy();
269     return false;
270 }
271
272 TextPosition ScriptController::eventHandlerPosition() const
273 {
274     ScriptableDocumentParser* parser = m_frame->document()->scriptableDocumentParser();
275     if (parser)
276         return parser->textPosition();
277     return TextPosition::minimumPosition();
278 }
279
280 // Create a V8 object with an interceptor of NPObjectPropertyGetter.
281 void ScriptController::bindToWindowObject(Frame* frame, const String& key, NPObject* object)
282 {
283     v8::HandleScope handleScope(m_isolate);
284
285     v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, frame, DOMWrapperWorld::mainWorld());
286     if (v8Context.IsEmpty())
287         return;
288
289     v8::Context::Scope scope(v8Context);
290
291     v8::Handle<v8::Object> value = createV8ObjectForNPObject(object, 0, m_isolate);
292
293     // Attach to the global object.
294     v8::Handle<v8::Object> global = v8Context->Global();
295     global->Set(v8String(m_isolate, key), value);
296 }
297
298 void ScriptController::enableEval()
299 {
300     if (!m_windowShell->isContextInitialized())
301         return;
302     v8::HandleScope handleScope(m_isolate);
303     m_windowShell->context()->AllowCodeGenerationFromStrings(true);
304 }
305
306 void ScriptController::disableEval(const String& errorMessage)
307 {
308     if (!m_windowShell->isContextInitialized())
309         return;
310     v8::HandleScope handleScope(m_isolate);
311     v8::Local<v8::Context> v8Context = m_windowShell->context();
312     v8Context->AllowCodeGenerationFromStrings(false);
313     v8Context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, errorMessage));
314 }
315
316 PassRefPtr<SharedPersistent<v8::Object> > ScriptController::createPluginWrapper(Widget* widget)
317 {
318     ASSERT(widget);
319
320     if (!widget->isPluginView())
321         return 0;
322
323     NPObject* npObject = toPluginView(widget)->scriptableObject();
324     if (!npObject)
325         return 0;
326
327     // Frame Memory Management for NPObjects
328     // -------------------------------------
329     // NPObjects are treated differently than other objects wrapped by JS.
330     // NPObjects can be created either by the browser (e.g. the main
331     // window object) or by the plugin (the main plugin object
332     // for a HTMLEmbedElement). Further, unlike most DOM Objects, the frame
333     // is especially careful to ensure NPObjects terminate at frame teardown because
334     // if a plugin leaks a reference, it could leak its objects (or the browser's objects).
335     //
336     // The Frame maintains a list of plugin objects (m_pluginObjects)
337     // which it can use to quickly find the wrapped embed object.
338     //
339     // Inside the NPRuntime, we've added a few methods for registering
340     // wrapped NPObjects. The purpose of the registration is because
341     // javascript garbage collection is non-deterministic, yet we need to
342     // be able to tear down the plugin objects immediately. When an object
343     // is registered, javascript can use it. When the object is destroyed,
344     // or when the object's "owning" object is destroyed, the object will
345     // be un-registered, and the javascript engine must not use it.
346     //
347     // Inside the javascript engine, the engine can keep a reference to the
348     // NPObject as part of its wrapper. However, before accessing the object
349     // it must consult the _NPN_Registry.
350
351     v8::Local<v8::Object> wrapper = createV8ObjectForNPObject(npObject, 0, m_isolate);
352
353     // Track the plugin object. We've been given a reference to the object.
354     m_pluginObjects.set(widget, npObject);
355
356     return SharedPersistent<v8::Object>::create(wrapper, m_isolate);
357 }
358
359 void ScriptController::cleanupScriptObjectsForPlugin(Widget* nativeHandle)
360 {
361     PluginObjectMap::iterator it = m_pluginObjects.find(nativeHandle);
362     if (it == m_pluginObjects.end())
363         return;
364     _NPN_UnregisterObject(it->value);
365     _NPN_ReleaseObject(it->value);
366     m_pluginObjects.remove(it);
367 }
368
369 V8Extensions& ScriptController::registeredExtensions()
370 {
371     DEFINE_STATIC_LOCAL(V8Extensions, extensions, ());
372     return extensions;
373 }
374
375 void ScriptController::registerExtensionIfNeeded(v8::Extension* extension)
376 {
377     const V8Extensions& extensions = registeredExtensions();
378     for (size_t i = 0; i < extensions.size(); ++i) {
379         if (extensions[i] == extension)
380             return;
381     }
382     v8::RegisterExtension(extension);
383     registeredExtensions().append(extension);
384 }
385
386 static NPObject* createNoScriptObject()
387 {
388     notImplemented();
389     return 0;
390 }
391
392 static NPObject* createScriptObject(Frame* frame, v8::Isolate* isolate)
393 {
394     v8::HandleScope handleScope(isolate);
395     v8::Handle<v8::Context> v8Context = toV8Context(isolate, frame, DOMWrapperWorld::mainWorld());
396     if (v8Context.IsEmpty())
397         return createNoScriptObject();
398
399     v8::Context::Scope scope(v8Context);
400     DOMWindow* window = frame->domWindow();
401     v8::Handle<v8::Value> global = toV8(window, v8::Handle<v8::Object>(), v8Context->GetIsolate());
402     ASSERT(global->IsObject());
403
404     return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(global), window, isolate);
405 }
406
407 NPObject* ScriptController::windowScriptNPObject()
408 {
409     if (m_windowScriptNPObject)
410         return m_windowScriptNPObject;
411
412     if (canExecuteScripts(NotAboutToExecuteScript)) {
413         // JavaScript is enabled, so there is a JavaScript window object.
414         // Return an NPObject bound to the window object.
415         m_windowScriptNPObject = createScriptObject(m_frame, m_isolate);
416         _NPN_RegisterObject(m_windowScriptNPObject, 0);
417     } else {
418         // JavaScript is not enabled, so we cannot bind the NPObject to the
419         // JavaScript window object. Instead, we create an NPObject of a
420         // different class, one which is not bound to a JavaScript object.
421         m_windowScriptNPObject = createNoScriptObject();
422     }
423     return m_windowScriptNPObject;
424 }
425
426 NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin)
427 {
428     // Can't create NPObjects when JavaScript is disabled.
429     if (!canExecuteScripts(NotAboutToExecuteScript))
430         return createNoScriptObject();
431
432     v8::HandleScope handleScope(m_isolate);
433     v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, m_frame, DOMWrapperWorld::mainWorld());
434     if (v8Context.IsEmpty())
435         return createNoScriptObject();
436     v8::Context::Scope scope(v8Context);
437
438     DOMWindow* window = m_frame->domWindow();
439     v8::Handle<v8::Value> v8plugin = toV8(plugin, v8::Handle<v8::Object>(), v8Context->GetIsolate());
440     if (!v8plugin->IsObject())
441         return createNoScriptObject();
442
443     return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(v8plugin), window, v8Context->GetIsolate());
444 }
445
446 void ScriptController::clearWindowShell()
447 {
448     double start = currentTime();
449     // V8 binding expects ScriptController::clearWindowShell only be called
450     // when a frame is loading a new page. This creates a new context for the new page.
451     m_windowShell->clearForNavigation();
452     for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
453         iter->value->clearForNavigation();
454     clearScriptObjects();
455     V8GCController::hintForCollectGarbage();
456     blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearWindowShell", (currentTime() - start) * 1000, 0, 10000, 50);
457 }
458
459 void ScriptController::setCaptureCallStackForUncaughtExceptions(bool value)
460 {
461     v8::V8::SetCaptureStackTraceForUncaughtExceptions(value, ScriptCallStack::maxCallStackSizeToCapture, stackTraceOptions);
462 }
463
464 void ScriptController::collectIsolatedContexts(Vector<std::pair<ScriptState*, SecurityOrigin*> >& result)
465 {
466     v8::HandleScope handleScope(m_isolate);
467     for (IsolatedWorldMap::iterator it = m_isolatedWorlds.begin(); it != m_isolatedWorlds.end(); ++it) {
468         V8WindowShell* isolatedWorldShell = it->value.get();
469         SecurityOrigin* origin = isolatedWorldShell->world()->isolatedWorldSecurityOrigin();
470         if (!origin)
471             continue;
472         v8::Local<v8::Context> v8Context = isolatedWorldShell->context();
473         if (v8Context.IsEmpty())
474             continue;
475         ScriptState* scriptState = ScriptState::forContext(v8Context);
476         result.append(std::pair<ScriptState*, SecurityOrigin*>(scriptState, origin));
477     }
478 }
479
480 bool ScriptController::setContextDebugId(int debugId)
481 {
482     ASSERT(debugId > 0);
483     if (!m_windowShell->isContextInitialized())
484         return false;
485     v8::HandleScope scope(m_isolate);
486     v8::Local<v8::Context> context = m_windowShell->context();
487     return V8PerContextDebugData::setContextDebugData(context, "page", debugId);
488 }
489
490 int ScriptController::contextDebugId(v8::Handle<v8::Context> context)
491 {
492     return V8PerContextDebugData::contextDebugId(context);
493 }
494
495 void ScriptController::updateDocument()
496 {
497     // For an uninitialized main window shell, do not incur the cost of context initialization during FrameLoader::init().
498     if ((!m_windowShell->isContextInitialized() || !m_windowShell->isGlobalInitialized()) && m_frame->loader().stateMachine()->creatingInitialEmptyDocument())
499         return;
500
501     if (!initializeMainWorld())
502         windowShell(DOMWrapperWorld::mainWorld())->updateDocument();
503 }
504
505 void ScriptController::namedItemAdded(HTMLDocument* doc, const AtomicString& name)
506 {
507     windowShell(DOMWrapperWorld::mainWorld())->namedItemAdded(doc, name);
508 }
509
510 void ScriptController::namedItemRemoved(HTMLDocument* doc, const AtomicString& name)
511 {
512     windowShell(DOMWrapperWorld::mainWorld())->namedItemRemoved(doc, name);
513 }
514
515 bool ScriptController::canExecuteScripts(ReasonForCallingCanExecuteScripts reason)
516 {
517     if (m_frame->document() && m_frame->document()->isSandboxed(SandboxScripts)) {
518         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
519         if (reason == AboutToExecuteScript)
520             m_frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked script execution in '" + m_frame->document()->url().elidedString() + "' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.");
521         return false;
522     }
523
524     if (m_frame->document() && m_frame->document()->isViewSource()) {
525         ASSERT(m_frame->document()->securityOrigin()->isUnique());
526         return true;
527     }
528
529     Settings* settings = m_frame->settings();
530     const bool allowed = m_frame->loader().client()->allowScript(settings && settings->scriptEnabled());
531     if (!allowed && reason == AboutToExecuteScript)
532         m_frame->loader().client()->didNotAllowScript();
533     return allowed;
534 }
535
536 bool ScriptController::executeScriptIfJavaScriptURL(const KURL& url)
537 {
538     if (!protocolIsJavaScript(url))
539         return false;
540
541     if (!m_frame->page()
542         || !m_frame->document()->contentSecurityPolicy()->allowJavaScriptURLs(m_frame->document()->url(), eventHandlerPosition().m_line))
543         return true;
544
545     // We need to hold onto the Frame here because executing script can
546     // destroy the frame.
547     RefPtr<Frame> protector(m_frame);
548     RefPtr<Document> ownerDocument(m_frame->document());
549
550     const int javascriptSchemeLength = sizeof("javascript:") - 1;
551
552     bool locationChangeBefore = m_frame->navigationScheduler().locationChangePending();
553
554     String decodedURL = decodeURLEscapeSequences(url.string());
555     ScriptValue result = evaluateScriptInMainWorld(ScriptSourceCode(decodedURL.substring(javascriptSchemeLength)), NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
556
557     // If executing script caused this frame to be removed from the page, we
558     // don't want to try to replace its document!
559     if (!m_frame->page())
560         return true;
561
562     String scriptResult;
563     if (!result.getString(scriptResult))
564         return true;
565
566     // We're still in a frame, so there should be a DocumentLoader.
567     ASSERT(m_frame->document()->loader());
568
569     if (!locationChangeBefore && m_frame->navigationScheduler().locationChangePending())
570         return true;
571
572     // DocumentWriter::replaceDocument can cause the DocumentLoader to get deref'ed and possible destroyed,
573     // so protect it with a RefPtr.
574     if (RefPtr<DocumentLoader> loader = m_frame->document()->loader()) {
575         UseCounter::count(*m_frame->document(), UseCounter::ReplaceDocumentViaJavaScriptURL);
576         loader->replaceDocument(scriptResult, ownerDocument.get());
577     }
578     return true;
579 }
580
581 void ScriptController::executeScriptInMainWorld(const String& script, ExecuteScriptPolicy policy)
582 {
583     evaluateScriptInMainWorld(ScriptSourceCode(script), NotSharableCrossOrigin, policy);
584 }
585
586 void ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus)
587 {
588     evaluateScriptInMainWorld(sourceCode, corsStatus, DoNotExecuteScriptWhenScriptsDisabled);
589 }
590
591 ScriptValue ScriptController::executeScriptInMainWorldAndReturnValue(const ScriptSourceCode& sourceCode)
592 {
593     return evaluateScriptInMainWorld(sourceCode, NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
594 }
595
596 ScriptValue ScriptController::evaluateScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus, ExecuteScriptPolicy policy)
597 {
598     if (policy == DoNotExecuteScriptWhenScriptsDisabled && !canExecuteScripts(AboutToExecuteScript))
599         return ScriptValue();
600
601     String sourceURL = sourceCode.url();
602     const String* savedSourceURL = m_sourceURL;
603     m_sourceURL = &sourceURL;
604
605     v8::HandleScope handleScope(m_isolate);
606     v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, m_frame, DOMWrapperWorld::mainWorld());
607     if (v8Context.IsEmpty())
608         return ScriptValue();
609
610     RefPtr<Frame> protect(m_frame);
611     if (m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument())
612         m_frame->loader().didAccessInitialDocument();
613
614     OwnPtr<ScriptSourceCode> maybeProcessedSourceCode =  InspectorInstrumentation::preprocess(m_frame, sourceCode);
615     const ScriptSourceCode& sourceCodeToCompile = maybeProcessedSourceCode ? *maybeProcessedSourceCode : sourceCode;
616
617     v8::Local<v8::Value> object = executeScriptAndReturnValue(v8Context, sourceCodeToCompile, corsStatus);
618     m_sourceURL = savedSourceURL;
619
620     if (object.IsEmpty())
621         return ScriptValue();
622
623     return ScriptValue(object, m_isolate);
624 }
625
626 void ScriptController::executeScriptInIsolatedWorld(int worldID, const Vector<ScriptSourceCode>& sources, int extensionGroup, Vector<ScriptValue>* results)
627 {
628     ASSERT(worldID > 0);
629
630     v8::HandleScope handleScope(m_isolate);
631     v8::Local<v8::Array> v8Results;
632     {
633         v8::EscapableHandleScope evaluateHandleScope(m_isolate);
634         RefPtr<DOMWrapperWorld> world = DOMWrapperWorld::ensureIsolatedWorld(worldID, extensionGroup);
635         V8WindowShell* isolatedWorldShell = windowShell(world.get());
636
637         if (!isolatedWorldShell->isContextInitialized())
638             return;
639
640         v8::Local<v8::Context> context = isolatedWorldShell->context();
641         v8::Context::Scope contextScope(context);
642         v8::Local<v8::Array> resultArray = v8::Array::New(m_isolate, sources.size());
643
644         for (size_t i = 0; i < sources.size(); ++i) {
645             v8::Local<v8::Value> evaluationResult = executeScriptAndReturnValue(context, sources[i]);
646             if (evaluationResult.IsEmpty())
647                 evaluationResult = v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
648             resultArray->Set(i, evaluationResult);
649         }
650
651         v8Results = evaluateHandleScope.Escape(resultArray);
652     }
653
654     if (results && !v8Results.IsEmpty()) {
655         for (size_t i = 0; i < v8Results->Length(); ++i)
656             results->append(ScriptValue(v8Results->Get(i), m_isolate));
657     }
658 }
659
660 } // namespace WebCore