Bug Summary

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