Bug Summary

File:Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore/page/FrameConsoleClient.cpp
Warning:line 371, column 35
Local variable 'cachedImage' is uncounted and unsafe

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple arm64-apple-ios26.2.0-simulator -O3 -Wundef-prefix=TARGET_OS_ -Werror=undef-prefix -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name UnifiedSource297.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=osx -analyzer-checker=security.insecureAPI.decodeValueOfObjCType -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -ffp-contract=on -fno-rounding-math -target-sdk-version=26.2 -fdepfile-entry=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/SDKSettings.json -fcompatibility-qualified-id-block-type-checking -fvisibility-inlines-hidden-static-local-var -fno-modulemap-allow-subdirectory-search -fdefine-target-os-macros -enable-tlsdesc -target-cpu apple-m1 -target-feature +v8.4a -target-feature +aes -target-feature +altnzcv -target-feature +ccdp -target-feature +ccpp -target-feature +complxnum -target-feature +crc -target-feature +dotprod -target-feature +flagm -target-feature +fp-armv8 -target-feature +fp16fml -target-feature +fptoint -target-feature +fullfp16 -target-feature +jsconv -target-feature +lse -target-feature +neon -target-feature +pauth -target-feature +perfmon -target-feature +predres -target-feature +ras -target-feature +rcpc -target-feature +rdm -target-feature +sb -target-feature +sha2 -target-feature +sha3 -target-feature +specrestrict -target-feature +ssbs -target-abi darwinpcs -dwarf-ext-refs -fmodule-format=obj -debug-info-kind=standalone -dwarf-version=5 -debugger-tuning=lldb -fdebug-compilation-dir=/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore -target-linker-version 1230.1 -fcoverage-compilation-dir=/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore -resource-dir /Users/buildbot/Library/Developer/Toolchains/swift-webkit.xctoolchain/usr/lib/clang/21 -dependency-file /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/scan-build-output/StaticAnalyzer/WebCore/WebCore/normal/arm64/UnifiedSource297.d -skip-unused-modulemap-deps -MT dependencies -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk -iquote /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-generated-files.hmap -iquote /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-project-headers.hmap -isystem /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore/PAL/ThirdParty/dav1d/include -isystem /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/SDKAdditions/usr/include -iframework /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/SDKAdditions/System/Library/Frameworks -iframework /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitLibraries/SDKs/iphonesimulator26.0-additions.sdk/System/Library/PrivateFrameworks -iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/System/Library/Frameworks -include-pch /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/PrecompiledHeaders/SharedPrecompiledHeaders/11721353671419897710/WebCorePrefix.h.gch -D _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE -D NDEBUG -D BUILDING_WEBKIT -D GL_SILENCE_DEPRECATION=1 -D GLES_SILENCE_DEPRECATION=1 -D __clang_analyzer__ -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-own-target-headers.hmap -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-all-target-headers.hmap -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/include -I PAL -I ForwardingHeaders -I /usr/include/libxslt -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/include/libxml2 -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/DerivedSources/WebCore -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include/WebKitAdditions -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include/WebKitAdditions -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitLibraries/SDKs/iphonesimulator26.0-additions.sdk/usr/local/include -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include/webrtc -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include/webrtc -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include/webm -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include/webm -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/PAL.build/PAL.build/DerivedSources -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/PAL.build/Release-iphonesimulator/PAL.build/DerivedSources -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/DerivedSources-normal/arm64 -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/DerivedSources/arm64 -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/DerivedSources -F/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator -F/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator -I/usr/local/include -stdlib=libc++ -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/include/c++/v1 -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include -internal-isystem /Users/buildbot/Library/Developer/Toolchains/swift-webkit.xctoolchain/usr/lib/clang/21/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/include -internal-iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/System/Library/Frameworks -internal-iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/System/Library/SubFrameworks -internal-iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/Library/Frameworks -Wno-trigraphs -Werror -Wno-missing-field-initializers -Wmissing-prototypes -Wunreachable-code -Wnon-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wsign-compare -Wno-shorten-64-to-32 -Wnewline-eof -Wno-c++11-extensions -Wno-implicit-fallthrough -Wdeprecated-declarations -Winvalid-offsetof -Wno-sign-conversion -Winfinite-recursion -Wmove -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wrange-loop-analysis -Wno-semicolon-before-method-body -Wall -Wc99-designator -Wconditional-uninitialized -Wextra -Wdeprecated-enum-enum-conversion -Wdeprecated-enum-float-conversion -Wenum-float-conversion -Wfinal-dtor-non-final-class -Wformat=2 -Wmisleading-indentation -Wpointer-to-int-cast -Wreorder-init-list -Wundef -Wunused-but-set-variable -Wvla -Werror=unguarded-availability -Wno-elaborated-enum-base -Wcast-qual -Wchar-subscripts -Wextra-tokens -Winit-self -Wmissing-noreturn -Wpacked -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wexit-time-destructors -Wglobal-constructors -Wtautological-compare -Wimplicit-fallthrough -Wvla -Wno-unknown-warning-option -Wliteral-conversion -Wthread-safety -Wno-profile-instr-out-of-date -Wno-profile-instr-unprofiled -Wno-backend-plugin -Wunsafe-buffer-usage -std=c++2b -fdeprecated-macro -ferror-limit 19 -fmacro-backtrace-limit=0 -fvisibility=hidden -fvisibility-inlines-hidden -stack-protector 1 -fblocks -fencode-extended-block-signature -fno-rtti -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fno-implicit-modules -fskip-odr-check-in-gmf -fpascal-strings -fmax-type-align=16 -fdiagnostics-show-note-include-stack -vectorize-loops -vectorize-slp -fsafe-buffer-usage-suggestions -analyzer-output=html -analyzer-config report-in-main-source-file=true -analyzer-config nullability:NoDiagnoseCallsToSystemHeaders=true -analyzer-checker optin.osx.cocoa.localizability.NonLocalizedStringChecker -analyzer-checker security.insecureAPI.UncheckedReturn -analyzer-checker security.insecureAPI.getpw -analyzer-checker security.insecureAPI.gets -analyzer-checker security.insecureAPI.mkstemp -analyzer-checker security.insecureAPI.mktemp -analyzer-disable-checker security.insecureAPI.rand -analyzer-disable-checker security.insecureAPI.strcpy -analyzer-checker security.insecureAPI.vfork -analyzer-disable-checker alpha,apiModeling,core,cplusplus,deadcode,debug,fuchsia,nullability,optin,osx,security,unix,webkit -analyzer-checker alpha.webkit.ForwardDeclChecker,alpha.webkit.MemoryUnsafeCastChecker,alpha.webkit.NoDeleteChecker,alpha.webkit.NoUncheckedPtrMemberChecker,alpha.webkit.NoUnretainedMemberChecker,alpha.webkit.RetainPtrCtorAdoptChecker,alpha.webkit.UncheckedCallArgsChecker,alpha.webkit.UncheckedLocalVarsChecker,alpha.webkit.UncountedCallArgsChecker,alpha.webkit.UncountedLocalVarsChecker,alpha.webkit.UnretainedCallArgsChecker,alpha.webkit.UnretainedLambdaCapturesChecker,alpha.webkit.UnretainedLocalVarsChecker,webkit.NoUncountedMemberChecker,webkit.RefCntblBaseVirtualDtor,webkit.UncountedLambdaCapturesChecker -analyzer-config max-nodes=10000000 -analyzer-config verbose-report-filename=true -fdwarf2-cfi-asm -o /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/scan-build-output/StaticAnalyzer/WebCore/WebCore/normal/arm64/UnifiedSource297.plist -x c++ /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/DerivedSources/WebCore/unified-sources/UnifiedSource297.cpp
1/*
2 * Copyright (C) 2013-2025 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
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 * 3. Neither the name of Apple Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include "config.h"
30#include "FrameConsoleClient.h"
31
32#include "CachedImage.h"
33#include "CanvasRenderingContext2D.h"
34#include "Chrome.h"
35#include "ChromeClient.h"
36#include "Document.h"
37#include "ElementChildIteratorInlines.h"
38#include "Frame.h"
39#include "FrameSnapshotting.h"
40#include "HTMLCanvasElement.h"
41#include "HTMLImageElement.h"
42#include "HTMLPictureElement.h"
43#include "HTMLVideoElement.h"
44#include "Image.h"
45#include "ImageBitmap.h"
46#include "ImageBitmapRenderingContext.h"
47#include "ImageBuffer.h"
48#include "ImageData.h"
49#include "ImageUtilities.h"
50#include "InspectorCanvas.h"
51#include "InspectorInstrumentation.h"
52#include "IntRect.h"
53#include "JSCanvasRenderingContext2D.h"
54#include "JSDOMRectReadOnly.h"
55#include "JSExecState.h"
56#include "JSHTMLCanvasElement.h"
57#include "JSImageBitmap.h"
58#include "JSImageBitmapRenderingContext.h"
59#include "JSImageData.h"
60#include "JSNode.h"
61#include "LocalFrame.h"
62#include "Node.h"
63#include "PageInspectorController.h"
64#include "ScriptableDocumentParser.h"
65#include "Settings.h"
66#include "StringCallback.h"
67#include <JavaScriptCore/ConsoleMessage.h>
68#include <JavaScriptCore/JSCInlines.h>
69#include <JavaScriptCore/ScriptArguments.h>
70#include <JavaScriptCore/ScriptCallStack.h>
71#include <JavaScriptCore/ScriptCallStackFactory.h>
72#include <JavaScriptCore/StrongInlines.h>
73#include <wtf/Stopwatch.h>
74#include <wtf/TZoneMallocInlines.h>
75#include <wtf/text/WTFString.h>
76
77#if ENABLE(OFFSCREEN_CANVAS)(defined 1 && 1)
78#include "JSOffscreenCanvas.h"
79#include "JSOffscreenCanvasRenderingContext2D.h"
80#include "OffscreenCanvas.h"
81#include "OffscreenCanvasRenderingContext2D.h"
82#endif
83
84#if ENABLE(WEBGL)(defined 1 && 1)
85#include "JSWebGL2RenderingContext.h"
86#include "JSWebGLRenderingContext.h"
87#include "WebGL2RenderingContext.h"
88#include "WebGLRenderingContext.h"
89#endif
90
91#if ENABLE(WEBDRIVER_BIDI)(defined 1 && 1)
92#include "AutomationInstrumentation.h"
93#endif
94
95namespace WebCore {
96using namespace Inspector;
97
98WTF_MAKE_TZONE_ALLOCATED_IMPL(FrameConsoleClient)::bmalloc::api::HeapRef FrameConsoleClient::s_heapRef; const TZoneSpecification
FrameConsoleClient::s_heapSpec = { &FrameConsoleClient::
s_heapRef, TZoneSpecification::encodeSize<FrameConsoleClient
>(), TZoneSpecification::encodeAlignment<FrameConsoleClient
>(), TZoneSpecification::encodeCategory<FrameConsoleClient
>(), ::bmalloc::api::compactAllocationMode<FrameConsoleClient
>(), TZoneSpecification::encodeDescriptor<FrameConsoleClient
>(), }; void* FrameConsoleClient::operatorNewSlow(size_t size
) { if constexpr (::bmalloc::api::compactAllocationMode<FrameConsoleClient
>() == CompactAllocationMode::Compact) return ::bmalloc::api
::tzoneAllocateCompactSlow(size, s_heapSpec); return ::bmalloc
::api::tzoneAllocateNonCompactSlow(size, s_heapSpec); } using
__makeBtzoneMallocedInlineMacroSemicolonifier __attribute__(
(unused)) = int
;
99
100FrameConsoleClient::FrameConsoleClient(LocalFrame& frame)
101 : m_frame(frame)
102{
103}
104
105FrameConsoleClient::~FrameConsoleClient() = default;
106
107static int muteCount = 0;
108static bool printExceptions = false;
109
110bool FrameConsoleClient::shouldPrintExceptions()
111{
112 return printExceptions;
113}
114
115void FrameConsoleClient::setShouldPrintExceptions(bool print)
116{
117 printExceptions = print;
118}
119
120void FrameConsoleClient::mute()
121{
122 muteCount++;
123}
124
125void FrameConsoleClient::unmute()
126{
127 ASSERT(muteCount > 0)((void)0);
128 muteCount--;
129}
130
131void FrameConsoleClient::logMessageToSystemConsole(const Inspector::ConsoleMessage& consoleMessage)
132{
133 if (consoleMessage.type() == MessageType::Image) {
134 RefPtr arguments = consoleMessage.arguments();
135 ConsoleClient::printConsoleMessageWithArguments(consoleMessage.source(), consoleMessage.type(), consoleMessage.level(), arguments->globalObject(), *arguments);
136 return;
137 }
138 ConsoleClient::printConsoleMessage(consoleMessage.source(), consoleMessage.type(), consoleMessage.level(), consoleMessage.toString(), consoleMessage.url(), consoleMessage.line(), consoleMessage.column());
139}
140
141void FrameConsoleClient::addMessage(std::unique_ptr<Inspector::ConsoleMessage>&& consoleMessage)
142{
143 Ref frame = m_frame.get();
144 RefPtr page = frame->page();
145 if (!page)
146 return;
147
148 if (!page->usesEphemeralSession()) {
149 String message;
150 std::span<const String> additionalArguments;
151 Vector<String> messageArgumentsVector;
152 if (consoleMessage->type() == MessageType::Image) {
153 messageArgumentsVector = RefPtr { consoleMessage->arguments() }->getArgumentsAsStrings();
154 if (!messageArgumentsVector.isEmpty()) {
155 message = messageArgumentsVector.first();
156 additionalArguments = messageArgumentsVector.subspan(1);
157 }
158 } else
159 message = consoleMessage->message();
160
161 page->chrome().client().addMessageToConsole(consoleMessage->source(), consoleMessage->level(), message, consoleMessage->line(), consoleMessage->column(), consoleMessage->url());
162
163 if (RefPtr consoleMessageListener = page->consoleMessageListenerForTesting())
164 consoleMessageListener->invoke(message);
165
166 if (page->settings().logsPageMessagesToSystemConsoleEnabled() || shouldPrintExceptions()) [[unlikely]]
167 logMessageToSystemConsole(*consoleMessage);
168 }
169
170#if ENABLE(WEBDRIVER_BIDI)(defined 1 && 1)
171 AutomationInstrumentation::addMessageToConsole(consoleMessage);
172#endif
173 InspectorInstrumentation::addMessageToConsole(frame.get(), WTF::move(consoleMessage));
174}
175
176void FrameConsoleClient::addMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier, Document* document)
177{
178 String url;
179 unsigned line = 0;
180 unsigned column = 0;
181 if (document)
182 document->getParserLocation(url, line, column);
183
184 addMessage(source, level, message, url, line, column, nullptr, JSExecState::currentState(), requestIdentifier);
185}
186
187void FrameConsoleClient::addMessage(MessageSource source, MessageLevel level, const String& message, Ref<ScriptCallStack>&& callStack)
188{
189 addMessage(source, level, message, String(), 0, 0, WTF::move(callStack), 0);
190}
191
192void FrameConsoleClient::addMessage(MessageSource source, MessageLevel level, const String& messageText, const String& suggestedURL, unsigned suggestedLineNumber, unsigned suggestedColumnNumber, RefPtr<ScriptCallStack>&& callStack, JSC::JSGlobalObject* lexicalGlobalObject, unsigned long requestIdentifier)
193{
194 if (muteCount && source != MessageSource::ConsoleAPI)
195 return;
196
197 std::unique_ptr<Inspector::ConsoleMessage> message;
198
199 if (callStack)
200 message = makeUnique<Inspector::ConsoleMessage>(source, MessageType::Log, level, messageText, callStack.releaseNonNull(), requestIdentifier);
201 else
202 message = makeUnique<Inspector::ConsoleMessage>(source, MessageType::Log, level, messageText, suggestedURL, suggestedLineNumber, suggestedColumnNumber, lexicalGlobalObject, requestIdentifier);
203
204 addMessage(WTF::move(message));
205}
206
207void FrameConsoleClient::messageWithTypeAndLevel(MessageType type, MessageLevel level, JSC::JSGlobalObject* lexicalGlobalObject, Ref<Inspector::ScriptArguments>&& arguments)
208{
209 String messageText;
210 std::span<const String> additionalArguments;
211 Vector<String> messageArgumentsVector = arguments->getArgumentsAsStrings();
212 if (!messageArgumentsVector.isEmpty()) {
213 messageText = messageArgumentsVector.first();
214 additionalArguments = messageArgumentsVector.subspan(1);
215 }
216
217 auto message = makeUnique<Inspector::ConsoleMessage>(MessageSource::ConsoleAPI, type, level, messageText, arguments.copyRef(), lexicalGlobalObject);
218
219 String url = message->url();
220 unsigned lineNumber = message->line();
221 unsigned columnNumber = message->column();
222
223#if ENABLE(WEBDRIVER_BIDI)(defined 1 && 1)
224 AutomationInstrumentation::addMessageToConsole(message);
225#endif
226 Ref frame = m_frame.get();
227 InspectorInstrumentation::addMessageToConsole(frame.get(), WTF::move(message));
228
229 RefPtr page = frame->page();
230 if (!page)
231 return;
232
233 if (page->usesEphemeralSession())
234 return;
235
236 if (!messageArgumentsVector.isEmpty()) {
237 page->chrome().client().addMessageToConsole(MessageSource::ConsoleAPI, level, messageText, lineNumber, columnNumber, url);
238
239 if (RefPtr consoleMessageListener = page->consoleMessageListenerForTesting())
240 consoleMessageListener->invoke(messageText);
241 }
242
243 if (page->settings().logsPageMessagesToSystemConsoleEnabled() || FrameConsoleClient::shouldPrintExceptions())
244 ConsoleClient::printConsoleMessageWithArguments(MessageSource::ConsoleAPI, type, level, lexicalGlobalObject, WTF::move(arguments));
245}
246
247void FrameConsoleClient::count(JSC::JSGlobalObject* lexicalGlobalObject, const String& label)
248{
249 Ref frame = m_frame.get();
250 InspectorInstrumentation::consoleCount(frame.get(), lexicalGlobalObject, label);
251}
252
253void FrameConsoleClient::countReset(JSC::JSGlobalObject* lexicalGlobalObject, const String& label)
254{
255 Ref frame = m_frame.get();
256 InspectorInstrumentation::consoleCountReset(frame.get(), lexicalGlobalObject, label);
257}
258
259void FrameConsoleClient::profile(JSC::JSGlobalObject*, const String& title)
260{
261 Ref frame = m_frame.get();
262 InspectorInstrumentation::startProfiling(frame.get(), title);
263}
264
265void FrameConsoleClient::profileEnd(JSC::JSGlobalObject*, const String& title)
266{
267 Ref frame = m_frame.get();
268 // FIXME: <https://webkit.org/b/153499> Web Inspector: console.profile should use the new Sampling Profiler
269 InspectorInstrumentation::stopProfiling(frame.get(), title);
270}
271
272void FrameConsoleClient::takeHeapSnapshot(JSC::JSGlobalObject*, const String& title)
273{
274 Ref frame = m_frame.get();
275 InspectorInstrumentation::takeHeapSnapshot(frame.get(), title);
276}
277
278void FrameConsoleClient::time(JSC::JSGlobalObject* lexicalGlobalObject, const String& label)
279{
280 Ref frame = m_frame.get();
281 InspectorInstrumentation::startConsoleTiming(frame.get(), lexicalGlobalObject, label);
282}
283
284void FrameConsoleClient::timeLog(JSC::JSGlobalObject* lexicalGlobalObject, const String& label, Ref<ScriptArguments>&& arguments)
285{
286 Ref frame = m_frame.get();
287 InspectorInstrumentation::logConsoleTiming(frame.get(), lexicalGlobalObject, label, WTF::move(arguments));
288}
289
290void FrameConsoleClient::timeEnd(JSC::JSGlobalObject* lexicalGlobalObject, const String& label)
291{
292 Ref frame = m_frame.get();
293 InspectorInstrumentation::stopConsoleTiming(frame.get(), lexicalGlobalObject, label);
294}
295
296void FrameConsoleClient::timeStamp(JSC::JSGlobalObject*, Ref<ScriptArguments>&& arguments)
297{
298 Ref frame = m_frame.get();
299 InspectorInstrumentation::consoleTimeStamp(frame.get(), WTF::move(arguments));
300}
301
302static JSC::JSObject* objectArgumentAt(ScriptArguments& arguments, unsigned index)
303{
304 return arguments.argumentCount() > index ? arguments.argumentAt(index).getObject() : nullptr;
305}
306
307static RefPtr<CanvasRenderingContext> canvasRenderingContext(JSC::VM& vm, JSC::JSValue target)
308{
309 if (RefPtr canvas = JSHTMLCanvasElement::toWrapped(vm, target))
310 return canvas->renderingContext();
311#if ENABLE(OFFSCREEN_CANVAS)(defined 1 && 1)
312 if (RefPtr canvas = JSOffscreenCanvas::toWrapped(vm, target))
313 return canvas->renderingContext();
314 if (RefPtr context = JSOffscreenCanvasRenderingContext2D::toWrapped(vm, target))
315 return context;
316#endif
317 if (RefPtr context = JSCanvasRenderingContext2D::toWrapped(vm, target))
318 return context;
319 if (RefPtr context = JSImageBitmapRenderingContext::toWrapped(vm, target))
320 return context;
321#if ENABLE(WEBGL)(defined 1 && 1)
322 if (RefPtr context = JSWebGLRenderingContext::toWrapped(vm, target))
323 return context;
324 if (RefPtr context = JSWebGL2RenderingContext::toWrapped(vm, target))
325 return context;
326#endif
327 return nullptr;
328}
329
330void FrameConsoleClient::record(JSC::JSGlobalObject* lexicalGlobalObject, Ref<ScriptArguments>&& arguments)
331{
332 if (!InspectorInstrumentation::hasFrontends()) [[likely]]
333 return;
334
335 if (auto* target = objectArgumentAt(arguments, 0)) {
336 if (RefPtr context = canvasRenderingContext(lexicalGlobalObject->vm(), target))
337 InspectorInstrumentation::consoleStartRecordingCanvas(*context, *lexicalGlobalObject, objectArgumentAt(arguments, 1));
338 }
339}
340
341void FrameConsoleClient::recordEnd(JSC::JSGlobalObject* lexicalGlobalObject, Ref<ScriptArguments>&& arguments)
342{
343 if (!InspectorInstrumentation::hasFrontends()) [[likely]]
344 return;
345
346 if (auto* target = objectArgumentAt(arguments, 0)) {
347 if (RefPtr context = canvasRenderingContext(lexicalGlobalObject->vm(), target))
348 InspectorInstrumentation::consoleStopRecordingCanvas(*context);
349 }
350}
351
352void FrameConsoleClient::screenshot(JSC::JSGlobalObject* lexicalGlobalObject, Ref<ScriptArguments>&& arguments)
353{
354 JSC::VM& vm = lexicalGlobalObject->vm();
355 String dataURL;
356 JSC::JSValue target;
357
358 auto timestamp = WallTime::now();
359
360 if (arguments->argumentCount()) {
361 auto possibleTarget = arguments->argumentAt(0);
362
363 if (RefPtr node = JSNode::toWrapped(vm, possibleTarget)) {
364 target = possibleTarget;
365 if (InspectorInstrumentation::hasFrontends()) [[unlikely]] {
366 RefPtr<ImageBuffer> snapshot;
367
368 // Only try to do something special for subclasses of Node if they're detached from the DOM tree.
369 if (!node->document().contains(*node)) {
370 auto snapshotImageElement = [&snapshot] (HTMLImageElement& imageElement) {
371 if (auto* cachedImage = imageElement.cachedImage()) {
Local variable 'cachedImage' is uncounted and unsafe
372 if (RefPtr image = cachedImage->image(); image && image != &Image::nullImage()) {
373 snapshot = ImageBuffer::create(image->size(), RenderingMode::Unaccelerated, RenderingPurpose::Unspecified, /* scale */ 1, DestinationColorSpace::SRGB(), PixelFormat::BGRA8);
374 snapshot->context().drawImage(*image, FloatPoint(0, 0));
375 }
376 }
377 };
378
379 if (RefPtr imgElement = dynamicDowncast<HTMLImageElement>(node))
380 snapshotImageElement(*imgElement);
381 else if (RefPtr pictureElement = dynamicDowncast<HTMLPictureElement>(node)) {
382 if (RefPtr firstImage = childrenOfType<HTMLImageElement>(*pictureElement).first())
383 snapshotImageElement(*firstImage);
384 }
385#if ENABLE(VIDEO)(defined 1 && 1)
386 else if (RefPtr videoElement = dynamicDowncast<HTMLVideoElement>(node)) {
387 unsigned videoWidth = videoElement->videoWidth();
388 unsigned videoHeight = videoElement->videoHeight();
389 snapshot = ImageBuffer::create(FloatSize(videoWidth, videoHeight), RenderingMode::Unaccelerated, RenderingPurpose::Unspecified, /* scale */ 1, DestinationColorSpace::SRGB(), PixelFormat::BGRA8);
390 videoElement->paintCurrentFrameInContext(snapshot->context(), FloatRect(0, 0, videoWidth, videoHeight));
391 }
392#endif
393 else if (RefPtr canvasElement = dynamicDowncast<HTMLCanvasElement>(node)) {
394 if (RefPtr canvasRenderingContext = canvasElement->renderingContext()) {
395 if (auto result = InspectorCanvas::getContentAsDataURL(*canvasRenderingContext))
396 dataURL = result.value();
397 }
398 }
399 }
400
401 if (dataURL.isEmpty()) {
402 if (!snapshot) {
403 Ref frame = m_frame.get();
404 if (RefPtr localMainFrame = frame->localMainFrame())
405 snapshot = WebCore::snapshotNode(*localMainFrame, *node, { { }, PixelFormat::BGRA8, DestinationColorSpace::SRGB() });
406 }
407
408 if (snapshot)
409 dataURL = encodeDataURL(WTF::move(snapshot), "image/png"_s);
410 }
411 }
412 } else if (RefPtr imageData = JSImageData::toWrapped(vm, possibleTarget)) {
413 target = possibleTarget;
414 if (InspectorInstrumentation::hasFrontends()) [[unlikely]] {
415 if (RefPtr imageBuffer = ImageBuffer::create(imageData->size(), RenderingMode::Unaccelerated, RenderingPurpose::Unspecified, /* scale */ 1, DestinationColorSpace::SRGB(), PixelFormat::BGRA8)) {
416 imageBuffer->putPixelBuffer(imageData->byteArrayPixelBuffer().get(), IntRect(IntPoint(), imageData->size()));
417 dataURL = encodeDataURL(WTF::move(imageBuffer), "image/png"_s);
418 }
419 }
420 } else if (RefPtr imageBitmap = JSImageBitmap::toWrapped(vm, possibleTarget)) {
421 target = possibleTarget;
422 if (InspectorInstrumentation::hasFrontends()) [[unlikely]] {
423 if (RefPtr imageBuffer = imageBitmap->buffer())
424 dataURL = encodeDataURL(WTF::move(imageBuffer), "image/png"_s);
425 }
426 } else if (RefPtr context = canvasRenderingContext(vm, possibleTarget)) {
427 target = possibleTarget;
428 if (InspectorInstrumentation::hasFrontends()) [[unlikely]] {
429 if (auto result = InspectorCanvas::getContentAsDataURL(*context))
430 dataURL = result.value();
431 }
432 } else if (RefPtr rect = JSDOMRectReadOnly::toWrapped(vm, possibleTarget)) {
433 target = possibleTarget;
434 if (InspectorInstrumentation::hasFrontends()) [[unlikely]] {
435 Ref frame = m_frame.get();
436 if (RefPtr localMainFrame = frame->localMainFrame()) {
437 if (RefPtr snapshot = WebCore::snapshotFrameRect(*localMainFrame, enclosingIntRect(rect->toFloatRect()), { { }, PixelFormat::BGRA8, DestinationColorSpace::SRGB() }))
438 dataURL = encodeDataURL(WTF::move(snapshot), "image/png"_s);
439 }
440 }
441 } else {
442 String base64;
443 if (possibleTarget.getString(lexicalGlobalObject, base64) && base64.length() > 5 && startsWithLettersIgnoringASCIICase(base64, "data:"_s)) {
444 target = possibleTarget;
445 dataURL = base64;
446 }
447 }
448 }
449
450 if (InspectorInstrumentation::hasFrontends()) [[unlikely]] {
451 if (!target) {
452 Ref frame = m_frame.get();
453 if (RefPtr localMainFrame = frame->localMainFrame()) {
454 // If no target is provided, capture an image of the viewport.
455 auto viewportRect = protect(localMainFrame->view())->unobscuredContentRect();
456 if (RefPtr snapshot = WebCore::snapshotFrameRect(*localMainFrame, viewportRect, { { }, PixelFormat::BGRA8, DestinationColorSpace::SRGB() }))
457 dataURL = encodeDataURL(WTF::move(snapshot), "image/png"_s);
458 }
459 }
460
461 if (dataURL.isEmpty()) {
462 addMessage(makeUnique<Inspector::ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Image, MessageLevel::Error, "Could not capture screenshot"_s, WTF::move(arguments)));
463 return;
464 }
465 }
466
467 Vector<JSC::Strong<JSC::Unknown>> adjustedArguments;
468 adjustedArguments.reserveInitialCapacity(arguments->argumentCount() + !target);
469 adjustedArguments.append({ vm, target ? target : JSC::jsNontrivialString(vm, "Viewport"_s) });
470 for (size_t i = (!target ? 0 : 1); i < arguments->argumentCount(); ++i)
471 adjustedArguments.append({ vm, arguments->argumentAt(i) });
472 addMessage(makeUnique<Inspector::ConsoleMessage>(MessageSource::ConsoleAPI, MessageType::Image, MessageLevel::Log, dataURL, ScriptArguments::create(lexicalGlobalObject, WTF::move(adjustedArguments)), lexicalGlobalObject, /* requestIdentifier */ 0, timestamp));
473}
474
475} // namespace WebCore