Bug Summary

File:Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore/page/PageSerializer.cpp
Warning:line 314, column 15
Local variable 'image' 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 UnifiedSource303.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/UnifiedSource303.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/UnifiedSource303.plist -x c++ /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/DerivedSources/WebCore/unified-sources/UnifiedSource303.cpp
1/*
2 * Copyright (C) 2023 Apple Inc. All rights reserved.
3 * Copyright (C) 2011-2013 Google 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 are
7 * met:
8 *
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
14 * distribution.
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#include "config.h"
33#include "PageSerializer.h"
34
35#include "CSSFontFaceRule.h"
36#include "CSSImageValue.h"
37#include "CSSImportRule.h"
38#include "CSSStyleRule.h"
39#include "CachedImage.h"
40#include "CommonAtomStrings.h"
41#include "ContainerNodeInlines.h"
42#include "DocumentInlines.h"
43#include "ElementInlines.h"
44#include "HTMLFrameOwnerElement.h"
45#include "HTMLHeadElement.h"
46#include "HTMLImageElement.h"
47#include "HTMLLinkElement.h"
48#include "HTMLMetaCharsetParser.h"
49#include "HTMLMetaElement.h"
50#include "HTMLNames.h"
51#include "HTMLObjectElement.h"
52#include "HTMLStyleElement.h"
53#include "HTTPParsers.h"
54#include "Image.h"
55#include "LocalFrameInlines.h"
56#include "MarkupAccumulator.h"
57#include "Page.h"
58#include "RenderElement.h"
59#include "StyleCachedImage.h"
60#include "StyleImage.h"
61#include "StylePropertiesInlines.h"
62#include "StyleRule.h"
63#include "StyleSheetContents.h"
64#include "Text.h"
65#include <pal/text/TextEncoding.h>
66#include <wtf/text/CString.h>
67#include <wtf/text/MakeString.h>
68#include <wtf/text/StringBuilder.h>
69#include <wtf/text/WTFString.h>
70
71namespace WebCore {
72
73static bool isCharsetSpecifyingNode(const HTMLMetaElement& element)
74{
75 if (!element.hasAttributes())
76 return false;
77 Vector<std::pair<StringView, StringView>> attributes;
78 for (auto& attribute : element.attributes()) {
79 if (attribute.name().hasPrefix())
80 continue;
81 attributes.append({ StringView { attribute.name().localName() }, StringView { attribute.value() } });
82 }
83 return HTMLMetaCharsetParser::encodingFromMetaAttributes(attributes).isValid();
84}
85
86template<typename NodeType> static bool isCharsetSpecifyingNode(const NodeType& node)
87{
88 auto* metaElement = dynamicDowncast<HTMLMetaElement>(node);
89 return metaElement && isCharsetSpecifyingNode(*metaElement);
90}
91
92static bool shouldIgnoreElement(const Element& element)
93{
94 return element.hasTagName(HTMLNames::scriptTag) || element.hasTagName(HTMLNames::noscriptTag) || isCharsetSpecifyingNode(element);
95}
96
97static const QualifiedName& NODELETE[[clang::annotate_type("webkit.nodelete")]] frameOwnerURLAttributeName(const HTMLFrameOwnerElement& frameOwner)
98{
99 // FIXME: We should support all frame owners including applets.
100 return is<HTMLObjectElement>(frameOwner) ? HTMLNames::dataAttr : HTMLNames::srcAttr;
101}
102
103class PageSerializer::SerializerMarkupAccumulator final : public MarkupAccumulator {
104public:
105 SerializerMarkupAccumulator(PageSerializer&, Document&, Vector<Ref<Node>>*);
106
107private:
108 PageSerializer& m_serializer;
109 WeakRef<Document, WeakPtrImplWithEventTargetData> m_document;
110
111 void appendText(StringBuilder&, const Text&) override;
112 void appendStartTag(StringBuilder&, const Element&, Namespaces*) override;
113 void appendCustomAttributes(StringBuilder&, const Element&, Namespaces*) override;
114 void appendEndTag(StringBuilder&, const Element&) override;
115};
116
117PageSerializer::SerializerMarkupAccumulator::SerializerMarkupAccumulator(PageSerializer& serializer, Document& document, Vector<Ref<Node>>* nodes)
118 : MarkupAccumulator(nodes, ResolveURLs::Yes, MarkupAccumulator::serializationSyntax(document))
119 , m_serializer(serializer)
120 , m_document(document)
121{
122 // MarkupAccumulator does not serialize the <?xml ... line, so we add it explicitly to ensure the right encoding is specified.
123 if (m_document->isXMLDocument() || m_document->xmlStandalone())
124 append("<?xml version=\""_s, m_document->xmlVersion(), "\" encoding=\""_s, m_document->charset(), "\"?>"_s);
125}
126
127void PageSerializer::SerializerMarkupAccumulator::appendText(StringBuilder& out, const Text& text)
128{
129 RefPtr parent = text.parentElement();
130 if (parent && !shouldIgnoreElement(*parent))
131 MarkupAccumulator::appendText(out, text);
132}
133
134void PageSerializer::SerializerMarkupAccumulator::appendStartTag(StringBuilder& out, const Element& element, Namespaces* namespaces)
135{
136 if (!shouldIgnoreElement(element))
137 MarkupAccumulator::appendStartTag(out, element, namespaces);
138
139 if (element.hasTagName(HTMLNames::headTag))
140 out.append("<meta charset=\""_s, m_document->charset(), "\">"_s);
141
142 // FIXME: For object (plugins) tags and video tag we could replace them by an image of their current contents.
143}
144
145void PageSerializer::SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& out, const Element& element, Namespaces* namespaces)
146{
147 RefPtr frameOwner = dynamicDowncast<HTMLFrameOwnerElement>(element);
148 if (!frameOwner)
149 return;
150
151 RefPtr frame = dynamicDowncast<LocalFrame>(frameOwner->contentFrame());
152 if (!frame)
153 return;
154
155 auto url = frame->document()->url();
156 if (url.isValid() && !url.protocolIsAbout())
157 return;
158
159 // We need to give a fake location to blank frames so they can be referenced by the serialized frame.
160 url = m_serializer.urlForBlankFrame(frame.get());
161 appendAttribute(out, element, Attribute(frameOwnerURLAttributeName(*frameOwner), AtomString { url.string() }), namespaces);
162}
163
164void PageSerializer::SerializerMarkupAccumulator::appendEndTag(StringBuilder& out, const Element& element)
165{
166 if (!shouldIgnoreElement(element))
167 MarkupAccumulator::appendEndTag(out, element);
168}
169
170PageSerializer::PageSerializer(Vector<PageSerializer::Resource>& resources)
171 : m_resources(resources)
172{
173}
174
175void PageSerializer::serialize(Page& page)
176{
177 if (RefPtr localMainFrame = page.localMainFrame())
178 serializeFrame(localMainFrame.get());
179}
180
181void PageSerializer::serializeFrame(LocalFrame* frame)
182{
183 RefPtr document = frame->document();
184 URL url = document->url();
185 if (!url.isValid() || url.protocolIsAbout()) {
186 // For blank frames we generate a fake URL so they can be referenced by their containing frame.
187 url = urlForBlankFrame(frame);
188 }
189
190 if (m_resourceURLs.contains(url)) {
191 // FIXME: We could have 2 frame with the same URL but which were dynamically changed and have now
192 // different content. So we should serialize both and somehow rename the frame src in the containing
193 // frame. Arg!
194 return;
195 }
196
197 PAL::TextEncoding textEncoding(document->charset());
198 if (!textEncoding.isValid()) {
199 // FIXME: iframes used as images trigger this. We should deal with them correctly.
200 return;
201 }
202
203 Vector<Ref<Node>> serializedNodes;
204 SerializerMarkupAccumulator accumulator(*this, *document, &serializedNodes);
205 String text = accumulator.serializeNodes(*protect(document->documentElement()), SerializedNodes::SubtreeIncludingNode);
206 m_resources.append({ url, document->suggestedMIMEType(), SharedBuffer::create(textEncoding.encode(text, PAL::UnencodableHandling::Entities)) });
207 m_resourceURLs.add(url);
208
209 for (auto&& node : WTF::move(serializedNodes)) {
210 RefPtr element = dynamicDowncast<Element>(WTF::move(node));
211 if (!element)
212 continue;
213 // We have to process in-line style as it might contain some resources (typically background images).
214 if (RefPtr styledElement = dynamicDowncast<StyledElement>(*element))
215 retrieveResourcesForProperties(protect(styledElement->inlineStyle()).get(), document.get());
216
217 if (RefPtr imageElement = dynamicDowncast<HTMLImageElement>(*element)) {
218 auto url = document->completeURL(imageElement->attributeWithoutSynchronization(HTMLNames::srcAttr));
219 auto* cachedImage = imageElement->cachedImage();
220 addImageToResources(cachedImage, imageElement->renderer(), url);
221 } else if (RefPtr linkElement = dynamicDowncast<HTMLLinkElement>(*element)) {
222 if (RefPtr sheet = linkElement->sheet()) {
223 auto url = document->completeURL(linkElement->attributeWithoutSynchronization(HTMLNames::hrefAttr));
224 serializeCSSStyleSheet(sheet.get(), url);
225 ASSERT(m_resourceURLs.contains(url))((void)0);
226 }
227 } else if (RefPtr styleElement = dynamicDowncast<HTMLStyleElement>(*element)) {
228 if (RefPtr sheet = styleElement->sheet())
229 serializeCSSStyleSheet(sheet.get(), URL());
230 }
231 }
232
233 for (RefPtr childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling()) {
234 auto* localFrame = dynamicDowncast<LocalFrame>(childFrame.get());
235 if (!localFrame)
236 continue;
237 serializeFrame(localFrame);
238 }
239}
240
241void PageSerializer::serializeCSSStyleSheet(CSSStyleSheet* styleSheet, const URL& url)
242{
243 StringBuilder cssText;
244 for (unsigned i = 0; i < styleSheet->length(); ++i) {
245 RefPtr rule = styleSheet->item(i);
246 String itemText = rule->cssText();
247 if (!itemText.isEmpty()) {
248 cssText.append(itemText);
249 if (i < styleSheet->length() - 1)
250 cssText.append("\n\n"_s);
251 }
252 RefPtr document = styleSheet->ownerDocument();
253 // Some rules have resources associated with them that we need to retrieve.
254 if (RefPtr importRule = dynamicDowncast<CSSImportRule>(*rule)) {
255 auto importURL = document->completeURL(importRule->href());
256 if (m_resourceURLs.contains(importURL))
257 continue;
258 serializeCSSStyleSheet(protect(importRule->styleSheet()).get(), importURL);
259 } else if (is<CSSFontFaceRule>(*rule)) {
260 // FIXME: Add support for font face rule. It is not clear to me at this point if the actual otf/eot file can
261 // be retrieved from the CSSFontFaceRule object.
262 } else if (RefPtr styleRule = dynamicDowncast<CSSStyleRule>(*rule))
263 retrieveResourcesForRule(styleRule->styleRule(), document.get());
264 }
265
266 if (url.isValid() && !m_resourceURLs.contains(url)) {
267 // FIXME: We should check whether a charset has been specified and if none was found add one.
268 PAL::TextEncoding textEncoding(styleSheet->contents().charset());
269 ASSERT(textEncoding.isValid())((void)0);
270 m_resources.append({ url, cssContentTypeAtom(), SharedBuffer::create(textEncoding.encode(cssText.toString(), PAL::UnencodableHandling::Entities)) });
271 m_resourceURLs.add(url);
272 }
273}
274
275void PageSerializer::addImageToResources(CachedImage* image, RenderElement* imageRenderer, const URL& url)
276{
277 if (!url.isValid() || m_resourceURLs.contains(url))
278 return;
279
280 if (!image || image->image() == &Image::nullImage())
281 return;
282
283 RefPtr<FragmentedSharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
284 if (!data)
285 data = image->image()->data();
286
287 if (!data) {
288 LOG_ERROR("No data for image %s", url.string().utf8().data())((void)0);
289 return;
290 }
291
292 m_resources.append({ url, image->response().mimeType(), data->makeContiguous() });
293 m_resourceURLs.add(url);
294}
295
296void PageSerializer::retrieveResourcesForRule(StyleRule& rule, Document* document)
297{
298 retrieveResourcesForProperties(protect(rule.properties()).ptr(), document);
299}
300
301void PageSerializer::retrieveResourcesForProperties(const StyleProperties* styleDeclaration, Document* document)
302{
303 if (!styleDeclaration)
304 return;
305
306 // The background-image and list-style-image (for ul or ol) are the CSS properties
307 // that make use of images. We iterate to make sure we include any other
308 // image properties there might be.
309 for (auto property : *styleDeclaration) {
310 RefPtr cssValue = dynamicDowncast<CSSImageValue>(property.value());
311 if (!cssValue)
312 continue;
313
314 auto* image = cssValue->cachedImage();
Local variable 'image' is uncounted and unsafe
315 if (!image)
316 continue;
317
318 addImageToResources(image, nullptr, document->completeURL(image->url().string()));
319 }
320}
321
322URL PageSerializer::urlForBlankFrame(LocalFrame* frame)
323{
324 auto iterator = m_blankFrameURLs.find(frame);
325 if (iterator != m_blankFrameURLs.end())
326 return iterator->value;
327 URL fakeURL { makeString("wyciwyg://frame/"_s, m_blankFrameCounter++) };
328 m_blankFrameURLs.add(frame, fakeURL);
329 return fakeURL;
330}
331
332}