1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
|
/*
* Copyright (C) 2014-2022 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "InspectorFrontendAPIDispatcher.h"
#include "DOMWrapperWorld.h"
#include "InspectorController.h"
#include "JSDOMPromise.h"
#include "LocalFrame.h"
#include "Page.h"
#include "ScriptController.h"
#include "ScriptDisallowedScope.h"
#include "ScriptSourceCode.h"
#include <JavaScriptCore/FrameTracers.h>
#include <JavaScriptCore/JSPromise.h>
#include <wtf/RunLoop.h>
#include <wtf/text/MakeString.h>
namespace WebCore {
using EvaluationError = InspectorFrontendAPIDispatcher::EvaluationError;
InspectorFrontendAPIDispatcher::InspectorFrontendAPIDispatcher(Page& frontendPage)
: m_frontendPage(frontendPage)
{
}
InspectorFrontendAPIDispatcher::~InspectorFrontendAPIDispatcher()
{
invalidateQueuedExpressions();
invalidatePendingResponses();
}
void InspectorFrontendAPIDispatcher::reset()
{
m_frontendLoaded = false;
m_suspended = false;
invalidateQueuedExpressions();
invalidatePendingResponses();
}
void InspectorFrontendAPIDispatcher::frontendLoaded()
{
ASSERT(m_frontendPage);
m_frontendLoaded = true;
// In some convoluted WebKitLegacy-only scenarios, the backend may try to dispatch events to the frontend
// underneath InspectorFrontendHost::loaded() when it is unsafe to execute script, causing suspend() to
// be called before the frontend has fully loaded. See <https://bugs.webkit.org/show_bug.cgi?id=218840>.
if (!m_suspended)
evaluateQueuedExpressions();
}
void InspectorFrontendAPIDispatcher::suspend(UnsuspendSoon unsuspendSoon)
{
if (m_suspended)
return;
m_suspended = true;
if (unsuspendSoon == UnsuspendSoon::Yes) {
RunLoop::protectedMain()->dispatch([protectedThis = Ref { *this }] {
// If the frontend page has been deallocated, there's nothing to do.
if (!protectedThis->m_frontendPage)
return;
protectedThis->unsuspend();
});
}
}
void InspectorFrontendAPIDispatcher::unsuspend()
{
if (!m_suspended)
return;
m_suspended = false;
if (m_frontendLoaded)
evaluateQueuedExpressions();
}
JSDOMGlobalObject* InspectorFrontendAPIDispatcher::frontendGlobalObject()
{
if (!m_frontendPage)
return nullptr;
RefPtr localMainFrame = m_frontendPage->localMainFrame();
if (!localMainFrame)
return nullptr;
return localMainFrame->script().globalObject(mainThreadNormalWorldSingleton());
}
static String expressionForEvaluatingCommand(const String& command, Vector<Ref<JSON::Value>>&& arguments)
{
StringBuilder expression;
expression.append("InspectorFrontendAPI.dispatch([\""_s, command, '"');
for (auto& argument : arguments) {
expression.append(", "_s);
argument->writeJSON(expression);
}
expression.append("])"_s);
return expression.toString();
}
InspectorFrontendAPIDispatcher::EvaluationResult InspectorFrontendAPIDispatcher::dispatchCommandWithResultSync(const String& command, Vector<Ref<JSON::Value>>&& arguments)
{
if (m_suspended)
return makeUnexpected(EvaluationError::ExecutionSuspended);
return evaluateExpression(expressionForEvaluatingCommand(command, WTFMove(arguments)));
}
void InspectorFrontendAPIDispatcher::dispatchCommandWithResultAsync(const String& command, Vector<Ref<JSON::Value>>&& arguments, EvaluationResultHandler&& resultHandler)
{
evaluateOrQueueExpression(expressionForEvaluatingCommand(command, WTFMove(arguments)), WTFMove(resultHandler));
}
void InspectorFrontendAPIDispatcher::dispatchMessageAsync(const String& message)
{
evaluateOrQueueExpression(makeString("InspectorFrontendAPI.dispatchMessageAsync("_s, message, ')'));
}
void InspectorFrontendAPIDispatcher::evaluateOrQueueExpression(const String& expression, EvaluationResultHandler&& optionalResultHandler)
{
// If the frontend page has been deallocated, then there is nothing to do.
if (!m_frontendPage) {
if (optionalResultHandler)
optionalResultHandler(makeUnexpected(EvaluationError::ContextDestroyed));
return;
}
// Sometimes we get here by sending messages for events triggered by DOM mutations earlier in the call stack.
// If this is the case, then it's not safe to evaluate script synchronously, so do it later. This only affects
// WebKit1 and some layout tests that use a single web process for both the inspector and inspected page.
if (!ScriptDisallowedScope::InMainThread::isScriptAllowed())
suspend(UnsuspendSoon::Yes);
if (!m_frontendLoaded || m_suspended) {
m_queuedEvaluations.append(std::make_pair(expression, WTFMove(optionalResultHandler)));
return;
}
ValueOrException result = evaluateExpression(expression);
if (!optionalResultHandler)
return;
if (!result.has_value()) {
optionalResultHandler(result);
return;
}
JSDOMGlobalObject* globalObject = frontendGlobalObject();
if (!globalObject) {
optionalResultHandler(makeUnexpected(EvaluationError::ContextDestroyed));
return;
}
JSC::JSLockHolder lock(globalObject);
auto* castedPromise = JSC::jsDynamicCast<JSC::JSPromise*>(result.value());
if (!castedPromise) {
// Simple case: result is NOT a promise, just return the JSValue.
optionalResultHandler(result);
return;
}
// If the result is a promise, call the result handler when the promise settles.
Ref<DOMPromise> promise = DOMPromise::create(*globalObject, *castedPromise);
m_pendingResponses.set(promise.copyRef(), WTFMove(optionalResultHandler));
auto isRegistered = promise->whenSettled([promise = promise.copyRef(), weakThis = WeakPtr { *this }] {
// If `this` is cleared or the responses map is empty, then the promise settled
// beyond the time when we care about its result. Ignore late-settled promises.
// We clear out completion handlers for pending responses during teardown.
if (!weakThis)
return;
Ref protectedThis = { *weakThis };
if (!protectedThis->m_pendingResponses.size())
return;
EvaluationResultHandler resultHandler = protectedThis->m_pendingResponses.take(promise);
ASSERT(resultHandler);
JSDOMGlobalObject* globalObject = protectedThis->frontendGlobalObject();
if (!globalObject) {
resultHandler(makeUnexpected(EvaluationError::ContextDestroyed));
return;
}
resultHandler({ promise->promise()->result(globalObject->vm()) });
});
if (isRegistered == DOMPromise::IsCallbackRegistered::No)
optionalResultHandler(makeUnexpected(EvaluationError::InternalError));
}
void InspectorFrontendAPIDispatcher::invalidateQueuedExpressions()
{
auto queuedEvaluations = std::exchange(m_queuedEvaluations, { });
for (auto& pair : queuedEvaluations) {
auto resultHandler = WTFMove(pair.second);
if (resultHandler)
resultHandler(makeUnexpected(EvaluationError::ContextDestroyed));
}
}
void InspectorFrontendAPIDispatcher::invalidatePendingResponses()
{
auto pendingResponses = std::exchange(m_pendingResponses, { });
for (auto& callback : pendingResponses.values())
callback(makeUnexpected(EvaluationError::ContextDestroyed));
// No more pending responses should have been added while erroring out the callbacks.
ASSERT(m_pendingResponses.isEmpty());
}
void InspectorFrontendAPIDispatcher::evaluateQueuedExpressions()
{
// If the frontend page has been deallocated, then there is nothing to do.
if (!m_frontendPage)
return;
if (m_queuedEvaluations.isEmpty())
return;
auto queuedEvaluations = std::exchange(m_queuedEvaluations, { });
for (auto& pair : queuedEvaluations) {
auto result = evaluateExpression(pair.first);
if (auto resultHandler = WTFMove(pair.second))
resultHandler(result);
}
}
ValueOrException InspectorFrontendAPIDispatcher::evaluateExpression(const String& expression)
{
ASSERT(m_frontendPage);
ASSERT(!m_suspended);
ASSERT(m_queuedEvaluations.isEmpty());
JSC::SuspendExceptionScope scope(m_frontendPage->inspectorController().vm());
RefPtr localMainFrame = m_frontendPage->localMainFrame();
return localMainFrame->script().evaluateInWorld(ScriptSourceCode(expression, JSC::SourceTaintedOrigin::Untainted), mainThreadNormalWorldSingleton());
}
void InspectorFrontendAPIDispatcher::evaluateExpressionForTesting(const String& expression)
{
evaluateOrQueueExpression(expression);
}
} // namespace WebKit
|