Bug Summary

File:root/firefox-clang/obj-x86_64-pc-linux-gnu/image/decoders/./../../../image/decoders/nsPNGDecoder.cpp
Warning:line 808, column 31
Result of 'malloc' is converted to a pointer of type 'uint8_t', which is incompatible with sizeof operand type 'uint32_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Unified_cpp_image_decoders0.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -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 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/image/decoders -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/image/decoders -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -D _GLIBCXX_ASSERTIONS=1 -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D MOZ_SUPPORT_LEAKCHECKING -D STATIC_EXPORTABLE_JS_API -I /root/firefox-clang/image/decoders -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/image/decoders -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /root/firefox-clang/ipc/chromium/src -I /root/firefox-clang/third_party/abseil-cpp -I /root/firefox-clang/toolkit/components/telemetry -I /root/firefox-clang/xpcom/base -I /root/firefox-clang/gfx/2d -I /root/firefox-clang/image -I /root/firefox-clang/media/libyuv/libyuv/include -I /root/firefox-clang/gfx/skia -I /root/firefox-clang/gfx/skia/skia -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=pessimizing-move -Wno-error=large-by-value-copy=128 -Wno-error=implicit-int-float-conversion -Wno-error=thread-safety-analysis -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -Wno-character-conversion -std=gnu++20 -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fno-implicit-modules -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-09-01-224014-2642839-1 -x c++ Unified_cpp_image_decoders0.cpp
1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6#include "nsPNGDecoder.h"
7
8#include <algorithm>
9#include <cstdint>
10
11#include "EXIF.h"
12#include "ImageLogging.h" // Must appear first
13#include "RasterImage.h"
14#include "SurfaceCache.h"
15#include "SurfacePipeFactory.h"
16#include "gfxColor.h"
17#include "gfxPlatform.h"
18#include "imgFrame.h"
19#include "mozilla/DebugOnly.h"
20#include "nsColor.h"
21#include "nsRect.h"
22#include "nspr.h"
23#include "png.h"
24
25using namespace mozilla::gfx;
26
27using std::min;
28
29namespace mozilla {
30namespace image {
31
32static LazyLogModule sPNGLog("PNGDecoder");
33static LazyLogModule sPNGDecoderAccountingLog("PNGDecoderAccounting");
34
35// limit image dimensions (bug #251381, #591822, #967656, and #1283961)
36#ifndef MOZ_PNG_MAX_WIDTH0x7fffffffL
37# define MOZ_PNG_MAX_WIDTH0x7fffffffL 0x7fffffff // Unlimited
38#endif
39#ifndef MOZ_PNG_MAX_HEIGHT0x7fffffffL
40# define MOZ_PNG_MAX_HEIGHT0x7fffffffL 0x7fffffff // Unlimited
41#endif
42
43/* Controls the maximum chunk size configuration for libpng. We set this to a
44 * very large number, 256MB specifically. */
45static constexpr png_alloc_size_t kPngMaxChunkSize = 0x10000000;
46
47nsPNGDecoder::AnimFrameInfo::AnimFrameInfo()
48 : mDispose(DisposalMethod::KEEP), mBlend(BlendMethod::OVER), mTimeout(0) {}
49
50#ifdef PNG_APNG_SUPPORTED
51
52int32_t GetNextFrameDelay(png_structp aPNG, png_infop aInfo) {
53 // Delay, in seconds, is delayNum / delayDen.
54 png_uint_16 delayNum = png_get_next_frame_delay_numMOZ_APNG_get_next_frame_delay_num(aPNG, aInfo);
55 png_uint_16 delayDen = png_get_next_frame_delay_denMOZ_APNG_get_next_frame_delay_den(aPNG, aInfo);
56
57 if (delayNum == 0) {
58 return 0; // SetFrameTimeout() will set to a minimum.
59 }
60
61 if (delayDen == 0) {
62 delayDen = 100; // So says the APNG spec.
63 }
64
65 // Need to cast delay_num to float to have a proper division and
66 // the result to int to avoid a compiler warning.
67 return static_cast<int32_t>(static_cast<double>(delayNum) * 1000 / delayDen);
68}
69
70nsPNGDecoder::AnimFrameInfo::AnimFrameInfo(png_structp aPNG, png_infop aInfo)
71 : mDispose(DisposalMethod::KEEP), mBlend(BlendMethod::OVER), mTimeout(0) {
72 png_byte dispose_op = png_get_next_frame_dispose_opMOZ_APNG_get_next_frame_dispose_op(aPNG, aInfo);
73 png_byte blend_op = png_get_next_frame_blend_opMOZ_APNG_get_next_frame_blend_op(aPNG, aInfo);
74
75 if (dispose_op == PNG_DISPOSE_OP_PREVIOUS0x02) {
76 mDispose = DisposalMethod::RESTORE_PREVIOUS;
77 } else if (dispose_op == PNG_DISPOSE_OP_BACKGROUND0x01) {
78 mDispose = DisposalMethod::CLEAR;
79 } else {
80 mDispose = DisposalMethod::KEEP;
81 }
82
83 if (blend_op == PNG_BLEND_OP_SOURCE0x00) {
84 mBlend = BlendMethod::SOURCE;
85 } else {
86 mBlend = BlendMethod::OVER;
87 }
88
89 mTimeout = GetNextFrameDelay(aPNG, aInfo);
90}
91#endif
92
93// First 8 bytes of a PNG file
94const uint8_t nsPNGDecoder::pngSignatureBytes[] = {137, 80, 78, 71,
95 13, 10, 26, 10};
96
97nsPNGDecoder::nsPNGDecoder(RasterImage* aImage)
98 : Decoder(aImage),
99 mLexer(Transition::ToUnbuffered(State::FINISHED_PNG_DATA, State::PNG_DATA,
100 SIZE_MAX(18446744073709551615UL)),
101 Transition::TerminateSuccess()),
102 mNextTransition(Transition::ContinueUnbuffered(State::PNG_DATA)),
103 mLastChunkLength(0),
104 mPNG(nullptr),
105 mInfo(nullptr),
106 mCMSLine(nullptr),
107 interlacebuf(nullptr),
108 mFormat(SurfaceFormat::UNKNOWN),
109 mChannels(0),
110 mPass(0),
111 mFrameIsHidden(false),
112 mDisablePremultipliedAlpha(false),
113 mGotInfoCallback(false),
114 mUsePipeTransform(false),
115 mErrorIsRecoverable(false),
116 mNumFrames(0) {}
117
118nsPNGDecoder::~nsPNGDecoder() {
119 if (mPNG) {
120 png_destroy_read_structMOZ_PNG_dest_read_str(&mPNG, mInfo ? &mInfo : nullptr, nullptr);
121 }
122 if (mCMSLine) {
123 free(mCMSLine);
124 }
125 if (interlacebuf) {
126 free(interlacebuf);
127 }
128}
129
130nsPNGDecoder::TransparencyType nsPNGDecoder::GetTransparencyType(
131 const UnorientedIntRect& aFrameRect) {
132 MOZ_ASSERT(GetOrientation().IsIdentity() || !HasAnimation(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetOrientation().IsIdentity() || !HasAnimation())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetOrientation().IsIdentity() || !HasAnimation()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("GetOrientation().IsIdentity() || !HasAnimation()"
" (" "can't be oriented and have animation" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 133); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetOrientation().IsIdentity() || !HasAnimation()"
") (" "can't be oriented and have animation" ")"); do { MOZ_CrashSequence
(__null, 133); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
133 "can't be oriented and have animation")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetOrientation().IsIdentity() || !HasAnimation())>
::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetOrientation().IsIdentity() || !HasAnimation()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("GetOrientation().IsIdentity() || !HasAnimation()"
" (" "can't be oriented and have animation" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 133); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetOrientation().IsIdentity() || !HasAnimation()"
") (" "can't be oriented and have animation" ")"); do { MOZ_CrashSequence
(__null, 133); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
134
135 // Check if the image has a transparent color in its palette.
136 if (HasAlphaChannel()) {
137 return TransparencyType::eAlpha;
138 }
139 if (!aFrameRect.IsEqualEdges(
140 UnorientedIntRect(IntPointTyped<mozilla::UnorientedPixel>(0, 0),
141 GetOrientation().ToUnoriented(Size())))) {
142 MOZ_ASSERT(HasAnimation())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnimation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(HasAnimation()))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("HasAnimation()"
, "./../../../image/decoders/nsPNGDecoder.cpp", 142); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "HasAnimation()" ")"); do { MOZ_CrashSequence
(__null, 142); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
143 return TransparencyType::eFrameRect;
144 }
145
146 return TransparencyType::eNone;
147}
148
149void nsPNGDecoder::PostHasTransparencyIfNeeded(
150 TransparencyType aTransparencyType) {
151 switch (aTransparencyType) {
152 case TransparencyType::eNone:
153 return;
154
155 case TransparencyType::eAlpha:
156 PostHasTransparency();
157 return;
158
159 case TransparencyType::eFrameRect:
160 // If the first frame of animated image doesn't draw into the whole image,
161 // then record that it is transparent. For subsequent frames, this doesn't
162 // affect transparency, because they're composited on top of all previous
163 // frames.
164 if (mNumFrames == 0) {
165 PostHasTransparency();
166 }
167 return;
168 }
169}
170
171// CreateFrame() is used for both simple and animated images.
172nsresult nsPNGDecoder::CreateFrame(const FrameInfo& aFrameInfo) {
173 MOZ_ASSERT(HasSize())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasSize())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(HasSize()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("HasSize()", "./../../../image/decoders/nsPNGDecoder.cpp"
, 173); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasSize()" ")"
); do { MOZ_CrashSequence(__null, 173); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
174 MOZ_ASSERT(!IsMetadataDecode())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!IsMetadataDecode())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!IsMetadataDecode()))), 0)))
{ do { } while (false); MOZ_ReportAssertionFailure("!IsMetadataDecode()"
, "./../../../image/decoders/nsPNGDecoder.cpp", 174); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!IsMetadataDecode()" ")"); do { MOZ_CrashSequence
(__null, 174); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
175
176 // Check if we have transparency, and send notifications if needed.
177 auto transparency = GetTransparencyType(aFrameInfo.mFrameRect);
178 PostHasTransparencyIfNeeded(transparency);
179 mFormat = transparency == TransparencyType::eNone ? SurfaceFormat::OS_RGBX
180 : SurfaceFormat::OS_RGBA;
181
182 // Make sure there's no animation or padding if we're downscaling.
183 MOZ_ASSERT_IF(Size() != OutputSize(), mNumFrames == 0)do { if (Size() != OutputSize()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(mNumFrames == 0)
>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mNumFrames == 0))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mNumFrames == 0", "./../../../image/decoders/nsPNGDecoder.cpp"
, 183); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mNumFrames == 0"
")"); do { MOZ_CrashSequence(__null, 183); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
184 MOZ_ASSERT_IF(Size() != OutputSize(), !GetImageMetadata().HasAnimation())do { if (Size() != OutputSize()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(!GetImageMetadata
().HasAnimation())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!GetImageMetadata().HasAnimation
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!GetImageMetadata().HasAnimation()", "./../../../image/decoders/nsPNGDecoder.cpp"
, 184); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!GetImageMetadata().HasAnimation()"
")"); do { MOZ_CrashSequence(__null, 184); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
185 MOZ_ASSERT_IF(Size() != OutputSize(),do { if (Size() != OutputSize()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(transparency != TransparencyType
::eFrameRect)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(transparency != TransparencyType::
eFrameRect))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("transparency != TransparencyType::eFrameRect", "./../../../image/decoders/nsPNGDecoder.cpp"
, 186); AnnotateMozCrashReason("MOZ_ASSERT" "(" "transparency != TransparencyType::eFrameRect"
")"); do { MOZ_CrashSequence(__null, 186); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
186 transparency != TransparencyType::eFrameRect)do { if (Size() != OutputSize()) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(transparency != TransparencyType
::eFrameRect)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(transparency != TransparencyType::
eFrameRect))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("transparency != TransparencyType::eFrameRect", "./../../../image/decoders/nsPNGDecoder.cpp"
, 186); AnnotateMozCrashReason("MOZ_ASSERT" "(" "transparency != TransparencyType::eFrameRect"
")"); do { MOZ_CrashSequence(__null, 186); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
187
188 Maybe<AnimationParams> animParams;
189#ifdef PNG_APNG_SUPPORTED
190 const bool isAnimated = png_get_validMOZ_PNG_get_valid(mPNG, mInfo, PNG_INFO_acTL0x100000U);
191 if (!IsFirstFrameDecode() && isAnimated) {
192 mAnimInfo = AnimFrameInfo(mPNG, mInfo);
193
194 if (mAnimInfo.mDispose == DisposalMethod::CLEAR) {
195 // We may have to display the background under this image during
196 // animation playback, so we regard it as transparent.
197 PostHasTransparency();
198 }
199
200 animParams.emplace(
201 AnimationParams{aFrameInfo.mFrameRect.ToUnknownRect(),
202 FrameTimeout::FromRawMilliseconds(mAnimInfo.mTimeout),
203 mNumFrames, mAnimInfo.mBlend, mAnimInfo.mDispose});
204 }
205#endif
206
207 MOZ_ASSERT(GetOrientation().IsIdentity() || !animParams.isSome(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetOrientation().IsIdentity() || !animParams.isSome(
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetOrientation().IsIdentity() || !animParams.isSome(
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("GetOrientation().IsIdentity() || !animParams.isSome()" " ("
"can't be oriented and have animation" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 208); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetOrientation().IsIdentity() || !animParams.isSome()"
") (" "can't be oriented and have animation" ")"); do { MOZ_CrashSequence
(__null, 208); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
208 "can't be oriented and have animation")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetOrientation().IsIdentity() || !animParams.isSome(
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetOrientation().IsIdentity() || !animParams.isSome(
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("GetOrientation().IsIdentity() || !animParams.isSome()" " ("
"can't be oriented and have animation" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 208); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetOrientation().IsIdentity() || !animParams.isSome()"
") (" "can't be oriented and have animation" ")"); do { MOZ_CrashSequence
(__null, 208); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
209 MOZ_ASSERT(GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced" " ("
"can't be oriented and be doing interlacing" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 210); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced"
") (" "can't be oriented and be doing interlacing" ")"); do {
MOZ_CrashSequence(__null, 210); __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
210 "can't be oriented and be doing interlacing")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced" " ("
"can't be oriented and be doing interlacing" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 210); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetOrientation().IsIdentity() || !aFrameInfo.mIsInterlaced"
") (" "can't be oriented and be doing interlacing" ")"); do {
MOZ_CrashSequence(__null, 210); __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
211
212 const bool wantToReorient = !GetOrientation().IsIdentity();
213
214#ifdef DEBUG1
215 const bool isFullFrame = aFrameInfo.mFrameRect.IsEqualEdges(
216 UnorientedIntRect(IntPointTyped<mozilla::UnorientedPixel>(0, 0),
217 GetOrientation().ToUnoriented(Size())));
218# ifdef PNG_APNG_SUPPORTED
219 MOZ_ASSERT(isAnimated || isFullFrame,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isAnimated || isFullFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isAnimated || isFullFrame)))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("isAnimated || isFullFrame"
" (" "can only have partial frames if animated" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 220); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isAnimated || isFullFrame"
") (" "can only have partial frames if animated" ")"); do { MOZ_CrashSequence
(__null, 220); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
220 "can only have partial frames if animated")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(isAnimated || isFullFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(isAnimated || isFullFrame)))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("isAnimated || isFullFrame"
" (" "can only have partial frames if animated" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 220); AnnotateMozCrashReason("MOZ_ASSERT" "(" "isAnimated || isFullFrame"
") (" "can only have partial frames if animated" ")"); do { MOZ_CrashSequence
(__null, 220); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
221# endif
222 MOZ_ASSERT(!wantToReorient || isFullFrame,do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!wantToReorient || isFullFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!wantToReorient || isFullFrame
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"!wantToReorient || isFullFrame" " (" "can only have partial frames if not re-orienting"
")", "./../../../image/decoders/nsPNGDecoder.cpp", 223); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!wantToReorient || isFullFrame" ") (" "can only have partial frames if not re-orienting"
")"); do { MOZ_CrashSequence(__null, 223); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
223 "can only have partial frames if not re-orienting")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!wantToReorient || isFullFrame)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!wantToReorient || isFullFrame
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"!wantToReorient || isFullFrame" " (" "can only have partial frames if not re-orienting"
")", "./../../../image/decoders/nsPNGDecoder.cpp", 223); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "!wantToReorient || isFullFrame" ") (" "can only have partial frames if not re-orienting"
")"); do { MOZ_CrashSequence(__null, 223); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
224#endif
225
226 SurfacePipeFlags pipeFlags = SurfacePipeFlags();
227
228 // We disable progressive display if we are reoriented because we don't
229 // support that yet in the reorienting pipeline. And the Adam7 flag doesn't do
230 // anything unless the progressive display flag is passed, so we've already
231 // disabled interlacing by the time we get here if we are reorienting (but we
232 // check again for symmetry).
233 if (!wantToReorient) {
234 if (mNumFrames == 0) {
235 // The first frame may be displayed progressively.
236 pipeFlags |= SurfacePipeFlags::PROGRESSIVE_DISPLAY;
237 }
238
239 if (aFrameInfo.mIsInterlaced) {
240 // If this image is interlaced, we can display better quality intermediate
241 // results to the user by post processing them with
242 // ADAM7InterpolatingFilter.
243 pipeFlags |= SurfacePipeFlags::ADAM7_INTERPOLATE;
244 }
245 }
246
247 SurfaceFormat inFormat;
248 if (mTransform && !mUsePipeTransform) {
249 // QCMS will output in the correct format.
250 inFormat = mFormat;
251 } else if (transparency == TransparencyType::eAlpha) {
252 // We are outputting directly as RGBA, so we need to swap at this step.
253 inFormat = SurfaceFormat::R8G8B8A8;
254 } else {
255 // We have no alpha channel, so we need to unpack from RGB to BGRA.
256 inFormat = SurfaceFormat::R8G8B8;
257 }
258
259 // Only apply premultiplication if the frame has true alpha. If we ever
260 // support downscaling animated images, we will need to premultiply for frame
261 // rect transparency when downscaling as well.
262 if (transparency == TransparencyType::eAlpha && !mDisablePremultipliedAlpha) {
263 pipeFlags |= SurfacePipeFlags::PREMULTIPLY_ALPHA;
264 }
265
266 qcms_transform* pipeTransform = mUsePipeTransform ? mTransform : nullptr;
267 Maybe<SurfacePipe> pipe;
268 if (!wantToReorient) {
269 // If we get here then the orientation is the identity, so it is valid to
270 // convert mFrameRect directly from Unoriented to Oriented.
271 pipe = SurfacePipeFactory::CreateSurfacePipe(
272 this, Size(), OutputSize(),
273 OrientedIntRect::FromUnknownRect(aFrameInfo.mFrameRect.ToUnknownRect()),
274 inFormat, mFormat, animParams, pipeTransform, pipeFlags);
275 } else {
276 pipe = SurfacePipeFactory::CreateReorientSurfacePipe(
277 this, Size(), OutputSize(), inFormat, mFormat, pipeTransform,
278 GetOrientation(), pipeFlags);
279 }
280
281 if (!pipe) {
282 mPipe = SurfacePipe();
283 return NS_ERROR_FAILURE;
284 }
285
286 mPipe = std::move(*pipe);
287
288 mFrameRect = aFrameInfo.mFrameRect;
289 mPass = 0;
290
291 MOZ_LOG(sPNGDecoderAccountingLog, LogLevel::Debug,do { const ::mozilla::LogModule* moz_real_module = sPNGDecoderAccountingLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Debug)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Debug, "PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "
"image frame with %dx%d pixels for decoder %p", mFrameRect.Width
(), mFrameRect.Height(), this); } } while (0)
292 ("PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "do { const ::mozilla::LogModule* moz_real_module = sPNGDecoderAccountingLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Debug)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Debug, "PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "
"image frame with %dx%d pixels for decoder %p", mFrameRect.Width
(), mFrameRect.Height(), this); } } while (0)
293 "image frame with %dx%d pixels for decoder %p",do { const ::mozilla::LogModule* moz_real_module = sPNGDecoderAccountingLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Debug)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Debug, "PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "
"image frame with %dx%d pixels for decoder %p", mFrameRect.Width
(), mFrameRect.Height(), this); } } while (0)
294 mFrameRect.Width(), mFrameRect.Height(), this))do { const ::mozilla::LogModule* moz_real_module = sPNGDecoderAccountingLog
; if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Debug)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Debug, "PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "
"image frame with %dx%d pixels for decoder %p", mFrameRect.Width
(), mFrameRect.Height(), this); } } while (0)
;
295
296 return NS_OK;
297}
298
299// set timeout and frame disposal method for the current frame
300void nsPNGDecoder::EndImageFrame() {
301 if (mFrameIsHidden) {
302 return;
303 }
304
305 mNumFrames++;
306
307 Opacity opacity = mFormat == SurfaceFormat::OS_RGBX
308 ? Opacity::FULLY_OPAQUE
309 : Opacity::SOME_TRANSPARENCY;
310
311 PostFrameStop(opacity);
312}
313
314nsresult nsPNGDecoder::InitInternal() {
315 mDisablePremultipliedAlpha =
316 bool(GetSurfaceFlags() & SurfaceFlags::NO_PREMULTIPLY_ALPHA);
317
318#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
319 static png_byte color_chunks[] = {99, 72, 82, 77, '\0', // cHRM
320 105, 67, 67, 80, '\0'}; // iCCP
321 static png_byte unused_chunks[] = {98, 75, 71, 68, '\0', // bKGD
322 104, 73, 83, 84, '\0', // hIST
323 105, 84, 88, 116, '\0', // iTXt
324 111, 70, 70, 115, '\0', // oFFs
325 112, 67, 65, 76, '\0', // pCAL
326 115, 67, 65, 76, '\0', // sCAL
327 112, 72, 89, 115, '\0', // pHYs
328 115, 66, 73, 84, '\0', // sBIT
329 115, 80, 76, 84, '\0', // sPLT
330 116, 69, 88, 116, '\0', // tEXt
331 116, 73, 77, 69, '\0', // tIME
332 122, 84, 88, 116, '\0'}; // zTXt
333#endif
334
335 // Initialize the container's source image header
336 // Always decode to 24 bit pixdepth
337
338 mPNG = png_create_read_structMOZ_PNG_cr_read_str(PNG_LIBPNG_VER_STRING"1.6.58", nullptr,
339 nsPNGDecoder::error_callback,
340 nsPNGDecoder::warning_callback);
341 if (!mPNG) {
342 return NS_ERROR_OUT_OF_MEMORY;
343 }
344
345 mInfo = png_create_info_structMOZ_PNG_cr_info_str(mPNG);
346 if (!mInfo) {
347 png_destroy_read_structMOZ_PNG_dest_read_str(&mPNG, nullptr, nullptr);
348 return NS_ERROR_OUT_OF_MEMORY;
349 }
350
351#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
352 // Ignore unused chunks
353 if (mCMSMode == CMSMode::Off || IsMetadataDecode()) {
354 png_set_keep_unknown_chunksMOZ_PNG_set_keep_unknown_chunks(mPNG, 1, color_chunks, 2);
355 }
356
357 png_set_keep_unknown_chunksMOZ_PNG_set_keep_unknown_chunks(mPNG, 1, unused_chunks,
358 (int)sizeof(unused_chunks) / 5);
359#endif
360
361#ifdef PNG_SET_USER_LIMITS_SUPPORTED
362 png_set_user_limitsMOZ_PNG_set_user_limits(mPNG, MOZ_PNG_MAX_WIDTH0x7fffffffL, MOZ_PNG_MAX_HEIGHT0x7fffffffL);
363 png_set_chunk_malloc_maxMOZ_PNG_set_chunk_malloc_max(mPNG, kPngMaxChunkSize);
364#endif
365
366#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
367 // Disallow palette-index checking, for speed; we would ignore the warning
368 // anyhow. This feature was added at libpng version 1.5.10 and is disabled
369 // in the embedded libpng but enabled by default in the system libpng. This
370 // call also disables it in the system libpng, for decoding speed.
371 // Bug #745202.
372 png_set_check_for_invalid_index(mPNG, 0);
373#endif
374
375#ifdef PNG_SET_OPTION_SUPPORTED
376# if defined(PNG_sRGB_PROFILE_CHECKS-1) && PNG_sRGB_PROFILE_CHECKS-1 >= 0
377 // Skip checking of sRGB ICC profiles
378 png_set_option(mPNG, PNG_SKIP_sRGB_CHECK_PROFILE4, PNG_OPTION_ON3);
379# endif
380
381# ifdef PNG_MAXIMUM_INFLATE_WINDOW2
382 // Force a larger zlib inflate window as some images in the wild have
383 // incorrectly set metadata (specifically CMF bits) which prevent us from
384 // decoding them otherwise.
385 png_set_option(mPNG, PNG_MAXIMUM_INFLATE_WINDOW2, PNG_OPTION_ON3);
386# endif
387#endif
388
389 // use this as libpng "progressive pointer" (retrieve in callbacks)
390 png_set_progressive_read_fnMOZ_PNG_set_progressive_read_fn(
391 mPNG, static_cast<png_voidp>(this), nsPNGDecoder::info_callback,
392 nsPNGDecoder::row_callback, nsPNGDecoder::end_callback);
393
394 return NS_OK;
395}
396
397LexerResult nsPNGDecoder::DoDecode(SourceBufferIterator& aIterator,
398 IResumable* aOnResume) {
399 MOZ_ASSERT(!HasError(), "Shouldn't call DoDecode after error!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasError())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasError()))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("!HasError()" " ("
"Shouldn't call DoDecode after error!" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 399); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasError()"
") (" "Shouldn't call DoDecode after error!" ")"); do { MOZ_CrashSequence
(__null, 399); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
400
401 return mLexer.Lex(aIterator, aOnResume,
402 [this](State aState, const char* aData, size_t aLength) {
403 switch (aState) {
404 case State::PNG_DATA:
405 return ReadPNGData(aData, aLength);
406 case State::FINISHED_PNG_DATA:
407 return FinishedPNGData();
408 }
409 MOZ_CRASH("Unknown State")do { do { } while (false); MOZ_ReportCrash("" "Unknown State"
, "./../../../image/decoders/nsPNGDecoder.cpp", 409); AnnotateMozCrashReason
("MOZ_CRASH(" "Unknown State" ")"); do { MOZ_CrashSequence(__null
, 409); __attribute__((nomerge)) ::abort(); } while (false); }
while (false)
;
410 });
411}
412
413LexerTransition<nsPNGDecoder::State> nsPNGDecoder::ReadPNGData(
414 const char* aData, size_t aLength) {
415 // If we were waiting until after returning from a yield to call
416 // CreateFrame(), call it now.
417 if (mNextFrameInfo) {
418 if (NS_FAILED(CreateFrame(*mNextFrameInfo))((bool)(__builtin_expect(!!(NS_FAILED_impl(CreateFrame(*mNextFrameInfo
))), 0)))
) {
419 return Transition::TerminateFailure();
420 }
421
422 MOZ_ASSERT(mImageData, "Should have a buffer now")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mImageData)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mImageData))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("mImageData" " (" "Should have a buffer now"
")", "./../../../image/decoders/nsPNGDecoder.cpp", 422); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "mImageData" ") (" "Should have a buffer now"
")"); do { MOZ_CrashSequence(__null, 422); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
423 mNextFrameInfo = Nothing();
424 }
425
426 // libpng uses setjmp/longjmp for error handling.
427 if (setjmp(png_jmpbuf(mPNG))_setjmp ((*MOZ_PNG_set_longjmp_fn((mPNG), longjmp, (sizeof (jmp_buf
)))))
) {
428 return (GetFrameCount() > 0 && mErrorIsRecoverable)
429 ? Transition::TerminateSuccess()
430 : Transition::TerminateFailure();
431 }
432
433 // Pass the data off to libpng.
434 mLastChunkLength = aLength;
435 mNextTransition = Transition::ContinueUnbuffered(State::PNG_DATA);
436 png_process_dataMOZ_PNG_process_data(mPNG, mInfo,
437 reinterpret_cast<unsigned char*>(const_cast<char*>((aData))),
438 aLength);
439
440 // Make sure that we've reached a terminal state if decoding is done.
441 MOZ_ASSERT_IF(GetDecodeDone(), mNextTransition.NextStateIsTerminal())do { if (GetDecodeDone()) { do { static_assert( mozilla::detail
::AssertionConditionType<decltype(mNextTransition.NextStateIsTerminal
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mNextTransition.NextStateIsTerminal()))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("mNextTransition.NextStateIsTerminal()"
, "./../../../image/decoders/nsPNGDecoder.cpp", 441); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "mNextTransition.NextStateIsTerminal()" ")"
); do { MOZ_CrashSequence(__null, 441); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
442 MOZ_ASSERT_IF(HasError(), mNextTransition.NextStateIsTerminal())do { if (HasError()) { do { static_assert( mozilla::detail::AssertionConditionType
<decltype(mNextTransition.NextStateIsTerminal())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(mNextTransition.NextStateIsTerminal()))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mNextTransition.NextStateIsTerminal()"
, "./../../../image/decoders/nsPNGDecoder.cpp", 442); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "mNextTransition.NextStateIsTerminal()" ")"
); do { MOZ_CrashSequence(__null, 442); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
443
444 // Continue with whatever transition the callback code requested. We
445 // initialized this to Transition::ContinueUnbuffered(State::PNG_DATA) above,
446 // so by default we just continue the unbuffered read.
447 return mNextTransition;
448}
449
450LexerTransition<nsPNGDecoder::State> nsPNGDecoder::FinishedPNGData() {
451 // Since we set up an unbuffered read for SIZE_MAX bytes, if we actually read
452 // all that data something is really wrong.
453 MOZ_ASSERT_UNREACHABLE("Read the entire address space?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Read the entire address space?" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 453); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Read the entire address space?" ")"
); do { MOZ_CrashSequence(__null, 453); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
454 return Transition::TerminateFailure();
455}
456
457// Sets up gamma pre-correction in libpng before our callback gets called.
458// We need to do this if we don't end up with a CMS profile.
459static void PNGDoGammaCorrection(png_structp png_ptr, png_infop info_ptr) {
460 double aGamma;
461
462 if (png_get_gAMAMOZ_PNG_get_gAMA(png_ptr, info_ptr, &aGamma)) {
463 if ((aGamma <= 0.0) || (aGamma > 21474.83)) {
464 aGamma = 0.45455;
465 png_set_gAMAMOZ_PNG_set_gAMA(png_ptr, info_ptr, aGamma);
466 }
467 png_set_gammaMOZ_PNG_set_gamma(png_ptr, 2.2, aGamma);
468 } else {
469 png_set_gammaMOZ_PNG_set_gamma(png_ptr, 2.2, 0.45455);
470 }
471}
472
473// Adapted from http://www.littlecms.com/pngchrm.c example code
474uint32_t nsPNGDecoder::ReadColorProfile(png_structp png_ptr, png_infop info_ptr,
475 int color_type, bool* sRGBTag) {
476 // Check if cICP chunk is present
477 if (png_get_validMOZ_PNG_get_valid(png_ptr, info_ptr, PNG_INFO_cICP0x20000U)) {
478 png_byte primaries;
479 png_byte tc;
480 png_byte matrix_coefficients;
481 png_byte range;
482 if (png_get_cICP(png_ptr, info_ptr, &primaries, &tc, &matrix_coefficients,
483 &range)) {
484 if (matrix_coefficients == 0 && range <= 1) {
485 if (range == 0) {
486 MOZ_LOG(sPNGLog, LogLevel::Warning,do { const ::mozilla::LogModule* moz_real_module = sPNGLog; if
((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Warning)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Warning, "limited range specified in cicp chunk not properly "
"supported\n"); } } while (0)
487 ("limited range specified in cicp chunk not properly "do { const ::mozilla::LogModule* moz_real_module = sPNGLog; if
((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Warning)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Warning, "limited range specified in cicp chunk not properly "
"supported\n"); } } while (0)
488 "supported\n"))do { const ::mozilla::LogModule* moz_real_module = sPNGLog; if
((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Warning)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Warning, "limited range specified in cicp chunk not properly "
"supported\n"); } } while (0)
;
489 }
490
491 mInProfile = qcms_profile_create_cicp(
492 primaries, ChooseTransferCharacteristics(tc));
493 if (mInProfile) {
494 return qcms_profile_get_rendering_intent(mInProfile);
495 }
496 }
497 }
498 }
499
500 // Check if iCCP chunk is present
501 if (png_get_validMOZ_PNG_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP0x1000U)) {
502 png_uint_32 profileLen;
503 png_bytep profileData;
504 png_charp profileName;
505 int compression;
506
507 png_get_iCCPMOZ_PNG_get_iCCP(png_ptr, info_ptr, &profileName, &compression, &profileData,
508 &profileLen);
509
510 mInProfile = qcms_profile_from_memory((char*)profileData, profileLen);
511 if (mInProfile) {
512 uint32_t profileSpace = qcms_profile_get_color_space(mInProfile);
513
514 bool mismatch = false;
515 if (color_type & PNG_COLOR_MASK_COLOR2) {
516 if (profileSpace != icSigRgbData) {
517 mismatch = true;
518 }
519 } else {
520 if (profileSpace != icSigRgbData && profileSpace != icSigGrayData) {
521 mismatch = true;
522 }
523 }
524
525 if (mismatch) {
526 qcms_profile_release(mInProfile);
527 mInProfile = nullptr;
528 } else {
529 return qcms_profile_get_rendering_intent(mInProfile);
530 }
531 }
532 }
533
534 // Check sRGB chunk
535 if (png_get_validMOZ_PNG_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB0x0800U)) {
536 *sRGBTag = true;
537
538 int fileIntent;
539 png_get_sRGBMOZ_PNG_get_sRGB(png_ptr, info_ptr, &fileIntent);
540 uint32_t map[] = {QCMS_INTENT_PERCEPTUAL, QCMS_INTENT_RELATIVE_COLORIMETRIC,
541 QCMS_INTENT_SATURATION,
542 QCMS_INTENT_ABSOLUTE_COLORIMETRIC};
543 return map[fileIntent];
544 }
545
546 // Check gAMA/cHRM chunks
547 if (png_get_validMOZ_PNG_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA0x0001U) &&
548 png_get_validMOZ_PNG_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM0x0004U)) {
549 qcms_CIE_xyYTRIPLE primaries;
550 qcms_CIE_xyY whitePoint;
551
552 png_get_cHRMMOZ_PNG_get_cHRM(png_ptr, info_ptr, &whitePoint.x, &whitePoint.y,
553 &primaries.red.x, &primaries.red.y, &primaries.green.x,
554 &primaries.green.y, &primaries.blue.x, &primaries.blue.y);
555 whitePoint.Y = primaries.red.Y = primaries.green.Y = primaries.blue.Y = 1.0;
556
557 double gammaOfFile;
558
559 png_get_gAMAMOZ_PNG_get_gAMA(png_ptr, info_ptr, &gammaOfFile);
560
561 mInProfile = qcms_profile_create_rgb_with_gamma(whitePoint, primaries,
562 1.0 / gammaOfFile);
563 }
564
565 return QCMS_INTENT_PERCEPTUAL; // Our default
566}
567
568void nsPNGDecoder::info_callback(png_structp png_ptr, png_infop info_ptr) {
569 png_uint_32 width, height;
570 int bit_depth, color_type, interlace_type, compression_type, filter_type;
571 unsigned int channels;
572
573 png_bytep trans = nullptr;
574 int num_trans = 0;
575
576 nsPNGDecoder* decoder =
577 static_cast<nsPNGDecoder*>(png_get_progressive_ptrMOZ_PNG_get_progressive_ptr(png_ptr));
578
579 if (decoder->mGotInfoCallback) {
580 MOZ_LOG(sPNGLog, LogLevel::Warning,do { const ::mozilla::LogModule* moz_real_module = sPNGLog; if
((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Warning)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Warning, "libpng called info_callback more than once\n"
); } } while (0)
581 ("libpng called info_callback more than once\n"))do { const ::mozilla::LogModule* moz_real_module = sPNGLog; if
((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Warning)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Warning, "libpng called info_callback more than once\n"
); } } while (0)
;
582 return;
583 }
584
585 decoder->mGotInfoCallback = true;
586
587 // Always decode to 24-bit RGB or 32-bit RGBA
588 png_get_IHDRMOZ_PNG_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
589 &interlace_type, &compression_type, &filter_type);
590
591#ifdef PNG_APNG_SUPPORTED
592 const bool isAnimated = png_get_validMOZ_PNG_get_valid(png_ptr, info_ptr, PNG_INFO_acTL0x100000U);
593#endif
594
595 // We only support exif orientation for non-animated images.
596 png_uint_32 num_exif_bytes = 0;
597 png_bytep exifdata = nullptr;
598 if (
599#ifdef PNG_APNG_SUPPORTED
600 !isAnimated &&
601#endif
602 png_get_eXIf_1(png_ptr, info_ptr, &num_exif_bytes, &exifdata) &&
603 num_exif_bytes > 0 && exifdata) {
604
605 EXIFData exif = EXIFParser::Parse(/* aExpectExifIdCode = */ false, exifdata,
606 static_cast<uint32_t>(num_exif_bytes),
607 gfx::IntSize(width, height));
608 decoder->PostSize(width, height, exif.orientation, exif.resolution);
609 } else {
610 decoder->PostSize(width, height);
611 }
612
613 const UnorientedIntRect frameRect(0, 0, width, height);
614
615 if (width > SurfaceCache::MaximumCapacity() / (bit_depth > 8 ? 16 : 8)) {
616 // libpng needs space to allocate two row buffers
617 png_error(decoder->mPNG, "Image is too wide");
618 }
619
620 auto imageSize = CheckedInt<int32_t>(width) * height * 4;
621 if (!imageSize.isValid()) {
622 png_error(decoder->mPNG, "Image is too big");
623 }
624
625 if (decoder->HasError()) {
626 // Setting the size led to an error.
627 png_error(decoder->mPNG, "Sizing error");
628 }
629
630 if (color_type == PNG_COLOR_TYPE_PALETTE(2 | 1)) {
631 png_set_expandMOZ_PNG_set_expand(png_ptr);
632 }
633
634 if (color_type == PNG_COLOR_TYPE_GRAY0 && bit_depth < 8) {
635 png_set_expandMOZ_PNG_set_expand(png_ptr);
636 }
637
638 if (png_get_validMOZ_PNG_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS0x0010U)) {
639 png_color_16p trans_values;
640 png_get_tRNSMOZ_PNG_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &trans_values);
641 if (num_trans != 0) {
642 png_set_expandMOZ_PNG_set_expand(png_ptr);
643 }
644 }
645
646 if (bit_depth == 16) {
647 png_set_scale_16MOZ_PNG_set_scale_16(png_ptr);
648 }
649
650 // We only need to extract the color profile for non-metadata decodes. It is
651 // fairly expensive to read the profile and create the transform so we should
652 // avoid it if not necessary.
653 if (!decoder->IsMetadataDecode()) {
654 uint32_t intent = -1;
655 bool sRGBTag = false;
656 if (decoder->mCMSMode != CMSMode::Off) {
657 intent = gfxPlatform::GetRenderingIntent();
658 uint32_t pIntent =
659 decoder->ReadColorProfile(png_ptr, info_ptr, color_type, &sRGBTag);
660 // If we're not mandating an intent, use the one from the image.
661 if (intent == uint32_t(-1)) {
662 intent = pIntent;
663 }
664
665 // png_get_channels won't return accurate info for determining the alpha
666 // status until after we call png_read_update_info below so we use this
667 // method of determining if we will have alpha so that we can select the
668 // correct qcms input type here.
669 const bool willHaveAlpha =
670 (color_type & PNG_COLOR_MASK_ALPHA4) || num_trans != 0;
671
672 // Determine the qcms transform here, before png_read_update_info commits
673 // libpng to a specific output format. For gray images the presence or
674 // absence of a qcms transform determines if we want libpng to output
675 // gray data (we call qcms to transform it to rgb before passing it to
676 // the surface pipe), or rgb data (no qcms transform so we need rgb data
677 // to pass directly into the surface pipe).
678 if (decoder->mInProfile && decoder->GetCMSOutputProfile()) {
679 uint32_t profileSpace =
680 qcms_profile_get_color_space(decoder->mInProfile);
681 decoder->mUsePipeTransform = profileSpace != icSigGrayData;
682
683 qcms_data_type inType, outType;
684 if (decoder->mUsePipeTransform) {
685 // libpng outputs data in RGBA order and we want our final output to
686 // be BGRA order. SurfacePipe takes care of this for us but
687 // unfortunately the swizzle to change the order can happen before or
688 // after color management depending on if we have alpha. If we have
689 // alpha then the order will be color management then swizzle. If we
690 // do not have alpha then the order will be swizzle then color
691 // management. See CreateSurfacePipe
692 // https://searchfox.org/mozilla-central/rev/7d6651d29c5c1620bc059f879a3e9bbfb53f271f/image/SurfacePipeFactory.h#133-145
693 if (willHaveAlpha) {
694 inType = QCMS_DATA_RGBA_8;
695 outType = QCMS_DATA_RGBA_8;
696 } else {
697 inType = gfxPlatform::GetCMSOSRGBAType();
698 outType = inType;
699 }
700 } else {
701 // qcms operates on the data before we hand it to SurfacePipe.
702 inType = willHaveAlpha ? QCMS_DATA_GRAYA_8 : QCMS_DATA_GRAY_8;
703 outType = gfxPlatform::GetCMSOSRGBAType();
704 }
705 decoder->mTransform = qcms_transform_create(
706 decoder->mInProfile, inType, decoder->GetCMSOutputProfile(),
707 outType, (qcms_intent)intent);
708 } else if ((sRGBTag && decoder->mCMSMode == CMSMode::TaggedOnly) ||
709 decoder->mCMSMode == CMSMode::All) {
710 // See comment above about SurfacePipe, color management and ordering.
711 decoder->mUsePipeTransform = true;
712 if (willHaveAlpha) {
713 decoder->mTransform =
714 decoder->GetCMSsRGBTransform(SurfaceFormat::R8G8B8A8);
715 } else {
716 decoder->mTransform =
717 decoder->GetCMSsRGBTransform(SurfaceFormat::OS_RGBA);
718 }
719 }
720 }
721
722 // Expand gray to RGB unless we will pass the data to qcms to handle it via
723 // a non-pipe transform.
724 if (!decoder->mTransform || decoder->mUsePipeTransform) {
725 png_set_gray_to_rgbMOZ_PNG_set_gray_to_rgb(png_ptr);
726 }
727
728 // Only apply libpng gamma correction when there is no qcms transform to
729 // handle it, and CMS is not entirely disabled.
730 if (!decoder->mTransform && decoder->mCMSMode != CMSMode::Off) {
731 PNGDoGammaCorrection(png_ptr, info_ptr);
732 }
733 }
734
735 // Let libpng expand interlaced images.
736 // We only support interlacing for images that aren't rotated with exif data.
737 const bool isInterlaced = (interlace_type == PNG_INTERLACE_ADAM71) &&
738 decoder->GetOrientation().IsIdentity();
739 if (isInterlaced) {
740 png_set_interlace_handlingMOZ_PNG_set_interlace_handling(png_ptr);
741 }
742
743 // now all of those things we set above are used to update various struct
744 // members and whatnot, after which we can get channels, rowbytes, etc.
745 png_read_update_infoMOZ_PNG_read_update_info(png_ptr, info_ptr);
746 decoder->mChannels = channels = png_get_channelsMOZ_PNG_get_channels(png_ptr, info_ptr);
747
748 //---------------------------------------------------------------//
749 // copy PNG info into imagelib structs (formerly png_set_dims()) //
750 //---------------------------------------------------------------//
751
752 if (channels < 1 || channels > 4) {
753 png_error(decoder->mPNG, "Invalid number of channels");
754 }
755
756#ifdef PNG_APNG_SUPPORTED
757 if (isAnimated) {
758 int32_t rawTimeout = GetNextFrameDelay(png_ptr, info_ptr);
759 decoder->PostIsAnimated(FrameTimeout::FromRawMilliseconds(rawTimeout));
760
761 if (decoder->Size() != decoder->OutputSize() &&
762 !decoder->IsFirstFrameDecode()) {
763 MOZ_ASSERT_UNREACHABLE(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Doing downscale-during-decode " "for an animated image?" ")"
, "./../../../image/decoders/nsPNGDecoder.cpp", 765); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "false" ") (" "MOZ_ASSERT_UNREACHABLE: " "Doing downscale-during-decode "
"for an animated image?" ")"); do { MOZ_CrashSequence(__null
, 765); __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
764 "Doing downscale-during-decode "do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Doing downscale-during-decode " "for an animated image?" ")"
, "./../../../image/decoders/nsPNGDecoder.cpp", 765); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "false" ") (" "MOZ_ASSERT_UNREACHABLE: " "Doing downscale-during-decode "
"for an animated image?" ")"); do { MOZ_CrashSequence(__null
, 765); __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
765 "for an animated image?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Doing downscale-during-decode " "for an animated image?" ")"
, "./../../../image/decoders/nsPNGDecoder.cpp", 765); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "false" ") (" "MOZ_ASSERT_UNREACHABLE: " "Doing downscale-during-decode "
"for an animated image?" ")"); do { MOZ_CrashSequence(__null
, 765); __attribute__((nomerge)) ::abort(); } while (false); }
} while (false)
;
766 png_error(decoder->mPNG, "Invalid downscale attempt"); // Abort decode.
767 }
768 }
769#endif
770
771 if (decoder->IsMetadataDecode()) {
772 // If we are animated then the first frame rect is either:
773 // 1) the whole image if the IDAT chunk is part of the animation
774 // 2) the frame rect of the first fDAT chunk otherwise.
775 // If we are not animated then we want to make sure to call
776 // PostHasTransparency in the metadata decode if we need to. So it's
777 // okay to pass IntRect(0, 0, width, height) here for animated images;
778 // they will call with the proper first frame rect in the full decode.
779 decoder->PostHasTransparencyIfNeeded(
780 decoder->GetTransparencyType(frameRect));
781
782 // We have the metadata we're looking for, so stop here, before we allocate
783 // buffers below.
784 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
785 }
786
787#ifdef PNG_APNG_SUPPORTED
788 if (isAnimated) {
789 png_set_progressive_frame_fnMOZ_APNG_set_prog_frame_fn(png_ptr, nsPNGDecoder::frame_info_callback,
790 nullptr);
791 }
792
793 if (png_get_first_frame_is_hiddenMOZ_APNG_get_first_frame_is_hidden(png_ptr, info_ptr)) {
794 decoder->mFrameIsHidden = true;
795 } else {
796#endif
797 nsresult rv = decoder->CreateFrame(FrameInfo{frameRect, isInterlaced});
798 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
799 png_error(decoder->mPNG, "CreateFrame failed");
800 }
801 MOZ_ASSERT(decoder->mImageData, "Should have a buffer now")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(decoder->mImageData)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(decoder->mImageData))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("decoder->mImageData"
" (" "Should have a buffer now" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 801); AnnotateMozCrashReason("MOZ_ASSERT" "(" "decoder->mImageData"
") (" "Should have a buffer now" ")"); do { MOZ_CrashSequence
(__null, 801); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
802#ifdef PNG_APNG_SUPPORTED
803 }
804#endif
805
806 if (decoder->mTransform && !decoder->mUsePipeTransform) {
807 decoder->mCMSLine =
808 static_cast<uint8_t*>(malloc(sizeof(uint32_t) * frameRect.Width()));
Result of 'malloc' is converted to a pointer of type 'uint8_t', which is incompatible with sizeof operand type 'uint32_t'
809 if (!decoder->mCMSLine) {
810 png_error(decoder->mPNG, "malloc of mCMSLine failed");
811 }
812 }
813
814 if (isInterlaced) {
815 auto bufferSize =
816 CheckedInt<int32_t>(frameRect.Width()) * frameRect.Height() * channels;
817 if (bufferSize.isValid() && bufferSize.value() > 0 &&
818 static_cast<size_t>(bufferSize.value()) <=
819 SurfaceCache::MaximumCapacity()) {
820 decoder->interlacebuf = static_cast<uint8_t*>(malloc(bufferSize.value()));
821 }
822 if (!decoder->interlacebuf) {
823 png_error(decoder->mPNG, "malloc of interlacebuf failed");
824 }
825 }
826}
827
828void nsPNGDecoder::PostInvalidationIfNeeded() {
829 Maybe<SurfaceInvalidRect> invalidRect = mPipe.TakeInvalidRect();
830 if (!invalidRect) {
831 return;
832 }
833
834 PostInvalidation(invalidRect->mInputSpaceRect,
835 Some(invalidRect->mOutputSpaceRect));
836}
837
838void nsPNGDecoder::row_callback(png_structp png_ptr, png_bytep new_row,
839 png_uint_32 row_num, int pass) {
840 /* libpng comments:
841 *
842 * This function is called for every row in the image. If the
843 * image is interlacing, and you turned on the interlace handler,
844 * this function will be called for every row in every pass.
845 * Some of these rows will not be changed from the previous pass.
846 * When the row is not changed, the new_row variable will be
847 * nullptr. The rows and passes are called in order, so you don't
848 * really need the row_num and pass, but I'm supplying them
849 * because it may make your life easier.
850 *
851 * For the non-nullptr rows of interlaced images, you must call
852 * png_progressive_combine_row() passing in the row and the
853 * old row. You can call this function for nullptr rows (it will
854 * just return) and for non-interlaced images (it just does the
855 * memcpy for you) if it will make the code easier. Thus, you
856 * can just do this for all cases:
857 *
858 * png_progressive_combine_row(png_ptr, old_row, new_row);
859 *
860 * where old_row is what was displayed for previous rows. Note
861 * that the first pass (pass == 0 really) will completely cover
862 * the old row, so the rows do not have to be initialized. After
863 * the first pass (and only for interlaced images), you will have
864 * to pass the current row, and the function will combine the
865 * old row and the new row.
866 */
867 nsPNGDecoder* decoder =
868 static_cast<nsPNGDecoder*>(png_get_progressive_ptrMOZ_PNG_get_progressive_ptr(png_ptr));
869
870 if (decoder->mFrameIsHidden) {
871 return; // Skip this frame.
872 }
873
874 MOZ_ASSERT_IF(decoder->IsFirstFrameDecode(), decoder->mNumFrames == 0)do { if (decoder->IsFirstFrameDecode()) { do { static_assert
( mozilla::detail::AssertionConditionType<decltype(decoder
->mNumFrames == 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(decoder->mNumFrames == 0)
)), 0))) { do { } while (false); MOZ_ReportAssertionFailure("decoder->mNumFrames == 0"
, "./../../../image/decoders/nsPNGDecoder.cpp", 874); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "decoder->mNumFrames == 0" ")"); do { MOZ_CrashSequence
(__null, 874); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false); } } while (false)
;
875
876 while (pass > decoder->mPass) {
877 // Advance to the next pass. We may have to do this multiple times because
878 // libpng will skip passes if the image is so small that no pixels have
879 // changed on a given pass, but ADAM7InterpolatingFilter needs to be reset
880 // once for every pass to perform interpolation properly.
881 decoder->mPipe.ResetToFirstRow();
882 decoder->mPass++;
883 }
884
885 const png_uint_32 height =
886 static_cast<png_uint_32>(decoder->mFrameRect.Height());
887
888 if (row_num >= height) {
889 // Bail if we receive extra rows. This is especially important because if we
890 // didn't, we might overflow the deinterlacing buffer.
891 MOZ_ASSERT_UNREACHABLE("libpng producing extra rows?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"libpng producing extra rows?" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 891); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "libpng producing extra rows?" ")"
); do { MOZ_CrashSequence(__null, 891); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
892 return;
893 }
894
895 // Note that |new_row| may be null here, indicating that this is an interlaced
896 // image and |row_callback| is being called for a row that hasn't changed.
897 MOZ_ASSERT_IF(!new_row, decoder->interlacebuf)do { if (!new_row) { do { static_assert( mozilla::detail::AssertionConditionType
<decltype(decoder->interlacebuf)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(decoder->interlacebuf))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("decoder->interlacebuf"
, "./../../../image/decoders/nsPNGDecoder.cpp", 897); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "decoder->interlacebuf" ")"); do { MOZ_CrashSequence
(__null, 897); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false); } } while (false)
;
898
899 if (decoder->interlacebuf) {
900 uint32_t width = uint32_t(decoder->mFrameRect.Width());
901
902 // We'll output the deinterlaced version of the row.
903 uint8_t* rowToWrite =
904 decoder->interlacebuf + (row_num * decoder->mChannels * width);
905
906 // Update the deinterlaced version of this row with the new data.
907 png_progressive_combine_rowMOZ_PNG_progressive_combine_row(png_ptr, rowToWrite, new_row);
908
909 decoder->WriteRow(rowToWrite);
910 } else {
911 decoder->WriteRow(new_row);
912 }
913}
914
915void nsPNGDecoder::WriteRow(uint8_t* aRow) {
916 MOZ_ASSERT(aRow)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aRow)>::isValid, "invalid assertion condition"); if
((__builtin_expect(!!(!(!!(aRow))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("aRow", "./../../../image/decoders/nsPNGDecoder.cpp"
, 916); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aRow" ")"); do
{ MOZ_CrashSequence(__null, 916); __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
917
918 uint8_t* rowToWrite = aRow;
919 uint32_t width = uint32_t(mFrameRect.Width());
920
921 // Apply color management to the row, if necessary, before writing it out.
922 // This is only needed for grayscale images.
923 if (mTransform && !mUsePipeTransform) {
924 MOZ_ASSERT(mCMSLine)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mCMSLine)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mCMSLine))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mCMSLine", "./../../../image/decoders/nsPNGDecoder.cpp"
, 924); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mCMSLine" ")"
); do { MOZ_CrashSequence(__null, 924); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
925 qcms_transform_data(mTransform, rowToWrite, mCMSLine, width);
926 rowToWrite = mCMSLine;
927 }
928
929 // Write this row to the SurfacePipe.
930 DebugOnly<WriteState> result =
931 mPipe.WriteBuffer(reinterpret_cast<uint32_t*>(rowToWrite));
932 MOZ_ASSERT(WriteState(result) != WriteState::FAILURE)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(WriteState(result) != WriteState::FAILURE)>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(WriteState(result) != WriteState::FAILURE))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("WriteState(result) != WriteState::FAILURE"
, "./../../../image/decoders/nsPNGDecoder.cpp", 932); AnnotateMozCrashReason
("MOZ_ASSERT" "(" "WriteState(result) != WriteState::FAILURE"
")"); do { MOZ_CrashSequence(__null, 932); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
933
934 PostInvalidationIfNeeded();
935}
936
937void nsPNGDecoder::DoTerminate(png_structp aPNGStruct, TerminalState aState) {
938 // Stop processing data. Note that we intentionally ignore the return value of
939 // png_process_data_pause(), which tells us how many bytes of the data that
940 // was passed to png_process_data() have not been consumed yet, because now
941 // that we've reached a terminal state, we won't do any more decoding or call
942 // back into libpng anymore.
943 png_process_data_pauseMOZ_PNG_process_data_pause(aPNGStruct, /* save = */ false);
944
945 mNextTransition = aState == TerminalState::SUCCESS
946 ? Transition::TerminateSuccess()
947 : Transition::TerminateFailure();
948}
949
950void nsPNGDecoder::DoYield(png_structp aPNGStruct) {
951 // Pause data processing. png_process_data_pause() returns how many bytes of
952 // the data that was passed to png_process_data() have not been consumed yet.
953 // We use this information to tell StreamingLexer where to place us in the
954 // input stream when we come back from the yield.
955 png_size_t pendingBytes = png_process_data_pauseMOZ_PNG_process_data_pause(aPNGStruct,
956 /* save = */ false);
957
958 MOZ_ASSERT(pendingBytes < mLastChunkLength)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(pendingBytes < mLastChunkLength)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(pendingBytes < mLastChunkLength
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"pendingBytes < mLastChunkLength", "./../../../image/decoders/nsPNGDecoder.cpp"
, 958); AnnotateMozCrashReason("MOZ_ASSERT" "(" "pendingBytes < mLastChunkLength"
")"); do { MOZ_CrashSequence(__null, 958); __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
959 size_t consumedBytes = mLastChunkLength - min(pendingBytes, mLastChunkLength);
960
961 mNextTransition =
962 Transition::ContinueUnbufferedAfterYield(State::PNG_DATA, consumedBytes);
963}
964
965nsresult nsPNGDecoder::FinishInternal() {
966 // We shouldn't be called in error cases.
967 MOZ_ASSERT(!HasError(), "Can't call FinishInternal on error!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!HasError())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!HasError()))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("!HasError()" " ("
"Can't call FinishInternal on error!" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 967); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!HasError()"
") (" "Can't call FinishInternal on error!" ")"); do { MOZ_CrashSequence
(__null, 967); __attribute__((nomerge)) ::abort(); } while (false
); } } while (false)
;
968
969 int32_t loop_count = 0;
970 uint32_t frame_count = 1;
971#ifdef PNG_APNG_SUPPORTED
972 uint32_t num_plays = 0;
973 if (png_get_acTLMOZ_APNG_get_acTL(mPNG, mInfo, &frame_count, &num_plays)) {
974 loop_count = int32_t(num_plays) - 1;
975 } else {
976 frame_count = 1;
977 }
978#endif
979
980 PostLoopCount(loop_count);
981
982 if (WantsFrameCount()) {
983 PostFrameCount(frame_count);
984 }
985
986 if (IsMetadataDecode()) {
987 return NS_OK;
988 }
989
990 if (InFrame()) {
991 EndImageFrame();
992 }
993 PostDecodeDone();
994
995 return NS_OK;
996}
997
998#ifdef PNG_APNG_SUPPORTED
999// got the header of a new frame that's coming
1000void nsPNGDecoder::frame_info_callback(png_structp png_ptr,
1001 png_uint_32 frame_num) {
1002 nsPNGDecoder* decoder =
1003 static_cast<nsPNGDecoder*>(png_get_progressive_ptrMOZ_PNG_get_progressive_ptr(png_ptr));
1004
1005 // old frame is done
1006 decoder->EndImageFrame();
1007
1008 const bool previousFrameWasHidden = decoder->mFrameIsHidden;
1009
1010 if (!previousFrameWasHidden && decoder->IsFirstFrameDecode()) {
1011 // We're about to get a second non-hidden frame, but we only want the first.
1012 // Stop decoding now. (And avoid allocating the unnecessary buffers below.)
1013 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
1014 }
1015
1016 // Only the first frame can be hidden, so unhide unconditionally here.
1017 decoder->mFrameIsHidden = false;
1018
1019 // Save the information necessary to create the frame; we'll actually create
1020 // it when we return from the yield.
1021 const UnorientedIntRect frameRect(
1022 png_get_next_frame_x_offsetMOZ_APNG_get_next_frame_x_offset(png_ptr, decoder->mInfo),
1023 png_get_next_frame_y_offsetMOZ_APNG_get_next_frame_y_offset(png_ptr, decoder->mInfo),
1024 png_get_next_frame_widthMOZ_APNG_get_next_frame_width(png_ptr, decoder->mInfo),
1025 png_get_next_frame_heightMOZ_APNG_get_next_frame_height(png_ptr, decoder->mInfo));
1026 const bool isInterlaced = bool(decoder->interlacebuf);
1027
1028# ifndef MOZ_EMBEDDED_LIBPNG
1029 // if using system library, check frame_width and height against 0
1030 if (frameRect.width == 0) {
1031 png_error(png_ptr, "Frame width must not be 0");
1032 }
1033 if (frameRect.height == 0) {
1034 png_error(png_ptr, "Frame height must not be 0");
1035 }
1036# endif
1037
1038 const FrameInfo info{frameRect, isInterlaced};
1039
1040 // If the previous frame was hidden, skip the yield (which will mislead the
1041 // caller, who will think the previous frame was real) and just allocate the
1042 // new frame here.
1043 if (previousFrameWasHidden) {
1044 if (NS_FAILED(decoder->CreateFrame(info))((bool)(__builtin_expect(!!(NS_FAILED_impl(decoder->CreateFrame
(info))), 0)))
) {
1045 return decoder->DoTerminate(png_ptr, TerminalState::FAILURE);
1046 }
1047
1048 MOZ_ASSERT(decoder->mImageData, "Should have a buffer now")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(decoder->mImageData)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(decoder->mImageData))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("decoder->mImageData"
" (" "Should have a buffer now" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 1048); AnnotateMozCrashReason("MOZ_ASSERT" "(" "decoder->mImageData"
") (" "Should have a buffer now" ")"); do { MOZ_CrashSequence
(__null, 1048); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1049 return; // No yield, so we'll just keep decoding.
1050 }
1051
1052 // Yield to the caller to notify them that the previous frame is now complete.
1053 decoder->mNextFrameInfo = Some(info);
1054 return decoder->DoYield(png_ptr);
1055}
1056#endif
1057
1058void nsPNGDecoder::end_callback(png_structp png_ptr, png_infop info_ptr) {
1059 /* libpng comments:
1060 *
1061 * this function is called when the whole image has been read,
1062 * including any chunks after the image (up to and including
1063 * the IEND). You will usually have the same info chunk as you
1064 * had in the header, although some data may have been added
1065 * to the comments and time fields.
1066 *
1067 * Most people won't do much here, perhaps setting a flag that
1068 * marks the image as finished.
1069 */
1070
1071 nsPNGDecoder* decoder =
1072 static_cast<nsPNGDecoder*>(png_get_progressive_ptrMOZ_PNG_get_progressive_ptr(png_ptr));
1073
1074 // We shouldn't get here if we've hit an error
1075 MOZ_ASSERT(!decoder->HasError(), "Finishing up PNG but hit error!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!decoder->HasError())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!decoder->HasError()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("!decoder->HasError()"
" (" "Finishing up PNG but hit error!" ")", "./../../../image/decoders/nsPNGDecoder.cpp"
, 1075); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!decoder->HasError()"
") (" "Finishing up PNG but hit error!" ")"); do { MOZ_CrashSequence
(__null, 1075); __attribute__((nomerge)) ::abort(); } while (
false); } } while (false)
;
1076
1077 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
1078}
1079
1080void nsPNGDecoder::error_callback(png_structp png_ptr,
1081 png_const_charp error_msg) {
1082 MOZ_LOG(sPNGLog, LogLevel::Error, ("libpng error: %s\n", error_msg))do { const ::mozilla::LogModule* moz_real_module = sPNGLog; if
((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Error)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Error, "libpng error: %s\n", error_msg); } } while
(0)
;
1083
1084 nsPNGDecoder* decoder =
1085 static_cast<nsPNGDecoder*>(png_get_progressive_ptrMOZ_PNG_get_progressive_ptr(png_ptr));
1086
1087 // A bad CRC on a critical chunk is recoverable: other browsers keep the rows
1088 // they decoded before the bad chunk instead of failing the whole image.
1089 if (strstr(error_msg, "invalid chunk type") ||
1090 strstr(error_msg, "bad header (invalid type)") ||
1091 strstr(error_msg, "CRC error")) {
1092 decoder->mErrorIsRecoverable = true;
1093 } else {
1094 decoder->mErrorIsRecoverable = false;
1095 }
1096
1097 png_longjmpMOZ_PNG_longjmp(png_ptr, 1);
1098}
1099
1100void nsPNGDecoder::warning_callback(png_structp png_ptr,
1101 png_const_charp warning_msg) {
1102 MOZ_LOG(sPNGLog, LogLevel::Warning, ("libpng warning: %s\n", warning_msg))do { const ::mozilla::LogModule* moz_real_module = sPNGLog; if
((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Warning)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Warning, "libpng warning: %s\n", warning_msg); } }
while (0)
;
1103}
1104
1105Maybe<glean::impl::MemoryDistributionMetric> nsPNGDecoder::SpeedMetric() const {
1106 return Some(glean::image_decode::speed_png);
1107}
1108
1109bool nsPNGDecoder::IsValidICOResource() const {
1110 // Only 32-bit RGBA PNGs are valid ICO resources; see here:
1111 // http://blogs.msdn.com/b/oldnewthing/archive/2010/10/22/10079192.aspx
1112
1113 // If there are errors in the call to png_get_IHDR, the error_callback in
1114 // nsPNGDecoder.cpp is called. In this error callback we do a longjmp, so
1115 // we need to save the jump buffer here. Otherwise we'll end up without a
1116 // proper callstack.
1117 if (setjmp(png_jmpbuf(mPNG))_setjmp ((*MOZ_PNG_set_longjmp_fn((mPNG), longjmp, (sizeof (jmp_buf
)))))
) {
1118 // We got here from a longjmp call indirectly from png_get_IHDR via
1119 // error_callback. Ignore mErrorIsRecoverable: if we got an invalid chunk
1120 // error before even reading the IHDR we can't recover from that.
1121 return false;
1122 }
1123
1124 png_uint_32 png_width, // Unused
1125 png_height; // Unused
1126
1127 int png_bit_depth, png_color_type;
1128
1129 if (png_get_IHDRMOZ_PNG_get_IHDR(mPNG, mInfo, &png_width, &png_height, &png_bit_depth,
1130 &png_color_type, nullptr, nullptr, nullptr)) {
1131 return ((png_color_type == PNG_COLOR_TYPE_RGB_ALPHA(2 | 4) ||
1132 png_color_type == PNG_COLOR_TYPE_RGB(2)) &&
1133 png_bit_depth == 8);
1134 } else {
1135 return false;
1136 }
1137}
1138
1139} // namespace image
1140} // namespace mozilla