• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "bindings/core/v8/V8Event.h"
36 #include "bindings/core/v8/V8HTMLElement.h"
37 #include "bindings/core/v8/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/LocalDOMWindow.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 
canAccessFromCurrentOrigin(LocalFrame * frame)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 
ScriptController(LocalFrame * frame)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 
~ScriptController()100 ScriptController::~ScriptController()
101 {
102     // V8WindowShell::clearForClose() must be invoked before destruction starts.
103     ASSERT(!m_windowShell->isContextInitialized());
104 }
105 
clearScriptObjects()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 
clearForClose()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 
updateSecurityOrigin(SecurityOrigin * origin)135 void ScriptController::updateSecurityOrigin(SecurityOrigin* origin)
136 {
137     m_windowShell->updateSecurityOrigin(origin);
138 }
139 
callFunction(v8::Handle<v8::Function> function,v8::Handle<v8::Value> receiver,int argc,v8::Handle<v8::Value> info[])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 
callFunction(ExecutionContext * context,v8::Handle<v8::Function> function,v8::Handle<v8::Value> receiver,int argc,v8::Handle<v8::Value> info[],v8::Isolate * isolate)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 
executeScriptAndReturnValue(v8::Handle<v8::Context> context,const ScriptSourceCode & source,AccessControlStatus corsStatus)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 
initializeMainWorld()197 bool ScriptController::initializeMainWorld()
198 {
199     if (m_windowShell->isContextInitialized())
200         return false;
201     return windowShell(DOMWrapperWorld::mainWorld())->isContextInitialized();
202 }
203 
existingWindowShell(DOMWrapperWorld & world)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 
windowShell(DOMWrapperWorld & world)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 
shouldBypassMainWorldContentSecurityPolicy()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 
eventHandlerPosition() const244 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.
bindToWindowObject(LocalFrame * frame,const String & key,NPObject * object)253 void ScriptController::bindToWindowObject(LocalFrame* frame, const String& key, NPObject* object)
254 {
255     ScriptState* scriptState = ScriptState::forMainWorld(frame);
256     if (scriptState->contextIsEmpty())
257         return;
258 
259     ScriptState::Scope scope(scriptState);
260     v8::Handle<v8::Object> value = createV8ObjectForNPObject(object, 0, m_isolate);
261 
262     // Attach to the global object.
263     scriptState->context()->Global()->Set(v8String(m_isolate, key), value);
264 }
265 
enableEval()266 void ScriptController::enableEval()
267 {
268     if (!m_windowShell->isContextInitialized())
269         return;
270     v8::HandleScope handleScope(m_isolate);
271     m_windowShell->context()->AllowCodeGenerationFromStrings(true);
272 }
273 
disableEval(const String & errorMessage)274 void ScriptController::disableEval(const String& errorMessage)
275 {
276     if (!m_windowShell->isContextInitialized())
277         return;
278     v8::HandleScope handleScope(m_isolate);
279     v8::Local<v8::Context> v8Context = m_windowShell->context();
280     v8Context->AllowCodeGenerationFromStrings(false);
281     v8Context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, errorMessage));
282 }
283 
createPluginWrapper(Widget * widget)284 PassRefPtr<SharedPersistent<v8::Object> > ScriptController::createPluginWrapper(Widget* widget)
285 {
286     ASSERT(widget);
287 
288     if (!widget->isPluginView())
289         return nullptr;
290 
291     NPObject* npObject = toPluginView(widget)->scriptableObject();
292     if (!npObject)
293         return nullptr;
294 
295     // LocalFrame Memory Management for NPObjects
296     // -------------------------------------
297     // NPObjects are treated differently than other objects wrapped by JS.
298     // NPObjects can be created either by the browser (e.g. the main
299     // window object) or by the plugin (the main plugin object
300     // for a HTMLEmbedElement). Further, unlike most DOM Objects, the frame
301     // is especially careful to ensure NPObjects terminate at frame teardown because
302     // if a plugin leaks a reference, it could leak its objects (or the browser's objects).
303     //
304     // The LocalFrame maintains a list of plugin objects (m_pluginObjects)
305     // which it can use to quickly find the wrapped embed object.
306     //
307     // Inside the NPRuntime, we've added a few methods for registering
308     // wrapped NPObjects. The purpose of the registration is because
309     // javascript garbage collection is non-deterministic, yet we need to
310     // be able to tear down the plugin objects immediately. When an object
311     // is registered, javascript can use it. When the object is destroyed,
312     // or when the object's "owning" object is destroyed, the object will
313     // be un-registered, and the javascript engine must not use it.
314     //
315     // Inside the javascript engine, the engine can keep a reference to the
316     // NPObject as part of its wrapper. However, before accessing the object
317     // it must consult the _NPN_Registry.
318 
319     v8::Local<v8::Object> wrapper = createV8ObjectForNPObject(npObject, 0, m_isolate);
320 
321     // Track the plugin object. We've been given a reference to the object.
322     m_pluginObjects.set(widget, npObject);
323 
324     return SharedPersistent<v8::Object>::create(wrapper, m_isolate);
325 }
326 
cleanupScriptObjectsForPlugin(Widget * nativeHandle)327 void ScriptController::cleanupScriptObjectsForPlugin(Widget* nativeHandle)
328 {
329     PluginObjectMap::iterator it = m_pluginObjects.find(nativeHandle);
330     if (it == m_pluginObjects.end())
331         return;
332     _NPN_UnregisterObject(it->value);
333     _NPN_ReleaseObject(it->value);
334     m_pluginObjects.remove(it);
335 }
336 
registeredExtensions()337 V8Extensions& ScriptController::registeredExtensions()
338 {
339     DEFINE_STATIC_LOCAL(V8Extensions, extensions, ());
340     return extensions;
341 }
342 
registerExtensionIfNeeded(v8::Extension * extension)343 void ScriptController::registerExtensionIfNeeded(v8::Extension* extension)
344 {
345     const V8Extensions& extensions = registeredExtensions();
346     for (size_t i = 0; i < extensions.size(); ++i) {
347         if (extensions[i] == extension)
348             return;
349     }
350     v8::RegisterExtension(extension);
351     registeredExtensions().append(extension);
352 }
353 
createNoScriptObject()354 static NPObject* createNoScriptObject()
355 {
356     notImplemented();
357     return 0;
358 }
359 
createScriptObject(LocalFrame * frame,v8::Isolate * isolate)360 static NPObject* createScriptObject(LocalFrame* frame, v8::Isolate* isolate)
361 {
362     ScriptState* scriptState = ScriptState::forMainWorld(frame);
363     if (scriptState->contextIsEmpty())
364         return createNoScriptObject();
365 
366     ScriptState::Scope scope(scriptState);
367     LocalDOMWindow* window = frame->domWindow();
368     v8::Handle<v8::Value> global = toV8(window, scriptState->context()->Global(), scriptState->isolate());
369     ASSERT(global->IsObject());
370     return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(global), window, isolate);
371 }
372 
windowScriptNPObject()373 NPObject* ScriptController::windowScriptNPObject()
374 {
375     if (m_windowScriptNPObject)
376         return m_windowScriptNPObject;
377 
378     if (canExecuteScripts(NotAboutToExecuteScript)) {
379         // JavaScript is enabled, so there is a JavaScript window object.
380         // Return an NPObject bound to the window object.
381         m_windowScriptNPObject = createScriptObject(m_frame, m_isolate);
382         _NPN_RegisterObject(m_windowScriptNPObject, 0);
383     } else {
384         // JavaScript is not enabled, so we cannot bind the NPObject to the
385         // JavaScript window object. Instead, we create an NPObject of a
386         // different class, one which is not bound to a JavaScript object.
387         m_windowScriptNPObject = createNoScriptObject();
388     }
389     return m_windowScriptNPObject;
390 }
391 
createScriptObjectForPluginElement(HTMLPlugInElement * plugin)392 NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin)
393 {
394     // Can't create NPObjects when JavaScript is disabled.
395     if (!canExecuteScripts(NotAboutToExecuteScript))
396         return createNoScriptObject();
397 
398     ScriptState* scriptState = ScriptState::forMainWorld(m_frame);
399     if (scriptState->contextIsEmpty())
400         return createNoScriptObject();
401 
402     ScriptState::Scope scope(scriptState);
403     LocalDOMWindow* window = m_frame->domWindow();
404     v8::Handle<v8::Value> v8plugin = toV8(plugin, scriptState->context()->Global(), scriptState->isolate());
405     if (!v8plugin->IsObject())
406         return createNoScriptObject();
407 
408     return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(v8plugin), window, scriptState->isolate());
409 }
410 
clearWindowShell()411 void ScriptController::clearWindowShell()
412 {
413     double start = currentTime();
414     // V8 binding expects ScriptController::clearWindowShell only be called
415     // when a frame is loading a new page. This creates a new context for the new page.
416     m_windowShell->clearForNavigation();
417     for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
418         iter->value->clearForNavigation();
419     clearScriptObjects();
420     blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearWindowShell", (currentTime() - start) * 1000, 0, 10000, 50);
421 }
422 
setCaptureCallStackForUncaughtExceptions(bool value)423 void ScriptController::setCaptureCallStackForUncaughtExceptions(bool value)
424 {
425     v8::V8::SetCaptureStackTraceForUncaughtExceptions(value, ScriptCallStack::maxCallStackSizeToCapture, stackTraceOptions);
426 }
427 
collectIsolatedContexts(Vector<std::pair<ScriptState *,SecurityOrigin * >> & result)428 void ScriptController::collectIsolatedContexts(Vector<std::pair<ScriptState*, SecurityOrigin*> >& result)
429 {
430     for (IsolatedWorldMap::iterator it = m_isolatedWorlds.begin(); it != m_isolatedWorlds.end(); ++it) {
431         V8WindowShell* isolatedWorldShell = it->value.get();
432         SecurityOrigin* origin = isolatedWorldShell->world().isolatedWorldSecurityOrigin();
433         if (!origin)
434             continue;
435         if (!isolatedWorldShell->isContextInitialized())
436             continue;
437         result.append(std::pair<ScriptState*, SecurityOrigin*>(isolatedWorldShell->scriptState(), origin));
438     }
439 }
440 
setContextDebugId(int debugId)441 bool ScriptController::setContextDebugId(int debugId)
442 {
443     ASSERT(debugId > 0);
444     if (!m_windowShell->isContextInitialized())
445         return false;
446     v8::HandleScope scope(m_isolate);
447     v8::Local<v8::Context> context = m_windowShell->context();
448     return V8PerContextDebugData::setContextDebugData(context, "page", debugId);
449 }
450 
contextDebugId(v8::Handle<v8::Context> context)451 int ScriptController::contextDebugId(v8::Handle<v8::Context> context)
452 {
453     return V8PerContextDebugData::contextDebugId(context);
454 }
455 
updateDocument()456 void ScriptController::updateDocument()
457 {
458     // For an uninitialized main window shell, do not incur the cost of context initialization.
459     if (!m_windowShell->isGlobalInitialized())
460         return;
461 
462     if (!initializeMainWorld())
463         windowShell(DOMWrapperWorld::mainWorld())->updateDocument();
464 }
465 
namedItemAdded(HTMLDocument * doc,const AtomicString & name)466 void ScriptController::namedItemAdded(HTMLDocument* doc, const AtomicString& name)
467 {
468     windowShell(DOMWrapperWorld::mainWorld())->namedItemAdded(doc, name);
469 }
470 
namedItemRemoved(HTMLDocument * doc,const AtomicString & name)471 void ScriptController::namedItemRemoved(HTMLDocument* doc, const AtomicString& name)
472 {
473     windowShell(DOMWrapperWorld::mainWorld())->namedItemRemoved(doc, name);
474 }
475 
canExecuteScripts(ReasonForCallingCanExecuteScripts reason)476 bool ScriptController::canExecuteScripts(ReasonForCallingCanExecuteScripts reason)
477 {
478     if (m_frame->document() && m_frame->document()->isSandboxed(SandboxScripts)) {
479         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
480         if (reason == AboutToExecuteScript)
481             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.");
482         return false;
483     }
484 
485     if (m_frame->document() && m_frame->document()->isViewSource()) {
486         ASSERT(m_frame->document()->securityOrigin()->isUnique());
487         return true;
488     }
489 
490     Settings* settings = m_frame->settings();
491     const bool allowed = m_frame->loader().client()->allowScript(settings && settings->scriptEnabled());
492     if (!allowed && reason == AboutToExecuteScript)
493         m_frame->loader().client()->didNotAllowScript();
494     return allowed;
495 }
496 
executeScriptIfJavaScriptURL(const KURL & url)497 bool ScriptController::executeScriptIfJavaScriptURL(const KURL& url)
498 {
499     if (!protocolIsJavaScript(url))
500         return false;
501 
502     if (!m_frame->page()
503         || !m_frame->document()->contentSecurityPolicy()->allowJavaScriptURLs(m_frame->document()->url(), eventHandlerPosition().m_line))
504         return true;
505 
506     // We need to hold onto the LocalFrame here because executing script can
507     // destroy the frame.
508     RefPtr<LocalFrame> protector(m_frame);
509     RefPtrWillBeRawPtr<Document> ownerDocument(m_frame->document());
510 
511     const int javascriptSchemeLength = sizeof("javascript:") - 1;
512 
513     bool locationChangeBefore = m_frame->navigationScheduler().locationChangePending();
514 
515     String decodedURL = decodeURLEscapeSequences(url.string());
516     v8::HandleScope handleScope(m_isolate);
517     v8::Local<v8::Value> result = evaluateScriptInMainWorld(ScriptSourceCode(decodedURL.substring(javascriptSchemeLength)), NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
518 
519     // If executing script caused this frame to be removed from the page, we
520     // don't want to try to replace its document!
521     if (!m_frame->page())
522         return true;
523 
524     if (result.IsEmpty() || !result->IsString())
525         return true;
526     String scriptResult = toCoreString(v8::Handle<v8::String>::Cast(result));
527 
528     // We're still in a frame, so there should be a DocumentLoader.
529     ASSERT(m_frame->document()->loader());
530     if (!locationChangeBefore && m_frame->navigationScheduler().locationChangePending())
531         return true;
532 
533     // DocumentWriter::replaceDocument can cause the DocumentLoader to get deref'ed and possible destroyed,
534     // so protect it with a RefPtr.
535     if (RefPtr<DocumentLoader> loader = m_frame->document()->loader()) {
536         UseCounter::count(*m_frame->document(), UseCounter::ReplaceDocumentViaJavaScriptURL);
537         loader->replaceDocument(scriptResult, ownerDocument.get());
538     }
539     return true;
540 }
541 
executeScriptInMainWorld(const String & script,ExecuteScriptPolicy policy)542 void ScriptController::executeScriptInMainWorld(const String& script, ExecuteScriptPolicy policy)
543 {
544     v8::HandleScope handleScope(m_isolate);
545     evaluateScriptInMainWorld(ScriptSourceCode(script), NotSharableCrossOrigin, policy);
546 }
547 
executeScriptInMainWorld(const ScriptSourceCode & sourceCode,AccessControlStatus corsStatus)548 void ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus)
549 {
550     v8::HandleScope handleScope(m_isolate);
551     evaluateScriptInMainWorld(sourceCode, corsStatus, DoNotExecuteScriptWhenScriptsDisabled);
552 }
553 
executeScriptInMainWorldAndReturnValue(const ScriptSourceCode & sourceCode)554 v8::Local<v8::Value> ScriptController::executeScriptInMainWorldAndReturnValue(const ScriptSourceCode& sourceCode)
555 {
556     return evaluateScriptInMainWorld(sourceCode, NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
557 }
558 
evaluateScriptInMainWorld(const ScriptSourceCode & sourceCode,AccessControlStatus corsStatus,ExecuteScriptPolicy policy)559 v8::Local<v8::Value> ScriptController::evaluateScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus, ExecuteScriptPolicy policy)
560 {
561     if (policy == DoNotExecuteScriptWhenScriptsDisabled && !canExecuteScripts(AboutToExecuteScript))
562         return v8::Local<v8::Value>();
563 
564     String sourceURL = sourceCode.url();
565     const String* savedSourceURL = m_sourceURL;
566     m_sourceURL = &sourceURL;
567 
568     ScriptState* scriptState = ScriptState::forMainWorld(m_frame);
569     if (scriptState->contextIsEmpty())
570         return v8::Local<v8::Value>();
571 
572     v8::EscapableHandleScope handleScope(scriptState->isolate());
573     ScriptState::Scope scope(scriptState);
574 
575     RefPtr<LocalFrame> protect(m_frame);
576     if (m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument())
577         m_frame->loader().didAccessInitialDocument();
578 
579     OwnPtr<ScriptSourceCode> maybeProcessedSourceCode =  InspectorInstrumentation::preprocess(m_frame, sourceCode);
580     const ScriptSourceCode& sourceCodeToCompile = maybeProcessedSourceCode ? *maybeProcessedSourceCode : sourceCode;
581 
582     v8::Local<v8::Value> object = executeScriptAndReturnValue(scriptState->context(), sourceCodeToCompile, corsStatus);
583     m_sourceURL = savedSourceURL;
584 
585     if (object.IsEmpty())
586         return v8::Local<v8::Value>();
587 
588     return handleScope.Escape(object);
589 }
590 
executeScriptInIsolatedWorld(int worldID,const Vector<ScriptSourceCode> & sources,int extensionGroup,Vector<v8::Local<v8::Value>> * results)591 void ScriptController::executeScriptInIsolatedWorld(int worldID, const Vector<ScriptSourceCode>& sources, int extensionGroup, Vector<v8::Local<v8::Value> >* results)
592 {
593     ASSERT(worldID > 0);
594 
595     RefPtr<DOMWrapperWorld> world = DOMWrapperWorld::ensureIsolatedWorld(worldID, extensionGroup);
596     V8WindowShell* isolatedWorldShell = windowShell(*world);
597     if (!isolatedWorldShell->isContextInitialized())
598         return;
599 
600     ScriptState* scriptState = isolatedWorldShell->scriptState();
601     v8::EscapableHandleScope handleScope(scriptState->isolate());
602     ScriptState::Scope scope(scriptState);
603     v8::Local<v8::Array> resultArray = v8::Array::New(m_isolate, sources.size());
604 
605     for (size_t i = 0; i < sources.size(); ++i) {
606         v8::Local<v8::Value> evaluationResult = executeScriptAndReturnValue(scriptState->context(), sources[i]);
607         if (evaluationResult.IsEmpty())
608             evaluationResult = v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
609         resultArray->Set(i, evaluationResult);
610     }
611 
612     if (results) {
613         for (size_t i = 0; i < resultArray->Length(); ++i)
614             results->append(handleScope.Escape(resultArray->Get(i)));
615     }
616 }
617 
618 } // namespace WebCore
619