1/*
2 * Copyright (C) 2010 Google, Inc. All Rights Reserved.
3 * Copyright (C) 2010-2017 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
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "config.h"
28#include "HTMLScriptRunner.h"
29
30#include "Element.h"
31#include "Event.h"
32#include "EventNames.h"
33#include "Frame.h"
34#include "HTMLInputStream.h"
35#include "HTMLNames.h"
36#include "HTMLScriptRunnerHost.h"
37#include "IgnoreDestructiveWriteCountIncrementer.h"
38#include "InlineClassicScript.h"
39#include "Microtasks.h"
40#include "MutationObserver.h"
41#include "NestingLevelIncrementer.h"
42#include "ScriptElement.h"
43#include "ScriptSourceCode.h"
44
45namespace WebCore {
46
47using namespace HTMLNames;
48
49HTMLScriptRunner::HTMLScriptRunner(Document& document, HTMLScriptRunnerHost& host)
50 : m_document(makeWeakPtr(document))
51 , m_host(host)
52 , m_scriptNestingLevel(0)
53 , m_hasScriptsWaitingForStylesheets(false)
54{
55}
56
57HTMLScriptRunner::~HTMLScriptRunner()
58{
59 // FIXME: Should we be passed a "done loading/parsing" callback sooner than destruction?
60 if (m_parserBlockingScript) {
61 if (m_parserBlockingScript->watchingForLoad())
62 stopWatchingForLoad(*m_parserBlockingScript);
63 }
64
65 while (!m_scriptsToExecuteAfterParsing.isEmpty()) {
66 auto pendingScript = m_scriptsToExecuteAfterParsing.takeFirst();
67 if (pendingScript->watchingForLoad())
68 stopWatchingForLoad(pendingScript);
69 }
70}
71
72void HTMLScriptRunner::detach()
73{
74 m_document = nullptr;
75}
76
77static URL documentURLForScriptExecution(Document* document)
78{
79 if (!document || !document->frame())
80 return URL();
81
82 // Use the URL of the currently active document for this frame.
83 return document->frame()->document()->url();
84}
85
86inline Ref<Event> createScriptLoadEvent()
87{
88 return Event::create(eventNames().loadEvent, Event::CanBubble::No, Event::IsCancelable::No);
89}
90
91bool HTMLScriptRunner::isPendingScriptReady(const PendingScript& script)
92{
93 if (!m_document)
94 return false;
95 m_hasScriptsWaitingForStylesheets = !m_document->haveStylesheetsLoaded();
96 if (m_hasScriptsWaitingForStylesheets)
97 return false;
98 if (script.needsLoading() && !script.isLoaded())
99 return false;
100 return true;
101}
102
103void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript)
104{
105 // Stop watching loads before executeScript to prevent recursion if the script reloads itself.
106 if (pendingScript.watchingForLoad())
107 stopWatchingForLoad(pendingScript);
108
109 if (!isExecutingScript())
110 MicrotaskQueue::mainThreadQueue().performMicrotaskCheckpoint();
111
112 {
113 NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
114 pendingScript.element().executePendingScript(pendingScript);
115 }
116 ASSERT(!isExecutingScript());
117}
118
119void HTMLScriptRunner::watchForLoad(PendingScript& pendingScript)
120{
121 ASSERT(!pendingScript.watchingForLoad());
122 m_host.watchForLoad(pendingScript);
123}
124
125void HTMLScriptRunner::stopWatchingForLoad(PendingScript& pendingScript)
126{
127 ASSERT(pendingScript.watchingForLoad());
128 m_host.stopWatchingForLoad(pendingScript);
129}
130
131// This function should match 10.2.5.11 "An end tag whose tag name is 'script'"
132// Script handling lives outside the tree builder to keep the each class simple.
133void HTMLScriptRunner::execute(Ref<ScriptElement>&& element, const TextPosition& scriptStartPosition)
134{
135 // FIXME: If scripting is disabled, always just return.
136
137 bool hadPreloadScanner = m_host.hasPreloadScanner();
138
139 // Try to execute the script given to us.
140 runScript(element.get(), scriptStartPosition);
141
142 if (hasParserBlockingScript()) {
143 if (isExecutingScript())
144 return; // Unwind to the outermost HTMLScriptRunner::execute before continuing parsing.
145 // If preload scanner got created, it is missing the source after the current insertion point. Append it and scan.
146 if (!hadPreloadScanner && m_host.hasPreloadScanner())
147 m_host.appendCurrentInputStreamToPreloadScannerAndScan();
148 executeParsingBlockingScripts();
149 }
150}
151
152bool HTMLScriptRunner::hasParserBlockingScript() const
153{
154 return !!m_parserBlockingScript;
155}
156
157void HTMLScriptRunner::executeParsingBlockingScripts()
158{
159 while (hasParserBlockingScript() && isPendingScriptReady(*m_parserBlockingScript)) {
160 ASSERT(m_document);
161 ASSERT(!isExecutingScript());
162 ASSERT(m_document->haveStylesheetsLoaded());
163 InsertionPointRecord insertionPointRecord(m_host.inputStream());
164 executePendingScriptAndDispatchEvent(m_parserBlockingScript.releaseNonNull().get());
165 }
166}
167
168void HTMLScriptRunner::executeScriptsWaitingForLoad(PendingScript& pendingScript)
169{
170 ASSERT(!isExecutingScript());
171 ASSERT(hasParserBlockingScript());
172 ASSERT_UNUSED(pendingScript, m_parserBlockingScript.get() == &pendingScript);
173 ASSERT(m_parserBlockingScript->isLoaded());
174 executeParsingBlockingScripts();
175}
176
177void HTMLScriptRunner::executeScriptsWaitingForStylesheets()
178{
179 ASSERT(m_document);
180 // Callers should check hasScriptsWaitingForStylesheets() before calling
181 // to prevent parser or script re-entry during </style> parsing.
182 ASSERT(hasScriptsWaitingForStylesheets());
183 ASSERT(!isExecutingScript());
184 ASSERT(m_document->haveStylesheetsLoaded());
185 executeParsingBlockingScripts();
186}
187
188bool HTMLScriptRunner::executeScriptsWaitingForParsing()
189{
190 while (!m_scriptsToExecuteAfterParsing.isEmpty()) {
191 ASSERT(!isExecutingScript());
192 ASSERT(!hasParserBlockingScript());
193 ASSERT(m_scriptsToExecuteAfterParsing.first()->needsLoading());
194 if (!m_scriptsToExecuteAfterParsing.first()->isLoaded()) {
195 watchForLoad(m_scriptsToExecuteAfterParsing.first());
196 return false;
197 }
198 executePendingScriptAndDispatchEvent(m_scriptsToExecuteAfterParsing.takeFirst().get());
199 // FIXME: What is this m_document check for?
200 if (!m_document)
201 return false;
202 }
203 return true;
204}
205
206static Ref<PendingScript> requestPendingScript(ScriptElement& scriptElement)
207{
208 ASSERT(scriptElement.willBeParserExecuted());
209 ASSERT(scriptElement.loadableScript());
210 return PendingScript::create(scriptElement, *scriptElement.loadableScript());
211}
212
213void HTMLScriptRunner::requestParsingBlockingScript(ScriptElement& scriptElement)
214{
215 ASSERT(!m_parserBlockingScript);
216 m_parserBlockingScript = requestPendingScript(scriptElement);
217 ASSERT(m_parserBlockingScript->needsLoading());
218
219 // We only care about a load callback if LoadableScript is not already
220 // in the cache. Callers will attempt to run the m_parserBlockingScript
221 // if possible before returning control to the parser.
222 if (!m_parserBlockingScript->isLoaded())
223 watchForLoad(*m_parserBlockingScript);
224}
225
226void HTMLScriptRunner::requestDeferredScript(ScriptElement& scriptElement)
227{
228 auto pendingScript = requestPendingScript(scriptElement);
229 ASSERT(pendingScript->needsLoading());
230 m_scriptsToExecuteAfterParsing.append(WTFMove(pendingScript));
231}
232
233// This method is meant to match the HTML5 definition of "running a script"
234// http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#running-a-script
235void HTMLScriptRunner::runScript(ScriptElement& scriptElement, const TextPosition& scriptStartPosition)
236{
237 ASSERT(m_document);
238 ASSERT(!hasParserBlockingScript());
239
240 // FIXME: This may be too agressive as we always deliver mutations at
241 // every script element, even if it's not ready to execute yet. There's
242 // unfortunately no obvious way to tell if prepareScript is going to
243 // execute the script before calling it.
244 if (!isExecutingScript())
245 MicrotaskQueue::mainThreadQueue().performMicrotaskCheckpoint();
246
247 InsertionPointRecord insertionPointRecord(m_host.inputStream());
248 NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
249
250 scriptElement.prepareScript(scriptStartPosition);
251
252 if (!scriptElement.willBeParserExecuted())
253 return;
254
255 if (scriptElement.willExecuteWhenDocumentFinishedParsing())
256 requestDeferredScript(scriptElement);
257 else if (scriptElement.readyToBeParserExecuted()) {
258 if (m_scriptNestingLevel == 1)
259 m_parserBlockingScript = PendingScript::create(scriptElement, scriptStartPosition);
260 else
261 scriptElement.executeClassicScript(ScriptSourceCode(scriptElement.element().textContent(), documentURLForScriptExecution(m_document.get()), scriptStartPosition, JSC::SourceProviderSourceType::Program, InlineClassicScript::create(scriptElement)));
262 } else
263 requestParsingBlockingScript(scriptElement);
264}
265
266}
267