Upstream version 7.36.149.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/frame/DOMWindow.h"
57 #include "core/frame/LocalFrame.h"
58 #include "core/frame/Settings.h"
59 #include "core/frame/csp/ContentSecurityPolicy.h"
60 #include "core/html/HTMLPlugInElement.h"
61 #include "core/inspector/InspectorInstrumentation.h"
62 #include "core/inspector/InspectorTraceEvents.h"
63 #include "core/inspector/ScriptCallStack.h"
64 #include "core/loader/DocumentLoader.h"
65 #include "core/loader/FrameLoader.h"
66 #include "core/loader/FrameLoaderClient.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(LocalFrame *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(LocalFrame* 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::clearForClose()
127 {
128     double start = currentTime();
129     m_windowShell->clearForClose();
130     for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
131         iter->value->clearForClose();
132     blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearForClose", (currentTime() - start) * 1000, 0, 10000, 50);
133 }
134
135 void ScriptController::updateSecurityOrigin(SecurityOrigin* origin)
136 {
137     m_windowShell->updateSecurityOrigin(origin);
138 }
139
140 v8::Local<v8::Value> ScriptController::callFunction(v8::Handle<v8::Function> function, v8::Handle<v8::Value> receiver, int argc, v8::Handle<v8::Value> info[])
141 {
142     // Keep LocalFrame (and therefore ScriptController) alive.
143     RefPtr<LocalFrame> protect(m_frame);
144     return ScriptController::callFunction(m_frame->document(), function, receiver, argc, info, m_isolate);
145 }
146
147 v8::Local<v8::Value> ScriptController::callFunction(ExecutionContext* context, v8::Handle<v8::Function> function, v8::Handle<v8::Value> receiver, int argc, v8::Handle<v8::Value> info[], v8::Isolate* isolate)
148 {
149     TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "FunctionCall", "data", devToolsTraceEventData(context, function, isolate));
150     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
151     // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
152     InspectorInstrumentationCookie cookie;
153     if (InspectorInstrumentation::timelineAgentEnabled(context)) {
154         int scriptId = 0;
155         String resourceName;
156         int lineNumber = 1;
157         GetDevToolsFunctionInfo(function, isolate, scriptId, resourceName, lineNumber);
158         cookie = InspectorInstrumentation::willCallFunction(context, scriptId, resourceName, lineNumber);
159     }
160
161     v8::Local<v8::Value> result = V8ScriptRunner::callFunction(function, context, receiver, argc, info, isolate);
162
163     InspectorInstrumentation::didCallFunction(cookie);
164     return result;
165 }
166
167 v8::Local<v8::Value> ScriptController::executeScriptAndReturnValue(v8::Handle<v8::Context> context, const ScriptSourceCode& source, AccessControlStatus corsStatus)
168 {
169     TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EvaluateScript", "data", InspectorEvaluateScriptEvent::data(m_frame, source.url().string(), source.startLine()));
170     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
171     // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
172     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willEvaluateScript(m_frame, source.url().string(), source.startLine());
173
174     v8::Local<v8::Value> result;
175     {
176         // Isolate exceptions that occur when compiling and executing
177         // the code. These exceptions should not interfere with
178         // javascript code we might evaluate from C++ when returning
179         // from here.
180         v8::TryCatch tryCatch;
181         tryCatch.SetVerbose(true);
182
183         v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(source, m_isolate, corsStatus);
184
185         // Keep LocalFrame (and therefore ScriptController) alive.
186         RefPtr<LocalFrame> protect(m_frame);
187         result = V8ScriptRunner::runCompiledScript(script, m_frame->document(), m_isolate);
188         ASSERT(!tryCatch.HasCaught() || result.IsEmpty());
189     }
190
191     InspectorInstrumentation::didEvaluateScript(cookie);
192     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data());
193
194     return result;
195 }
196
197 bool ScriptController::initializeMainWorld()
198 {
199     if (m_windowShell->isContextInitialized())
200         return false;
201     return windowShell(DOMWrapperWorld::mainWorld())->isContextInitialized();
202 }
203
204 V8WindowShell* ScriptController::existingWindowShell(DOMWrapperWorld& world)
205 {
206     if (world.isMainWorld())
207         return m_windowShell->isContextInitialized() ? m_windowShell.get() : 0;
208
209     IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world.worldId());
210     if (iter == m_isolatedWorlds.end())
211         return 0;
212     return iter->value->isContextInitialized() ? iter->value.get() : 0;
213 }
214
215 V8WindowShell* ScriptController::windowShell(DOMWrapperWorld& world)
216 {
217     V8WindowShell* shell = 0;
218     if (world.isMainWorld())
219         shell = m_windowShell.get();
220     else {
221         IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world.worldId());
222         if (iter != m_isolatedWorlds.end())
223             shell = iter->value.get();
224         else {
225             OwnPtr<V8WindowShell> isolatedWorldShell = V8WindowShell::create(m_frame, world, m_isolate);
226             shell = isolatedWorldShell.get();
227             m_isolatedWorlds.set(world.worldId(), isolatedWorldShell.release());
228         }
229     }
230     if (!shell->isContextInitialized() && shell->initializeIfNeeded() && world.isMainWorld())
231         m_frame->loader().dispatchDidClearWindowObjectInMainWorld();
232     return shell;
233 }
234
235 bool ScriptController::shouldBypassMainWorldContentSecurityPolicy()
236 {
237     v8::Handle<v8::Context> context = m_isolate->GetCurrentContext();
238     if (context.IsEmpty() || !toDOMWindow(context))
239         return false;
240     DOMWrapperWorld& world = DOMWrapperWorld::current(m_isolate);
241     return world.isIsolatedWorld() ? world.isolatedWorldHasContentSecurityPolicy() : false;
242 }
243
244 TextPosition ScriptController::eventHandlerPosition() const
245 {
246     ScriptableDocumentParser* parser = m_frame->document()->scriptableDocumentParser();
247     if (parser)
248         return parser->textPosition();
249     return TextPosition::minimumPosition();
250 }
251
252 // Create a V8 object with an interceptor of NPObjectPropertyGetter.
253 void ScriptController::bindToWindowObject(LocalFrame* frame, const String& key, NPObject* object)
254 {
255     v8::HandleScope handleScope(m_isolate);
256
257     v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, frame, DOMWrapperWorld::mainWorld());
258     if (v8Context.IsEmpty())
259         return;
260
261     v8::Context::Scope scope(v8Context);
262
263     v8::Handle<v8::Object> value = createV8ObjectForNPObject(object, 0, m_isolate);
264
265     // Attach to the global object.
266     v8::Handle<v8::Object> global = v8Context->Global();
267     global->Set(v8String(m_isolate, key), value);
268 }
269
270 void ScriptController::enableEval()
271 {
272     if (!m_windowShell->isContextInitialized())
273         return;
274     v8::HandleScope handleScope(m_isolate);
275     m_windowShell->context()->AllowCodeGenerationFromStrings(true);
276 }
277
278 void ScriptController::disableEval(const String& errorMessage)
279 {
280     if (!m_windowShell->isContextInitialized())
281         return;
282     v8::HandleScope handleScope(m_isolate);
283     v8::Local<v8::Context> v8Context = m_windowShell->context();
284     v8Context->AllowCodeGenerationFromStrings(false);
285     v8Context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, errorMessage));
286 }
287
288 PassRefPtr<SharedPersistent<v8::Object> > ScriptController::createPluginWrapper(Widget* widget)
289 {
290     ASSERT(widget);
291
292     if (!widget->isPluginView())
293         return nullptr;
294
295     NPObject* npObject = toPluginView(widget)->scriptableObject();
296     if (!npObject)
297         return nullptr;
298
299     // LocalFrame Memory Management for NPObjects
300     // -------------------------------------
301     // NPObjects are treated differently than other objects wrapped by JS.
302     // NPObjects can be created either by the browser (e.g. the main
303     // window object) or by the plugin (the main plugin object
304     // for a HTMLEmbedElement). Further, unlike most DOM Objects, the frame
305     // is especially careful to ensure NPObjects terminate at frame teardown because
306     // if a plugin leaks a reference, it could leak its objects (or the browser's objects).
307     //
308     // The LocalFrame maintains a list of plugin objects (m_pluginObjects)
309     // which it can use to quickly find the wrapped embed object.
310     //
311     // Inside the NPRuntime, we've added a few methods for registering
312     // wrapped NPObjects. The purpose of the registration is because
313     // javascript garbage collection is non-deterministic, yet we need to
314     // be able to tear down the plugin objects immediately. When an object
315     // is registered, javascript can use it. When the object is destroyed,
316     // or when the object's "owning" object is destroyed, the object will
317     // be un-registered, and the javascript engine must not use it.
318     //
319     // Inside the javascript engine, the engine can keep a reference to the
320     // NPObject as part of its wrapper. However, before accessing the object
321     // it must consult the _NPN_Registry.
322
323     v8::Local<v8::Object> wrapper = createV8ObjectForNPObject(npObject, 0, m_isolate);
324
325     // Track the plugin object. We've been given a reference to the object.
326     m_pluginObjects.set(widget, npObject);
327
328     return SharedPersistent<v8::Object>::create(wrapper, m_isolate);
329 }
330
331 void ScriptController::cleanupScriptObjectsForPlugin(Widget* nativeHandle)
332 {
333     PluginObjectMap::iterator it = m_pluginObjects.find(nativeHandle);
334     if (it == m_pluginObjects.end())
335         return;
336     _NPN_UnregisterObject(it->value);
337     _NPN_ReleaseObject(it->value);
338     m_pluginObjects.remove(it);
339 }
340
341 V8Extensions& ScriptController::registeredExtensions()
342 {
343     DEFINE_STATIC_LOCAL(V8Extensions, extensions, ());
344     return extensions;
345 }
346
347 void ScriptController::registerExtensionIfNeeded(v8::Extension* extension)
348 {
349     const V8Extensions& extensions = registeredExtensions();
350     for (size_t i = 0; i < extensions.size(); ++i) {
351         if (extensions[i] == extension)
352             return;
353     }
354     v8::RegisterExtension(extension);
355     registeredExtensions().append(extension);
356 }
357
358 static NPObject* createNoScriptObject()
359 {
360     notImplemented();
361     return 0;
362 }
363
364 static NPObject* createScriptObject(LocalFrame* frame, v8::Isolate* isolate)
365 {
366     v8::HandleScope handleScope(isolate);
367     v8::Handle<v8::Context> v8Context = toV8Context(isolate, frame, DOMWrapperWorld::mainWorld());
368     if (v8Context.IsEmpty())
369         return createNoScriptObject();
370
371     v8::Context::Scope scope(v8Context);
372     DOMWindow* window = frame->domWindow();
373     v8::Handle<v8::Value> global = toV8(window, v8::Handle<v8::Object>(), v8Context->GetIsolate());
374     ASSERT(global->IsObject());
375
376     return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(global), window, isolate);
377 }
378
379 NPObject* ScriptController::windowScriptNPObject()
380 {
381     if (m_windowScriptNPObject)
382         return m_windowScriptNPObject;
383
384     if (canExecuteScripts(NotAboutToExecuteScript)) {
385         // JavaScript is enabled, so there is a JavaScript window object.
386         // Return an NPObject bound to the window object.
387         m_windowScriptNPObject = createScriptObject(m_frame, m_isolate);
388         _NPN_RegisterObject(m_windowScriptNPObject, 0);
389     } else {
390         // JavaScript is not enabled, so we cannot bind the NPObject to the
391         // JavaScript window object. Instead, we create an NPObject of a
392         // different class, one which is not bound to a JavaScript object.
393         m_windowScriptNPObject = createNoScriptObject();
394     }
395     return m_windowScriptNPObject;
396 }
397
398 NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin)
399 {
400     // Can't create NPObjects when JavaScript is disabled.
401     if (!canExecuteScripts(NotAboutToExecuteScript))
402         return createNoScriptObject();
403
404     v8::HandleScope handleScope(m_isolate);
405     v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, m_frame, DOMWrapperWorld::mainWorld());
406     if (v8Context.IsEmpty())
407         return createNoScriptObject();
408     v8::Context::Scope scope(v8Context);
409
410     DOMWindow* window = m_frame->domWindow();
411     v8::Handle<v8::Value> v8plugin = toV8(plugin, v8::Handle<v8::Object>(), v8Context->GetIsolate());
412     if (!v8plugin->IsObject())
413         return createNoScriptObject();
414
415     return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(v8plugin), window, v8Context->GetIsolate());
416 }
417
418 void ScriptController::clearWindowShell()
419 {
420     double start = currentTime();
421     // V8 binding expects ScriptController::clearWindowShell only be called
422     // when a frame is loading a new page. This creates a new context for the new page.
423     m_windowShell->clearForNavigation();
424     for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
425         iter->value->clearForNavigation();
426     clearScriptObjects();
427     blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearWindowShell", (currentTime() - start) * 1000, 0, 10000, 50);
428 }
429
430 void ScriptController::setCaptureCallStackForUncaughtExceptions(bool value)
431 {
432     v8::V8::SetCaptureStackTraceForUncaughtExceptions(value, ScriptCallStack::maxCallStackSizeToCapture, stackTraceOptions);
433 }
434
435 void ScriptController::collectIsolatedContexts(Vector<std::pair<ScriptState*, SecurityOrigin*> >& result)
436 {
437     v8::HandleScope handleScope(m_isolate);
438     for (IsolatedWorldMap::iterator it = m_isolatedWorlds.begin(); it != m_isolatedWorlds.end(); ++it) {
439         V8WindowShell* isolatedWorldShell = it->value.get();
440         SecurityOrigin* origin = isolatedWorldShell->world().isolatedWorldSecurityOrigin();
441         if (!origin)
442             continue;
443         v8::Local<v8::Context> v8Context = isolatedWorldShell->context();
444         if (v8Context.IsEmpty())
445             continue;
446         ScriptState* scriptState = ScriptState::from(v8Context);
447         result.append(std::pair<ScriptState*, SecurityOrigin*>(scriptState, origin));
448     }
449 }
450
451 bool ScriptController::setContextDebugId(int debugId)
452 {
453     ASSERT(debugId > 0);
454     if (!m_windowShell->isContextInitialized())
455         return false;
456     v8::HandleScope scope(m_isolate);
457     v8::Local<v8::Context> context = m_windowShell->context();
458     return V8PerContextDebugData::setContextDebugData(context, "page", debugId);
459 }
460
461 int ScriptController::contextDebugId(v8::Handle<v8::Context> context)
462 {
463     return V8PerContextDebugData::contextDebugId(context);
464 }
465
466 void ScriptController::updateDocument()
467 {
468     // For an uninitialized main window shell, do not incur the cost of context initialization during FrameLoader::init().
469     if ((!m_windowShell->isContextInitialized() || !m_windowShell->isGlobalInitialized()) && m_frame->loader().stateMachine()->creatingInitialEmptyDocument())
470         return;
471
472     if (!initializeMainWorld())
473         windowShell(DOMWrapperWorld::mainWorld())->updateDocument();
474 }
475
476 void ScriptController::namedItemAdded(HTMLDocument* doc, const AtomicString& name)
477 {
478     windowShell(DOMWrapperWorld::mainWorld())->namedItemAdded(doc, name);
479 }
480
481 void ScriptController::namedItemRemoved(HTMLDocument* doc, const AtomicString& name)
482 {
483     windowShell(DOMWrapperWorld::mainWorld())->namedItemRemoved(doc, name);
484 }
485
486 bool ScriptController::canExecuteScripts(ReasonForCallingCanExecuteScripts reason)
487 {
488     if (m_frame->document() && m_frame->document()->isSandboxed(SandboxScripts)) {
489         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
490         if (reason == AboutToExecuteScript)
491             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.");
492         return false;
493     }
494
495     if (m_frame->document() && m_frame->document()->isViewSource()) {
496         ASSERT(m_frame->document()->securityOrigin()->isUnique());
497         return true;
498     }
499
500     Settings* settings = m_frame->settings();
501     const bool allowed = m_frame->loader().client()->allowScript(settings && settings->scriptEnabled());
502     if (!allowed && reason == AboutToExecuteScript)
503         m_frame->loader().client()->didNotAllowScript();
504     return allowed;
505 }
506
507 bool ScriptController::executeScriptIfJavaScriptURL(const KURL& url)
508 {
509     if (!protocolIsJavaScript(url))
510         return false;
511
512     if (!m_frame->page()
513         || !m_frame->document()->contentSecurityPolicy()->allowJavaScriptURLs(m_frame->document()->url(), eventHandlerPosition().m_line))
514         return true;
515
516     // We need to hold onto the LocalFrame here because executing script can
517     // destroy the frame.
518     RefPtr<LocalFrame> protector(m_frame);
519     RefPtr<Document> ownerDocument(m_frame->document());
520
521     const int javascriptSchemeLength = sizeof("javascript:") - 1;
522
523     bool locationChangeBefore = m_frame->navigationScheduler().locationChangePending();
524
525     String decodedURL = decodeURLEscapeSequences(url.string());
526     ScriptValue result = evaluateScriptInMainWorld(ScriptSourceCode(decodedURL.substring(javascriptSchemeLength)), NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
527
528     // If executing script caused this frame to be removed from the page, we
529     // don't want to try to replace its document!
530     if (!m_frame->page())
531         return true;
532
533     String scriptResult;
534     if (!result.toString(scriptResult))
535         return true;
536
537     // We're still in a frame, so there should be a DocumentLoader.
538     ASSERT(m_frame->document()->loader());
539
540     if (!locationChangeBefore && m_frame->navigationScheduler().locationChangePending())
541         return true;
542
543     // DocumentWriter::replaceDocument can cause the DocumentLoader to get deref'ed and possible destroyed,
544     // so protect it with a RefPtr.
545     if (RefPtr<DocumentLoader> loader = m_frame->document()->loader()) {
546         UseCounter::count(*m_frame->document(), UseCounter::ReplaceDocumentViaJavaScriptURL);
547         loader->replaceDocument(scriptResult, ownerDocument.get());
548     }
549     return true;
550 }
551
552 void ScriptController::executeScriptInMainWorld(const String& script, ExecuteScriptPolicy policy)
553 {
554     evaluateScriptInMainWorld(ScriptSourceCode(script), NotSharableCrossOrigin, policy);
555 }
556
557 void ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus)
558 {
559     evaluateScriptInMainWorld(sourceCode, corsStatus, DoNotExecuteScriptWhenScriptsDisabled);
560 }
561
562 ScriptValue ScriptController::executeScriptInMainWorldAndReturnValue(const ScriptSourceCode& sourceCode)
563 {
564     return evaluateScriptInMainWorld(sourceCode, NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
565 }
566
567 ScriptValue ScriptController::evaluateScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus, ExecuteScriptPolicy policy)
568 {
569     if (policy == DoNotExecuteScriptWhenScriptsDisabled && !canExecuteScripts(AboutToExecuteScript))
570         return ScriptValue();
571
572     String sourceURL = sourceCode.url();
573     const String* savedSourceURL = m_sourceURL;
574     m_sourceURL = &sourceURL;
575
576     v8::HandleScope handleScope(m_isolate);
577     v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, m_frame, DOMWrapperWorld::mainWorld());
578     if (v8Context.IsEmpty())
579         return ScriptValue();
580     v8::Context::Scope scope(v8Context);
581
582     RefPtr<LocalFrame> protect(m_frame);
583     if (m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument())
584         m_frame->loader().didAccessInitialDocument();
585
586     OwnPtr<ScriptSourceCode> maybeProcessedSourceCode =  InspectorInstrumentation::preprocess(m_frame, sourceCode);
587     const ScriptSourceCode& sourceCodeToCompile = maybeProcessedSourceCode ? *maybeProcessedSourceCode : sourceCode;
588
589     v8::Local<v8::Value> object = executeScriptAndReturnValue(v8Context, sourceCodeToCompile, corsStatus);
590     m_sourceURL = savedSourceURL;
591
592     if (object.IsEmpty())
593         return ScriptValue();
594
595     return ScriptValue(ScriptState::from(v8Context), object);
596 }
597
598 void ScriptController::executeScriptInIsolatedWorld(int worldID, const Vector<ScriptSourceCode>& sources, int extensionGroup, Vector<ScriptValue>* results)
599 {
600     ASSERT(worldID > 0);
601
602     v8::HandleScope handleScope(m_isolate);
603     RefPtr<DOMWrapperWorld> world = DOMWrapperWorld::ensureIsolatedWorld(worldID, extensionGroup);
604     V8WindowShell* isolatedWorldShell = windowShell(*world);
605     if (!isolatedWorldShell->isContextInitialized())
606         return;
607
608     v8::Local<v8::Context> context = isolatedWorldShell->context();
609     v8::Context::Scope contextScope(context);
610     v8::Local<v8::Array> resultArray = v8::Array::New(m_isolate, sources.size());
611
612     for (size_t i = 0; i < sources.size(); ++i) {
613         v8::Local<v8::Value> evaluationResult = executeScriptAndReturnValue(context, sources[i]);
614         if (evaluationResult.IsEmpty())
615             evaluationResult = v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
616         resultArray->Set(i, evaluationResult);
617     }
618
619     if (results) {
620         for (size_t i = 0; i < resultArray->Length(); ++i)
621             results->append(ScriptValue(ScriptState::from(context), resultArray->Get(i)));
622     }
623 }
624
625 } // namespace WebCore