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