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