Bug Summary

File:Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore/inspector/InspectorResourceUtilities.cpp
Warning:line 115, column 15
Local variable 'cachedResource' 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 UnifiedSource259.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/UnifiedSource259.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/UnifiedSource259.plist -x c++ /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/DerivedSources/WebCore/unified-sources/UnifiedSource259.cpp
1/*
2 * Copyright (C) 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 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include "InspectorResourceUtilities.h"
28
29#include "CachedCSSStyleSheet.h"
30#include "CachedResourceLoader.h"
31#include "CachedScript.h"
32#include "DocumentInlines.h"
33#include "DocumentLoader.h"
34#include "DocumentResourceLoader.h"
35#include "FrameLoader.h"
36#include "InspectorResourceType.h"
37#include "LocalFrame.h"
38#include "MIMETypeRegistry.h"
39#include "MemoryCache.h"
40#include "SharedBuffer.h"
41
42namespace Inspector {
43
44namespace ResourceUtilities {
45
46using namespace WebCore;
47
48Inspector::Protocol::Page::ResourceType resourceTypeToProtocol(Inspector::ResourceType resourceType)
49{
50 switch (resourceType) {
51 case ResourceType::Document:
52 return Inspector::Protocol::Page::ResourceType::Document;
53 case ResourceType::Image:
54 return Inspector::Protocol::Page::ResourceType::Image;
55 case ResourceType::Font:
56 return Inspector::Protocol::Page::ResourceType::Font;
57 case ResourceType::StyleSheet:
58 return Inspector::Protocol::Page::ResourceType::StyleSheet;
59 case ResourceType::Script:
60 return Inspector::Protocol::Page::ResourceType::Script;
61 case ResourceType::XHR:
62 return Inspector::Protocol::Page::ResourceType::XHR;
63 case ResourceType::Fetch:
64 return Inspector::Protocol::Page::ResourceType::Fetch;
65 case ResourceType::Ping:
66 return Inspector::Protocol::Page::ResourceType::Ping;
67 case ResourceType::Beacon:
68 return Inspector::Protocol::Page::ResourceType::Beacon;
69 case ResourceType::WebSocket:
70 return Inspector::Protocol::Page::ResourceType::WebSocket;
71 case ResourceType::EventSource:
72 return Inspector::Protocol::Page::ResourceType::EventSource;
73 case ResourceType::Other:
74 return Inspector::Protocol::Page::ResourceType::Other;
75#if ENABLE(APPLICATION_MANIFEST)(defined 1 && 1)
76 case ResourceType::ApplicationManifest:
77 break;
78#endif
79 }
80 return Inspector::Protocol::Page::ResourceType::Other;
81}
82
83[[nodiscard]] static bool decodeBuffer(std::span<const uint8_t> buffer, const String& textEncodingName, String* result)
84{
85 if (buffer.data()) {
86 PAL::TextEncoding encoding(textEncodingName);
87 if (!encoding.isValid())
88 encoding = PAL::WindowsLatin1Encoding();
89 *result = encoding.decode(buffer);
90 return true;
91 }
92 return false;
93}
94
95static bool dataContent(std::span<const uint8_t> data, const String& textEncodingName, bool withBase64Encode, String* result)
96{
97 if (withBase64Encode) {
98 *result = base64EncodeToString(data);
99 return true;
100 }
101
102 return decodeBuffer(data, textEncodingName, result);
103}
104
105bool sharedBufferContent(RefPtr<FragmentedSharedBuffer>&& buffer, const String& textEncodingName, bool withBase64Encode, String* result)
106{
107 return dataContent(buffer ? buffer->makeContiguous()->span() : std::span<const uint8_t> { }, textEncodingName, withBase64Encode, result);
108}
109
110Vector<CachedResource*> cachedResourcesForFrame(LocalFrame* frame)
111{
112 Vector<CachedResource*> result;
113
114 for (auto& cachedResourceHandle : frame->document()->cachedResourceLoader().allCachedResources().values()) {
115 auto* cachedResource = cachedResourceHandle.get();
Local variable 'cachedResource' is uncounted and unsafe
116 if (cachedResource->resourceRequest().hiddenFromInspector())
117 continue;
118
119 switch (cachedResource->type()) {
120 case CachedResource::Type::ImageResource:
121 // Skip images that were not auto loaded (images disabled in the user agent).
122 case CachedResource::Type::SVGFontResource:
123 case CachedResource::Type::FontResource:
124 // Skip fonts that were referenced in CSS but never used/downloaded.
125 if (cachedResource->stillNeedsLoad())
126 continue;
127 break;
128 default:
129 // All other CachedResource types download immediately.
130 break;
131 }
132
133 result.append(cachedResource);
134 }
135
136 return result;
137}
138
139bool mainResourceContent(LocalFrame* frame, bool withBase64Encode, String* result)
140{
141 RefPtr<FragmentedSharedBuffer> buffer = frame->loader().documentLoader()->mainResourceData();
142 if (!buffer)
143 return false;
144 return dataContent(buffer->makeContiguous()->span(), frame->document()->encoding(), withBase64Encode, result);
145}
146
147void resourceContent(Inspector::Protocol::ErrorString& errorString, LocalFrame* frame, const URL& url, String* result, bool* base64Encoded)
148{
149 RefPtr<DocumentLoader> loader = assertDocumentLoader(errorString, frame);
150 if (!loader)
151 return;
152
153 RefPtr<FragmentedSharedBuffer> buffer;
154 bool success = false;
155 if (equalIgnoringFragmentIdentifier(url, loader->url())) {
156 *base64Encoded = false;
157 success = mainResourceContent(frame, *base64Encoded, result);
158 }
159
160 if (!success) {
161 if (auto* resource = cachedResource(frame, url))
162 success = cachedResourceContent(*resource, result, base64Encoded);
163 }
164
165 if (!success)
166 errorString = "Missing resource for given url"_s;
167}
168
169String sourceMapURLForResource(CachedResource* cachedResource)
170{
171 if (!cachedResource)
172 return String();
173
174 // Scripts are handled in a separate path.
175 if (cachedResource->type() != CachedResource::Type::CSSStyleSheet)
176 return String();
177
178 String sourceMapHeader = cachedResource->response().httpHeaderField(HTTPHeaderName::SourceMap);
179 if (!sourceMapHeader.isEmpty())
180 return sourceMapHeader;
181
182 sourceMapHeader = cachedResource->response().httpHeaderField(HTTPHeaderName::XSourceMap);
183 if (!sourceMapHeader.isEmpty())
184 return sourceMapHeader;
185
186 String content;
187 bool base64Encoded;
188 if (cachedResourceContent(*cachedResource, &content, &base64Encoded) && !base64Encoded)
189 return ContentSearchUtilities::findStylesheetSourceMapURL(content);
190
191 return String();
192}
193
194CachedResource* cachedResource(const LocalFrame* frame, const URL& url)
195{
196 if (url.isNull())
197 return nullptr;
198
199 CachedResource* cachedResource = frame->document()->cachedResourceLoader().cachedResource(MemoryCache::removeFragmentIdentifierIfNeeded(url));
200 if (!cachedResource) {
201 ResourceRequest request(URL { url });
202 request.setDomainForCachePartition(frame->document()->domainForCachePartition());
203 cachedResource = MemoryCache::singleton().resourceForRequest(request, frame->page()->sessionID());
204 }
205
206 return cachedResource;
207}
208
209Inspector::ResourceType inspectorResourceType(CachedResource::Type type)
210{
211 switch (type) {
212 case CachedResource::Type::ImageResource:
213 return ResourceType::Image;
214 case CachedResource::Type::SVGFontResource:
215 case CachedResource::Type::FontResource:
216 return ResourceType::Font;
217#if ENABLE(XSLT)(defined 1 && 1)
218 case CachedResource::Type::XSLStyleSheet:
219#endif
220 case CachedResource::Type::CSSStyleSheet:
221 return ResourceType::StyleSheet;
222 case CachedResource::Type::JSON: // FIXME: Add ResourceType::JSON.
223 case CachedResource::Type::Script:
224 return ResourceType::Script;
225 case CachedResource::Type::MainResource:
226 return ResourceType::Document;
227 case CachedResource::Type::Beacon:
228 return ResourceType::Beacon;
229#if ENABLE(APPLICATION_MANIFEST)(defined 1 && 1)
230 case CachedResource::Type::ApplicationManifest:
231 return ResourceType::ApplicationManifest;
232#endif
233 case CachedResource::Type::Ping:
234 return ResourceType::Ping;
235 case CachedResource::Type::MediaResource:
236 case CachedResource::Type::Icon:
237 case CachedResource::Type::RawResource:
238 default:
239 return ResourceType::Other;
240 }
241}
242
243ResourceType inspectorResourceType(const CachedResource& cachedResource)
244{
245 if (cachedResource.type() == CachedResource::Type::MainResource && MIMETypeRegistry::isSupportedImageMIMEType(cachedResource.mimeType()))
246 return ResourceType::Image;
247
248 if (cachedResource.type() == CachedResource::Type::RawResource) {
249 switch (cachedResource.resourceRequest().requester()) {
250 case ResourceRequestRequester::Fetch:
251 return ResourceType::Fetch;
252 case ResourceRequestRequester::Main:
253 return ResourceType::Document;
254 case ResourceRequestRequester::EventSource:
255 return ResourceType::EventSource;
256 default:
257 return ResourceType::XHR;
258 }
259 }
260
261 return inspectorResourceType(cachedResource.type());
262}
263
264Inspector::Protocol::Page::ResourceType cachedResourceTypeToProtocol(const CachedResource& cachedResource)
265{
266 return resourceTypeToProtocol(inspectorResourceType(cachedResource));
267}
268
269LocalFrame* findFrameWithSecurityOrigin(Page& page, const String& originRawString)
270{
271 // FIXME: this frame tree traversal needs to be redesigned for Site Isolation.
272 for (SUPPRESS_UNCOUNTED_LOCAL[[clang::suppress]] auto* frame = &page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
273 SUPPRESS_UNCOUNTED_LOCAL[[clang::suppress]] auto* localFrame = dynamicDowncast<LocalFrame>(frame);
274 if (!localFrame)
275 continue;
276 if (localFrame->document()->securityOrigin().toRawString() == originRawString)
277 return localFrame;
278 }
279 return nullptr;
280}
281
282DocumentLoader* assertDocumentLoader(Inspector::Protocol::ErrorString& errorString, LocalFrame* frame)
283{
284 FrameLoader& frameLoader = frame->loader();
285 SUPPRESS_UNCOUNTED_LOCAL[[clang::suppress]] auto* documentLoader = frameLoader.documentLoader();
286 if (!documentLoader)
287 errorString = "Missing document loader for given frame"_s;
288 return documentLoader;
289}
290
291bool shouldTreatAsText(const String& mimeType)
292{
293 return startsWithLettersIgnoringASCIICase(mimeType, "text/"_s)
294 || MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType)
295 || MIMETypeRegistry::isSupportedJSONMIMEType(mimeType)
296 || MIMETypeRegistry::isXMLMIMEType(mimeType)
297 || MIMETypeRegistry::isTextMediaPlaylistMIMEType(mimeType);
298}
299
300Ref<TextResourceDecoder> createTextDecoder(const String& mimeType, const String& textEncodingName)
301{
302 if (!textEncodingName.isEmpty())
303 return TextResourceDecoder::create("text/plain"_s, textEncodingName);
304
305 if (MIMETypeRegistry::isTextMIMEType(mimeType))
306 return TextResourceDecoder::create(mimeType, "UTF-8"_s);
307
308 if (MIMETypeRegistry::isXMLMIMEType(mimeType)) {
309 auto decoder = TextResourceDecoder::create("application/xml"_s);
310 decoder->useLenientXMLDecoding();
311 return decoder;
312 }
313
314 return TextResourceDecoder::create("text/plain"_s, "UTF-8"_s);
315}
316
317std::optional<String> textContentForCachedResource(CachedResource& cachedResource)
318{
319 if (!shouldTreatAsText(cachedResource.mimeType()))
320 return std::nullopt;
321
322 String result;
323 bool base64Encoded;
324 if (cachedResourceContent(cachedResource, &result, &base64Encoded)) {
325 ASSERT(!base64Encoded)((void)0);
326 return result;
327 }
328
329 return std::nullopt;
330}
331
332bool cachedResourceContent(CachedResource& resource, String* result, bool* base64Encoded)
333{
334 ASSERT(result)((void)0);
335 ASSERT(base64Encoded)((void)0);
336
337 if (!resource.encodedSize()) {
338 *base64Encoded = false;
339 *result = String();
340 return true;
341 }
342
343 switch (resource.type()) {
344 case CachedResource::Type::CSSStyleSheet:
345 *base64Encoded = false;
346 *result = downcast<CachedCSSStyleSheet>(resource).sheetText();
347 // The above can return a null String if the MIME type is invalid.
348 return !result->isNull();
349 case CachedResource::Type::JSON:
350 case CachedResource::Type::Script:
351 *base64Encoded = false;
352 *result = downcast<CachedScript>(resource).script().toString();
353 return true;
354 default:
355 RefPtr buffer = resource.resourceBuffer();
356 if (!buffer)
357 return false;
358
359 if (shouldTreatAsText(resource.mimeType())) {
360 auto decoder = createTextDecoder(resource.mimeType(), resource.response().textEncodingName());
361 *base64Encoded = false;
362 *result = decoder->decodeAndFlush(buffer->makeContiguous()->span());
363 return true;
364 }
365
366 *base64Encoded = true;
367 *result = base64EncodeToString(buffer->makeContiguous()->span());
368 return true;
369 }
370}
371
372} // namespace ResourceUtilities
373
374} // namespace Inspector