ScriptExecutionContext.cpp [plain text]
#include "config.h"
#include "ScriptExecutionContext.h"
#include "CachedScript.h"
#include "CommonVM.h"
#include "DOMTimer.h"
#include "DatabaseContext.h"
#include "Document.h"
#include "ErrorEvent.h"
#include "JSDOMExceptionHandling.h"
#include "JSDOMWindow.h"
#include "MessagePort.h"
#include "NoEventDispatchAssertion.h"
#include "PublicURLManager.h"
#include "RejectedPromiseTracker.h"
#include "ResourceRequest.h"
#include "ScriptState.h"
#include "Settings.h"
#include "WorkerGlobalScope.h"
#include "WorkerThread.h"
#include <heap/StrongInlines.h>
#include <inspector/ScriptCallStack.h>
#include <runtime/CatchScope.h>
#include <runtime/Exception.h>
#include <runtime/JSPromise.h>
#include <wtf/MainThread.h>
#include <wtf/Ref.h>
using namespace Inspector;
namespace WebCore {
struct ScriptExecutionContext::PendingException {
WTF_MAKE_FAST_ALLOCATED;
public:
PendingException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, RefPtr<ScriptCallStack>&& callStack)
: m_errorMessage(errorMessage)
, m_lineNumber(lineNumber)
, m_columnNumber(columnNumber)
, m_sourceURL(sourceURL)
, m_callStack(WTFMove(callStack))
{
}
String m_errorMessage;
int m_lineNumber;
int m_columnNumber;
String m_sourceURL;
RefPtr<ScriptCallStack> m_callStack;
};
ScriptExecutionContext::ScriptExecutionContext()
{
}
#if ASSERT_DISABLED
inline void ScriptExecutionContext::checkConsistency() const
{
}
#else
void ScriptExecutionContext::checkConsistency() const
{
for (auto* messagePort : m_messagePorts)
ASSERT(messagePort->scriptExecutionContext() == this);
for (auto* destructionObserver : m_destructionObservers)
ASSERT(destructionObserver->scriptExecutionContext() == this);
for (auto* activeDOMObject : m_activeDOMObjects) {
ASSERT(activeDOMObject->scriptExecutionContext() == this);
activeDOMObject->assertSuspendIfNeededWasCalled();
}
}
#endif
ScriptExecutionContext::~ScriptExecutionContext()
{
checkConsistency();
#if !ASSERT_DISABLED
m_inScriptExecutionContextDestructor = true;
#endif
while (auto* destructionObserver = m_destructionObservers.takeAny())
destructionObserver->contextDestroyed();
for (auto* messagePort : m_messagePorts)
messagePort->contextDestroyed();
#if !ASSERT_DISABLED
m_inScriptExecutionContextDestructor = false;
#endif
}
void ScriptExecutionContext::processMessagePortMessagesSoon()
{
if (m_willProcessMessagePortMessagesSoon)
return;
m_willProcessMessagePortMessagesSoon = true;
postTask([] (ScriptExecutionContext& context) {
context.dispatchMessagePortEvents();
});
}
void ScriptExecutionContext::dispatchMessagePortEvents()
{
checkConsistency();
Ref<ScriptExecutionContext> protectedThis(*this);
ASSERT(m_willProcessMessagePortMessagesSoon);
m_willProcessMessagePortMessagesSoon = false;
Vector<MessagePort*> possibleMessagePorts;
copyToVector(m_messagePorts, possibleMessagePorts);
for (auto* messagePort : possibleMessagePorts) {
if (m_messagePorts.contains(messagePort) && messagePort->started())
messagePort->dispatchMessages();
}
}
void ScriptExecutionContext::createdMessagePort(MessagePort& messagePort)
{
ASSERT((is<Document>(*this) && isMainThread())
|| (is<WorkerGlobalScope>(*this) && currentThread() == downcast<WorkerGlobalScope>(*this).thread().threadID()));
m_messagePorts.add(&messagePort);
}
void ScriptExecutionContext::destroyedMessagePort(MessagePort& messagePort)
{
ASSERT((is<Document>(*this) && isMainThread())
|| (is<WorkerGlobalScope>(*this) && currentThread() == downcast<WorkerGlobalScope>(*this).thread().threadID()));
m_messagePorts.remove(&messagePort);
}
void ScriptExecutionContext::didLoadResourceSynchronously()
{
}
bool ScriptExecutionContext::canSuspendActiveDOMObjectsForDocumentSuspension(Vector<ActiveDOMObject*>* unsuspendableObjects)
{
checkConsistency();
bool canSuspend = true;
m_activeDOMObjectAdditionForbidden = true;
#if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
m_activeDOMObjectRemovalForbidden = true;
#endif
NoEventDispatchAssertion assertNoEventDispatch;
for (auto* activeDOMObject : m_activeDOMObjects) {
if (!activeDOMObject->canSuspendForDocumentSuspension()) {
canSuspend = false;
if (unsuspendableObjects)
unsuspendableObjects->append(activeDOMObject);
else
break;
}
}
m_activeDOMObjectAdditionForbidden = false;
#if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
m_activeDOMObjectRemovalForbidden = false;
#endif
return canSuspend;
}
void ScriptExecutionContext::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
{
checkConsistency();
if (m_activeDOMObjectsAreSuspended) {
ASSERT(m_reasonForSuspendingActiveDOMObjects == ActiveDOMObject::PageWillBeSuspended);
return;
}
m_activeDOMObjectsAreSuspended = true;
m_activeDOMObjectAdditionForbidden = true;
#if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
m_activeDOMObjectRemovalForbidden = true;
#endif
NoEventDispatchAssertion assertNoEventDispatch;
for (auto* activeDOMObject : m_activeDOMObjects)
activeDOMObject->suspend(why);
m_activeDOMObjectAdditionForbidden = false;
#if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
m_activeDOMObjectRemovalForbidden = false;
#endif
m_reasonForSuspendingActiveDOMObjects = why;
}
void ScriptExecutionContext::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
{
checkConsistency();
if (m_reasonForSuspendingActiveDOMObjects != why)
return;
m_activeDOMObjectsAreSuspended = false;
m_activeDOMObjectAdditionForbidden = true;
#if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
m_activeDOMObjectRemovalForbidden = true;
#endif
NoEventDispatchAssertion assertNoEventDispatch;
for (auto* activeDOMObject : m_activeDOMObjects)
activeDOMObject->resume();
m_activeDOMObjectAdditionForbidden = false;
#if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
m_activeDOMObjectRemovalForbidden = false;
#endif
}
void ScriptExecutionContext::stopActiveDOMObjects()
{
checkConsistency();
if (m_activeDOMObjectsAreStopped)
return;
m_activeDOMObjectsAreStopped = true;
Vector<ActiveDOMObject*> possibleActiveDOMObjects;
copyToVector(m_activeDOMObjects, possibleActiveDOMObjects);
m_activeDOMObjectAdditionForbidden = true;
NoEventDispatchAssertion assertNoEventDispatch;
for (auto* activeDOMObject : possibleActiveDOMObjects) {
if (!m_activeDOMObjects.contains(activeDOMObject))
continue;
activeDOMObject->stop();
}
m_activeDOMObjectAdditionForbidden = false;
for (auto* messagePort : m_messagePorts)
messagePort->close();
}
void ScriptExecutionContext::suspendActiveDOMObjectIfNeeded(ActiveDOMObject& activeDOMObject)
{
ASSERT(m_activeDOMObjects.contains(&activeDOMObject));
if (m_activeDOMObjectsAreSuspended)
activeDOMObject.suspend(m_reasonForSuspendingActiveDOMObjects);
if (m_activeDOMObjectsAreStopped)
activeDOMObject.stop();
}
void ScriptExecutionContext::didCreateActiveDOMObject(ActiveDOMObject& activeDOMObject)
{
ASSERT(!m_inScriptExecutionContextDestructor);
RELEASE_ASSERT(!m_activeDOMObjectAdditionForbidden);
m_activeDOMObjects.add(&activeDOMObject);
}
void ScriptExecutionContext::willDestroyActiveDOMObject(ActiveDOMObject& activeDOMObject)
{
ASSERT_WITH_SECURITY_IMPLICATION(!m_activeDOMObjectRemovalForbidden);
m_activeDOMObjects.remove(&activeDOMObject);
}
void ScriptExecutionContext::didCreateDestructionObserver(ContextDestructionObserver& observer)
{
ASSERT(!m_inScriptExecutionContextDestructor);
m_destructionObservers.add(&observer);
}
void ScriptExecutionContext::willDestroyDestructionObserver(ContextDestructionObserver& observer)
{
m_destructionObservers.remove(&observer);
}
bool ScriptExecutionContext::sanitizeScriptError(String& errorMessage, int& lineNumber, int& columnNumber, String& sourceURL, JSC::Strong<JSC::Unknown>& error, CachedScript* cachedScript)
{
ASSERT(securityOrigin());
if (cachedScript) {
ASSERT(cachedScript->origin());
ASSERT(securityOrigin()->toString() == cachedScript->origin()->toString());
if (cachedScript->isCORSSameOrigin())
return false;
} else if (securityOrigin()->canRequest(completeURL(sourceURL)))
return false;
errorMessage = ASCIILiteral { "Script error." };
sourceURL = { };
lineNumber = 0;
columnNumber = 0;
error = { };
return true;
}
void ScriptExecutionContext::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, JSC::Exception* exception, RefPtr<ScriptCallStack>&& callStack, CachedScript* cachedScript)
{
if (m_inDispatchErrorEvent) {
if (!m_pendingExceptions)
m_pendingExceptions = std::make_unique<Vector<std::unique_ptr<PendingException>>>();
m_pendingExceptions->append(std::make_unique<PendingException>(errorMessage, lineNumber, columnNumber, sourceURL, WTFMove(callStack)));
return;
}
if (!dispatchErrorEvent(errorMessage, lineNumber, columnNumber, sourceURL, exception, cachedScript))
logExceptionToConsole(errorMessage, sourceURL, lineNumber, columnNumber, callStack.copyRef());
if (!m_pendingExceptions)
return;
auto pendingExceptions = WTFMove(m_pendingExceptions);
for (auto& exception : *pendingExceptions)
logExceptionToConsole(exception->m_errorMessage, exception->m_sourceURL, exception->m_lineNumber, exception->m_columnNumber, WTFMove(exception->m_callStack));
}
void ScriptExecutionContext::reportUnhandledPromiseRejection(JSC::ExecState& state, JSC::JSPromise& promise, RefPtr<Inspector::ScriptCallStack>&& callStack)
{
JSC::VM& vm = state.vm();
auto scope = DECLARE_CATCH_SCOPE(vm);
int lineNumber = 0;
int columnNumber = 0;
String sourceURL;
JSC::JSValue result = promise.result(vm);
String resultMessage = retrieveErrorMessage(state, vm, result, scope);
String errorMessage = makeString("Unhandled Promise Rejection: ", resultMessage);
if (callStack) {
if (const ScriptCallFrame* callFrame = callStack->firstNonNativeCallFrame()) {
lineNumber = callFrame->lineNumber();
columnNumber = callFrame->columnNumber();
sourceURL = callFrame->sourceURL();
}
}
logExceptionToConsole(errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
}
void ScriptExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, JSC::ExecState* state, unsigned long requestIdentifier)
{
addMessage(source, level, message, sourceURL, lineNumber, columnNumber, 0, state, requestIdentifier);
}
bool ScriptExecutionContext::dispatchErrorEvent(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, JSC::Exception* exception, CachedScript* cachedScript)
{
EventTarget* target = errorEventTarget();
if (!target)
return false;
String message = errorMessage;
int line = lineNumber;
int column = columnNumber;
String sourceName = sourceURL;
JSC::Strong<JSC::Unknown> error = exception && exception->value() ? JSC::Strong<JSC::Unknown>(vm(), exception->value()) : JSC::Strong<JSC::Unknown>();
sanitizeScriptError(message, line, column, sourceName, error, cachedScript);
ASSERT(!m_inDispatchErrorEvent);
m_inDispatchErrorEvent = true;
Ref<ErrorEvent> errorEvent = ErrorEvent::create(message, sourceName, line, column, error);
target->dispatchEvent(errorEvent);
m_inDispatchErrorEvent = false;
return errorEvent->defaultPrevented();
}
int ScriptExecutionContext::circularSequentialID()
{
++m_circularSequentialID;
if (m_circularSequentialID <= 0)
m_circularSequentialID = 1;
return m_circularSequentialID;
}
PublicURLManager& ScriptExecutionContext::publicURLManager()
{
if (!m_publicURLManager)
m_publicURLManager = PublicURLManager::create(this);
return *m_publicURLManager;
}
void ScriptExecutionContext::adjustMinimumDOMTimerInterval(Seconds oldMinimumTimerInterval)
{
if (minimumDOMTimerInterval() != oldMinimumTimerInterval) {
for (auto& timer : m_timeouts.values())
timer->updateTimerIntervalIfNecessary();
}
}
Seconds ScriptExecutionContext::minimumDOMTimerInterval() const
{
return DOMTimer::defaultMinimumInterval();
}
void ScriptExecutionContext::didChangeTimerAlignmentInterval()
{
for (auto& timer : m_timeouts.values())
timer->didChangeAlignmentInterval();
}
Seconds ScriptExecutionContext::domTimerAlignmentInterval(bool) const
{
return DOMTimer::defaultAlignmentInterval();
}
JSC::VM& ScriptExecutionContext::vm()
{
if (is<Document>(*this))
return commonVM();
return downcast<WorkerGlobalScope>(*this).script()->vm();
}
RejectedPromiseTracker& ScriptExecutionContext::ensureRejectedPromiseTrackerSlow()
{
ASSERT(!m_rejectedPromiseTracker);
m_rejectedPromiseTracker = std::make_unique<RejectedPromiseTracker>(*this, vm());
return *m_rejectedPromiseTracker.get();
}
void ScriptExecutionContext::setDatabaseContext(DatabaseContext* databaseContext)
{
m_databaseContext = databaseContext;
}
bool ScriptExecutionContext::hasPendingActivity() const
{
checkConsistency();
for (auto* activeDOMObject : m_activeDOMObjects) {
if (activeDOMObject->hasPendingActivity())
return true;
}
for (auto* messagePort : m_messagePorts) {
if (messagePort->hasPendingActivity())
return true;
}
return false;
}
JSC::ExecState* ScriptExecutionContext::execState()
{
if (is<Document>(*this)) {
Document& document = downcast<Document>(*this);
return execStateFromPage(mainThreadNormalWorld(), document.page());
}
WorkerGlobalScope* workerGlobalScope = static_cast<WorkerGlobalScope*>(this);
return execStateFromWorkerGlobalScope(workerGlobalScope);
}
}