Coverage Report

Created: 2025-10-12 07:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libpng/pngrutil.c
Line
Count
Source
1
/* pngrutil.c - utilities to read a PNG file
2
 *
3
 * Copyright (c) 2018-2025 Cosmin Truta
4
 * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
5
 * Copyright (c) 1996-1997 Andreas Dilger
6
 * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
7
 *
8
 * This code is released under the libpng license.
9
 * For conditions of distribution and use, see the disclaimer
10
 * and license in png.h
11
 *
12
 * This file contains routines that are only called from within
13
 * libpng itself during the course of reading an image.
14
 */
15
16
#include "pngpriv.h"
17
18
#ifdef PNG_READ_SUPPORTED
19
20
/* The minimum 'zlib' stream is assumed to be just the 2 byte header, 5 bytes
21
 * minimum 'deflate' stream, and the 4 byte checksum.
22
 */
23
55.3k
#define LZ77Min  (2U+5U+4U)
24
25
#ifdef PNG_READ_INTERLACING_SUPPORTED
26
/* Arrays to facilitate interlacing - use pass (0 - 6) as index. */
27
28
/* Start of interlace block */
29
static const png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
30
/* Offset to next interlace block */
31
static const png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
32
/* Start of interlace block in the y direction */
33
static const png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
34
/* Offset to next interlace block in the y direction */
35
static const png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
36
37
/* TODO: Move these arrays to a common utility module to avoid duplication. */
38
#endif
39
40
png_uint_32
41
png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf)
42
913k
{
43
913k
   png_uint_32 uval = png_get_uint_32(buf);
44
45
913k
   if (uval > PNG_UINT_31_MAX)
46
1.12k
      png_error(png_ptr, "PNG unsigned integer out of range");
47
48
912k
   return uval;
49
913k
}
50
51
#ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
52
/* NOTE: the read macros will obscure these definitions, so that if
53
 * PNG_USE_READ_MACROS is set the library will not use them internally,
54
 * but the APIs will still be available externally.
55
 *
56
 * The parentheses around function names in the following three functions
57
 * are necessary, because they allow the macros to co-exist with these
58
 * (unused but exported) functions.
59
 */
60
61
/* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
62
png_uint_32
63
(png_get_uint_32)(png_const_bytep buf)
64
0
{
65
0
   png_uint_32 uval =
66
0
       ((png_uint_32)(*(buf    )) << 24) +
67
0
       ((png_uint_32)(*(buf + 1)) << 16) +
68
0
       ((png_uint_32)(*(buf + 2)) <<  8) +
69
0
       ((png_uint_32)(*(buf + 3))      ) ;
70
71
0
   return uval;
72
0
}
73
74
/* Grab a signed 32-bit integer from a buffer in big-endian format.  The
75
 * data is stored in the PNG file in two's complement format and there
76
 * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore
77
 * the following code does a two's complement to native conversion.
78
 */
79
png_int_32
80
(png_get_int_32)(png_const_bytep buf)
81
0
{
82
0
   png_uint_32 uval = png_get_uint_32(buf);
83
0
   if ((uval & 0x80000000) == 0) /* non-negative */
84
0
      return (png_int_32)uval;
85
86
0
   uval = (uval ^ 0xffffffff) + 1;  /* 2's complement: -x = ~x+1 */
87
0
   if ((uval & 0x80000000) == 0) /* no overflow */
88
0
      return -(png_int_32)uval;
89
   /* The following has to be safe; this function only gets called on PNG data
90
    * and if we get here that data is invalid.  0 is the most safe value and
91
    * if not then an attacker would surely just generate a PNG with 0 instead.
92
    */
93
0
   return 0;
94
0
}
95
96
/* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
97
png_uint_16
98
(png_get_uint_16)(png_const_bytep buf)
99
0
{
100
   /* ANSI-C requires an int value to accommodate at least 16 bits so this
101
    * works and allows the compiler not to worry about possible narrowing
102
    * on 32-bit systems.  (Pre-ANSI systems did not make integers smaller
103
    * than 16 bits either.)
104
    */
105
0
   unsigned int val =
106
0
       ((unsigned int)(*buf) << 8) +
107
0
       ((unsigned int)(*(buf + 1)));
108
109
0
   return (png_uint_16)val;
110
0
}
111
112
#endif /* READ_INT_FUNCTIONS */
113
114
/* Read and check the PNG file signature */
115
void /* PRIVATE */
116
png_read_sig(png_structrp png_ptr, png_inforp info_ptr)
117
87.5k
{
118
87.5k
   size_t num_checked, num_to_check;
119
120
   /* Exit if the user application does not expect a signature. */
121
87.5k
   if (png_ptr->sig_bytes >= 8)
122
87.5k
      return;
123
124
0
   num_checked = png_ptr->sig_bytes;
125
0
   num_to_check = 8 - num_checked;
126
127
0
#ifdef PNG_IO_STATE_SUPPORTED
128
0
   png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE;
129
0
#endif
130
131
   /* The signature must be serialized in a single I/O call. */
132
0
   png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
133
0
   png_ptr->sig_bytes = 8;
134
135
0
   if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0)
136
0
   {
137
0
      if (num_checked < 4 &&
138
0
          png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4) != 0)
139
0
         png_error(png_ptr, "Not a PNG file");
140
0
      else
141
0
         png_error(png_ptr, "PNG file corrupted by ASCII conversion");
142
0
   }
143
0
   if (num_checked < 3)
144
0
      png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
145
0
}
146
147
/* This function is called to verify that a chunk name is valid.
148
 * Do this using the bit-whacking approach from contrib/tools/pngfix.c
149
 *
150
 * Copied from libpng 1.7.
151
 */
152
static int
153
check_chunk_name(png_uint_32 name)
154
771k
{
155
771k
   png_uint_32 t;
156
157
   /* Remove bit 5 from all but the reserved byte; this means
158
    * every 8-bit unit must be in the range 65-90 to be valid.
159
    * So bit 5 must be zero, bit 6 must be set and bit 7 zero.
160
    */
161
771k
   name &= ~PNG_U32(32,32,0,32);
162
771k
   t = (name & ~0x1f1f1f1fU) ^ 0x40404040U;
163
164
   /* Subtract 65 for each 8-bit quantity, this must not
165
    * overflow and each byte must then be in the range 0-25.
166
    */
167
771k
   name -= PNG_U32(65,65,65,65);
168
771k
   t |= name;
169
170
   /* Subtract 26, handling the overflow which should set the
171
    * top three bits of each byte.
172
    */
173
771k
   name -= PNG_U32(25,25,25,26);
174
771k
   t |= ~name;
175
176
771k
   return (t & 0xe0e0e0e0U) == 0U;
177
771k
}
178
179
/* Read the chunk header (length + type name).
180
 * Put the type name into png_ptr->chunk_name, and return the length.
181
 */
182
png_uint_32 /* PRIVATE */
183
png_read_chunk_header(png_structrp png_ptr)
184
787k
{
185
787k
   png_byte buf[8];
186
787k
   png_uint_32 chunk_name, length;
187
188
787k
#ifdef PNG_IO_STATE_SUPPORTED
189
787k
   png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR;
190
787k
#endif
191
192
   /* Read the length and the chunk name.  png_struct::chunk_name is immediately
193
    * updated even if they are detectably wrong.  This aids error message
194
    * handling by allowing png_chunk_error to be used.
195
    */
196
787k
   png_read_data(png_ptr, buf, 8);
197
787k
   length = png_get_uint_31(png_ptr, buf);
198
787k
   png_ptr->chunk_name = chunk_name = PNG_CHUNK_FROM_STRING(buf+4);
199
200
   /* Reset the crc and run it over the chunk name. */
201
787k
   png_reset_crc(png_ptr);
202
787k
   png_calculate_crc(png_ptr, buf + 4, 4);
203
204
787k
   png_debug2(0, "Reading chunk typeid = 0x%lx, length = %lu",
205
787k
       (unsigned long)png_ptr->chunk_name, (unsigned long)length);
206
207
   /* Sanity check the length (first by <= 0x80) and the chunk name.  An error
208
    * here indicates a broken stream and libpng has no recovery from this.
209
    */
210
787k
   if (buf[0] >= 0x80U)
211
0
      png_chunk_error(png_ptr, "bad header (invalid length)");
212
213
   /* Check to see if chunk name is valid. */
214
787k
   if (!check_chunk_name(chunk_name))
215
4.31k
      png_chunk_error(png_ptr, "bad header (invalid type)");
216
217
782k
#ifdef PNG_IO_STATE_SUPPORTED
218
782k
   png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA;
219
782k
#endif
220
221
782k
   return length;
222
787k
}
223
224
/* Read data, and (optionally) run it through the CRC. */
225
void /* PRIVATE */
226
png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length)
227
697k
{
228
697k
   if (png_ptr == NULL)
229
0
      return;
230
231
697k
   png_read_data(png_ptr, buf, length);
232
697k
   png_calculate_crc(png_ptr, buf, length);
233
697k
}
234
235
/* Compare the CRC stored in the PNG file with that calculated by libpng from
236
 * the data it has read thus far.
237
 */
238
static int
239
png_crc_error(png_structrp png_ptr, int handle_as_ancillary)
240
744k
{
241
744k
   png_byte crc_bytes[4];
242
744k
   png_uint_32 crc;
243
744k
   int need_crc = 1;
244
245
   /* There are four flags two for ancillary and two for critical chunks.  The
246
    * default setting of these flags is all zero.
247
    *
248
    * PNG_FLAG_CRC_ANCILLARY_USE
249
    * PNG_FLAG_CRC_ANCILLARY_NOWARN
250
    *  USE+NOWARN: no CRC calculation (implemented here), else;
251
    *  NOWARN:     png_chunk_error on error (implemented in png_crc_finish)
252
    *  else:       png_chunk_warning on error (implemented in png_crc_finish)
253
    *              This is the default.
254
    *
255
    *    I.e. NOWARN without USE produces png_chunk_error.  The default setting
256
    *    where neither are set does the same thing.
257
    *
258
    * PNG_FLAG_CRC_CRITICAL_USE
259
    * PNG_FLAG_CRC_CRITICAL_IGNORE
260
    *  IGNORE: no CRC calculation (implemented here), else;
261
    *  USE:    png_chunk_warning on error (implemented in png_crc_finish)
262
    *  else:   png_chunk_error on error (implemented in png_crc_finish)
263
    *          This is the default.
264
    *
265
    * This arose because of original mis-implementation and has persisted for
266
    * compatibility reasons.
267
    *
268
    * TODO: the flag names are internal so maybe this can be changed to
269
    * something comprehensible.
270
    */
271
744k
   if (handle_as_ancillary || PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
272
543k
   {
273
543k
      if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
274
543k
          (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
275
0
         need_crc = 0;
276
543k
   }
277
278
200k
   else /* critical */
279
200k
   {
280
200k
      if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
281
0
         need_crc = 0;
282
200k
   }
283
284
744k
#ifdef PNG_IO_STATE_SUPPORTED
285
744k
   png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC;
286
744k
#endif
287
288
   /* The chunk CRC must be serialized in a single I/O call. */
289
744k
   png_read_data(png_ptr, crc_bytes, 4);
290
291
744k
   if (need_crc != 0)
292
736k
   {
293
736k
      crc = png_get_uint_32(crc_bytes);
294
736k
      return crc != png_ptr->crc;
295
736k
   }
296
297
7.74k
   else
298
7.74k
      return 0;
299
744k
}
300
301
/* Optionally skip data and then check the CRC.  Depending on whether we
302
 * are reading an ancillary or critical chunk, and how the program has set
303
 * things up, we may calculate the CRC on the data and print a message.
304
 * Returns '1' if there was a CRC error, '0' otherwise.
305
 *
306
 * There is one public version which is used in most places and another which
307
 * takes the value for the 'critical' flag to check.  This allows PLTE and IEND
308
 * handling code to ignore the CRC error and removes some confusing code
309
 * duplication.
310
 */
311
static int
312
png_crc_finish_critical(png_structrp png_ptr, png_uint_32 skip,
313
      int handle_as_ancillary)
314
754k
{
315
   /* The size of the local buffer for inflate is a good guess as to a
316
    * reasonable size to use for buffering reads from the application.
317
    */
318
817k
   while (skip > 0)
319
63.3k
   {
320
63.3k
      png_uint_32 len;
321
63.3k
      png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
322
323
63.3k
      len = (sizeof tmpbuf);
324
63.3k
      if (len > skip)
325
56.7k
         len = skip;
326
63.3k
      skip -= len;
327
328
63.3k
      png_crc_read(png_ptr, tmpbuf, len);
329
63.3k
   }
330
331
   /* If 'handle_as_ancillary' has been requested and this is a critical chunk
332
    * but PNG_FLAG_CRC_CRITICAL_IGNORE was set then png_read_crc did not, in
333
    * fact, calculate the CRC so the ANCILLARY settings should not be used
334
    * instead.
335
    */
336
754k
   if (handle_as_ancillary &&
337
42.0k
       (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
338
0
      handle_as_ancillary = 0;
339
340
   /* TODO: this might be more comprehensible if png_crc_error was inlined here.
341
    */
342
754k
   if (png_crc_error(png_ptr, handle_as_ancillary) != 0)
343
429k
   {
344
      /* See above for the explanation of how the flags work. */
345
429k
      if (handle_as_ancillary || PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ?
346
428k
          (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 :
347
429k
          (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0)
348
428k
         png_chunk_warning(png_ptr, "CRC error");
349
350
1.19k
      else
351
1.19k
         png_chunk_error(png_ptr, "CRC error");
352
353
428k
      return 1;
354
429k
   }
355
356
324k
   return 0;
357
754k
}
358
359
int /* PRIVATE */
360
png_crc_finish(png_structrp png_ptr, png_uint_32 skip)
361
710k
{
362
710k
   return png_crc_finish_critical(png_ptr, skip, 0/*critical handling*/);
363
710k
}
364
365
#if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\
366
    defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\
367
    defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\
368
    defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_eXIf_SUPPORTED) ||\
369
    defined(PNG_SEQUENTIAL_READ_SUPPORTED)
370
/* Manage the read buffer; this simply reallocates the buffer if it is not small
371
 * enough (or if it is not allocated).  The routine returns a pointer to the
372
 * buffer; if an error occurs and 'warn' is set the routine returns NULL, else
373
 * it will call png_error on failure.
374
 */
375
static png_bytep
376
png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size)
377
204k
{
378
204k
   png_bytep buffer = png_ptr->read_buffer;
379
380
204k
   if (new_size > png_chunk_max(png_ptr)) return NULL;
381
382
204k
   if (buffer != NULL && new_size > png_ptr->read_buffer_size)
383
5.44k
   {
384
5.44k
      png_ptr->read_buffer = NULL;
385
5.44k
      png_ptr->read_buffer_size = 0;
386
5.44k
      png_free(png_ptr, buffer);
387
5.44k
      buffer = NULL;
388
5.44k
   }
389
390
204k
   if (buffer == NULL)
391
62.8k
   {
392
62.8k
      buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size));
393
394
62.8k
      if (buffer != NULL)
395
62.8k
      {
396
62.8k
#        ifndef PNG_NO_MEMZERO /* for detecting UIM bugs **only** */
397
62.8k
            memset(buffer, 0, new_size); /* just in case */
398
62.8k
#        endif
399
62.8k
         png_ptr->read_buffer = buffer;
400
62.8k
         png_ptr->read_buffer_size = new_size;
401
62.8k
      }
402
62.8k
   }
403
404
204k
   return buffer;
405
204k
}
406
#endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|eXIf|SEQUENTIAL_READ */
407
408
/* png_inflate_claim: claim the zstream for some nefarious purpose that involves
409
 * decompression.  Returns Z_OK on success, else a zlib error code.  It checks
410
 * the owner but, in final release builds, just issues a warning if some other
411
 * chunk apparently owns the stream.  Prior to release it does a png_error.
412
 */
413
static int
414
png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
415
104k
{
416
104k
   if (png_ptr->zowner != 0)
417
0
   {
418
0
      char msg[64];
419
420
0
      PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner);
421
      /* So the message that results is "<chunk> using zstream"; this is an
422
       * internal error, but is very useful for debugging.  i18n requirements
423
       * are minimal.
424
       */
425
0
      (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
426
#if PNG_RELEASE_BUILD
427
      png_chunk_warning(png_ptr, msg);
428
      png_ptr->zowner = 0;
429
#else
430
0
      png_chunk_error(png_ptr, msg);
431
0
#endif
432
0
   }
433
434
   /* Implementation note: unlike 'png_deflate_claim' this internal function
435
    * does not take the size of the data as an argument.  Some efficiency could
436
    * be gained by using this when it is known *if* the zlib stream itself does
437
    * not record the number; however, this is an illusion: the original writer
438
    * of the PNG may have selected a lower window size, and we really must
439
    * follow that because, for systems with with limited capabilities, we
440
    * would otherwise reject the application's attempts to use a smaller window
441
    * size (zlib doesn't have an interface to say "this or lower"!).
442
    *
443
    * inflateReset2 was added to zlib 1.2.4; before this the window could not be
444
    * reset, therefore it is necessary to always allocate the maximum window
445
    * size with earlier zlibs just in case later compressed chunks need it.
446
    */
447
104k
   {
448
104k
      int ret; /* zlib return code */
449
104k
#if ZLIB_VERNUM >= 0x1240
450
104k
      int window_bits = 0;
451
452
104k
      if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) ==
453
104k
          PNG_OPTION_ON)
454
0
      {
455
0
         window_bits = 15;
456
0
         png_ptr->zstream_start = 0; /* fixed window size */
457
0
      }
458
459
104k
      else
460
104k
      {
461
104k
         png_ptr->zstream_start = 1;
462
104k
      }
463
104k
#endif /* ZLIB_VERNUM >= 0x1240 */
464
465
      /* Set this for safety, just in case the previous owner left pointers to
466
       * memory allocations.
467
       */
468
104k
      png_ptr->zstream.next_in = NULL;
469
104k
      png_ptr->zstream.avail_in = 0;
470
104k
      png_ptr->zstream.next_out = NULL;
471
104k
      png_ptr->zstream.avail_out = 0;
472
473
104k
      if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
474
46.9k
      {
475
46.9k
#if ZLIB_VERNUM >= 0x1240
476
46.9k
         ret = inflateReset2(&png_ptr->zstream, window_bits);
477
#else
478
         ret = inflateReset(&png_ptr->zstream);
479
#endif
480
46.9k
      }
481
482
57.1k
      else
483
57.1k
      {
484
57.1k
#if ZLIB_VERNUM >= 0x1240
485
57.1k
         ret = inflateInit2(&png_ptr->zstream, window_bits);
486
#else
487
         ret = inflateInit(&png_ptr->zstream);
488
#endif
489
490
57.1k
         if (ret == Z_OK)
491
57.1k
            png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED;
492
57.1k
      }
493
494
#ifdef PNG_DISABLE_ADLER32_CHECK_SUPPORTED
495
      if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON)
496
         /* Turn off validation of the ADLER32 checksum in IDAT chunks */
497
         ret = inflateValidate(&png_ptr->zstream, 0);
498
#endif
499
500
104k
      if (ret == Z_OK)
501
104k
         png_ptr->zowner = owner;
502
503
0
      else
504
0
         png_zstream_error(png_ptr, ret);
505
506
104k
      return ret;
507
104k
   }
508
509
#ifdef window_bits
510
# undef window_bits
511
#endif
512
104k
}
513
514
#if ZLIB_VERNUM >= 0x1240
515
/* Handle the start of the inflate stream if we called inflateInit2(strm,0);
516
 * in this case some zlib versions skip validation of the CINFO field and, in
517
 * certain circumstances, libpng may end up displaying an invalid image, in
518
 * contrast to implementations that call zlib in the normal way (e.g. libpng
519
 * 1.5).
520
 */
521
int /* PRIVATE */
522
png_zlib_inflate(png_structrp png_ptr, int flush)
523
1.29M
{
524
1.29M
   if (png_ptr->zstream_start && png_ptr->zstream.avail_in > 0)
525
101k
   {
526
101k
      if ((*png_ptr->zstream.next_in >> 4) > 7)
527
817
      {
528
817
         png_ptr->zstream.msg = "invalid window size (libpng)";
529
817
         return Z_DATA_ERROR;
530
817
      }
531
532
100k
      png_ptr->zstream_start = 0;
533
100k
   }
534
535
1.29M
   return inflate(&png_ptr->zstream, flush);
536
1.29M
}
537
#endif /* Zlib >= 1.2.4 */
538
539
#ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED
540
#if defined(PNG_READ_zTXt_SUPPORTED) || defined (PNG_READ_iTXt_SUPPORTED)
541
/* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to
542
 * allow the caller to do multiple calls if required.  If the 'finish' flag is
543
 * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must
544
 * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and
545
 * Z_OK or Z_STREAM_END will be returned on success.
546
 *
547
 * The input and output sizes are updated to the actual amounts of data consumed
548
 * or written, not the amount available (as in a z_stream).  The data pointers
549
 * are not changed, so the next input is (data+input_size) and the next
550
 * available output is (output+output_size).
551
 */
552
static int
553
png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish,
554
    /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr,
555
    /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr)
556
12.6k
{
557
12.6k
   if (png_ptr->zowner == owner) /* Else not claimed */
558
12.6k
   {
559
12.6k
      int ret;
560
12.6k
      png_alloc_size_t avail_out = *output_size_ptr;
561
12.6k
      png_uint_32 avail_in = *input_size_ptr;
562
563
      /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it
564
       * can't even necessarily handle 65536 bytes) because the type uInt is
565
       * "16 bits or more".  Consequently it is necessary to chunk the input to
566
       * zlib.  This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the
567
       * maximum value that can be stored in a uInt.)  It is possible to set
568
       * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have
569
       * a performance advantage, because it reduces the amount of data accessed
570
       * at each step and that may give the OS more time to page it in.
571
       */
572
12.6k
      png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input);
573
      /* avail_in and avail_out are set below from 'size' */
574
12.6k
      png_ptr->zstream.avail_in = 0;
575
12.6k
      png_ptr->zstream.avail_out = 0;
576
577
      /* Read directly into the output if it is available (this is set to
578
       * a local buffer below if output is NULL).
579
       */
580
12.6k
      if (output != NULL)
581
5.16k
         png_ptr->zstream.next_out = output;
582
583
12.6k
      do
584
83.3k
      {
585
83.3k
         uInt avail;
586
83.3k
         Byte local_buffer[PNG_INFLATE_BUF_SIZE];
587
588
         /* zlib INPUT BUFFER */
589
         /* The setting of 'avail_in' used to be outside the loop; by setting it
590
          * inside it is possible to chunk the input to zlib and simply rely on
591
          * zlib to advance the 'next_in' pointer.  This allows arbitrary
592
          * amounts of data to be passed through zlib at the unavoidable cost of
593
          * requiring a window save (memcpy of up to 32768 output bytes)
594
          * every ZLIB_IO_MAX input bytes.
595
          */
596
83.3k
         avail_in += png_ptr->zstream.avail_in; /* not consumed last time */
597
598
83.3k
         avail = ZLIB_IO_MAX;
599
600
83.3k
         if (avail_in < avail)
601
83.3k
            avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */
602
603
83.3k
         avail_in -= avail;
604
83.3k
         png_ptr->zstream.avail_in = avail;
605
606
         /* zlib OUTPUT BUFFER */
607
83.3k
         avail_out += png_ptr->zstream.avail_out; /* not written last time */
608
609
83.3k
         avail = ZLIB_IO_MAX; /* maximum zlib can process */
610
611
83.3k
         if (output == NULL)
612
78.2k
         {
613
            /* Reset the output buffer each time round if output is NULL and
614
             * make available the full buffer, up to 'remaining_space'
615
             */
616
78.2k
            png_ptr->zstream.next_out = local_buffer;
617
78.2k
            if ((sizeof local_buffer) < avail)
618
78.2k
               avail = (sizeof local_buffer);
619
78.2k
         }
620
621
83.3k
         if (avail_out < avail)
622
5.16k
            avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */
623
624
83.3k
         png_ptr->zstream.avail_out = avail;
625
83.3k
         avail_out -= avail;
626
627
         /* zlib inflate call */
628
         /* In fact 'avail_out' may be 0 at this point, that happens at the end
629
          * of the read when the final LZ end code was not passed at the end of
630
          * the previous chunk of input data.  Tell zlib if we have reached the
631
          * end of the output buffer.
632
          */
633
83.3k
         ret = PNG_INFLATE(png_ptr, avail_out > 0 ? Z_NO_FLUSH :
634
83.3k
             (finish ? Z_FINISH : Z_SYNC_FLUSH));
635
83.3k
      } while (ret == Z_OK);
636
637
      /* For safety kill the local buffer pointer now */
638
12.6k
      if (output == NULL)
639
7.53k
         png_ptr->zstream.next_out = NULL;
640
641
      /* Claw back the 'size' and 'remaining_space' byte counts. */
642
12.6k
      avail_in += png_ptr->zstream.avail_in;
643
12.6k
      avail_out += png_ptr->zstream.avail_out;
644
645
      /* Update the input and output sizes; the updated values are the amount
646
       * consumed or written, effectively the inverse of what zlib uses.
647
       */
648
12.6k
      if (avail_out > 0)
649
7.53k
         *output_size_ptr -= avail_out;
650
651
12.6k
      if (avail_in > 0)
652
4.27k
         *input_size_ptr -= avail_in;
653
654
      /* Ensure png_ptr->zstream.msg is set (even in the success case!) */
655
12.6k
      png_zstream_error(png_ptr, ret);
656
12.6k
      return ret;
657
12.6k
   }
658
659
0
   else
660
0
   {
661
      /* This is a bad internal error.  The recovery assigns to the zstream msg
662
       * pointer, which is not owned by the caller, but this is safe; it's only
663
       * used on errors!
664
       */
665
0
      png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
666
0
      return Z_STREAM_ERROR;
667
0
   }
668
12.6k
}
669
670
/*
671
 * Decompress trailing data in a chunk.  The assumption is that read_buffer
672
 * points at an allocated area holding the contents of a chunk with a
673
 * trailing compressed part.  What we get back is an allocated area
674
 * holding the original prefix part and an uncompressed version of the
675
 * trailing part (the malloc area passed in is freed).
676
 */
677
static int
678
png_decompress_chunk(png_structrp png_ptr,
679
    png_uint_32 chunklength, png_uint_32 prefix_size,
680
    png_alloc_size_t *newlength /* must be initialized to the maximum! */,
681
    int terminate /*add a '\0' to the end of the uncompressed data*/)
682
7.53k
{
683
   /* TODO: implement different limits for different types of chunk.
684
    *
685
    * The caller supplies *newlength set to the maximum length of the
686
    * uncompressed data, but this routine allocates space for the prefix and
687
    * maybe a '\0' terminator too.  We have to assume that 'prefix_size' is
688
    * limited only by the maximum chunk size.
689
    */
690
7.53k
   png_alloc_size_t limit = png_chunk_max(png_ptr);
691
692
7.53k
   if (limit >= prefix_size + (terminate != 0))
693
7.53k
   {
694
7.53k
      int ret;
695
696
7.53k
      limit -= prefix_size + (terminate != 0);
697
698
7.53k
      if (limit < *newlength)
699
7.53k
         *newlength = limit;
700
701
      /* Now try to claim the stream. */
702
7.53k
      ret = png_inflate_claim(png_ptr, png_ptr->chunk_name);
703
704
7.53k
      if (ret == Z_OK)
705
7.53k
      {
706
7.53k
         png_uint_32 lzsize = chunklength - prefix_size;
707
708
7.53k
         ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
709
7.53k
             /* input: */ png_ptr->read_buffer + prefix_size, &lzsize,
710
7.53k
             /* output: */ NULL, newlength);
711
712
7.53k
         if (ret == Z_STREAM_END)
713
5.16k
         {
714
            /* Use 'inflateReset' here, not 'inflateReset2' because this
715
             * preserves the previously decided window size (otherwise it would
716
             * be necessary to store the previous window size.)  In practice
717
             * this doesn't matter anyway, because png_inflate will call inflate
718
             * with Z_FINISH in almost all cases, so the window will not be
719
             * maintained.
720
             */
721
5.16k
            if (inflateReset(&png_ptr->zstream) == Z_OK)
722
5.16k
            {
723
               /* Because of the limit checks above we know that the new,
724
                * expanded, size will fit in a size_t (let alone an
725
                * png_alloc_size_t).  Use png_malloc_base here to avoid an
726
                * extra OOM message.
727
                */
728
5.16k
               png_alloc_size_t new_size = *newlength;
729
5.16k
               png_alloc_size_t buffer_size = prefix_size + new_size +
730
5.16k
                   (terminate != 0);
731
5.16k
               png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr,
732
5.16k
                   buffer_size));
733
734
5.16k
               if (text != NULL)
735
5.16k
               {
736
5.16k
                  memset(text, 0, buffer_size);
737
738
5.16k
                  ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/,
739
5.16k
                      png_ptr->read_buffer + prefix_size, &lzsize,
740
5.16k
                      text + prefix_size, newlength);
741
742
5.16k
                  if (ret == Z_STREAM_END)
743
5.16k
                  {
744
5.16k
                     if (new_size == *newlength)
745
5.16k
                     {
746
5.16k
                        if (terminate != 0)
747
5.16k
                           text[prefix_size + *newlength] = 0;
748
749
5.16k
                        if (prefix_size > 0)
750
5.16k
                           memcpy(text, png_ptr->read_buffer, prefix_size);
751
752
5.16k
                        {
753
5.16k
                           png_bytep old_ptr = png_ptr->read_buffer;
754
755
5.16k
                           png_ptr->read_buffer = text;
756
5.16k
                           png_ptr->read_buffer_size = buffer_size;
757
5.16k
                           text = old_ptr; /* freed below */
758
5.16k
                        }
759
5.16k
                     }
760
761
0
                     else
762
0
                     {
763
                        /* The size changed on the second read, there can be no
764
                         * guarantee that anything is correct at this point.
765
                         * The 'msg' pointer has been set to "unexpected end of
766
                         * LZ stream", which is fine, but return an error code
767
                         * that the caller won't accept.
768
                         */
769
0
                        ret = PNG_UNEXPECTED_ZLIB_RETURN;
770
0
                     }
771
5.16k
                  }
772
773
0
                  else if (ret == Z_OK)
774
0
                     ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */
775
776
                  /* Free the text pointer (this is the old read_buffer on
777
                   * success)
778
                   */
779
5.16k
                  png_free(png_ptr, text);
780
781
                  /* This really is very benign, but it's still an error because
782
                   * the extra space may otherwise be used as a Trojan Horse.
783
                   */
784
5.16k
                  if (ret == Z_STREAM_END &&
785
5.16k
                      chunklength - prefix_size != lzsize)
786
2.71k
                     png_chunk_benign_error(png_ptr, "extra compressed data");
787
5.16k
               }
788
789
0
               else
790
0
               {
791
                  /* Out of memory allocating the buffer */
792
0
                  ret = Z_MEM_ERROR;
793
0
                  png_zstream_error(png_ptr, Z_MEM_ERROR);
794
0
               }
795
5.16k
            }
796
797
0
            else
798
0
            {
799
               /* inflateReset failed, store the error message */
800
0
               png_zstream_error(png_ptr, ret);
801
0
               ret = PNG_UNEXPECTED_ZLIB_RETURN;
802
0
            }
803
5.16k
         }
804
805
2.36k
         else if (ret == Z_OK)
806
0
            ret = PNG_UNEXPECTED_ZLIB_RETURN;
807
808
         /* Release the claimed stream */
809
7.53k
         png_ptr->zowner = 0;
810
7.53k
      }
811
812
0
      else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */
813
0
         ret = PNG_UNEXPECTED_ZLIB_RETURN;
814
815
7.53k
      return ret;
816
7.53k
   }
817
818
0
   else
819
0
   {
820
      /* Application/configuration limits exceeded */
821
0
      png_zstream_error(png_ptr, Z_MEM_ERROR);
822
0
      return Z_MEM_ERROR;
823
0
   }
824
7.53k
}
825
#endif /* READ_zTXt || READ_iTXt */
826
#endif /* READ_COMPRESSED_TEXT */
827
828
#ifdef PNG_READ_iCCP_SUPPORTED
829
/* Perform a partial read and decompress, producing 'avail_out' bytes and
830
 * reading from the current chunk as required.
831
 */
832
static int
833
png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size,
834
    png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size,
835
    int finish)
836
83.5k
{
837
83.5k
   if (png_ptr->zowner == png_ptr->chunk_name)
838
83.5k
   {
839
83.5k
      int ret;
840
841
      /* next_in and avail_in must have been initialized by the caller. */
842
83.5k
      png_ptr->zstream.next_out = next_out;
843
83.5k
      png_ptr->zstream.avail_out = 0; /* set in the loop */
844
845
83.5k
      do
846
110k
      {
847
110k
         if (png_ptr->zstream.avail_in == 0)
848
33.0k
         {
849
33.0k
            if (read_size > *chunk_bytes)
850
29.0k
               read_size = (uInt)*chunk_bytes;
851
33.0k
            *chunk_bytes -= read_size;
852
853
33.0k
            if (read_size > 0)
854
23.3k
               png_crc_read(png_ptr, read_buffer, read_size);
855
856
33.0k
            png_ptr->zstream.next_in = read_buffer;
857
33.0k
            png_ptr->zstream.avail_in = read_size;
858
33.0k
         }
859
860
110k
         if (png_ptr->zstream.avail_out == 0)
861
83.5k
         {
862
83.5k
            uInt avail = ZLIB_IO_MAX;
863
83.5k
            if (avail > *out_size)
864
83.5k
               avail = (uInt)*out_size;
865
83.5k
            *out_size -= avail;
866
867
83.5k
            png_ptr->zstream.avail_out = avail;
868
83.5k
         }
869
870
         /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all
871
          * the available output is produced; this allows reading of truncated
872
          * streams.
873
          */
874
110k
         ret = PNG_INFLATE(png_ptr, *chunk_bytes > 0 ?
875
110k
             Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH));
876
110k
      }
877
110k
      while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0));
878
879
83.5k
      *out_size += png_ptr->zstream.avail_out;
880
83.5k
      png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */
881
882
      /* Ensure the error message pointer is always set: */
883
83.5k
      png_zstream_error(png_ptr, ret);
884
83.5k
      return ret;
885
83.5k
   }
886
887
0
   else
888
0
   {
889
0
      png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed");
890
0
      return Z_STREAM_ERROR;
891
0
   }
892
83.5k
}
893
#endif /* READ_iCCP */
894
895
/* CHUNK HANDLING */
896
/* Read and check the IDHR chunk */
897
static png_handle_result_code
898
png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
899
70.6k
{
900
70.6k
   png_byte buf[13];
901
70.6k
   png_uint_32 width, height;
902
70.6k
   int bit_depth, color_type, compression_type, filter_type;
903
70.6k
   int interlace_type;
904
905
70.6k
   png_debug(1, "in png_handle_IHDR");
906
907
   /* Length and position are checked by the caller. */
908
909
70.6k
   png_ptr->mode |= PNG_HAVE_IHDR;
910
911
70.6k
   png_crc_read(png_ptr, buf, 13);
912
70.6k
   png_crc_finish(png_ptr, 0);
913
914
70.6k
   width = png_get_uint_31(png_ptr, buf);
915
70.6k
   height = png_get_uint_31(png_ptr, buf + 4);
916
70.6k
   bit_depth = buf[8];
917
70.6k
   color_type = buf[9];
918
70.6k
   compression_type = buf[10];
919
70.6k
   filter_type = buf[11];
920
70.6k
   interlace_type = buf[12];
921
922
70.6k
#ifdef PNG_READ_APNG_SUPPORTED
923
70.6k
   png_ptr->first_frame_width = width;
924
70.6k
   png_ptr->first_frame_height = height;
925
70.6k
#endif
926
927
   /* Set internal variables */
928
70.6k
   png_ptr->width = width;
929
70.6k
   png_ptr->height = height;
930
70.6k
   png_ptr->bit_depth = (png_byte)bit_depth;
931
70.6k
   png_ptr->interlaced = (png_byte)interlace_type;
932
70.6k
   png_ptr->color_type = (png_byte)color_type;
933
70.6k
#ifdef PNG_MNG_FEATURES_SUPPORTED
934
70.6k
   png_ptr->filter_type = (png_byte)filter_type;
935
70.6k
#endif
936
70.6k
   png_ptr->compression_type = (png_byte)compression_type;
937
938
   /* Find number of channels */
939
70.6k
   switch (png_ptr->color_type)
940
70.6k
   {
941
206
      default: /* invalid, png_set_IHDR calls png_error */
942
45.2k
      case PNG_COLOR_TYPE_GRAY:
943
51.4k
      case PNG_COLOR_TYPE_PALETTE:
944
51.4k
         png_ptr->channels = 1;
945
51.4k
         break;
946
947
9.25k
      case PNG_COLOR_TYPE_RGB:
948
9.25k
         png_ptr->channels = 3;
949
9.25k
         break;
950
951
2.20k
      case PNG_COLOR_TYPE_GRAY_ALPHA:
952
2.20k
         png_ptr->channels = 2;
953
2.20k
         break;
954
955
7.61k
      case PNG_COLOR_TYPE_RGB_ALPHA:
956
7.61k
         png_ptr->channels = 4;
957
7.61k
         break;
958
70.6k
   }
959
960
   /* Set up other useful info */
961
70.4k
   png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels);
962
70.4k
   png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width);
963
70.4k
   png_debug1(3, "bit_depth = %d", png_ptr->bit_depth);
964
70.4k
   png_debug1(3, "channels = %d", png_ptr->channels);
965
70.4k
   png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes);
966
967
   /* Rely on png_set_IHDR to completely validate the data and call png_error if
968
    * it's wrong.
969
    */
970
70.4k
   png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
971
70.4k
       color_type, interlace_type, compression_type, filter_type);
972
973
70.4k
   return handled_ok;
974
0
   PNG_UNUSED(length)
975
0
}
976
977
/* Read and check the palette */
978
/* TODO: there are several obvious errors in this code when handling
979
 * out-of-place chunks and there is much over-complexity caused by trying to
980
 * patch up the problems.
981
 */
982
static png_handle_result_code
983
png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
984
10.9k
{
985
10.9k
   png_const_charp errmsg = NULL;
986
987
10.9k
   png_debug(1, "in png_handle_PLTE");
988
989
   /* 1.6.47: consistency.  This used to be especially treated as a critical
990
    * error even in an image which is not colour mapped, there isn't a good
991
    * justification for treating some errors here one way and others another so
992
    * everything uses the same logic.
993
    */
994
10.9k
   if ((png_ptr->mode & PNG_HAVE_PLTE) != 0)
995
2.18k
      errmsg = "duplicate";
996
997
8.71k
   else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
998
1.14k
      errmsg = "out of place";
999
1000
7.56k
   else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
1001
2.10k
      errmsg = "ignored in grayscale PNG";
1002
1003
5.46k
   else if (length > 3*PNG_MAX_PALETTE_LENGTH || (length % 3) != 0)
1004
991
      errmsg = "invalid";
1005
1006
   /* This drops PLTE in favour of tRNS or bKGD because both of those chunks
1007
    * can have an effect on the rendering of the image whereas PLTE only matters
1008
    * in the case of an 8-bit display with a decoder which controls the palette.
1009
    *
1010
    * The alternative here is to ignore the error and store the palette anyway;
1011
    * destroying the tRNS will definately cause problems.
1012
    *
1013
    * NOTE: the case of PNG_COLOR_TYPE_PALETTE need not be considered because
1014
    * the png_handle_ routines for the three 'after PLTE' chunks tRNS, bKGD and
1015
    * hIST all check for a preceding PLTE in these cases.
1016
    */
1017
4.47k
   else if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE &&
1018
2.46k
            (png_has_chunk(png_ptr, tRNS) || png_has_chunk(png_ptr, bKGD)))
1019
2.15k
      errmsg = "out of place";
1020
1021
2.31k
   else
1022
2.31k
   {
1023
      /* If the palette has 256 or fewer entries but is too large for the bit
1024
       * depth we don't issue an error to preserve the behavior of previous
1025
       * libpng versions. We silently truncate the unused extra palette entries
1026
       * here.
1027
       */
1028
2.31k
      const unsigned max_palette_length =
1029
2.31k
         (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
1030
2.01k
            1U << png_ptr->bit_depth : PNG_MAX_PALETTE_LENGTH;
1031
1032
      /* The cast is safe because 'length' is less than
1033
       * 3*PNG_MAX_PALETTE_LENGTH
1034
       */
1035
2.31k
      const unsigned num = (length > 3U*max_palette_length) ?
1036
2.26k
         max_palette_length : (unsigned)length / 3U;
1037
1038
2.31k
      unsigned i, j;
1039
2.31k
      png_byte buf[3*PNG_MAX_PALETTE_LENGTH];
1040
2.31k
      png_color palette[PNG_MAX_PALETTE_LENGTH];
1041
1042
      /* Read the chunk into the buffer then read to the end of the chunk. */
1043
2.31k
      png_crc_read(png_ptr, buf, num*3U);
1044
2.31k
      png_crc_finish_critical(png_ptr, length - 3U*num,
1045
            /* Handle as ancillary if PLTE is optional: */
1046
2.31k
            png_ptr->color_type != PNG_COLOR_TYPE_PALETTE);
1047
1048
32.0k
      for (i = 0U, j = 0U; i < num; i++)
1049
29.7k
      {
1050
29.7k
         palette[i].red = buf[j++];
1051
29.7k
         palette[i].green = buf[j++];
1052
29.7k
         palette[i].blue = buf[j++];
1053
29.7k
      }
1054
1055
      /* A valid PLTE chunk has been read */
1056
2.31k
      png_ptr->mode |= PNG_HAVE_PLTE;
1057
1058
      /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to
1059
       * its own copy of the palette.  This has the side effect that when
1060
       * png_start_row is called (this happens after any call to
1061
       * png_read_update_info) the info_ptr palette gets changed.  This is
1062
       * extremely unexpected and confusing.
1063
       *
1064
       * REVIEW: there have been consistent bugs in the past about gamma and
1065
       * similar transforms to colour mapped images being useless because the
1066
       * modified palette cannot be accessed because of the above.
1067
       *
1068
       * CONSIDER: Fix this by not sharing the palette in this way.  But does
1069
       * this completely fix the problem?
1070
       */
1071
2.31k
      png_set_PLTE(png_ptr, info_ptr, palette, num);
1072
2.31k
      return handled_ok;
1073
2.31k
   }
1074
1075
   /* Here on error: errmsg is non NULL. */
1076
8.58k
   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1077
126
   {
1078
126
      png_crc_finish(png_ptr, length);
1079
126
      png_chunk_error(png_ptr, errmsg);
1080
126
   }
1081
1082
8.46k
   else /* not critical to this image */
1083
8.46k
   {
1084
8.46k
      png_crc_finish_critical(png_ptr, length, 1/*handle as ancillary*/);
1085
8.46k
      png_chunk_benign_error(png_ptr, errmsg);
1086
8.46k
   }
1087
1088
   /* Because PNG_UNUSED(errmsg) does not work if all the uses are compiled out
1089
    * (this does happen).
1090
    */
1091
8.46k
   return errmsg != NULL ? handled_error : handled_error;
1092
8.58k
}
1093
1094
/* On read the IDAT chunk is always handled specially, even if marked for
1095
 * unknown handling (this is allowed), so:
1096
 */
1097
#define png_handle_IDAT NULL
1098
1099
static png_handle_result_code
1100
png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1101
33.6k
{
1102
33.6k
   png_debug(1, "in png_handle_IEND");
1103
1104
33.6k
   png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
1105
1106
33.6k
   if (length != 0)
1107
2.85k
      png_chunk_benign_error(png_ptr, "invalid");
1108
1109
33.6k
   png_crc_finish_critical(png_ptr, length, 1/*handle as ancillary*/);
1110
1111
33.6k
   return handled_ok;
1112
0
   PNG_UNUSED(info_ptr)
1113
0
}
1114
1115
#ifdef PNG_READ_gAMA_SUPPORTED
1116
static png_handle_result_code
1117
png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1118
4.07k
{
1119
4.07k
   png_uint_32 ugamma;
1120
4.07k
   png_byte buf[4];
1121
1122
4.07k
   png_debug(1, "in png_handle_gAMA");
1123
1124
4.07k
   png_crc_read(png_ptr, buf, 4);
1125
1126
4.07k
   if (png_crc_finish(png_ptr, 0) != 0)
1127
2.11k
      return handled_error;
1128
1129
1.95k
   ugamma = png_get_uint_32(buf);
1130
1131
1.95k
   if (ugamma > PNG_UINT_31_MAX)
1132
1.25k
   {
1133
1.25k
      png_chunk_benign_error(png_ptr, "invalid");
1134
1.25k
      return handled_error;
1135
1.25k
   }
1136
1137
703
   png_set_gAMA_fixed(png_ptr, info_ptr, (png_fixed_point)/*SAFE*/ugamma);
1138
1139
703
#ifdef PNG_READ_GAMMA_SUPPORTED
1140
      /* PNGv3: chunk precedence for gamma is cICP, [iCCP], sRGB, gAMA.  gAMA is
1141
       * at the end of the chain so simply check for an unset value.
1142
       */
1143
703
      if (png_ptr->chunk_gamma == 0)
1144
647
         png_ptr->chunk_gamma = (png_fixed_point)/*SAFE*/ugamma;
1145
703
#endif /*READ_GAMMA*/
1146
1147
703
   return handled_ok;
1148
0
   PNG_UNUSED(length)
1149
0
}
1150
#else
1151
#  define png_handle_gAMA NULL
1152
#endif
1153
1154
#ifdef PNG_READ_sBIT_SUPPORTED
1155
static png_handle_result_code /* PRIVATE */
1156
png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1157
7.91k
{
1158
7.91k
   unsigned int truelen, i;
1159
7.91k
   png_byte sample_depth;
1160
7.91k
   png_byte buf[4];
1161
1162
7.91k
   png_debug(1, "in png_handle_sBIT");
1163
1164
7.91k
   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1165
2.32k
   {
1166
2.32k
      truelen = 3;
1167
2.32k
      sample_depth = 8;
1168
2.32k
   }
1169
1170
5.59k
   else
1171
5.59k
   {
1172
5.59k
      truelen = png_ptr->channels;
1173
5.59k
      sample_depth = png_ptr->bit_depth;
1174
5.59k
   }
1175
1176
7.91k
   if (length != truelen)
1177
1.64k
   {
1178
1.64k
      png_crc_finish(png_ptr, length);
1179
1.64k
      png_chunk_benign_error(png_ptr, "bad length");
1180
1.64k
      return handled_error;
1181
1.64k
   }
1182
1183
6.26k
   buf[0] = buf[1] = buf[2] = buf[3] = sample_depth;
1184
6.26k
   png_crc_read(png_ptr, buf, truelen);
1185
1186
6.26k
   if (png_crc_finish(png_ptr, 0) != 0)
1187
2.03k
      return handled_error;
1188
1189
10.8k
   for (i=0; i<truelen; ++i)
1190
10.7k
   {
1191
10.7k
      if (buf[i] == 0 || buf[i] > sample_depth)
1192
4.13k
      {
1193
4.13k
         png_chunk_benign_error(png_ptr, "invalid");
1194
4.13k
         return handled_error;
1195
4.13k
      }
1196
10.7k
   }
1197
1198
92
   if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1199
14
   {
1200
14
      png_ptr->sig_bit.red = buf[0];
1201
14
      png_ptr->sig_bit.green = buf[1];
1202
14
      png_ptr->sig_bit.blue = buf[2];
1203
14
      png_ptr->sig_bit.alpha = buf[3];
1204
14
   }
1205
1206
78
   else /* grayscale */
1207
78
   {
1208
78
      png_ptr->sig_bit.gray = buf[0];
1209
78
      png_ptr->sig_bit.red = buf[0];
1210
78
      png_ptr->sig_bit.green = buf[0];
1211
78
      png_ptr->sig_bit.blue = buf[0];
1212
78
      png_ptr->sig_bit.alpha = buf[1];
1213
78
   }
1214
1215
92
   png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
1216
92
   return handled_ok;
1217
4.22k
}
1218
#else
1219
#  define png_handle_sBIT NULL
1220
#endif
1221
1222
#ifdef PNG_READ_cHRM_SUPPORTED
1223
static png_int_32
1224
png_get_int_32_checked(png_const_bytep buf, int *error)
1225
18.5k
{
1226
18.5k
   png_uint_32 uval = png_get_uint_32(buf);
1227
18.5k
   if ((uval & 0x80000000) == 0) /* non-negative */
1228
9.42k
      return (png_int_32)uval;
1229
1230
9.08k
   uval = (uval ^ 0xffffffff) + 1;  /* 2's complement: -x = ~x+1 */
1231
9.08k
   if ((uval & 0x80000000) == 0) /* no overflow */
1232
5.70k
      return -(png_int_32)uval;
1233
1234
   /* This version of png_get_int_32 has a way of returning the error to the
1235
    * caller, so:
1236
    */
1237
3.38k
   *error = 1;
1238
3.38k
   return 0; /* Safe */
1239
9.08k
}
1240
1241
static png_handle_result_code /* PRIVATE */
1242
png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1243
5.11k
{
1244
5.11k
   int error = 0;
1245
5.11k
   png_xy xy;
1246
5.11k
   png_byte buf[32];
1247
1248
5.11k
   png_debug(1, "in png_handle_cHRM");
1249
1250
5.11k
   png_crc_read(png_ptr, buf, 32);
1251
1252
5.11k
   if (png_crc_finish(png_ptr, 0) != 0)
1253
2.74k
      return handled_error;
1254
1255
2.37k
   xy.whitex = png_get_int_32_checked(buf +  0, &error);
1256
2.37k
   xy.whitey = png_get_int_32_checked(buf +  4, &error);
1257
2.37k
   xy.redx   = png_get_int_32_checked(buf +  8, &error);
1258
2.37k
   xy.redy   = png_get_int_32_checked(buf + 12, &error);
1259
2.37k
   xy.greenx = png_get_int_32_checked(buf + 16, &error);
1260
2.37k
   xy.greeny = png_get_int_32_checked(buf + 20, &error);
1261
2.37k
   xy.bluex  = png_get_int_32_checked(buf + 24, &error);
1262
2.37k
   xy.bluey  = png_get_int_32_checked(buf + 28, &error);
1263
1264
2.37k
   if (error)
1265
1.82k
   {
1266
1.82k
      png_chunk_benign_error(png_ptr, "invalid");
1267
1.82k
      return handled_error;
1268
1.82k
   }
1269
1270
   /* png_set_cHRM may complain about some of the values but this doesn't matter
1271
    * because it was a cHRM and it did have vaguely (if, perhaps, ridiculous)
1272
    * values.  Ridiculousity will be checked if the values are used later.
1273
    */
1274
556
   png_set_cHRM_fixed(png_ptr, info_ptr, xy.whitex, xy.whitey, xy.redx, xy.redy,
1275
556
         xy.greenx, xy.greeny, xy.bluex, xy.bluey);
1276
1277
   /* We only use 'chromaticities' for RGB to gray */
1278
556
#  ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1279
      /* There is no need to check sRGB here, cICP is NYI and iCCP is not
1280
       * supported so just check mDCV.
1281
       */
1282
556
      if (!png_has_chunk(png_ptr, mDCV))
1283
492
      {
1284
492
         png_ptr->chromaticities = xy;
1285
492
      }
1286
556
#  endif /* READ_RGB_TO_GRAY */
1287
1288
556
   return handled_ok;
1289
0
   PNG_UNUSED(length)
1290
0
}
1291
#else
1292
#  define png_handle_cHRM NULL
1293
#endif
1294
1295
#ifdef PNG_READ_sRGB_SUPPORTED
1296
static png_handle_result_code /* PRIVATE */
1297
png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1298
3.52k
{
1299
3.52k
   png_byte intent;
1300
1301
3.52k
   png_debug(1, "in png_handle_sRGB");
1302
1303
3.52k
   png_crc_read(png_ptr, &intent, 1);
1304
1305
3.52k
   if (png_crc_finish(png_ptr, 0) != 0)
1306
2.00k
      return handled_error;
1307
1308
   /* This checks the range of the "rendering intent" because it is specified in
1309
    * the PNG spec itself; the "reserved" values will result in the chunk not
1310
    * being accepted, just as they do with the various "reserved" values in
1311
    * IHDR.
1312
    */
1313
1.52k
   if (intent > 3/*PNGv3 spec*/)
1314
1.30k
   {
1315
1.30k
      png_chunk_benign_error(png_ptr, "invalid");
1316
1.30k
      return handled_error;
1317
1.30k
   }
1318
1319
217
   png_set_sRGB(png_ptr, info_ptr, intent);
1320
   /* NOTE: png_struct::chromaticities is not set here because the RGB to gray
1321
    * coefficients are known without a need for the chromaticities.
1322
    */
1323
1324
217
#ifdef PNG_READ_GAMMA_SUPPORTED
1325
      /* PNGv3: chunk precedence for gamma is cICP, [iCCP], sRGB, gAMA.  iCCP is
1326
       * not supported by libpng so the only requirement is to check for cICP
1327
       * setting the gamma (this is NYI, but this check is safe.)
1328
       */
1329
217
      if (!png_has_chunk(png_ptr, cICP) || png_ptr->chunk_gamma == 0)
1330
181
         png_ptr->chunk_gamma = PNG_GAMMA_sRGB_INVERSE;
1331
217
#endif /*READ_GAMMA*/
1332
1333
217
   return handled_ok;
1334
0
   PNG_UNUSED(length)
1335
0
}
1336
#else
1337
#  define png_handle_sRGB NULL
1338
#endif /* READ_sRGB */
1339
1340
#ifdef PNG_READ_iCCP_SUPPORTED
1341
static png_handle_result_code /* PRIVATE */
1342
png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1343
/* Note: this does not properly handle profiles that are > 64K under DOS */
1344
55.3k
{
1345
55.3k
   png_const_charp errmsg = NULL; /* error message output, or no error */
1346
55.3k
   int finished = 0; /* crc checked */
1347
1348
55.3k
   png_debug(1, "in png_handle_iCCP");
1349
1350
   /* PNGv3: allow PNG files with both sRGB and iCCP because the PNG spec only
1351
    * ever said that there "should" be only one, not "shall" and the PNGv3
1352
    * colour chunk precedence rules give a handling for this case anyway.
1353
    */
1354
55.3k
   {
1355
55.3k
      uInt read_length, keyword_length;
1356
55.3k
      char keyword[81];
1357
1358
      /* Find the keyword; the keyword plus separator and compression method
1359
       * bytes can be at most 81 characters long.
1360
       */
1361
55.3k
      read_length = 81; /* maximum */
1362
55.3k
      if (read_length > length)
1363
3.20k
         read_length = (uInt)/*SAFE*/length;
1364
1365
55.3k
      png_crc_read(png_ptr, (png_bytep)keyword, read_length);
1366
55.3k
      length -= read_length;
1367
1368
55.3k
      if (length < LZ77Min)
1369
3.22k
      {
1370
3.22k
         png_crc_finish(png_ptr, length);
1371
3.22k
         png_chunk_benign_error(png_ptr, "too short");
1372
3.22k
         return handled_error;
1373
3.22k
      }
1374
1375
52.1k
      keyword_length = 0;
1376
410k
      while (keyword_length < 80 && keyword_length < read_length &&
1377
409k
         keyword[keyword_length] != 0)
1378
358k
         ++keyword_length;
1379
1380
      /* TODO: make the keyword checking common */
1381
52.1k
      if (keyword_length >= 1 && keyword_length <= 79)
1382
50.9k
      {
1383
         /* We only understand '0' compression - deflate - so if we get a
1384
          * different value we can't safely decode the chunk.
1385
          */
1386
50.9k
         if (keyword_length+1 < read_length &&
1387
50.9k
            keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE)
1388
50.0k
         {
1389
50.0k
            read_length -= keyword_length+2;
1390
1391
50.0k
            if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK)
1392
50.0k
            {
1393
50.0k
               Byte profile_header[132]={0};
1394
50.0k
               Byte local_buffer[PNG_INFLATE_BUF_SIZE];
1395
50.0k
               png_alloc_size_t size = (sizeof profile_header);
1396
1397
50.0k
               png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2);
1398
50.0k
               png_ptr->zstream.avail_in = read_length;
1399
50.0k
               (void)png_inflate_read(png_ptr, local_buffer,
1400
50.0k
                   (sizeof local_buffer), &length, profile_header, &size,
1401
50.0k
                   0/*finish: don't, because the output is too small*/);
1402
1403
50.0k
               if (size == 0)
1404
32.6k
               {
1405
                  /* We have the ICC profile header; do the basic header checks.
1406
                   */
1407
32.6k
                  png_uint_32 profile_length = png_get_uint_32(profile_header);
1408
1409
32.6k
                  if (png_icc_check_length(png_ptr, keyword, profile_length) !=
1410
32.6k
                      0)
1411
31.1k
                  {
1412
                     /* The length is apparently ok, so we can check the 132
1413
                      * byte header.
1414
                      */
1415
31.1k
                     if (png_icc_check_header(png_ptr, keyword, profile_length,
1416
31.1k
                              profile_header, png_ptr->color_type) != 0)
1417
18.9k
                     {
1418
                        /* Now read the tag table; a variable size buffer is
1419
                         * needed at this point, allocate one for the whole
1420
                         * profile.  The header check has already validated
1421
                         * that none of this stuff will overflow.
1422
                         */
1423
18.9k
                        png_uint_32 tag_count =
1424
18.9k
                           png_get_uint_32(profile_header + 128);
1425
18.9k
                        png_bytep profile = png_read_buffer(png_ptr,
1426
18.9k
                              profile_length);
1427
1428
18.9k
                        if (profile != NULL)
1429
18.9k
                        {
1430
18.9k
                           memcpy(profile, profile_header,
1431
18.9k
                               (sizeof profile_header));
1432
1433
18.9k
                           size = 12 * tag_count;
1434
1435
18.9k
                           (void)png_inflate_read(png_ptr, local_buffer,
1436
18.9k
                               (sizeof local_buffer), &length,
1437
18.9k
                               profile + (sizeof profile_header), &size, 0);
1438
1439
                           /* Still expect a buffer error because we expect
1440
                            * there to be some tag data!
1441
                            */
1442
18.9k
                           if (size == 0)
1443
16.9k
                           {
1444
16.9k
                              if (png_icc_check_tag_table(png_ptr,
1445
16.9k
                                       keyword, profile_length, profile) != 0)
1446
14.5k
                              {
1447
                                 /* The profile has been validated for basic
1448
                                  * security issues, so read the whole thing in.
1449
                                  */
1450
14.5k
                                 size = profile_length - (sizeof profile_header)
1451
14.5k
                                     - 12 * tag_count;
1452
1453
14.5k
                                 (void)png_inflate_read(png_ptr, local_buffer,
1454
14.5k
                                     (sizeof local_buffer), &length,
1455
14.5k
                                     profile + (sizeof profile_header) +
1456
14.5k
                                     12 * tag_count, &size, 1/*finish*/);
1457
1458
14.5k
                                 if (length > 0 && !(png_ptr->flags &
1459
4.48k
                                     PNG_FLAG_BENIGN_ERRORS_WARN))
1460
0
                                    errmsg = "extra compressed data";
1461
1462
                                 /* But otherwise allow extra data: */
1463
14.5k
                                 else if (size == 0)
1464
3.52k
                                 {
1465
3.52k
                                    if (length > 0)
1466
643
                                    {
1467
                                       /* This can be handled completely, so
1468
                                        * keep going.
1469
                                        */
1470
643
                                       png_chunk_warning(png_ptr,
1471
643
                                           "extra compressed data");
1472
643
                                    }
1473
1474
3.52k
                                    png_crc_finish(png_ptr, length);
1475
3.52k
                                    finished = 1;
1476
1477
                                    /* Steal the profile for info_ptr. */
1478
3.52k
                                    if (info_ptr != NULL)
1479
3.40k
                                    {
1480
3.40k
                                       png_free_data(png_ptr, info_ptr,
1481
3.40k
                                           PNG_FREE_ICCP, 0);
1482
1483
3.40k
                                       info_ptr->iccp_name = png_voidcast(char*,
1484
3.40k
                                           png_malloc_base(png_ptr,
1485
3.40k
                                           keyword_length+1));
1486
3.40k
                                       if (info_ptr->iccp_name != NULL)
1487
3.40k
                                       {
1488
3.40k
                                          memcpy(info_ptr->iccp_name, keyword,
1489
3.40k
                                              keyword_length+1);
1490
3.40k
                                          info_ptr->iccp_proflen =
1491
3.40k
                                              profile_length;
1492
3.40k
                                          info_ptr->iccp_profile = profile;
1493
3.40k
                                          png_ptr->read_buffer = NULL; /*steal*/
1494
3.40k
                                          info_ptr->free_me |= PNG_FREE_ICCP;
1495
3.40k
                                          info_ptr->valid |= PNG_INFO_iCCP;
1496
3.40k
                                       }
1497
1498
0
                                       else
1499
0
                                          errmsg = "out of memory";
1500
3.40k
                                    }
1501
1502
                                    /* else the profile remains in the read
1503
                                     * buffer which gets reused for subsequent
1504
                                     * chunks.
1505
                                     */
1506
1507
3.52k
                                    if (errmsg == NULL)
1508
3.40k
                                    {
1509
3.40k
                                       png_ptr->zowner = 0;
1510
3.40k
                                       return handled_ok;
1511
3.40k
                                    }
1512
3.52k
                                 }
1513
11.1k
                                 if (errmsg == NULL)
1514
10.5k
                                    errmsg = png_ptr->zstream.msg;
1515
11.1k
                              }
1516
                              /* else png_icc_check_tag_table output an error */
1517
16.9k
                           }
1518
2.03k
                           else /* profile truncated */
1519
2.03k
                              errmsg = png_ptr->zstream.msg;
1520
18.9k
                        }
1521
1522
0
                        else
1523
0
                           errmsg = "out of memory";
1524
18.9k
                     }
1525
1526
                     /* else png_icc_check_header output an error */
1527
31.1k
                  }
1528
1529
                  /* else png_icc_check_length output an error */
1530
32.6k
               }
1531
1532
17.3k
               else /* profile truncated */
1533
17.3k
                  errmsg = png_ptr->zstream.msg;
1534
1535
               /* Release the stream */
1536
46.6k
               png_ptr->zowner = 0;
1537
46.6k
            }
1538
1539
0
            else /* png_inflate_claim failed */
1540
0
               errmsg = png_ptr->zstream.msg;
1541
50.0k
         }
1542
1543
871
         else
1544
871
            errmsg = "bad compression method"; /* or missing */
1545
50.9k
      }
1546
1547
1.21k
      else
1548
1.21k
         errmsg = "bad keyword";
1549
52.1k
   }
1550
1551
   /* Failure: the reason is in 'errmsg' */
1552
48.7k
   if (finished == 0)
1553
47.4k
      png_crc_finish(png_ptr, length);
1554
1555
48.7k
   if (errmsg != NULL) /* else already output */
1556
28.7k
      png_chunk_benign_error(png_ptr, errmsg);
1557
1558
48.7k
   return handled_error;
1559
52.1k
}
1560
#else
1561
#  define png_handle_iCCP NULL
1562
#endif /* READ_iCCP */
1563
1564
#ifdef PNG_READ_sPLT_SUPPORTED
1565
static png_handle_result_code /* PRIVATE */
1566
png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1567
/* Note: this does not properly handle chunks that are > 64K under DOS */
1568
0
{
1569
0
   png_bytep entry_start, buffer;
1570
0
   png_sPLT_t new_palette;
1571
0
   png_sPLT_entryp pp;
1572
0
   png_uint_32 data_length;
1573
0
   int entry_size, i;
1574
0
   png_uint_32 skip = 0;
1575
0
   png_uint_32 dl;
1576
0
   size_t max_dl;
1577
1578
0
   png_debug(1, "in png_handle_sPLT");
1579
1580
0
#ifdef PNG_USER_LIMITS_SUPPORTED
1581
0
   if (png_ptr->user_chunk_cache_max != 0)
1582
0
   {
1583
0
      if (png_ptr->user_chunk_cache_max == 1)
1584
0
      {
1585
0
         png_crc_finish(png_ptr, length);
1586
0
         return handled_error;
1587
0
      }
1588
1589
0
      if (--png_ptr->user_chunk_cache_max == 1)
1590
0
      {
1591
0
         png_warning(png_ptr, "No space in chunk cache for sPLT");
1592
0
         png_crc_finish(png_ptr, length);
1593
0
         return handled_error;
1594
0
      }
1595
0
   }
1596
0
#endif
1597
1598
0
   buffer = png_read_buffer(png_ptr, length+1);
1599
0
   if (buffer == NULL)
1600
0
   {
1601
0
      png_crc_finish(png_ptr, length);
1602
0
      png_chunk_benign_error(png_ptr, "out of memory");
1603
0
      return handled_error;
1604
0
   }
1605
1606
1607
   /* WARNING: this may break if size_t is less than 32 bits; it is assumed
1608
    * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a
1609
    * potential breakage point if the types in pngconf.h aren't exactly right.
1610
    */
1611
0
   png_crc_read(png_ptr, buffer, length);
1612
1613
0
   if (png_crc_finish(png_ptr, skip) != 0)
1614
0
      return handled_error;
1615
1616
0
   buffer[length] = 0;
1617
1618
0
   for (entry_start = buffer; *entry_start; entry_start++)
1619
0
      /* Empty loop to find end of name */ ;
1620
1621
0
   ++entry_start;
1622
1623
   /* A sample depth should follow the separator, and we should be on it  */
1624
0
   if (length < 2U || entry_start > buffer + (length - 2U))
1625
0
   {
1626
0
      png_warning(png_ptr, "malformed sPLT chunk");
1627
0
      return handled_error;
1628
0
   }
1629
1630
0
   new_palette.depth = *entry_start++;
1631
0
   entry_size = (new_palette.depth == 8 ? 6 : 10);
1632
   /* This must fit in a png_uint_32 because it is derived from the original
1633
    * chunk data length.
1634
    */
1635
0
   data_length = length - (png_uint_32)(entry_start - buffer);
1636
1637
   /* Integrity-check the data length */
1638
0
   if ((data_length % (unsigned int)entry_size) != 0)
1639
0
   {
1640
0
      png_warning(png_ptr, "sPLT chunk has bad length");
1641
0
      return handled_error;
1642
0
   }
1643
1644
0
   dl = (png_uint_32)(data_length / (unsigned int)entry_size);
1645
0
   max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry));
1646
1647
0
   if (dl > max_dl)
1648
0
   {
1649
0
      png_warning(png_ptr, "sPLT chunk too long");
1650
0
      return handled_error;
1651
0
   }
1652
1653
0
   new_palette.nentries = (png_int_32)(data_length / (unsigned int)entry_size);
1654
1655
0
   new_palette.entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
1656
0
       (png_alloc_size_t) new_palette.nentries * (sizeof (png_sPLT_entry)));
1657
1658
0
   if (new_palette.entries == NULL)
1659
0
   {
1660
0
      png_warning(png_ptr, "sPLT chunk requires too much memory");
1661
0
      return handled_error;
1662
0
   }
1663
1664
0
   for (i = 0; i < new_palette.nentries; i++)
1665
0
   {
1666
0
      pp = new_palette.entries + i;
1667
1668
0
      if (new_palette.depth == 8)
1669
0
      {
1670
0
         pp->red = *entry_start++;
1671
0
         pp->green = *entry_start++;
1672
0
         pp->blue = *entry_start++;
1673
0
         pp->alpha = *entry_start++;
1674
0
      }
1675
1676
0
      else
1677
0
      {
1678
0
         pp->red   = png_get_uint_16(entry_start); entry_start += 2;
1679
0
         pp->green = png_get_uint_16(entry_start); entry_start += 2;
1680
0
         pp->blue  = png_get_uint_16(entry_start); entry_start += 2;
1681
0
         pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
1682
0
      }
1683
1684
0
      pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
1685
0
   }
1686
1687
   /* Discard all chunk data except the name and stash that */
1688
0
   new_palette.name = (png_charp)buffer;
1689
1690
0
   png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
1691
1692
0
   png_free(png_ptr, new_palette.entries);
1693
0
   return handled_ok;
1694
0
}
1695
#else
1696
#  define png_handle_sPLT NULL
1697
#endif /* READ_sPLT */
1698
1699
#ifdef PNG_READ_tRNS_SUPPORTED
1700
static png_handle_result_code /* PRIVATE */
1701
png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1702
21.0k
{
1703
21.0k
   png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
1704
1705
21.0k
   png_debug(1, "in png_handle_tRNS");
1706
1707
21.0k
   if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
1708
5.83k
   {
1709
5.83k
      png_byte buf[2];
1710
1711
5.83k
      if (length != 2)
1712
3.19k
      {
1713
3.19k
         png_crc_finish(png_ptr, length);
1714
3.19k
         png_chunk_benign_error(png_ptr, "invalid");
1715
3.19k
         return handled_error;
1716
3.19k
      }
1717
1718
2.63k
      png_crc_read(png_ptr, buf, 2);
1719
2.63k
      png_ptr->num_trans = 1;
1720
2.63k
      png_ptr->trans_color.gray = png_get_uint_16(buf);
1721
2.63k
   }
1722
1723
15.2k
   else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
1724
4.84k
   {
1725
4.84k
      png_byte buf[6];
1726
1727
4.84k
      if (length != 6)
1728
2.23k
      {
1729
2.23k
         png_crc_finish(png_ptr, length);
1730
2.23k
         png_chunk_benign_error(png_ptr, "invalid");
1731
2.23k
         return handled_error;
1732
2.23k
      }
1733
1734
2.61k
      png_crc_read(png_ptr, buf, length);
1735
2.61k
      png_ptr->num_trans = 1;
1736
2.61k
      png_ptr->trans_color.red = png_get_uint_16(buf);
1737
2.61k
      png_ptr->trans_color.green = png_get_uint_16(buf + 2);
1738
2.61k
      png_ptr->trans_color.blue = png_get_uint_16(buf + 4);
1739
2.61k
   }
1740
1741
10.4k
   else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1742
8.20k
   {
1743
8.20k
      if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1744
1.72k
      {
1745
1.72k
         png_crc_finish(png_ptr, length);
1746
1.72k
         png_chunk_benign_error(png_ptr, "out of place");
1747
1.72k
         return handled_error;
1748
1.72k
      }
1749
1750
6.48k
      if (length > (unsigned int) png_ptr->num_palette ||
1751
4.75k
         length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
1752
4.75k
         length == 0)
1753
3.42k
      {
1754
3.42k
         png_crc_finish(png_ptr, length);
1755
3.42k
         png_chunk_benign_error(png_ptr, "invalid");
1756
3.42k
         return handled_error;
1757
3.42k
      }
1758
1759
3.05k
      png_crc_read(png_ptr, readbuf, length);
1760
3.05k
      png_ptr->num_trans = (png_uint_16)length;
1761
3.05k
   }
1762
1763
2.21k
   else
1764
2.21k
   {
1765
2.21k
      png_crc_finish(png_ptr, length);
1766
2.21k
      png_chunk_benign_error(png_ptr, "invalid with alpha channel");
1767
2.21k
      return handled_error;
1768
2.21k
   }
1769
1770
8.30k
   if (png_crc_finish(png_ptr, 0) != 0)
1771
6.65k
   {
1772
6.65k
      png_ptr->num_trans = 0;
1773
6.65k
      return handled_error;
1774
6.65k
   }
1775
1776
   /* TODO: this is a horrible side effect in the palette case because the
1777
    * png_struct ends up with a pointer to the tRNS buffer owned by the
1778
    * png_info.  Fix this.
1779
    */
1780
1.65k
   png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
1781
1.65k
       &(png_ptr->trans_color));
1782
1.65k
   return handled_ok;
1783
8.30k
}
1784
#else
1785
#  define png_handle_tRNS NULL
1786
#endif
1787
1788
#ifdef PNG_READ_bKGD_SUPPORTED
1789
static png_handle_result_code /* PRIVATE */
1790
png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1791
16.4k
{
1792
16.4k
   unsigned int truelen;
1793
16.4k
   png_byte buf[6];
1794
16.4k
   png_color_16 background;
1795
1796
16.4k
   png_debug(1, "in png_handle_bKGD");
1797
1798
16.4k
   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1799
6.06k
   {
1800
6.06k
      if ((png_ptr->mode & PNG_HAVE_PLTE) == 0)
1801
1.76k
      {
1802
1.76k
         png_crc_finish(png_ptr, length);
1803
1.76k
         png_chunk_benign_error(png_ptr, "out of place");
1804
1.76k
         return handled_error;
1805
1.76k
      }
1806
1807
4.30k
      truelen = 1;
1808
4.30k
   }
1809
1810
10.3k
   else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1811
5.85k
      truelen = 6;
1812
1813
4.52k
   else
1814
4.52k
      truelen = 2;
1815
1816
14.6k
   if (length != truelen)
1817
1.98k
   {
1818
1.98k
      png_crc_finish(png_ptr, length);
1819
1.98k
      png_chunk_benign_error(png_ptr, "invalid");
1820
1.98k
      return handled_error;
1821
1.98k
   }
1822
1823
12.6k
   png_crc_read(png_ptr, buf, truelen);
1824
1825
12.6k
   if (png_crc_finish(png_ptr, 0) != 0)
1826
2.71k
      return handled_error;
1827
1828
   /* We convert the index value into RGB components so that we can allow
1829
    * arbitrary RGB values for background when we have transparency, and
1830
    * so it is easy to determine the RGB values of the background color
1831
    * from the info_ptr struct.
1832
    */
1833
9.97k
   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
1834
2.23k
   {
1835
2.23k
      background.index = buf[0];
1836
1837
2.23k
      if (info_ptr != NULL && info_ptr->num_palette != 0)
1838
2.23k
      {
1839
2.23k
         if (buf[0] >= info_ptr->num_palette)
1840
2.17k
         {
1841
2.17k
            png_chunk_benign_error(png_ptr, "invalid index");
1842
2.17k
            return handled_error;
1843
2.17k
         }
1844
1845
59
         background.red = (png_uint_16)png_ptr->palette[buf[0]].red;
1846
59
         background.green = (png_uint_16)png_ptr->palette[buf[0]].green;
1847
59
         background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue;
1848
59
      }
1849
1850
0
      else
1851
0
         background.red = background.green = background.blue = 0;
1852
1853
59
      background.gray = 0;
1854
59
   }
1855
1856
7.74k
   else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */
1857
3.00k
   {
1858
3.00k
      if (png_ptr->bit_depth <= 8)
1859
2.97k
      {
1860
2.97k
         if (buf[0] != 0 || buf[1] >= (unsigned int)(1 << png_ptr->bit_depth))
1861
2.93k
         {
1862
2.93k
            png_chunk_benign_error(png_ptr, "invalid gray level");
1863
2.93k
            return handled_error;
1864
2.93k
         }
1865
2.97k
      }
1866
1867
70
      background.index = 0;
1868
70
      background.red =
1869
70
      background.green =
1870
70
      background.blue =
1871
70
      background.gray = png_get_uint_16(buf);
1872
70
   }
1873
1874
4.73k
   else
1875
4.73k
   {
1876
4.73k
      if (png_ptr->bit_depth <= 8)
1877
4.64k
      {
1878
4.64k
         if (buf[0] != 0 || buf[2] != 0 || buf[4] != 0)
1879
4.46k
         {
1880
4.46k
            png_chunk_benign_error(png_ptr, "invalid color");
1881
4.46k
            return handled_error;
1882
4.46k
         }
1883
4.64k
      }
1884
1885
272
      background.index = 0;
1886
272
      background.red = png_get_uint_16(buf);
1887
272
      background.green = png_get_uint_16(buf + 2);
1888
272
      background.blue = png_get_uint_16(buf + 4);
1889
272
      background.gray = 0;
1890
272
   }
1891
1892
401
   png_set_bKGD(png_ptr, info_ptr, &background);
1893
401
   return handled_ok;
1894
9.97k
}
1895
#else
1896
#  define png_handle_bKGD NULL
1897
#endif
1898
1899
#ifdef PNG_READ_cICP_SUPPORTED
1900
static png_handle_result_code /* PRIVATE */
1901
png_handle_cICP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1902
1.23k
{
1903
1.23k
   png_byte buf[4];
1904
1905
1.23k
   png_debug(1, "in png_handle_cICP");
1906
1907
1.23k
   png_crc_read(png_ptr, buf, 4);
1908
1909
1.23k
   if (png_crc_finish(png_ptr, 0) != 0)
1910
1.18k
      return handled_error;
1911
1912
55
   png_set_cICP(png_ptr, info_ptr, buf[0], buf[1],  buf[2], buf[3]);
1913
1914
   /* We only use 'chromaticities' for RGB to gray */
1915
55
#  ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1916
55
      if (!png_has_chunk(png_ptr, mDCV))
1917
17
      {
1918
         /* TODO: png_ptr->chromaticities = chromaticities; */
1919
17
      }
1920
55
#  endif /* READ_RGB_TO_GRAY */
1921
1922
55
#ifdef PNG_READ_GAMMA_SUPPORTED
1923
      /* PNGv3: chunk precedence for gamma is cICP, [iCCP], sRGB, gAMA.  cICP is
1924
       * at the head so simply set the gamma if it can be determined.  If not
1925
       * chunk_gamma remains unchanged; sRGB and gAMA handling check it for
1926
       * being zero.
1927
       */
1928
      /* TODO: set png_struct::chunk_gamma when possible */
1929
55
#endif /*READ_GAMMA*/
1930
1931
55
   return handled_ok;
1932
0
   PNG_UNUSED(length)
1933
0
}
1934
#else
1935
#  define png_handle_cICP NULL
1936
#endif
1937
1938
#ifdef PNG_READ_cLLI_SUPPORTED
1939
static png_handle_result_code /* PRIVATE */
1940
png_handle_cLLI(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1941
869
{
1942
869
   png_byte buf[8];
1943
1944
869
   png_debug(1, "in png_handle_cLLI");
1945
1946
869
   png_crc_read(png_ptr, buf, 8);
1947
1948
869
   if (png_crc_finish(png_ptr, 0) != 0)
1949
790
      return handled_error;
1950
1951
   /* The error checking happens here, this puts it in just one place: */
1952
79
   png_set_cLLI_fixed(png_ptr, info_ptr, png_get_uint_32(buf),
1953
79
         png_get_uint_32(buf+4));
1954
79
   return handled_ok;
1955
0
   PNG_UNUSED(length)
1956
0
}
1957
#else
1958
#  define png_handle_cLLI NULL
1959
#endif
1960
1961
#ifdef PNG_READ_mDCV_SUPPORTED
1962
static png_handle_result_code /* PRIVATE */
1963
png_handle_mDCV(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
1964
1.69k
{
1965
1.69k
   png_xy chromaticities;
1966
1.69k
   png_byte buf[24];
1967
1968
1.69k
   png_debug(1, "in png_handle_mDCV");
1969
1970
1.69k
   png_crc_read(png_ptr, buf, 24);
1971
1972
1.69k
   if (png_crc_finish(png_ptr, 0) != 0)
1973
1.51k
      return handled_error;
1974
1975
   /* The error checking happens here, this puts it in just one place.  The
1976
    * odd /50000 scaling factor makes it more difficult but the (x.y) values are
1977
    * only two bytes so a <<1 is safe.
1978
    *
1979
    * WARNING: the PNG specification defines the cHRM chunk to **start** with
1980
    * the white point (x,y).  The W3C PNG v3 specification puts the white point
1981
    * **after* R,G,B.  The x,y values in mDCV are also scaled by 50,000 and
1982
    * stored in just two bytes, whereas those in cHRM are scaled by 100,000 and
1983
    * stored in four bytes.  This is very, very confusing.  These APIs remove
1984
    * the confusion by copying the existing, well established, API.
1985
    */
1986
184
   chromaticities.redx   = png_get_uint_16(buf+ 0U) << 1; /* red x */
1987
184
   chromaticities.redy   = png_get_uint_16(buf+ 2U) << 1; /* red y */
1988
184
   chromaticities.greenx = png_get_uint_16(buf+ 4U) << 1; /* green x */
1989
184
   chromaticities.greeny = png_get_uint_16(buf+ 6U) << 1; /* green y */
1990
184
   chromaticities.bluex  = png_get_uint_16(buf+ 8U) << 1; /* blue x */
1991
184
   chromaticities.bluey  = png_get_uint_16(buf+10U) << 1; /* blue y */
1992
184
   chromaticities.whitex = png_get_uint_16(buf+12U) << 1; /* white x */
1993
184
   chromaticities.whitey = png_get_uint_16(buf+14U) << 1; /* white y */
1994
1995
184
   png_set_mDCV_fixed(png_ptr, info_ptr,
1996
184
         chromaticities.whitex, chromaticities.whitey,
1997
184
         chromaticities.redx, chromaticities.redy,
1998
184
         chromaticities.greenx, chromaticities.greeny,
1999
184
         chromaticities.bluex, chromaticities.bluey,
2000
184
         png_get_uint_32(buf+16U), /* peak luminance */
2001
184
         png_get_uint_32(buf+20U));/* minimum perceivable luminance */
2002
2003
   /* We only use 'chromaticities' for RGB to gray */
2004
184
#  ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2005
184
      png_ptr->chromaticities = chromaticities;
2006
184
#  endif /* READ_RGB_TO_GRAY */
2007
2008
184
   return handled_ok;
2009
0
   PNG_UNUSED(length)
2010
0
}
2011
#else
2012
#  define png_handle_mDCV NULL
2013
#endif
2014
2015
#ifdef PNG_READ_eXIf_SUPPORTED
2016
static png_handle_result_code /* PRIVATE */
2017
png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2018
5.51k
{
2019
5.51k
   png_bytep buffer = NULL;
2020
2021
5.51k
   png_debug(1, "in png_handle_eXIf");
2022
2023
5.51k
   buffer = png_read_buffer(png_ptr, length);
2024
2025
5.51k
   if (buffer == NULL)
2026
0
   {
2027
0
      png_crc_finish(png_ptr, length);
2028
0
      png_chunk_benign_error(png_ptr, "out of memory");
2029
0
      return handled_error;
2030
0
   }
2031
2032
5.51k
   png_crc_read(png_ptr, buffer, length);
2033
2034
5.51k
   if (png_crc_finish(png_ptr, 0) != 0)
2035
4.40k
      return handled_error;
2036
2037
   /* PNGv3: the code used to check the byte order mark at the start for MM or
2038
    * II, however PNGv3 states that the the first 4 bytes should be checked.
2039
    * The caller ensures that there are four bytes available.
2040
    */
2041
1.10k
   {
2042
1.10k
      png_uint_32 header = png_get_uint_32(buffer);
2043
2044
      /* These numbers are copied from the PNGv3 spec: */
2045
1.10k
      if (header != 0x49492A00 && header != 0x4D4D002A)
2046
701
      {
2047
701
         png_chunk_benign_error(png_ptr, "invalid");
2048
701
         return handled_error;
2049
701
      }
2050
1.10k
   }
2051
2052
406
   png_set_eXIf_1(png_ptr, info_ptr, length, buffer);
2053
406
   return handled_ok;
2054
1.10k
}
2055
#else
2056
#  define png_handle_eXIf NULL
2057
#endif
2058
2059
#ifdef PNG_READ_hIST_SUPPORTED
2060
static png_handle_result_code /* PRIVATE */
2061
png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2062
0
{
2063
0
   unsigned int num, i;
2064
0
   png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
2065
2066
0
   png_debug(1, "in png_handle_hIST");
2067
2068
   /* This cast is safe because the chunk definition limits the length to a
2069
    * maximum of 1024 bytes.
2070
    *
2071
    * TODO: maybe use png_uint_32 anyway, not unsigned int, to reduce the
2072
    * casts.
2073
    */
2074
0
   num = (unsigned int)length / 2 ;
2075
2076
0
   if (length != num * 2 ||
2077
0
       num != (unsigned int)png_ptr->num_palette ||
2078
0
       num > (unsigned int)PNG_MAX_PALETTE_LENGTH)
2079
0
   {
2080
0
      png_crc_finish(png_ptr, length);
2081
0
      png_chunk_benign_error(png_ptr, "invalid");
2082
0
      return handled_error;
2083
0
   }
2084
2085
0
   for (i = 0; i < num; i++)
2086
0
   {
2087
0
      png_byte buf[2];
2088
2089
0
      png_crc_read(png_ptr, buf, 2);
2090
0
      readbuf[i] = png_get_uint_16(buf);
2091
0
   }
2092
2093
0
   if (png_crc_finish(png_ptr, 0) != 0)
2094
0
      return handled_error;
2095
2096
0
   png_set_hIST(png_ptr, info_ptr, readbuf);
2097
0
   return handled_ok;
2098
0
}
2099
#else
2100
#  define png_handle_hIST NULL
2101
#endif
2102
2103
#ifdef PNG_READ_pHYs_SUPPORTED
2104
static png_handle_result_code /* PRIVATE */
2105
png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2106
2.84k
{
2107
2.84k
   png_byte buf[9];
2108
2.84k
   png_uint_32 res_x, res_y;
2109
2.84k
   int unit_type;
2110
2111
2.84k
   png_debug(1, "in png_handle_pHYs");
2112
2113
2.84k
   png_crc_read(png_ptr, buf, 9);
2114
2115
2.84k
   if (png_crc_finish(png_ptr, 0) != 0)
2116
2.60k
      return handled_error;
2117
2118
240
   res_x = png_get_uint_32(buf);
2119
240
   res_y = png_get_uint_32(buf + 4);
2120
240
   unit_type = buf[8];
2121
240
   png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
2122
240
   return handled_ok;
2123
0
   PNG_UNUSED(length)
2124
0
}
2125
#else
2126
#  define png_handle_pHYs NULL
2127
#endif
2128
2129
#ifdef PNG_READ_oFFs_SUPPORTED
2130
static png_handle_result_code /* PRIVATE */
2131
png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2132
2.03k
{
2133
2.03k
   png_byte buf[9];
2134
2.03k
   png_int_32 offset_x, offset_y;
2135
2.03k
   int unit_type;
2136
2137
2.03k
   png_debug(1, "in png_handle_oFFs");
2138
2139
2.03k
   png_crc_read(png_ptr, buf, 9);
2140
2141
2.03k
   if (png_crc_finish(png_ptr, 0) != 0)
2142
1.90k
      return handled_error;
2143
2144
128
   offset_x = png_get_int_32(buf);
2145
128
   offset_y = png_get_int_32(buf + 4);
2146
128
   unit_type = buf[8];
2147
128
   png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
2148
128
   return handled_ok;
2149
0
   PNG_UNUSED(length)
2150
0
}
2151
#else
2152
#  define png_handle_oFFs NULL
2153
#endif
2154
2155
#ifdef PNG_READ_pCAL_SUPPORTED
2156
/* Read the pCAL chunk (described in the PNG Extensions document) */
2157
static png_handle_result_code /* PRIVATE */
2158
png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2159
0
{
2160
0
   png_int_32 X0, X1;
2161
0
   png_byte type, nparams;
2162
0
   png_bytep buffer, buf, units, endptr;
2163
0
   png_charpp params;
2164
0
   int i;
2165
2166
0
   png_debug(1, "in png_handle_pCAL");
2167
0
   png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)",
2168
0
       length + 1);
2169
2170
0
   buffer = png_read_buffer(png_ptr, length+1);
2171
2172
0
   if (buffer == NULL)
2173
0
   {
2174
0
      png_crc_finish(png_ptr, length);
2175
0
      png_chunk_benign_error(png_ptr, "out of memory");
2176
0
      return handled_error;
2177
0
   }
2178
2179
0
   png_crc_read(png_ptr, buffer, length);
2180
2181
0
   if (png_crc_finish(png_ptr, 0) != 0)
2182
0
      return handled_error;
2183
2184
0
   buffer[length] = 0; /* Null terminate the last string */
2185
2186
0
   png_debug(3, "Finding end of pCAL purpose string");
2187
0
   for (buf = buffer; *buf; buf++)
2188
0
      /* Empty loop */ ;
2189
2190
0
   endptr = buffer + length;
2191
2192
   /* We need to have at least 12 bytes after the purpose string
2193
    * in order to get the parameter information.
2194
    */
2195
0
   if (endptr - buf <= 12)
2196
0
   {
2197
0
      png_chunk_benign_error(png_ptr, "invalid");
2198
0
      return handled_error;
2199
0
   }
2200
2201
0
   png_debug(3, "Reading pCAL X0, X1, type, nparams, and units");
2202
0
   X0 = png_get_int_32((png_bytep)buf+1);
2203
0
   X1 = png_get_int_32((png_bytep)buf+5);
2204
0
   type = buf[9];
2205
0
   nparams = buf[10];
2206
0
   units = buf + 11;
2207
2208
0
   png_debug(3, "Checking pCAL equation type and number of parameters");
2209
   /* Check that we have the right number of parameters for known
2210
    * equation types.
2211
    */
2212
0
   if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
2213
0
       (type == PNG_EQUATION_BASE_E && nparams != 3) ||
2214
0
       (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
2215
0
       (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
2216
0
   {
2217
0
      png_chunk_benign_error(png_ptr, "invalid parameter count");
2218
0
      return handled_error;
2219
0
   }
2220
2221
0
   else if (type >= PNG_EQUATION_LAST)
2222
0
   {
2223
0
      png_chunk_benign_error(png_ptr, "unrecognized equation type");
2224
0
   }
2225
2226
0
   for (buf = units; *buf; buf++)
2227
0
      /* Empty loop to move past the units string. */ ;
2228
2229
0
   png_debug(3, "Allocating pCAL parameters array");
2230
2231
0
   params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
2232
0
       nparams * (sizeof (png_charp))));
2233
2234
0
   if (params == NULL)
2235
0
   {
2236
0
      png_chunk_benign_error(png_ptr, "out of memory");
2237
0
      return handled_error;
2238
0
   }
2239
2240
   /* Get pointers to the start of each parameter string. */
2241
0
   for (i = 0; i < nparams; i++)
2242
0
   {
2243
0
      buf++; /* Skip the null string terminator from previous parameter. */
2244
2245
0
      png_debug1(3, "Reading pCAL parameter %d", i);
2246
2247
0
      for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++)
2248
0
         /* Empty loop to move past each parameter string */ ;
2249
2250
      /* Make sure we haven't run out of data yet */
2251
0
      if (buf > endptr)
2252
0
      {
2253
0
         png_free(png_ptr, params);
2254
0
         png_chunk_benign_error(png_ptr, "invalid data");
2255
0
         return handled_error;
2256
0
      }
2257
0
   }
2258
2259
0
   png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams,
2260
0
       (png_charp)units, params);
2261
2262
   /* TODO: BUG: png_set_pCAL calls png_chunk_report which, in this case, calls
2263
    * png_benign_error and that can error out.
2264
    *
2265
    * png_read_buffer needs to be allocated with space for both nparams and the
2266
    * parameter strings.  Not hard to do.
2267
    */
2268
0
   png_free(png_ptr, params);
2269
0
   return handled_ok;
2270
0
}
2271
#else
2272
#  define png_handle_pCAL NULL
2273
#endif
2274
2275
#ifdef PNG_READ_sCAL_SUPPORTED
2276
/* Read the sCAL chunk */
2277
static png_handle_result_code /* PRIVATE */
2278
png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2279
0
{
2280
0
   png_bytep buffer;
2281
0
   size_t i;
2282
0
   int state;
2283
2284
0
   png_debug(1, "in png_handle_sCAL");
2285
0
   png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)",
2286
0
       length + 1);
2287
2288
0
   buffer = png_read_buffer(png_ptr, length+1);
2289
2290
0
   if (buffer == NULL)
2291
0
   {
2292
0
      png_crc_finish(png_ptr, length);
2293
0
      png_chunk_benign_error(png_ptr, "out of memory");
2294
0
      return handled_error;
2295
0
   }
2296
2297
0
   png_crc_read(png_ptr, buffer, length);
2298
0
   buffer[length] = 0; /* Null terminate the last string */
2299
2300
0
   if (png_crc_finish(png_ptr, 0) != 0)
2301
0
      return handled_error;
2302
2303
   /* Validate the unit. */
2304
0
   if (buffer[0] != 1 && buffer[0] != 2)
2305
0
   {
2306
0
      png_chunk_benign_error(png_ptr, "invalid unit");
2307
0
      return handled_error;
2308
0
   }
2309
2310
   /* Validate the ASCII numbers, need two ASCII numbers separated by
2311
    * a '\0' and they need to fit exactly in the chunk data.
2312
    */
2313
0
   i = 1;
2314
0
   state = 0;
2315
2316
0
   if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 ||
2317
0
       i >= length || buffer[i++] != 0)
2318
0
      png_chunk_benign_error(png_ptr, "bad width format");
2319
2320
0
   else if (PNG_FP_IS_POSITIVE(state) == 0)
2321
0
      png_chunk_benign_error(png_ptr, "non-positive width");
2322
2323
0
   else
2324
0
   {
2325
0
      size_t heighti = i;
2326
2327
0
      state = 0;
2328
0
      if (png_check_fp_number((png_const_charp)buffer, length,
2329
0
          &state, &i) == 0 || i != length)
2330
0
         png_chunk_benign_error(png_ptr, "bad height format");
2331
2332
0
      else if (PNG_FP_IS_POSITIVE(state) == 0)
2333
0
         png_chunk_benign_error(png_ptr, "non-positive height");
2334
2335
0
      else
2336
0
      {
2337
         /* This is the (only) success case. */
2338
0
         png_set_sCAL_s(png_ptr, info_ptr, buffer[0],
2339
0
             (png_charp)buffer+1, (png_charp)buffer+heighti);
2340
0
         return handled_ok;
2341
0
      }
2342
0
   }
2343
2344
0
   return handled_error;
2345
0
}
2346
#else
2347
#  define png_handle_sCAL NULL
2348
#endif
2349
2350
#ifdef PNG_READ_tIME_SUPPORTED
2351
static png_handle_result_code /* PRIVATE */
2352
png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2353
3.41k
{
2354
3.41k
   png_byte buf[7];
2355
3.41k
   png_time mod_time;
2356
2357
3.41k
   png_debug(1, "in png_handle_tIME");
2358
2359
   /* TODO: what is this doing here?  It should be happened in pngread.c and
2360
    * pngpread.c, although it could be moved to png_handle_chunk below and
2361
    * thereby avoid some code duplication.
2362
    */
2363
3.41k
   if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
2364
1.33k
      png_ptr->mode |= PNG_AFTER_IDAT;
2365
2366
3.41k
   png_crc_read(png_ptr, buf, 7);
2367
2368
3.41k
   if (png_crc_finish(png_ptr, 0) != 0)
2369
3.11k
      return handled_error;
2370
2371
300
   mod_time.second = buf[6];
2372
300
   mod_time.minute = buf[5];
2373
300
   mod_time.hour = buf[4];
2374
300
   mod_time.day = buf[3];
2375
300
   mod_time.month = buf[2];
2376
300
   mod_time.year = png_get_uint_16(buf);
2377
2378
300
   png_set_tIME(png_ptr, info_ptr, &mod_time);
2379
300
   return handled_ok;
2380
0
   PNG_UNUSED(length)
2381
0
}
2382
#else
2383
#  define png_handle_tIME NULL
2384
#endif
2385
2386
#ifdef PNG_READ_tEXt_SUPPORTED
2387
/* Note: this does not properly handle chunks that are > 64K under DOS */
2388
static png_handle_result_code /* PRIVATE */
2389
png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2390
42.3k
{
2391
42.3k
   png_text  text_info;
2392
42.3k
   png_bytep buffer;
2393
42.3k
   png_charp key;
2394
42.3k
   png_charp text;
2395
42.3k
   png_uint_32 skip = 0;
2396
2397
42.3k
   png_debug(1, "in png_handle_tEXt");
2398
2399
42.3k
#ifdef PNG_USER_LIMITS_SUPPORTED
2400
42.3k
   if (png_ptr->user_chunk_cache_max != 0)
2401
42.3k
   {
2402
42.3k
      if (png_ptr->user_chunk_cache_max == 1)
2403
0
      {
2404
0
         png_crc_finish(png_ptr, length);
2405
0
         return handled_error;
2406
0
      }
2407
2408
42.3k
      if (--png_ptr->user_chunk_cache_max == 1)
2409
0
      {
2410
0
         png_crc_finish(png_ptr, length);
2411
0
         png_chunk_benign_error(png_ptr, "no space in chunk cache");
2412
0
         return handled_error;
2413
0
      }
2414
42.3k
   }
2415
42.3k
#endif
2416
2417
42.3k
   buffer = png_read_buffer(png_ptr, length+1);
2418
2419
42.3k
   if (buffer == NULL)
2420
97
   {
2421
97
      png_crc_finish(png_ptr, length);
2422
97
      png_chunk_benign_error(png_ptr, "out of memory");
2423
97
      return handled_error;
2424
97
   }
2425
2426
42.2k
   png_crc_read(png_ptr, buffer, length);
2427
2428
42.2k
   if (png_crc_finish(png_ptr, skip) != 0)
2429
3.92k
      return handled_error;
2430
2431
38.3k
   key = (png_charp)buffer;
2432
38.3k
   key[length] = 0;
2433
2434
130k
   for (text = key; *text; text++)
2435
92.0k
      /* Empty loop to find end of key */ ;
2436
2437
38.3k
   if (text != key + length)
2438
10.9k
      text++;
2439
2440
38.3k
   text_info.compression = PNG_TEXT_COMPRESSION_NONE;
2441
38.3k
   text_info.key = key;
2442
38.3k
   text_info.lang = NULL;
2443
38.3k
   text_info.lang_key = NULL;
2444
38.3k
   text_info.itxt_length = 0;
2445
38.3k
   text_info.text = text;
2446
38.3k
   text_info.text_length = strlen(text);
2447
2448
38.3k
   if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) == 0)
2449
37.9k
      return handled_ok;
2450
2451
346
   png_chunk_benign_error(png_ptr, "out of memory");
2452
346
   return handled_error;
2453
38.3k
}
2454
#else
2455
#  define png_handle_tEXt NULL
2456
#endif
2457
2458
#ifdef PNG_READ_zTXt_SUPPORTED
2459
/* Note: this does not correctly handle chunks that are > 64K under DOS */
2460
static png_handle_result_code /* PRIVATE */
2461
png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2462
13.7k
{
2463
13.7k
   png_const_charp errmsg = NULL;
2464
13.7k
   png_bytep       buffer;
2465
13.7k
   png_uint_32     keyword_length;
2466
2467
13.7k
   png_debug(1, "in png_handle_zTXt");
2468
2469
13.7k
#ifdef PNG_USER_LIMITS_SUPPORTED
2470
13.7k
   if (png_ptr->user_chunk_cache_max != 0)
2471
13.7k
   {
2472
13.7k
      if (png_ptr->user_chunk_cache_max == 1)
2473
0
      {
2474
0
         png_crc_finish(png_ptr, length);
2475
0
         return handled_error;
2476
0
      }
2477
2478
13.7k
      if (--png_ptr->user_chunk_cache_max == 1)
2479
0
      {
2480
0
         png_crc_finish(png_ptr, length);
2481
0
         png_chunk_benign_error(png_ptr, "no space in chunk cache");
2482
0
         return handled_error;
2483
0
      }
2484
13.7k
   }
2485
13.7k
#endif
2486
2487
   /* Note, "length" is sufficient here; we won't be adding
2488
    * a null terminator later.  The limit check in png_handle_chunk should be
2489
    * sufficient.
2490
    */
2491
13.7k
   buffer = png_read_buffer(png_ptr, length);
2492
2493
13.7k
   if (buffer == NULL)
2494
0
   {
2495
0
      png_crc_finish(png_ptr, length);
2496
0
      png_chunk_benign_error(png_ptr, "out of memory");
2497
0
      return handled_error;
2498
0
   }
2499
2500
13.7k
   png_crc_read(png_ptr, buffer, length);
2501
2502
13.7k
   if (png_crc_finish(png_ptr, 0) != 0)
2503
3.54k
      return handled_error;
2504
2505
   /* TODO: also check that the keyword contents match the spec! */
2506
10.1k
   for (keyword_length = 0;
2507
93.3k
      keyword_length < length && buffer[keyword_length] != 0;
2508
83.1k
      ++keyword_length)
2509
83.1k
      /* Empty loop to find end of name */ ;
2510
2511
10.1k
   if (keyword_length > 79 || keyword_length < 1)
2512
1.04k
      errmsg = "bad keyword";
2513
2514
   /* zTXt must have some LZ data after the keyword, although it may expand to
2515
    * zero bytes; we need a '\0' at the end of the keyword, the compression type
2516
    * then the LZ data:
2517
    */
2518
9.12k
   else if (keyword_length + 3 > length)
2519
557
      errmsg = "truncated";
2520
2521
8.57k
   else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE)
2522
516
      errmsg = "unknown compression type";
2523
2524
8.05k
   else
2525
8.05k
   {
2526
8.05k
      png_alloc_size_t uncompressed_length = PNG_SIZE_MAX;
2527
2528
      /* TODO: at present png_decompress_chunk imposes a single application
2529
       * level memory limit, this should be split to different values for iCCP
2530
       * and text chunks.
2531
       */
2532
8.05k
      if (png_decompress_chunk(png_ptr, length, keyword_length+2,
2533
8.05k
          &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2534
5.16k
      {
2535
5.16k
         png_text text;
2536
2537
5.16k
         if (png_ptr->read_buffer == NULL)
2538
0
           errmsg="Read failure in png_handle_zTXt";
2539
5.16k
         else
2540
5.16k
         {
2541
            /* It worked; png_ptr->read_buffer now looks like a tEXt chunk
2542
             * except for the extra compression type byte and the fact that
2543
             * it isn't necessarily '\0' terminated.
2544
             */
2545
5.16k
            buffer = png_ptr->read_buffer;
2546
5.16k
            buffer[uncompressed_length+(keyword_length+2)] = 0;
2547
2548
5.16k
            text.compression = PNG_TEXT_COMPRESSION_zTXt;
2549
5.16k
            text.key = (png_charp)buffer;
2550
5.16k
            text.text = (png_charp)(buffer + keyword_length+2);
2551
5.16k
            text.text_length = uncompressed_length;
2552
5.16k
            text.itxt_length = 0;
2553
5.16k
            text.lang = NULL;
2554
5.16k
            text.lang_key = NULL;
2555
2556
5.16k
            if (png_set_text_2(png_ptr, info_ptr, &text, 1) == 0)
2557
5.16k
               return handled_ok;
2558
2559
0
            errmsg = "out of memory";
2560
0
         }
2561
5.16k
      }
2562
2563
2.89k
      else
2564
2.89k
         errmsg = png_ptr->zstream.msg;
2565
8.05k
   }
2566
2567
5.01k
   png_chunk_benign_error(png_ptr, errmsg);
2568
5.01k
   return handled_error;
2569
10.1k
}
2570
#else
2571
#  define png_handle_zTXt NULL
2572
#endif
2573
2574
#ifdef PNG_READ_iTXt_SUPPORTED
2575
/* Note: this does not correctly handle chunks that are > 64K under DOS */
2576
static png_handle_result_code /* PRIVATE */
2577
png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
2578
0
{
2579
0
   png_const_charp errmsg = NULL;
2580
0
   png_bytep buffer;
2581
0
   png_uint_32 prefix_length;
2582
2583
0
   png_debug(1, "in png_handle_iTXt");
2584
2585
0
#ifdef PNG_USER_LIMITS_SUPPORTED
2586
0
   if (png_ptr->user_chunk_cache_max != 0)
2587
0
   {
2588
0
      if (png_ptr->user_chunk_cache_max == 1)
2589
0
      {
2590
0
         png_crc_finish(png_ptr, length);
2591
0
         return handled_error;
2592
0
      }
2593
2594
0
      if (--png_ptr->user_chunk_cache_max == 1)
2595
0
      {
2596
0
         png_crc_finish(png_ptr, length);
2597
0
         png_chunk_benign_error(png_ptr, "no space in chunk cache");
2598
0
         return handled_error;
2599
0
      }
2600
0
   }
2601
0
#endif
2602
2603
0
   buffer = png_read_buffer(png_ptr, length+1);
2604
2605
0
   if (buffer == NULL)
2606
0
   {
2607
0
      png_crc_finish(png_ptr, length);
2608
0
      png_chunk_benign_error(png_ptr, "out of memory");
2609
0
      return handled_error;
2610
0
   }
2611
2612
0
   png_crc_read(png_ptr, buffer, length);
2613
2614
0
   if (png_crc_finish(png_ptr, 0) != 0)
2615
0
      return handled_error;
2616
2617
   /* First the keyword. */
2618
0
   for (prefix_length=0;
2619
0
      prefix_length < length && buffer[prefix_length] != 0;
2620
0
      ++prefix_length)
2621
0
      /* Empty loop */ ;
2622
2623
   /* Perform a basic check on the keyword length here. */
2624
0
   if (prefix_length > 79 || prefix_length < 1)
2625
0
      errmsg = "bad keyword";
2626
2627
   /* Expect keyword, compression flag, compression type, language, translated
2628
    * keyword (both may be empty but are 0 terminated) then the text, which may
2629
    * be empty.
2630
    */
2631
0
   else if (prefix_length + 5 > length)
2632
0
      errmsg = "truncated";
2633
2634
0
   else if (buffer[prefix_length+1] == 0 ||
2635
0
      (buffer[prefix_length+1] == 1 &&
2636
0
      buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE))
2637
0
   {
2638
0
      int compressed = buffer[prefix_length+1] != 0;
2639
0
      png_uint_32 language_offset, translated_keyword_offset;
2640
0
      png_alloc_size_t uncompressed_length = 0;
2641
2642
      /* Now the language tag */
2643
0
      prefix_length += 3;
2644
0
      language_offset = prefix_length;
2645
2646
0
      for (; prefix_length < length && buffer[prefix_length] != 0;
2647
0
         ++prefix_length)
2648
0
         /* Empty loop */ ;
2649
2650
      /* WARNING: the length may be invalid here, this is checked below. */
2651
0
      translated_keyword_offset = ++prefix_length;
2652
2653
0
      for (; prefix_length < length && buffer[prefix_length] != 0;
2654
0
         ++prefix_length)
2655
0
         /* Empty loop */ ;
2656
2657
      /* prefix_length should now be at the trailing '\0' of the translated
2658
       * keyword, but it may already be over the end.  None of this arithmetic
2659
       * can overflow because chunks are at most 2^31 bytes long, but on 16-bit
2660
       * systems the available allocation may overflow.
2661
       */
2662
0
      ++prefix_length;
2663
2664
0
      if (compressed == 0 && prefix_length <= length)
2665
0
         uncompressed_length = length - prefix_length;
2666
2667
0
      else if (compressed != 0 && prefix_length < length)
2668
0
      {
2669
0
         uncompressed_length = PNG_SIZE_MAX;
2670
2671
         /* TODO: at present png_decompress_chunk imposes a single application
2672
          * level memory limit, this should be split to different values for
2673
          * iCCP and text chunks.
2674
          */
2675
0
         if (png_decompress_chunk(png_ptr, length, prefix_length,
2676
0
             &uncompressed_length, 1/*terminate*/) == Z_STREAM_END)
2677
0
            buffer = png_ptr->read_buffer;
2678
2679
0
         else
2680
0
            errmsg = png_ptr->zstream.msg;
2681
0
      }
2682
2683
0
      else
2684
0
         errmsg = "truncated";
2685
2686
0
      if (errmsg == NULL)
2687
0
      {
2688
0
         png_text text;
2689
2690
0
         buffer[uncompressed_length+prefix_length] = 0;
2691
2692
0
         if (compressed == 0)
2693
0
            text.compression = PNG_ITXT_COMPRESSION_NONE;
2694
2695
0
         else
2696
0
            text.compression = PNG_ITXT_COMPRESSION_zTXt;
2697
2698
0
         text.key = (png_charp)buffer;
2699
0
         text.lang = (png_charp)buffer + language_offset;
2700
0
         text.lang_key = (png_charp)buffer + translated_keyword_offset;
2701
0
         text.text = (png_charp)buffer + prefix_length;
2702
0
         text.text_length = 0;
2703
0
         text.itxt_length = uncompressed_length;
2704
2705
0
         if (png_set_text_2(png_ptr, info_ptr, &text, 1) == 0)
2706
0
            return handled_ok;
2707
2708
0
         errmsg = "out of memory";
2709
0
      }
2710
0
   }
2711
2712
0
   else
2713
0
      errmsg = "bad compression info";
2714
2715
0
   if (errmsg != NULL)
2716
0
      png_chunk_benign_error(png_ptr, errmsg);
2717
0
   return handled_error;
2718
0
}
2719
#else
2720
#  define png_handle_iTXt NULL
2721
#endif
2722
2723
#ifdef PNG_READ_APNG_SUPPORTED
2724
void /* PRIVATE */
2725
png_handle_acTL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
2726
0
{
2727
0
   png_byte data[8];
2728
0
   png_uint_32 num_frames;
2729
0
   png_uint_32 num_plays;
2730
2731
0
   png_debug(1, "in png_handle_acTL");
2732
2733
0
   if (!(png_ptr->mode & PNG_HAVE_IHDR))
2734
0
   {
2735
0
      png_error(png_ptr, "Missing IHDR before acTL");
2736
0
   }
2737
0
   else if (png_ptr->mode & PNG_HAVE_IDAT)
2738
0
   {
2739
0
      png_warning(png_ptr, "Ignoring misplaced acTL after IDAT");
2740
0
      png_crc_finish(png_ptr, length);
2741
0
      return;
2742
0
   }
2743
0
   else if (png_ptr->mode & PNG_HAVE_acTL)
2744
0
   {
2745
0
      png_warning(png_ptr, "Ignoring duplicate acTL");
2746
0
      png_crc_finish(png_ptr, length);
2747
0
      return;
2748
0
   }
2749
0
   else if (length != 8)
2750
0
   {
2751
0
      png_warning(png_ptr, "Ignoring acTL with incorrect length");
2752
0
      png_crc_finish(png_ptr, length);
2753
0
      return;
2754
0
   }
2755
2756
0
   png_crc_read(png_ptr, data, 8);
2757
0
   png_crc_finish(png_ptr, 0);
2758
2759
0
   num_frames = png_get_uint_31(png_ptr, data);
2760
0
   num_plays = png_get_uint_31(png_ptr, data + 4);
2761
2762
   /* The set function will do error checking on num_frames. */
2763
0
   if (png_set_acTL(png_ptr, info_ptr, num_frames, num_plays))
2764
0
      png_ptr->mode |= PNG_HAVE_acTL;
2765
0
}
2766
2767
void /* PRIVATE */
2768
png_handle_fcTL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
2769
0
{
2770
0
   png_byte data[22];
2771
0
   png_uint_32 width;
2772
0
   png_uint_32 height;
2773
0
   png_uint_32 x_offset;
2774
0
   png_uint_32 y_offset;
2775
0
   png_uint_16 delay_num;
2776
0
   png_uint_16 delay_den;
2777
0
   png_byte dispose_op;
2778
0
   png_byte blend_op;
2779
2780
0
   png_debug(1, "in png_handle_fcTL");
2781
2782
0
   png_ensure_sequence_number(png_ptr, length);
2783
2784
0
   if (!(png_ptr->mode & PNG_HAVE_IHDR))
2785
0
   {
2786
0
      png_error(png_ptr, "Missing IHDR before fcTL");
2787
0
   }
2788
0
   else if (png_ptr->mode & PNG_HAVE_IDAT)
2789
0
   {
2790
      /* For any frames other then the first this message may be misleading,
2791
       * but correct. PNG_HAVE_IDAT is unset before the frame head is read.
2792
       * I can't think of a better message.
2793
       */
2794
0
      png_warning(png_ptr, "Ignoring invalid fcTL after IDAT");
2795
0
      png_crc_finish(png_ptr, length-4);
2796
0
      return;
2797
0
   }
2798
0
   else if (png_ptr->mode & PNG_HAVE_fcTL)
2799
0
   {
2800
0
      png_warning(png_ptr, "Ignoring duplicate fcTL within one frame");
2801
0
      png_crc_finish(png_ptr, length-4);
2802
0
      return;
2803
0
   }
2804
0
   else if (length != 26)
2805
0
   {
2806
0
      png_warning(png_ptr, "Ignoring fcTL with incorrect length");
2807
0
      png_crc_finish(png_ptr, length-4);
2808
0
      return;
2809
0
   }
2810
2811
0
   png_crc_read(png_ptr, data, 22);
2812
0
   png_crc_finish(png_ptr, 0);
2813
2814
0
   width = png_get_uint_31(png_ptr, data);
2815
0
   height = png_get_uint_31(png_ptr, data + 4);
2816
0
   x_offset = png_get_uint_31(png_ptr, data + 8);
2817
0
   y_offset = png_get_uint_31(png_ptr, data + 12);
2818
0
   delay_num = png_get_uint_16(data + 16);
2819
0
   delay_den = png_get_uint_16(data + 18);
2820
0
   dispose_op = data[20];
2821
0
   blend_op = data[21];
2822
2823
0
   if (png_ptr->num_frames_read == 0 && (x_offset != 0 || y_offset != 0))
2824
0
   {
2825
0
      png_warning(png_ptr, "Ignoring leading fcTL with non-zero frame offset");
2826
0
      return;
2827
0
   }
2828
2829
0
   if (info_ptr != NULL)
2830
0
   {
2831
0
      if (png_ptr->num_frames_read == 0 &&
2832
0
          (width != info_ptr->width || height != info_ptr->height))
2833
0
      {
2834
0
         png_warning(png_ptr,
2835
0
                     "Ignoring leading fcTL with incorrect frame size");
2836
0
         return;
2837
0
      }
2838
2839
      /* The set function will do more error checking. */
2840
0
      png_set_next_frame_fcTL(png_ptr, info_ptr, width, height,
2841
0
                              x_offset, y_offset, delay_num, delay_den,
2842
0
                              dispose_op, blend_op);
2843
2844
0
      png_read_reinit(png_ptr, info_ptr);
2845
2846
0
      png_ptr->mode |= PNG_HAVE_fcTL;
2847
0
   }
2848
0
}
2849
2850
void /* PRIVATE */
2851
png_have_info(png_structp png_ptr, png_infop info_ptr)
2852
46.5k
{
2853
46.5k
   if ((info_ptr->valid & PNG_INFO_acTL) && !(info_ptr->valid & PNG_INFO_fcTL))
2854
0
   {
2855
0
      png_ptr->apng_flags |= PNG_FIRST_FRAME_HIDDEN;
2856
0
      info_ptr->num_frames++;
2857
0
   }
2858
46.5k
}
2859
2860
void /* PRIVATE */
2861
png_handle_fdAT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
2862
0
{
2863
0
   png_ensure_sequence_number(png_ptr, length);
2864
2865
   /* This function is called only from png_read_end(), png_read_info(),
2866
    * and png_push_read_chunk(). This means one of the following:
2867
    * - The user doesn't want to read this frame.
2868
    * - This is an out-of-place fdAT.
2869
    * In either case, it is safe to ignore the chunk with a warning.
2870
    */
2871
0
   png_warning(png_ptr, "Ignoring fdAT chunk");
2872
0
   png_crc_finish(png_ptr, length - 4);
2873
0
   PNG_UNUSED(info_ptr)
2874
0
}
2875
2876
void /* PRIVATE */
2877
png_ensure_sequence_number(png_structp png_ptr, png_uint_32 length)
2878
163
{
2879
163
   png_byte data[4];
2880
163
   png_uint_32 sequence_number;
2881
2882
163
   if (length < 4)
2883
7
   {
2884
      /* TODO: Write a more precise message. */
2885
7
      png_error(png_ptr, "Invalid fcTL or fdAT chunk");
2886
7
   }
2887
2888
156
   png_crc_read(png_ptr, data, 4);
2889
156
   sequence_number = png_get_uint_31(png_ptr, data);
2890
2891
156
   if (sequence_number != png_ptr->next_seq_num)
2892
138
   {
2893
      /* TODO: Write a more precise message. */
2894
138
      png_error(png_ptr, "Out-of-order sequence number in fcTL or fdAT");
2895
138
   }
2896
2897
18
   png_ptr->next_seq_num++;
2898
18
}
2899
#endif /* PNG_READ_APNG_SUPPORTED */
2900
2901
#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2902
/* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
2903
static int
2904
png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
2905
298k
{
2906
298k
   const png_alloc_size_t limit = png_chunk_max(png_ptr);
2907
2908
298k
   if (png_ptr->unknown_chunk.data != NULL)
2909
0
   {
2910
0
      png_free(png_ptr, png_ptr->unknown_chunk.data);
2911
0
      png_ptr->unknown_chunk.data = NULL;
2912
0
   }
2913
2914
298k
   if (length <= limit)
2915
296k
   {
2916
296k
      PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name);
2917
      /* The following is safe because of the PNG_SIZE_MAX init above */
2918
296k
      png_ptr->unknown_chunk.size = (size_t)length/*SAFE*/;
2919
      /* 'mode' is a flag array, only the bottom four bits matter here */
2920
296k
      png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/;
2921
2922
296k
      if (length == 0)
2923
52.1k
         png_ptr->unknown_chunk.data = NULL;
2924
2925
244k
      else
2926
244k
      {
2927
         /* Do a 'warn' here - it is handled below. */
2928
244k
         png_ptr->unknown_chunk.data = png_voidcast(png_bytep,
2929
244k
             png_malloc_warn(png_ptr, length));
2930
244k
      }
2931
296k
   }
2932
2933
298k
   if (png_ptr->unknown_chunk.data == NULL && length > 0)
2934
1.74k
   {
2935
      /* This is benign because we clean up correctly */
2936
1.74k
      png_crc_finish(png_ptr, length);
2937
1.74k
      png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits");
2938
1.74k
      return 0;
2939
1.74k
   }
2940
2941
296k
   else
2942
296k
   {
2943
296k
      if (length > 0)
2944
244k
         png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length);
2945
296k
      png_crc_finish(png_ptr, 0);
2946
296k
      return 1;
2947
296k
   }
2948
298k
}
2949
#endif /* READ_UNKNOWN_CHUNKS */
2950
2951
/* Handle an unknown, or known but disabled, chunk */
2952
png_handle_result_code /*PRIVATE*/
2953
png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
2954
    png_uint_32 length, int keep)
2955
298k
{
2956
298k
   png_handle_result_code handled = handled_discarded; /* the default */
2957
2958
298k
   png_debug(1, "in png_handle_unknown");
2959
2960
298k
#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
2961
   /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing
2962
    * the bug which meant that setting a non-default behavior for a specific
2963
    * chunk would be ignored (the default was always used unless a user
2964
    * callback was installed).
2965
    *
2966
    * 'keep' is the value from the png_chunk_unknown_handling, the setting for
2967
    * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it
2968
    * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here.
2969
    * This is just an optimization to avoid multiple calls to the lookup
2970
    * function.
2971
    */
2972
#  ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
2973
#     ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
2974
   keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
2975
#     endif
2976
#  endif
2977
2978
   /* One of the following methods will read the chunk or skip it (at least one
2979
    * of these is always defined because this is the only way to switch on
2980
    * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
2981
    */
2982
298k
#  ifdef PNG_READ_USER_CHUNKS_SUPPORTED
2983
   /* The user callback takes precedence over the chunk keep value, but the
2984
    * keep value is still required to validate a save of a critical chunk.
2985
    */
2986
298k
   if (png_ptr->read_user_chunk_fn != NULL)
2987
298k
   {
2988
298k
      if (png_cache_unknown_chunk(png_ptr, length) != 0)
2989
293k
      {
2990
         /* Callback to user unknown chunk handler */
2991
293k
         int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
2992
293k
             &png_ptr->unknown_chunk);
2993
2994
         /* ret is:
2995
          * negative: An error occurred; png_chunk_error will be called.
2996
          *     zero: The chunk was not handled, the chunk will be discarded
2997
          *           unless png_set_keep_unknown_chunks has been used to set
2998
          *           a 'keep' behavior for this particular chunk, in which
2999
          *           case that will be used.  A critical chunk will cause an
3000
          *           error at this point unless it is to be saved.
3001
          * positive: The chunk was handled, libpng will ignore/discard it.
3002
          */
3003
293k
         if (ret < 0) /* handled_error */
3004
93
            png_chunk_error(png_ptr, "error in user chunk");
3005
3006
292k
         else if (ret == 0)
3007
79.6k
         {
3008
            /* If the keep value is 'default' or 'never' override it, but
3009
             * still error out on critical chunks unless the keep value is
3010
             * 'always'  While this is weird it is the behavior in 1.4.12.
3011
             * A possible improvement would be to obey the value set for the
3012
             * chunk, but this would be an API change that would probably
3013
             * damage some applications.
3014
             *
3015
             * The png_app_warning below catches the case that matters, where
3016
             * the application has not set specific save or ignore for this
3017
             * chunk or global save or ignore.
3018
             */
3019
79.6k
            if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
3020
78.1k
            {
3021
78.1k
#              ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
3022
78.1k
               if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
3023
78.1k
               {
3024
78.1k
                  png_chunk_warning(png_ptr, "Saving unknown chunk:");
3025
78.1k
                  png_app_warning(png_ptr,
3026
78.1k
                      "forcing save of an unhandled chunk;"
3027
78.1k
                      " please call png_set_keep_unknown_chunks");
3028
                      /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
3029
78.1k
               }
3030
78.1k
#              endif
3031
78.1k
               keep = PNG_HANDLE_CHUNK_IF_SAFE;
3032
78.1k
            }
3033
79.6k
         }
3034
3035
213k
         else /* chunk was handled */
3036
213k
         {
3037
213k
            handled = handled_ok;
3038
            /* Critical chunks can be safely discarded at this point. */
3039
213k
            keep = PNG_HANDLE_CHUNK_NEVER;
3040
213k
         }
3041
293k
      }
3042
3043
5.26k
      else
3044
5.26k
         keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
3045
298k
   }
3046
3047
0
   else
3048
   /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
3049
0
#  endif /* READ_USER_CHUNKS */
3050
3051
0
#  ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
3052
0
   {
3053
      /* keep is currently just the per-chunk setting, if there was no
3054
       * setting change it to the global default now (not that this may
3055
       * still be AS_DEFAULT) then obtain the cache of the chunk if required,
3056
       * if not simply skip the chunk.
3057
       */
3058
0
      if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
3059
0
         keep = png_ptr->unknown_default;
3060
3061
0
      if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
3062
0
         (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
3063
0
          PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
3064
0
      {
3065
0
         if (png_cache_unknown_chunk(png_ptr, length) == 0)
3066
0
            keep = PNG_HANDLE_CHUNK_NEVER;
3067
0
      }
3068
3069
0
      else
3070
0
         png_crc_finish(png_ptr, length);
3071
0
   }
3072
#  else
3073
#     ifndef PNG_READ_USER_CHUNKS_SUPPORTED
3074
#        error no method to support READ_UNKNOWN_CHUNKS
3075
#     endif
3076
3077
   {
3078
      /* If here there is no read callback pointer set and no support is
3079
       * compiled in to just save the unknown chunks, so simply skip this
3080
       * chunk.  If 'keep' is something other than AS_DEFAULT or NEVER then
3081
       * the app has erroneously asked for unknown chunk saving when there
3082
       * is no support.
3083
       */
3084
      if (keep > PNG_HANDLE_CHUNK_NEVER)
3085
         png_app_error(png_ptr, "no unknown chunk support available");
3086
3087
      png_crc_finish(png_ptr, length);
3088
   }
3089
#  endif
3090
3091
298k
#  ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
3092
   /* Now store the chunk in the chunk list if appropriate, and if the limits
3093
    * permit it.
3094
    */
3095
298k
   if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
3096
292k
      (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
3097
79.6k
       PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
3098
79.6k
   {
3099
79.6k
#     ifdef PNG_USER_LIMITS_SUPPORTED
3100
79.6k
      switch (png_ptr->user_chunk_cache_max)
3101
79.6k
      {
3102
0
         case 2:
3103
0
            png_ptr->user_chunk_cache_max = 1;
3104
0
            png_chunk_benign_error(png_ptr, "no space in chunk cache");
3105
            /* FALLTHROUGH */
3106
0
         case 1:
3107
            /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
3108
             * chunk being skipped, now there will be a hard error below.
3109
             */
3110
0
            break;
3111
3112
79.6k
         default: /* not at limit */
3113
79.6k
            --(png_ptr->user_chunk_cache_max);
3114
            /* FALLTHROUGH */
3115
79.6k
         case 0: /* no limit */
3116
79.6k
#  endif /* USER_LIMITS */
3117
            /* Here when the limit isn't reached or when limits are compiled
3118
             * out; store the chunk.
3119
             */
3120
79.6k
            png_set_unknown_chunks(png_ptr, info_ptr,
3121
79.6k
                &png_ptr->unknown_chunk, 1);
3122
79.6k
            handled = handled_saved;
3123
79.6k
#  ifdef PNG_USER_LIMITS_SUPPORTED
3124
79.6k
            break;
3125
79.6k
      }
3126
79.6k
#  endif
3127
79.6k
   }
3128
#  else /* no store support: the chunk must be handled by the user callback */
3129
   PNG_UNUSED(info_ptr)
3130
#  endif
3131
3132
   /* Regardless of the error handling below the cached data (if any) can be
3133
    * freed now.  Notice that the data is not freed if there is a png_error, but
3134
    * it will be freed by destroy_read_struct.
3135
    */
3136
296k
   if (png_ptr->unknown_chunk.data != NULL)
3137
239k
      png_free(png_ptr, png_ptr->unknown_chunk.data);
3138
296k
   png_ptr->unknown_chunk.data = NULL;
3139
3140
#else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */
3141
   /* There is no support to read an unknown chunk, so just skip it. */
3142
   png_crc_finish(png_ptr, length);
3143
   PNG_UNUSED(info_ptr)
3144
   PNG_UNUSED(keep)
3145
#endif /* !READ_UNKNOWN_CHUNKS */
3146
3147
   /* Check for unhandled critical chunks */
3148
296k
   if (handled < handled_saved && PNG_CHUNK_CRITICAL(png_ptr->chunk_name))
3149
26
      png_chunk_error(png_ptr, "unhandled critical chunk");
3150
3151
296k
   return handled;
3152
296k
}
3153
3154
/* APNG handling: the minimal implementation of APNG handling in libpng 1.6
3155
 * requires that those significant applications which already handle APNG not
3156
 * get hosed.  To do this ensure the code here will have to ensure than APNG
3157
 * data by default (at least in 1.6) gets stored in the unknown chunk list.
3158
 * Maybe this can be relaxed in a few years but at present it's just the only
3159
 * safe way.
3160
 *
3161
 * ATM just cause unknown handling for all three chunks:
3162
 */
3163
#define png_handle_acTL NULL
3164
#define png_handle_fcTL NULL
3165
#define png_handle_fdAT NULL
3166
3167
/*
3168
 * 1.6.47: This is the new table driven interface to all the chunk handling.
3169
 *
3170
 * The table describes the PNG standard rules for **reading** known chunks -
3171
 * every chunk which has an entry in PNG_KNOWN_CHUNKS.  The table contains an
3172
 * entry for each PNG_INDEX_cHNK describing the rules.
3173
 *
3174
 * In this initial version the only information in the entry is the
3175
 * png_handle_cHNK function for the chunk in question.  When chunk support is
3176
 * compiled out the entry will be NULL.
3177
 */
3178
static const struct
3179
{
3180
   png_handle_result_code (*handler)(
3181
         png_structrp, png_inforp, png_uint_32 length);
3182
      /* A chunk-specific 'handler', NULL if the chunk is not supported in this
3183
       * build.
3184
       */
3185
3186
   /* Crushing these values helps on modern 32-bit architectures because the
3187
    * pointer and the following bit fields both end up requiring 32 bits.
3188
    * Typically this will halve the table size.  On 64-bit architectures the
3189
    * table entries will typically be 8 bytes.
3190
    */
3191
   png_uint_32 max_length :12; /* Length min, max in bytes */
3192
   png_uint_32 min_length :8;
3193
      /* Length errors on critical chunks have special handling to preserve the
3194
       * existing behaviour in libpng 1.6.  Anciallary chunks are checked below
3195
       * and produce a 'benign' error.
3196
       */
3197
   png_uint_32 pos_before :4; /* PNG_HAVE_ values chunk must precede */
3198
   png_uint_32 pos_after  :4; /* PNG_HAVE_ values chunk must follow */
3199
      /* NOTE: PLTE, tRNS and bKGD require special handling which depends on
3200
       * the colour type of the base image.
3201
       */
3202
   png_uint_32 multiple   :1; /* Multiple occurences permitted */
3203
      /* This is enabled for PLTE because PLTE may, in practice, be optional */
3204
}
3205
read_chunks[PNG_INDEX_unknown] =
3206
{
3207
   /* Definitions as above but done indirectly by #define so that
3208
    * PNG_KNOWN_CHUNKS can be used safely to build the table in order.
3209
    *
3210
    * Each CDcHNK definition lists the values for the parameters **after**
3211
    * the first, 'handler', function.  'handler' is NULL when the chunk has no
3212
    * compiled in support.
3213
    */
3214
142k
#  define NoCheck 0x801U      /* Do not check the maximum length */
3215
19.3k
#  define Limit   0x802U      /* Limit to png_chunk_max bytes */
3216
#  define LKMin   3U+LZ77Min  /* Minimum length of keyword+LZ77 */
3217
3218
#define hIHDR PNG_HAVE_IHDR
3219
#define hPLTE PNG_HAVE_PLTE
3220
#define hIDAT PNG_HAVE_IDAT
3221
   /* For the two chunks, tRNS and bKGD which can occur in PNGs without a PLTE
3222
    * but must occur after the PLTE use this and put the check in the handler
3223
    * routine for colour mapped images were PLTE is required.  Also put a check
3224
    * in PLTE for other image types to drop the PLTE if tRNS or bKGD have been
3225
    * seen.
3226
    */
3227
#define hCOL  (PNG_HAVE_PLTE|PNG_HAVE_IDAT)
3228
   /* Used for the decoding chunks which must be before PLTE. */
3229
#define aIDAT PNG_AFTER_IDAT
3230
3231
   /* Chunks from W3C PNG v3: */
3232
   /*       cHNK  max_len,   min, before, after, multiple */
3233
#  define CDIHDR      13U,   13U,  hIHDR,     0,        0
3234
#  define CDPLTE  NoCheck,    0U,      0, hIHDR,        1
3235
      /* PLTE errors are only critical for colour-map images, consequently the
3236
       * hander does all the checks.
3237
       */
3238
#  define CDIDAT  NoCheck,    0U,  aIDAT, hIHDR,        1
3239
#  define CDIEND  NoCheck,    0U,      0, aIDAT,        0
3240
      /* Historically data was allowed in IEND */
3241
#  define CDtRNS     256U,    0U,  hIDAT, hIHDR,        0
3242
#  define CDcHRM      32U,   32U,   hCOL, hIHDR,        0
3243
#  define CDgAMA       4U,    4U,   hCOL, hIHDR,        0
3244
#  define CDiCCP  NoCheck, LKMin,   hCOL, hIHDR,        0
3245
#  define CDsBIT       4U,    1U,   hCOL, hIHDR,        0
3246
#  define CDsRGB       1U,    1U,   hCOL, hIHDR,        0
3247
#  define CDcICP       4U,    4U,   hCOL, hIHDR,        0
3248
#  define CDmDCV      24U,   24U,   hCOL, hIHDR,        0
3249
#  define CDeXIf    Limit,    4U,      0, hIHDR,        0
3250
#  define CDcLLI       8U,    8U,   hCOL, hIHDR,        0
3251
#  define CDtEXt  NoCheck,    2U,      0, hIHDR,        1
3252
      /* Allocates 'length+1'; checked in the handler */
3253
#  define CDzTXt    Limit, LKMin,      0, hIHDR,        1
3254
#  define CDiTXt  NoCheck,    6U,      0, hIHDR,        1
3255
      /* Allocates 'length+1'; checked in the handler */
3256
#  define CDbKGD       6U,    1U,  hIDAT, hIHDR,        0
3257
#  define CDhIST    1024U,    0U,  hPLTE, hIHDR,        0
3258
#  define CDpHYs       9U,    9U,  hIDAT, hIHDR,        0
3259
#  define CDsPLT  NoCheck,    3U,  hIDAT, hIHDR,        1
3260
      /* Allocates 'length+1'; checked in the handler */
3261
#  define CDtIME       7U,    7U,      0, hIHDR,        0
3262
#  define CDacTL       8U,    8U,  hIDAT, hIHDR,        0
3263
#  define CDfcTL      25U,   26U,      0, hIHDR,        1
3264
#  define CDfdAT    Limit,    4U,  hIDAT, hIHDR,        1
3265
   /* Supported chunks from PNG extensions 1.5.0, NYI so limit */
3266
#  define CDoFFs       9U,    9U,  hIDAT, hIHDR,        0
3267
#  define CDpCAL  NoCheck,   14U,  hIDAT, hIHDR,        0
3268
      /* Allocates 'length+1'; checked in the handler */
3269
#  define CDsCAL    Limit,    4U,  hIDAT, hIHDR,        0
3270
      /* Allocates 'length+1'; checked in the handler */
3271
3272
#  define PNG_CHUNK(cHNK, index) { png_handle_ ## cHNK, CD ## cHNK },
3273
   PNG_KNOWN_CHUNKS
3274
#  undef PNG_CHUNK
3275
};
3276
3277
3278
static png_index
3279
png_chunk_index_from_name(png_uint_32 chunk_name)
3280
456k
{
3281
   /* For chunk png_cHNK return PNG_INDEX_cHNK.  Return PNG_INDEX_unknown if
3282
    * chunk_name is not known.  Notice that in a particular build "known" does
3283
    * not necessarily mean "supported", although the inverse applies.
3284
    */
3285
456k
   switch (chunk_name)
3286
456k
   {
3287
0
#     define PNG_CHUNK(cHNK, index)\
3288
332k
         case png_ ## cHNK: return PNG_INDEX_ ## cHNK; /* == index */
3289
3290
0
      PNG_KNOWN_CHUNKS
3291
3292
0
#     undef PNG_CHUNK
3293
3294
123k
      default: return PNG_INDEX_unknown;
3295
456k
   }
3296
456k
}
3297
3298
png_handle_result_code /*PRIVATE*/
3299
png_handle_chunk(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
3300
456k
{
3301
   /* CSE: these things don't change, these autos are just to save typing and
3302
    * make the code more clear.
3303
    */
3304
456k
   const png_uint_32 chunk_name = png_ptr->chunk_name;
3305
456k
   const png_index chunk_index = png_chunk_index_from_name(chunk_name);
3306
3307
456k
   png_handle_result_code handled = handled_error;
3308
456k
   png_const_charp errmsg = NULL;
3309
3310
   /* Is this a known chunk?  If not there are no checks performed here;
3311
    * png_handle_unknown does the correct checks.  This means that the values
3312
    * for known but unsupported chunks in the above table are not used here
3313
    * however the chunks_seen fields in png_struct are still set.
3314
    */
3315
456k
   if (chunk_index == PNG_INDEX_unknown ||
3316
332k
       read_chunks[chunk_index].handler == NULL)
3317
123k
   {
3318
123k
      handled = png_handle_unknown(
3319
123k
            png_ptr, info_ptr, length, PNG_HANDLE_CHUNK_AS_DEFAULT);
3320
123k
   }
3321
3322
   /* First check the position.   The first check is historical; the stream must
3323
    * start with IHDR and anything else causes libpng to give up immediately.
3324
    */
3325
332k
   else if (chunk_index != PNG_INDEX_IHDR &&
3326
261k
            (png_ptr->mode & PNG_HAVE_IHDR) == 0)
3327
81
      png_chunk_error(png_ptr, "missing IHDR"); /* NORETURN */
3328
3329
   /* Before all the pos_before chunks, after all the pos_after chunks. */
3330
332k
   else if (((png_ptr->mode & read_chunks[chunk_index].pos_before) != 0) ||
3331
329k
            ((png_ptr->mode & read_chunks[chunk_index].pos_after) !=
3332
329k
             read_chunks[chunk_index].pos_after))
3333
3.21k
   {
3334
3.21k
      errmsg = "out of place";
3335
3.21k
   }
3336
3337
   /* Now check for duplicates: duplicated critical chunks also produce a
3338
    * full error.
3339
    */
3340
329k
   else if (read_chunks[chunk_index].multiple == 0 &&
3341
255k
            png_file_has_chunk(png_ptr, chunk_index))
3342
4.02k
   {
3343
4.02k
      errmsg = "duplicate";
3344
4.02k
   }
3345
3346
325k
   else if (length < read_chunks[chunk_index].min_length)
3347
20.3k
      errmsg = "too short";
3348
305k
   else
3349
305k
   {
3350
      /* NOTE: apart from IHDR the critical chunks (PLTE, IDAT and IEND) are set
3351
       * up above not to do any length checks.
3352
       *
3353
       * The png_chunk_max check ensures that the variable length chunks are
3354
       * always checked at this point for being within the system allocation
3355
       * limits.
3356
       */
3357
305k
      unsigned max_length = read_chunks[chunk_index].max_length;
3358
3359
305k
      switch (max_length)
3360
305k
      {
3361
19.3k
         case Limit:
3362
            /* png_read_chunk_header has already png_error'ed chunks with a
3363
             * length exceeding the 31-bit PNG limit, so just check the memory
3364
             * limit:
3365
             */
3366
19.3k
            if (length <= png_chunk_max(png_ptr))
3367
19.2k
               goto MeetsLimit;
3368
3369
89
            errmsg = "length exceeds libpng limit";
3370
89
            break;
3371
3372
143k
         default:
3373
143k
            if (length <= max_length)
3374
140k
               goto MeetsLimit;
3375
3376
2.69k
            errmsg = "too long";
3377
2.69k
            break;
3378
3379
142k
         case NoCheck:
3380
302k
         MeetsLimit:
3381
302k
            handled = read_chunks[chunk_index].handler(
3382
302k
                  png_ptr, info_ptr, length);
3383
302k
            break;
3384
305k
      }
3385
305k
   }
3386
3387
   /* If there was an error or the chunk was simply skipped it is not counted as
3388
    * 'seen'.
3389
    */
3390
443k
   if (errmsg != NULL)
3391
30.3k
   {
3392
30.3k
      if (PNG_CHUNK_CRITICAL(chunk_name)) /* stop immediately */
3393
476
         png_chunk_error(png_ptr, errmsg);
3394
29.8k
      else /* ancillary chunk */
3395
29.8k
      {
3396
         /* The chunk data is skipped: */
3397
29.8k
         png_crc_finish(png_ptr, length);
3398
29.8k
         png_chunk_benign_error(png_ptr, errmsg);
3399
29.8k
      }
3400
30.3k
   }
3401
3402
412k
   else if (handled >= handled_saved)
3403
273k
   {
3404
273k
      if (chunk_index != PNG_INDEX_unknown)
3405
156k
         png_file_add_chunk(png_ptr, chunk_index);
3406
273k
   }
3407
3408
442k
   return handled;
3409
443k
}
3410
3411
/* Combines the row recently read in with the existing pixels in the row.  This
3412
 * routine takes care of alpha and transparency if requested.  This routine also
3413
 * handles the two methods of progressive display of interlaced images,
3414
 * depending on the 'display' value; if 'display' is true then the whole row
3415
 * (dp) is filled from the start by replicating the available pixels.  If
3416
 * 'display' is false only those pixels present in the pass are filled in.
3417
 */
3418
void /* PRIVATE */
3419
png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
3420
943k
{
3421
943k
   unsigned int pixel_depth = png_ptr->transformed_pixel_depth;
3422
943k
   png_const_bytep sp = png_ptr->row_buf + 1;
3423
943k
   png_alloc_size_t row_width = png_ptr->width;
3424
943k
   unsigned int pass = png_ptr->pass;
3425
943k
   png_bytep end_ptr = 0;
3426
943k
   png_byte end_byte = 0;
3427
943k
   unsigned int end_mask;
3428
3429
943k
   png_debug(1, "in png_combine_row");
3430
3431
   /* Added in 1.5.6: it should not be possible to enter this routine until at
3432
    * least one row has been read from the PNG data and transformed.
3433
    */
3434
943k
   if (pixel_depth == 0)
3435
0
      png_error(png_ptr, "internal row logic error");
3436
3437
   /* Added in 1.5.4: the pixel depth should match the information returned by
3438
    * any call to png_read_update_info at this point.  Do not continue if we got
3439
    * this wrong.
3440
    */
3441
943k
   if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes !=
3442
943k
          PNG_ROWBYTES(pixel_depth, row_width))
3443
0
      png_error(png_ptr, "internal row size calculation error");
3444
3445
   /* Don't expect this to ever happen: */
3446
943k
   if (row_width == 0)
3447
0
      png_error(png_ptr, "internal row width error");
3448
3449
   /* Preserve the last byte in cases where only part of it will be overwritten,
3450
    * the multiply below may overflow, we don't care because ANSI-C guarantees
3451
    * we get the low bits.
3452
    */
3453
943k
   end_mask = (pixel_depth * row_width) & 7;
3454
943k
   if (end_mask != 0)
3455
0
   {
3456
      /* end_ptr == NULL is a flag to say do nothing */
3457
0
      end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
3458
0
      end_byte = *end_ptr;
3459
0
#     ifdef PNG_READ_PACKSWAP_SUPPORTED
3460
0
      if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3461
         /* little-endian byte */
3462
0
         end_mask = (unsigned int)(0xff << end_mask);
3463
3464
0
      else /* big-endian byte */
3465
0
#     endif
3466
0
      end_mask = 0xff >> end_mask;
3467
      /* end_mask is now the bits to *keep* from the destination row */
3468
0
   }
3469
3470
   /* For non-interlaced images this reduces to a memcpy(). A memcpy()
3471
    * will also happen if interlacing isn't supported or if the application
3472
    * does not call png_set_interlace_handling().  In the latter cases the
3473
    * caller just gets a sequence of the unexpanded rows from each interlace
3474
    * pass.
3475
    */
3476
943k
#ifdef PNG_READ_INTERLACING_SUPPORTED
3477
943k
   if (png_ptr->interlaced != 0 &&
3478
460k
       (png_ptr->transformations & PNG_INTERLACE) != 0 &&
3479
460k
       pass < 6 && (display == 0 ||
3480
       /* The following copies everything for 'display' on passes 0, 2 and 4. */
3481
0
       (display == 1 && (pass & 1) != 0)))
3482
387k
   {
3483
      /* Narrow images may have no bits in a pass; the caller should handle
3484
       * this, but this test is cheap:
3485
       */
3486
387k
      if (row_width <= PNG_PASS_START_COL(pass))
3487
0
         return;
3488
3489
387k
      if (pixel_depth < 8)
3490
0
      {
3491
         /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit
3492
          * into 32 bits, then a single loop over the bytes using the four byte
3493
          * values in the 32-bit mask can be used.  For the 'display' option the
3494
          * expanded mask may also not require any masking within a byte.  To
3495
          * make this work the PACKSWAP option must be taken into account - it
3496
          * simply requires the pixels to be reversed in each byte.
3497
          *
3498
          * The 'regular' case requires a mask for each of the first 6 passes,
3499
          * the 'display' case does a copy for the even passes in the range
3500
          * 0..6.  This has already been handled in the test above.
3501
          *
3502
          * The masks are arranged as four bytes with the first byte to use in
3503
          * the lowest bits (little-endian) regardless of the order (PACKSWAP or
3504
          * not) of the pixels in each byte.
3505
          *
3506
          * NOTE: the whole of this logic depends on the caller of this function
3507
          * only calling it on rows appropriate to the pass.  This function only
3508
          * understands the 'x' logic; the 'y' logic is handled by the caller.
3509
          *
3510
          * The following defines allow generation of compile time constant bit
3511
          * masks for each pixel depth and each possibility of swapped or not
3512
          * swapped bytes.  Pass 'p' is in the range 0..6; 'x', a pixel index,
3513
          * is in the range 0..7; and the result is 1 if the pixel is to be
3514
          * copied in the pass, 0 if not.  'S' is for the sparkle method, 'B'
3515
          * for the block method.
3516
          *
3517
          * With some compilers a compile time expression of the general form:
3518
          *
3519
          *    (shift >= 32) ? (a >> (shift-32)) : (b >> shift)
3520
          *
3521
          * Produces warnings with values of 'shift' in the range 33 to 63
3522
          * because the right hand side of the ?: expression is evaluated by
3523
          * the compiler even though it isn't used.  Microsoft Visual C (various
3524
          * versions) and the Intel C compiler are known to do this.  To avoid
3525
          * this the following macros are used in 1.5.6.  This is a temporary
3526
          * solution to avoid destabilizing the code during the release process.
3527
          */
3528
0
#        if PNG_USE_COMPILE_TIME_MASKS
3529
0
#           define PNG_LSR(x,s) ((x)>>((s) & 0x1f))
3530
0
#           define PNG_LSL(x,s) ((x)<<((s) & 0x1f))
3531
#        else
3532
#           define PNG_LSR(x,s) ((x)>>(s))
3533
#           define PNG_LSL(x,s) ((x)<<(s))
3534
#        endif
3535
0
#        define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\
3536
0
           PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1)
3537
0
#        define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\
3538
0
           PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1)
3539
3540
         /* Return a mask for pass 'p' pixel 'x' at depth 'd'.  The mask is
3541
          * little endian - the first pixel is at bit 0 - however the extra
3542
          * parameter 's' can be set to cause the mask position to be swapped
3543
          * within each byte, to match the PNG format.  This is done by XOR of
3544
          * the shift with 7, 6 or 4 for bit depths 1, 2 and 4.
3545
          */
3546
0
#        define PIXEL_MASK(p,x,d,s) \
3547
0
            (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0))))
3548
3549
         /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask.
3550
          */
3551
0
#        define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3552
0
#        define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0)
3553
3554
         /* Combine 8 of these to get the full mask.  For the 1-bpp and 2-bpp
3555
          * cases the result needs replicating, for the 4-bpp case the above
3556
          * generates a full 32 bits.
3557
          */
3558
0
#        define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1)))
3559
3560
0
#        define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\
3561
0
            S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\
3562
0
            S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d)
3563
3564
0
#        define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\
3565
0
            B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\
3566
0
            B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d)
3567
3568
0
#if PNG_USE_COMPILE_TIME_MASKS
3569
         /* Utility macros to construct all the masks for a depth/swap
3570
          * combination.  The 's' parameter says whether the format is PNG
3571
          * (big endian bytes) or not.  Only the three odd-numbered passes are
3572
          * required for the display/block algorithm.
3573
          */
3574
0
#        define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\
3575
0
            S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) }
3576
3577
0
#        define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) }
3578
3579
0
#        define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2))
3580
3581
         /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and
3582
          * then pass:
3583
          */
3584
0
         static const png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] =
3585
0
         {
3586
            /* Little-endian byte masks for PACKSWAP */
3587
0
            { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) },
3588
            /* Normal (big-endian byte) masks - PNG format */
3589
0
            { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) }
3590
0
         };
3591
3592
         /* display_mask has only three entries for the odd passes, so index by
3593
          * pass>>1.
3594
          */
3595
0
         static const png_uint_32 display_mask[2][3][3] =
3596
0
         {
3597
            /* Little-endian byte masks for PACKSWAP */
3598
0
            { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) },
3599
            /* Normal (big-endian byte) masks - PNG format */
3600
0
            { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) }
3601
0
         };
3602
3603
0
#        define MASK(pass,depth,display,png)\
3604
0
            ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\
3605
0
               row_mask[png][DEPTH_INDEX(depth)][pass])
3606
3607
#else /* !PNG_USE_COMPILE_TIME_MASKS */
3608
         /* This is the runtime alternative: it seems unlikely that this will
3609
          * ever be either smaller or faster than the compile time approach.
3610
          */
3611
#        define MASK(pass,depth,display,png)\
3612
            ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png))
3613
#endif /* !USE_COMPILE_TIME_MASKS */
3614
3615
         /* Use the appropriate mask to copy the required bits.  In some cases
3616
          * the byte mask will be 0 or 0xff; optimize these cases.  row_width is
3617
          * the number of pixels, but the code copies bytes, so it is necessary
3618
          * to special case the end.
3619
          */
3620
0
         png_uint_32 pixels_per_byte = 8 / pixel_depth;
3621
0
         png_uint_32 mask;
3622
3623
0
#        ifdef PNG_READ_PACKSWAP_SUPPORTED
3624
0
         if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
3625
0
            mask = MASK(pass, pixel_depth, display, 0);
3626
3627
0
         else
3628
0
#        endif
3629
0
         mask = MASK(pass, pixel_depth, display, 1);
3630
3631
0
         for (;;)
3632
0
         {
3633
0
            png_uint_32 m;
3634
3635
            /* It doesn't matter in the following if png_uint_32 has more than
3636
             * 32 bits because the high bits always match those in m<<24; it is,
3637
             * however, essential to use OR here, not +, because of this.
3638
             */
3639
0
            m = mask;
3640
0
            mask = (m >> 8) | (m << 24); /* rotate right to good compilers */
3641
0
            m &= 0xff;
3642
3643
0
            if (m != 0) /* something to copy */
3644
0
            {
3645
0
               if (m != 0xff)
3646
0
                  *dp = (png_byte)((*dp & ~m) | (*sp & m));
3647
0
               else
3648
0
                  *dp = *sp;
3649
0
            }
3650
3651
            /* NOTE: this may overwrite the last byte with garbage if the image
3652
             * is not an exact number of bytes wide; libpng has always done
3653
             * this.
3654
             */
3655
0
            if (row_width <= pixels_per_byte)
3656
0
               break; /* May need to restore part of the last byte */
3657
3658
0
            row_width -= pixels_per_byte;
3659
0
            ++dp;
3660
0
            ++sp;
3661
0
         }
3662
0
      }
3663
3664
387k
      else /* pixel_depth >= 8 */
3665
387k
      {
3666
387k
         unsigned int bytes_to_copy, bytes_to_jump;
3667
3668
         /* Validate the depth - it must be a multiple of 8 */
3669
387k
         if (pixel_depth & 7)
3670
0
            png_error(png_ptr, "invalid user transform pixel depth");
3671
3672
387k
         pixel_depth >>= 3; /* now in bytes */
3673
387k
         row_width *= pixel_depth;
3674
3675
         /* Regardless of pass number the Adam 7 interlace always results in a
3676
          * fixed number of pixels to copy then to skip.  There may be a
3677
          * different number of pixels to skip at the start though.
3678
          */
3679
387k
         {
3680
387k
            unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth;
3681
3682
387k
            row_width -= offset;
3683
387k
            dp += offset;
3684
387k
            sp += offset;
3685
387k
         }
3686
3687
         /* Work out the bytes to copy. */
3688
387k
         if (display != 0)
3689
0
         {
3690
            /* When doing the 'block' algorithm the pixel in the pass gets
3691
             * replicated to adjacent pixels.  This is why the even (0,2,4,6)
3692
             * passes are skipped above - the entire expanded row is copied.
3693
             */
3694
0
            bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth;
3695
3696
            /* But don't allow this number to exceed the actual row width. */
3697
0
            if (bytes_to_copy > row_width)
3698
0
               bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3699
0
         }
3700
3701
387k
         else /* normal row; Adam7 only ever gives us one pixel to copy. */
3702
387k
            bytes_to_copy = pixel_depth;
3703
3704
         /* In Adam7 there is a constant offset between where the pixels go. */
3705
387k
         bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth;
3706
3707
         /* And simply copy these bytes.  Some optimization is possible here,
3708
          * depending on the value of 'bytes_to_copy'.  Special case the low
3709
          * byte counts, which we know to be frequent.
3710
          *
3711
          * Notice that these cases all 'return' rather than 'break' - this
3712
          * avoids an unnecessary test on whether to restore the last byte
3713
          * below.
3714
          */
3715
387k
         switch (bytes_to_copy)
3716
387k
         {
3717
103k
            case 1:
3718
103k
               for (;;)
3719
3.69M
               {
3720
3.69M
                  *dp = *sp;
3721
3722
3.69M
                  if (row_width <= bytes_to_jump)
3723
103k
                     return;
3724
3725
3.58M
                  dp += bytes_to_jump;
3726
3.58M
                  sp += bytes_to_jump;
3727
3.58M
                  row_width -= bytes_to_jump;
3728
3.58M
               }
3729
3730
151k
            case 2:
3731
               /* There is a possibility of a partial copy at the end here; this
3732
                * slows the code down somewhat.
3733
                */
3734
151k
               do
3735
1.80M
               {
3736
1.80M
                  dp[0] = sp[0]; dp[1] = sp[1];
3737
3738
1.80M
                  if (row_width <= bytes_to_jump)
3739
151k
                     return;
3740
3741
1.64M
                  sp += bytes_to_jump;
3742
1.64M
                  dp += bytes_to_jump;
3743
1.64M
                  row_width -= bytes_to_jump;
3744
1.64M
               }
3745
1.64M
               while (row_width > 1);
3746
3747
               /* And there can only be one byte left at this point: */
3748
0
               *dp = *sp;
3749
0
               return;
3750
3751
87.8k
            case 3:
3752
               /* This can only be the RGB case, so each copy is exactly one
3753
                * pixel and it is not necessary to check for a partial copy.
3754
                */
3755
87.8k
               for (;;)
3756
3.14M
               {
3757
3.14M
                  dp[0] = sp[0]; dp[1] = sp[1]; dp[2] = sp[2];
3758
3759
3.14M
                  if (row_width <= bytes_to_jump)
3760
87.8k
                     return;
3761
3762
3.06M
                  sp += bytes_to_jump;
3763
3.06M
                  dp += bytes_to_jump;
3764
3.06M
                  row_width -= bytes_to_jump;
3765
3.06M
               }
3766
3767
44.6k
            default:
3768
44.6k
#if PNG_ALIGN_TYPE != PNG_ALIGN_NONE
3769
               /* Check for double byte alignment and, if possible, use a
3770
                * 16-bit copy.  Don't attempt this for narrow images - ones that
3771
                * are less than an interlace panel wide.  Don't attempt it for
3772
                * wide bytes_to_copy either - use the memcpy there.
3773
                */
3774
44.6k
               if (bytes_to_copy < 16 /*else use memcpy*/ &&
3775
44.6k
                   png_isaligned(dp, png_uint_16) &&
3776
44.6k
                   png_isaligned(sp, png_uint_16) &&
3777
44.6k
                   bytes_to_copy % (sizeof (png_uint_16)) == 0 &&
3778
44.6k
                   bytes_to_jump % (sizeof (png_uint_16)) == 0)
3779
44.6k
               {
3780
                  /* Everything is aligned for png_uint_16 copies, but try for
3781
                   * png_uint_32 first.
3782
                   */
3783
44.6k
                  if (png_isaligned(dp, png_uint_32) &&
3784
40.8k
                      png_isaligned(sp, png_uint_32) &&
3785
40.8k
                      bytes_to_copy % (sizeof (png_uint_32)) == 0 &&
3786
28.3k
                      bytes_to_jump % (sizeof (png_uint_32)) == 0)
3787
28.3k
                  {
3788
28.3k
                     png_uint_32p dp32 = png_aligncast(png_uint_32p,dp);
3789
28.3k
                     png_const_uint_32p sp32 = png_aligncastconst(
3790
28.3k
                         png_const_uint_32p, sp);
3791
28.3k
                     size_t skip = (bytes_to_jump-bytes_to_copy) /
3792
28.3k
                         (sizeof (png_uint_32));
3793
3794
28.3k
                     do
3795
227k
                     {
3796
227k
                        size_t c = bytes_to_copy;
3797
227k
                        do
3798
308k
                        {
3799
308k
                           *dp32++ = *sp32++;
3800
308k
                           c -= (sizeof (png_uint_32));
3801
308k
                        }
3802
308k
                        while (c > 0);
3803
3804
227k
                        if (row_width <= bytes_to_jump)
3805
28.3k
                           return;
3806
3807
199k
                        dp32 += skip;
3808
199k
                        sp32 += skip;
3809
199k
                        row_width -= bytes_to_jump;
3810
199k
                     }
3811
199k
                     while (bytes_to_copy <= row_width);
3812
3813
                     /* Get to here when the row_width truncates the final copy.
3814
                      * There will be 1-3 bytes left to copy, so don't try the
3815
                      * 16-bit loop below.
3816
                      */
3817
0
                     dp = (png_bytep)dp32;
3818
0
                     sp = (png_const_bytep)sp32;
3819
0
                     do
3820
0
                        *dp++ = *sp++;
3821
0
                     while (--row_width > 0);
3822
0
                     return;
3823
28.3k
                  }
3824
3825
                  /* Else do it in 16-bit quantities, but only if the size is
3826
                   * not too large.
3827
                   */
3828
16.3k
                  else
3829
16.3k
                  {
3830
16.3k
                     png_uint_16p dp16 = png_aligncast(png_uint_16p, dp);
3831
16.3k
                     png_const_uint_16p sp16 = png_aligncastconst(
3832
16.3k
                        png_const_uint_16p, sp);
3833
16.3k
                     size_t skip = (bytes_to_jump-bytes_to_copy) /
3834
16.3k
                        (sizeof (png_uint_16));
3835
3836
16.3k
                     do
3837
78.9k
                     {
3838
78.9k
                        size_t c = bytes_to_copy;
3839
78.9k
                        do
3840
236k
                        {
3841
236k
                           *dp16++ = *sp16++;
3842
236k
                           c -= (sizeof (png_uint_16));
3843
236k
                        }
3844
236k
                        while (c > 0);
3845
3846
78.9k
                        if (row_width <= bytes_to_jump)
3847
16.3k
                           return;
3848
3849
62.6k
                        dp16 += skip;
3850
62.6k
                        sp16 += skip;
3851
62.6k
                        row_width -= bytes_to_jump;
3852
62.6k
                     }
3853
62.6k
                     while (bytes_to_copy <= row_width);
3854
3855
                     /* End of row - 1 byte left, bytes_to_copy > row_width: */
3856
0
                     dp = (png_bytep)dp16;
3857
0
                     sp = (png_const_bytep)sp16;
3858
0
                     do
3859
0
                        *dp++ = *sp++;
3860
0
                     while (--row_width > 0);
3861
0
                     return;
3862
16.3k
                  }
3863
44.6k
               }
3864
0
#endif /* ALIGN_TYPE code */
3865
3866
               /* The true default - use a memcpy: */
3867
0
               for (;;)
3868
0
               {
3869
0
                  memcpy(dp, sp, bytes_to_copy);
3870
3871
0
                  if (row_width <= bytes_to_jump)
3872
0
                     return;
3873
3874
0
                  sp += bytes_to_jump;
3875
0
                  dp += bytes_to_jump;
3876
0
                  row_width -= bytes_to_jump;
3877
0
                  if (bytes_to_copy > row_width)
3878
0
                     bytes_to_copy = (unsigned int)/*SAFE*/row_width;
3879
0
               }
3880
387k
         }
3881
3882
         /* NOT REACHED*/
3883
387k
      } /* pixel_depth >= 8 */
3884
3885
      /* Here if pixel_depth < 8 to check 'end_ptr' below. */
3886
387k
   }
3887
555k
   else
3888
555k
#endif /* READ_INTERLACING */
3889
3890
   /* If here then the switch above wasn't used so just memcpy the whole row
3891
    * from the temporary row buffer (notice that this overwrites the end of the
3892
    * destination row if it is a partial byte.)
3893
    */
3894
555k
   memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width));
3895
3896
   /* Restore the overwritten bits from the last byte if necessary. */
3897
555k
   if (end_ptr != NULL)
3898
0
      *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask));
3899
555k
}
3900
3901
#ifdef PNG_READ_INTERLACING_SUPPORTED
3902
void /* PRIVATE */
3903
png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
3904
    png_uint_32 transformations /* Because these may affect the byte layout */)
3905
387k
{
3906
387k
   png_debug(1, "in png_do_read_interlace");
3907
387k
   if (row != NULL && row_info != NULL)
3908
387k
   {
3909
387k
      png_uint_32 final_width;
3910
3911
387k
      final_width = row_info->width * png_pass_inc[pass];
3912
3913
387k
      switch (row_info->pixel_depth)
3914
387k
      {
3915
0
         case 1:
3916
0
         {
3917
0
            png_bytep sp = row + (size_t)((row_info->width - 1) >> 3);
3918
0
            png_bytep dp = row + (size_t)((final_width - 1) >> 3);
3919
0
            unsigned int sshift, dshift;
3920
0
            unsigned int s_start, s_end;
3921
0
            int s_inc;
3922
0
            int jstop = (int)png_pass_inc[pass];
3923
0
            png_byte v;
3924
0
            png_uint_32 i;
3925
0
            int j;
3926
3927
0
#ifdef PNG_READ_PACKSWAP_SUPPORTED
3928
0
            if ((transformations & PNG_PACKSWAP) != 0)
3929
0
            {
3930
0
                sshift = ((row_info->width + 7) & 0x07);
3931
0
                dshift = ((final_width + 7) & 0x07);
3932
0
                s_start = 7;
3933
0
                s_end = 0;
3934
0
                s_inc = -1;
3935
0
            }
3936
3937
0
            else
3938
0
#endif
3939
0
            {
3940
0
                sshift = 7 - ((row_info->width + 7) & 0x07);
3941
0
                dshift = 7 - ((final_width + 7) & 0x07);
3942
0
                s_start = 0;
3943
0
                s_end = 7;
3944
0
                s_inc = 1;
3945
0
            }
3946
3947
0
            for (i = 0; i < row_info->width; i++)
3948
0
            {
3949
0
               v = (png_byte)((*sp >> sshift) & 0x01);
3950
0
               for (j = 0; j < jstop; j++)
3951
0
               {
3952
0
                  unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
3953
0
                  tmp |= (unsigned int)(v << dshift);
3954
0
                  *dp = (png_byte)(tmp & 0xff);
3955
3956
0
                  if (dshift == s_end)
3957
0
                  {
3958
0
                     dshift = s_start;
3959
0
                     dp--;
3960
0
                  }
3961
3962
0
                  else
3963
0
                     dshift = (unsigned int)((int)dshift + s_inc);
3964
0
               }
3965
3966
0
               if (sshift == s_end)
3967
0
               {
3968
0
                  sshift = s_start;
3969
0
                  sp--;
3970
0
               }
3971
3972
0
               else
3973
0
                  sshift = (unsigned int)((int)sshift + s_inc);
3974
0
            }
3975
0
            break;
3976
0
         }
3977
3978
0
         case 2:
3979
0
         {
3980
0
            png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
3981
0
            png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
3982
0
            unsigned int sshift, dshift;
3983
0
            unsigned int s_start, s_end;
3984
0
            int s_inc;
3985
0
            int jstop = (int)png_pass_inc[pass];
3986
0
            png_uint_32 i;
3987
3988
0
#ifdef PNG_READ_PACKSWAP_SUPPORTED
3989
0
            if ((transformations & PNG_PACKSWAP) != 0)
3990
0
            {
3991
0
               sshift = (((row_info->width + 3) & 0x03) << 1);
3992
0
               dshift = (((final_width + 3) & 0x03) << 1);
3993
0
               s_start = 6;
3994
0
               s_end = 0;
3995
0
               s_inc = -2;
3996
0
            }
3997
3998
0
            else
3999
0
#endif
4000
0
            {
4001
0
               sshift = ((3 - ((row_info->width + 3) & 0x03)) << 1);
4002
0
               dshift = ((3 - ((final_width + 3) & 0x03)) << 1);
4003
0
               s_start = 0;
4004
0
               s_end = 6;
4005
0
               s_inc = 2;
4006
0
            }
4007
4008
0
            for (i = 0; i < row_info->width; i++)
4009
0
            {
4010
0
               png_byte v;
4011
0
               int j;
4012
4013
0
               v = (png_byte)((*sp >> sshift) & 0x03);
4014
0
               for (j = 0; j < jstop; j++)
4015
0
               {
4016
0
                  unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
4017
0
                  tmp |= (unsigned int)(v << dshift);
4018
0
                  *dp = (png_byte)(tmp & 0xff);
4019
4020
0
                  if (dshift == s_end)
4021
0
                  {
4022
0
                     dshift = s_start;
4023
0
                     dp--;
4024
0
                  }
4025
4026
0
                  else
4027
0
                     dshift = (unsigned int)((int)dshift + s_inc);
4028
0
               }
4029
4030
0
               if (sshift == s_end)
4031
0
               {
4032
0
                  sshift = s_start;
4033
0
                  sp--;
4034
0
               }
4035
4036
0
               else
4037
0
                  sshift = (unsigned int)((int)sshift + s_inc);
4038
0
            }
4039
0
            break;
4040
0
         }
4041
4042
0
         case 4:
4043
0
         {
4044
0
            png_bytep sp = row + (size_t)((row_info->width - 1) >> 1);
4045
0
            png_bytep dp = row + (size_t)((final_width - 1) >> 1);
4046
0
            unsigned int sshift, dshift;
4047
0
            unsigned int s_start, s_end;
4048
0
            int s_inc;
4049
0
            png_uint_32 i;
4050
0
            int jstop = (int)png_pass_inc[pass];
4051
4052
0
#ifdef PNG_READ_PACKSWAP_SUPPORTED
4053
0
            if ((transformations & PNG_PACKSWAP) != 0)
4054
0
            {
4055
0
               sshift = (((row_info->width + 1) & 0x01) << 2);
4056
0
               dshift = (((final_width + 1) & 0x01) << 2);
4057
0
               s_start = 4;
4058
0
               s_end = 0;
4059
0
               s_inc = -4;
4060
0
            }
4061
4062
0
            else
4063
0
#endif
4064
0
            {
4065
0
               sshift = ((1 - ((row_info->width + 1) & 0x01)) << 2);
4066
0
               dshift = ((1 - ((final_width + 1) & 0x01)) << 2);
4067
0
               s_start = 0;
4068
0
               s_end = 4;
4069
0
               s_inc = 4;
4070
0
            }
4071
4072
0
            for (i = 0; i < row_info->width; i++)
4073
0
            {
4074
0
               png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
4075
0
               int j;
4076
4077
0
               for (j = 0; j < jstop; j++)
4078
0
               {
4079
0
                  unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
4080
0
                  tmp |= (unsigned int)(v << dshift);
4081
0
                  *dp = (png_byte)(tmp & 0xff);
4082
4083
0
                  if (dshift == s_end)
4084
0
                  {
4085
0
                     dshift = s_start;
4086
0
                     dp--;
4087
0
                  }
4088
4089
0
                  else
4090
0
                     dshift = (unsigned int)((int)dshift + s_inc);
4091
0
               }
4092
4093
0
               if (sshift == s_end)
4094
0
               {
4095
0
                  sshift = s_start;
4096
0
                  sp--;
4097
0
               }
4098
4099
0
               else
4100
0
                  sshift = (unsigned int)((int)sshift + s_inc);
4101
0
            }
4102
0
            break;
4103
0
         }
4104
4105
387k
         default:
4106
387k
         {
4107
387k
            size_t pixel_bytes = (row_info->pixel_depth >> 3);
4108
4109
387k
            png_bytep sp = row + (size_t)(row_info->width - 1)
4110
387k
                * pixel_bytes;
4111
4112
387k
            png_bytep dp = row + (size_t)(final_width - 1) * pixel_bytes;
4113
4114
387k
            int jstop = (int)png_pass_inc[pass];
4115
387k
            png_uint_32 i;
4116
4117
9.33M
            for (i = 0; i < row_info->width; i++)
4118
8.94M
            {
4119
8.94M
               png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
4120
8.94M
               int j;
4121
4122
8.94M
               memcpy(v, sp, pixel_bytes);
4123
4124
41.7M
               for (j = 0; j < jstop; j++)
4125
32.7M
               {
4126
32.7M
                  memcpy(dp, v, pixel_bytes);
4127
32.7M
                  dp -= pixel_bytes;
4128
32.7M
               }
4129
4130
8.94M
               sp -= pixel_bytes;
4131
8.94M
            }
4132
387k
            break;
4133
0
         }
4134
387k
      }
4135
4136
387k
      row_info->width = final_width;
4137
387k
      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
4138
387k
   }
4139
#ifndef PNG_READ_PACKSWAP_SUPPORTED
4140
   PNG_UNUSED(transformations)  /* Silence compiler warning */
4141
#endif
4142
387k
}
4143
#endif /* READ_INTERLACING */
4144
4145
static void
4146
png_read_filter_row_sub(png_row_infop row_info, png_bytep row,
4147
    png_const_bytep prev_row)
4148
63.2k
{
4149
63.2k
   size_t i;
4150
63.2k
   size_t istop = row_info->rowbytes;
4151
63.2k
   unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4152
63.2k
   png_bytep rp = row + bpp;
4153
4154
63.2k
   PNG_UNUSED(prev_row)
4155
4156
7.31M
   for (i = bpp; i < istop; i++)
4157
7.25M
   {
4158
7.25M
      *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff);
4159
7.25M
      rp++;
4160
7.25M
   }
4161
63.2k
}
4162
4163
static void
4164
png_read_filter_row_up(png_row_infop row_info, png_bytep row,
4165
    png_const_bytep prev_row)
4166
89.9k
{
4167
89.9k
   size_t i;
4168
89.9k
   size_t istop = row_info->rowbytes;
4169
89.9k
   png_bytep rp = row;
4170
89.9k
   png_const_bytep pp = prev_row;
4171
4172
25.9M
   for (i = 0; i < istop; i++)
4173
25.8M
   {
4174
25.8M
      *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
4175
25.8M
      rp++;
4176
25.8M
   }
4177
89.9k
}
4178
4179
static void
4180
png_read_filter_row_avg(png_row_infop row_info, png_bytep row,
4181
    png_const_bytep prev_row)
4182
101k
{
4183
101k
   size_t i;
4184
101k
   png_bytep rp = row;
4185
101k
   png_const_bytep pp = prev_row;
4186
101k
   unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4187
101k
   size_t istop = row_info->rowbytes - bpp;
4188
4189
235k
   for (i = 0; i < bpp; i++)
4190
133k
   {
4191
133k
      *rp = (png_byte)(((int)(*rp) +
4192
133k
         ((int)(*pp++) / 2 )) & 0xff);
4193
4194
133k
      rp++;
4195
133k
   }
4196
4197
3.68M
   for (i = 0; i < istop; i++)
4198
3.58M
   {
4199
3.58M
      *rp = (png_byte)(((int)(*rp) +
4200
3.58M
         (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff);
4201
4202
3.58M
      rp++;
4203
3.58M
   }
4204
101k
}
4205
4206
static void
4207
png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
4208
    png_const_bytep prev_row)
4209
43.7k
{
4210
43.7k
   png_bytep rp_end = row + row_info->rowbytes;
4211
43.7k
   int a, c;
4212
4213
   /* First pixel/byte */
4214
43.7k
   c = *prev_row++;
4215
43.7k
   a = *row + c;
4216
43.7k
   *row++ = (png_byte)a;
4217
4218
   /* Remainder */
4219
535k
   while (row < rp_end)
4220
492k
   {
4221
492k
      int b, pa, pb, pc, p;
4222
4223
492k
      a &= 0xff; /* From previous iteration or start */
4224
492k
      b = *prev_row++;
4225
4226
492k
      p = b - c;
4227
492k
      pc = a - c;
4228
4229
#ifdef PNG_USE_ABS
4230
      pa = abs(p);
4231
      pb = abs(pc);
4232
      pc = abs(p + pc);
4233
#else
4234
492k
      pa = p < 0 ? -p : p;
4235
492k
      pb = pc < 0 ? -pc : pc;
4236
492k
      pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4237
492k
#endif
4238
4239
      /* Find the best predictor, the least of pa, pb, pc favoring the earlier
4240
       * ones in the case of a tie.
4241
       */
4242
492k
      if (pb < pa)
4243
74.6k
      {
4244
74.6k
         pa = pb; a = b;
4245
74.6k
      }
4246
492k
      if (pc < pa) a = c;
4247
4248
      /* Calculate the current pixel in a, and move the previous row pixel to c
4249
       * for the next time round the loop
4250
       */
4251
492k
      c = b;
4252
492k
      a += *row;
4253
492k
      *row++ = (png_byte)a;
4254
492k
   }
4255
43.7k
}
4256
4257
static void
4258
png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
4259
    png_const_bytep prev_row)
4260
31.0k
{
4261
31.0k
   unsigned int bpp = (row_info->pixel_depth + 7) >> 3;
4262
31.0k
   png_bytep rp_end = row + bpp;
4263
4264
   /* Process the first pixel in the row completely (this is the same as 'up'
4265
    * because there is only one candidate predictor for the first row).
4266
    */
4267
126k
   while (row < rp_end)
4268
95.7k
   {
4269
95.7k
      int a = *row + *prev_row++;
4270
95.7k
      *row++ = (png_byte)a;
4271
95.7k
   }
4272
4273
   /* Remainder */
4274
31.0k
   rp_end = rp_end + (row_info->rowbytes - bpp);
4275
4276
2.45M
   while (row < rp_end)
4277
2.42M
   {
4278
2.42M
      int a, b, c, pa, pb, pc, p;
4279
4280
2.42M
      c = *(prev_row - bpp);
4281
2.42M
      a = *(row - bpp);
4282
2.42M
      b = *prev_row++;
4283
4284
2.42M
      p = b - c;
4285
2.42M
      pc = a - c;
4286
4287
#ifdef PNG_USE_ABS
4288
      pa = abs(p);
4289
      pb = abs(pc);
4290
      pc = abs(p + pc);
4291
#else
4292
2.42M
      pa = p < 0 ? -p : p;
4293
2.42M
      pb = pc < 0 ? -pc : pc;
4294
2.42M
      pc = (p + pc) < 0 ? -(p + pc) : p + pc;
4295
2.42M
#endif
4296
4297
2.42M
      if (pb < pa)
4298
428k
      {
4299
428k
         pa = pb; a = b;
4300
428k
      }
4301
2.42M
      if (pc < pa) a = c;
4302
4303
2.42M
      a += *row;
4304
2.42M
      *row++ = (png_byte)a;
4305
2.42M
   }
4306
31.0k
}
4307
4308
static void
4309
png_init_filter_functions(png_structrp pp)
4310
   /* This function is called once for every PNG image (except for PNG images
4311
    * that only use PNG_FILTER_VALUE_NONE for all rows) to set the
4312
    * implementations required to reverse the filtering of PNG rows.  Reversing
4313
    * the filter is the first transformation performed on the row data.  It is
4314
    * performed in place, therefore an implementation can be selected based on
4315
    * the image pixel format.  If the implementation depends on image width then
4316
    * take care to ensure that it works correctly if the image is interlaced -
4317
    * interlacing causes the actual row width to vary.
4318
    */
4319
8.02k
{
4320
8.02k
   unsigned int bpp = (pp->pixel_depth + 7) >> 3;
4321
4322
8.02k
   pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub;
4323
8.02k
   pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up;
4324
8.02k
   pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg;
4325
8.02k
   if (bpp == 1)
4326
2.74k
      pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4327
2.74k
         png_read_filter_row_paeth_1byte_pixel;
4328
5.28k
   else
4329
5.28k
      pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
4330
5.28k
         png_read_filter_row_paeth_multibyte_pixel;
4331
4332
8.02k
#  ifdef PNG_TARGET_IMPLEMENTS_FILTERS
4333
8.02k
      png_target_init_filter_functions(pp, bpp);
4334
8.02k
#  endif
4335
8.02k
}
4336
4337
void /* PRIVATE */
4338
png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row,
4339
    png_const_bytep prev_row, int filter)
4340
432k
{
4341
432k
   if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST)
4342
432k
   {
4343
432k
      if (pp->read_filter[0] == NULL)
4344
8.02k
         png_init_filter_functions(pp);
4345
4346
432k
      pp->read_filter[filter-1](row_info, row, prev_row);
4347
432k
   }
4348
432k
}
4349
4350
#ifdef PNG_SEQUENTIAL_READ_SUPPORTED
4351
void /* PRIVATE */
4352
png_read_IDAT_data(png_structrp png_ptr, png_bytep output,
4353
    png_alloc_size_t avail_out)
4354
978k
{
4355
   /* Loop reading IDATs and decompressing the result into output[avail_out] */
4356
978k
   png_ptr->zstream.next_out = output;
4357
978k
   png_ptr->zstream.avail_out = 0; /* safety: set below */
4358
4359
978k
   if (output == NULL)
4360
26.0k
      avail_out = 0;
4361
4362
978k
   do
4363
1.10M
   {
4364
1.10M
      int ret;
4365
1.10M
      png_byte tmpbuf[PNG_INFLATE_BUF_SIZE];
4366
4367
1.10M
      if (png_ptr->zstream.avail_in == 0)
4368
129k
      {
4369
129k
         uInt avail_in;
4370
129k
         png_bytep buffer;
4371
129k
#ifdef PNG_READ_APNG_SUPPORTED
4372
129k
         png_uint_32 bytes_to_skip = 0;
4373
4374
215k
         while (png_ptr->idat_size == 0 || bytes_to_skip != 0)
4375
86.7k
         {
4376
86.7k
            png_crc_finish(png_ptr, bytes_to_skip);
4377
86.7k
            bytes_to_skip = 0;
4378
4379
86.7k
            png_ptr->idat_size = png_read_chunk_header(png_ptr);
4380
86.7k
            if (png_ptr->num_frames_read == 0)
4381
80.0k
            {
4382
80.0k
               if (png_ptr->chunk_name != png_IDAT)
4383
318
                  png_error(png_ptr, "Not enough image data");
4384
80.0k
            }
4385
6.71k
            else
4386
6.71k
            {
4387
6.71k
               if (png_ptr->chunk_name == png_IEND)
4388
7
                  png_error(png_ptr, "Not enough image data");
4389
6.70k
               if (png_ptr->chunk_name != png_fdAT)
4390
1.67k
               {
4391
1.67k
                  png_warning(png_ptr,
4392
1.67k
                              "Ignoring unexpected chunk in APNG sequence");
4393
1.67k
                  bytes_to_skip = png_ptr->idat_size;
4394
1.67k
                  continue;
4395
1.67k
               }
4396
4397
5.02k
               png_ensure_sequence_number(png_ptr, png_ptr->idat_size);
4398
4399
5.02k
               png_ptr->idat_size -= 4;
4400
5.02k
            }
4401
86.7k
         }
4402
#else
4403
         while (png_ptr->idat_size == 0)
4404
         {
4405
            png_crc_finish(png_ptr, 0);
4406
4407
            png_ptr->idat_size = png_read_chunk_header(png_ptr);
4408
            /* This is an error even in the 'check' case because the code just
4409
             * consumed a non-IDAT header.
4410
             */
4411
            if (png_ptr->chunk_name != png_IDAT)
4412
               png_error(png_ptr, "Not enough image data");
4413
         }
4414
#endif /* PNG_READ_APNG_SUPPORTED */
4415
129k
         avail_in = png_ptr->IDAT_read_size;
4416
4417
129k
         if (avail_in > png_chunk_max(png_ptr))
4418
0
            avail_in = (uInt)/*SAFE*/png_chunk_max(png_ptr);
4419
4420
129k
         if (avail_in > png_ptr->idat_size)
4421
123k
            avail_in = (uInt)png_ptr->idat_size;
4422
4423
         /* A PNG with a gradually increasing IDAT size will defeat this attempt
4424
          * to minimize memory usage by causing lots of re-allocs, but
4425
          * realistically doing IDAT_read_size re-allocs is not likely to be a
4426
          * big problem.
4427
          *
4428
          * An error here corresponds to the system being out of memory.
4429
          */
4430
129k
         buffer = png_read_buffer(png_ptr, avail_in);
4431
4432
129k
         if (buffer == NULL)
4433
0
            png_chunk_error(png_ptr, "out of memory");
4434
4435
129k
         png_crc_read(png_ptr, buffer, avail_in);
4436
129k
         png_ptr->idat_size -= avail_in;
4437
4438
129k
         png_ptr->zstream.next_in = buffer;
4439
129k
         png_ptr->zstream.avail_in = avail_in;
4440
129k
      }
4441
4442
      /* And set up the output side. */
4443
1.10M
      if (output != NULL) /* standard read */
4444
1.01M
      {
4445
1.01M
         uInt out = ZLIB_IO_MAX;
4446
4447
1.01M
         if (out > avail_out)
4448
1.01M
            out = (uInt)avail_out;
4449
4450
1.01M
         avail_out -= out;
4451
1.01M
         png_ptr->zstream.avail_out = out;
4452
1.01M
      }
4453
4454
94.4k
      else /* after last row, checking for end */
4455
94.4k
      {
4456
94.4k
         png_ptr->zstream.next_out = tmpbuf;
4457
94.4k
         png_ptr->zstream.avail_out = (sizeof tmpbuf);
4458
94.4k
      }
4459
4460
      /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the
4461
       * process.  If the LZ stream is truncated the sequential reader will
4462
       * terminally damage the stream, above, by reading the chunk header of the
4463
       * following chunk (it then exits with png_error).
4464
       *
4465
       * TODO: deal more elegantly with truncated IDAT lists.
4466
       */
4467
1.10M
      ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH);
4468
4469
      /* Take the unconsumed output back. */
4470
1.10M
      if (output != NULL)
4471
1.01M
         avail_out += png_ptr->zstream.avail_out;
4472
4473
94.4k
      else /* avail_out counts the extra bytes */
4474
94.4k
         avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out;
4475
4476
1.10M
      png_ptr->zstream.avail_out = 0;
4477
4478
1.10M
      if (ret == Z_STREAM_END)
4479
12.6k
      {
4480
         /* Do this for safety; we won't read any more into this row. */
4481
12.6k
         png_ptr->zstream.next_out = NULL;
4482
4483
12.6k
         png_ptr->mode |= PNG_AFTER_IDAT;
4484
12.6k
         png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4485
12.6k
#ifdef PNG_READ_APNG_SUPPORTED
4486
12.6k
         png_ptr->num_frames_read++;
4487
12.6k
#endif
4488
4489
12.6k
         if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
4490
117
            png_chunk_benign_error(png_ptr, "Extra compressed data");
4491
12.6k
         break;
4492
12.6k
      }
4493
4494
1.09M
      if (ret != Z_OK)
4495
25.7k
      {
4496
25.7k
         png_zstream_error(png_ptr, ret);
4497
4498
25.7k
         if (output != NULL)
4499
2.58k
            png_chunk_error(png_ptr, png_ptr->zstream.msg);
4500
4501
23.1k
         else /* checking */
4502
23.1k
         {
4503
23.1k
            png_chunk_benign_error(png_ptr, png_ptr->zstream.msg);
4504
23.1k
            return;
4505
23.1k
         }
4506
25.7k
      }
4507
1.09M
   } while (avail_out > 0);
4508
4509
952k
   if (avail_out > 0)
4510
1.46k
   {
4511
      /* The stream ended before the image; this is the same as too few IDATs so
4512
       * should be handled the same way.
4513
       */
4514
1.46k
      if (output != NULL)
4515
27
         png_error(png_ptr, "Not enough image data");
4516
4517
1.43k
      else /* the deflate stream contained extra data */
4518
1.43k
         png_chunk_benign_error(png_ptr, "Too much image data");
4519
1.46k
   }
4520
952k
}
4521
4522
void /* PRIVATE */
4523
png_read_finish_IDAT(png_structrp png_ptr)
4524
71.6k
{
4525
   /* We don't need any more data and the stream should have ended, however the
4526
    * LZ end code may actually not have been processed.  In this case we must
4527
    * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk
4528
    * may still remain to be consumed.
4529
    */
4530
71.6k
   if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4531
26.0k
   {
4532
      /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in
4533
       * the compressed stream, but the stream may be damaged too, so even after
4534
       * this call we may need to terminate the zstream ownership.
4535
       */
4536
26.0k
      png_read_IDAT_data(png_ptr, NULL, 0);
4537
26.0k
      png_ptr->zstream.next_out = NULL; /* safety */
4538
4539
      /* Now clear everything out for safety; the following may not have been
4540
       * done.
4541
       */
4542
26.0k
      if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0)
4543
23.4k
      {
4544
23.4k
         png_ptr->mode |= PNG_AFTER_IDAT;
4545
23.4k
         png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
4546
23.4k
      }
4547
26.0k
   }
4548
4549
   /* If the zstream has not been released do it now *and* terminate the reading
4550
    * of the final IDAT chunk.
4551
    */
4552
71.6k
   if (png_ptr->zowner == png_IDAT)
4553
35.5k
   {
4554
      /* Always do this; the pointers otherwise point into the read buffer. */
4555
35.5k
      png_ptr->zstream.next_in = NULL;
4556
35.5k
      png_ptr->zstream.avail_in = 0;
4557
4558
      /* Now we no longer own the zstream. */
4559
35.5k
      png_ptr->zowner = 0;
4560
4561
      /* The slightly weird semantics of the sequential IDAT reading is that we
4562
       * are always in or at the end of an IDAT chunk, so we always need to do a
4563
       * crc_finish here.  If idat_size is non-zero we also need to read the
4564
       * spurious bytes at the end of the chunk now.
4565
       */
4566
35.5k
      (void)png_crc_finish(png_ptr, png_ptr->idat_size);
4567
35.5k
   }
4568
71.6k
}
4569
4570
void /* PRIVATE */
4571
png_read_finish_row(png_structrp png_ptr)
4572
3.00M
{
4573
3.00M
   png_debug(1, "in png_read_finish_row");
4574
3.00M
   png_ptr->row_number++;
4575
3.00M
   if (png_ptr->row_number < png_ptr->num_rows)
4576
2.83M
      return;
4577
4578
167k
   if (png_ptr->interlaced != 0)
4579
151k
   {
4580
151k
      png_ptr->row_number = 0;
4581
4582
      /* TO DO: don't do this if prev_row isn't needed (requires
4583
       * read-ahead of the next row's filter byte.
4584
       */
4585
151k
      memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4586
4587
151k
      do
4588
151k
      {
4589
151k
         png_ptr->pass++;
4590
4591
151k
         if (png_ptr->pass >= 7)
4592
20.7k
            break;
4593
4594
131k
         png_ptr->iwidth = (png_ptr->width +
4595
131k
            png_pass_inc[png_ptr->pass] - 1 -
4596
131k
            png_pass_start[png_ptr->pass]) /
4597
131k
            png_pass_inc[png_ptr->pass];
4598
4599
131k
         if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4600
0
         {
4601
0
            png_ptr->num_rows = (png_ptr->height +
4602
0
                png_pass_yinc[png_ptr->pass] - 1 -
4603
0
                png_pass_ystart[png_ptr->pass]) /
4604
0
                png_pass_yinc[png_ptr->pass];
4605
0
         }
4606
4607
131k
         else  /* if (png_ptr->transformations & PNG_INTERLACE) */
4608
131k
            break; /* libpng deinterlacing sees every row */
4609
4610
131k
      } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0);
4611
4612
151k
      if (png_ptr->pass < 7)
4613
131k
         return;
4614
151k
   }
4615
4616
   /* Here after at the end of the last row of the last pass. */
4617
36.6k
   png_read_finish_IDAT(png_ptr);
4618
36.6k
}
4619
#endif /* SEQUENTIAL_READ */
4620
4621
void /* PRIVATE */
4622
png_read_start_row(png_structrp png_ptr)
4623
46.5k
{
4624
46.5k
   unsigned int max_pixel_depth;
4625
46.5k
   size_t row_bytes;
4626
4627
46.5k
   png_debug(1, "in png_read_start_row");
4628
4629
46.5k
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
4630
46.5k
   png_init_read_transformations(png_ptr);
4631
46.5k
#endif
4632
46.5k
   if (png_ptr->interlaced != 0)
4633
25.1k
   {
4634
25.1k
      if ((png_ptr->transformations & PNG_INTERLACE) == 0)
4635
0
         png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4636
0
             png_pass_ystart[0]) / png_pass_yinc[0];
4637
4638
25.1k
      else
4639
25.1k
         png_ptr->num_rows = png_ptr->height;
4640
4641
25.1k
      png_ptr->iwidth = (png_ptr->width +
4642
25.1k
          png_pass_inc[png_ptr->pass] - 1 -
4643
25.1k
          png_pass_start[png_ptr->pass]) /
4644
25.1k
          png_pass_inc[png_ptr->pass];
4645
25.1k
   }
4646
4647
21.3k
   else
4648
21.3k
   {
4649
21.3k
      png_ptr->num_rows = png_ptr->height;
4650
21.3k
      png_ptr->iwidth = png_ptr->width;
4651
21.3k
   }
4652
4653
46.5k
   max_pixel_depth = (unsigned int)png_ptr->pixel_depth;
4654
4655
   /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of
4656
    * calculations to calculate the final pixel depth, then
4657
    * png_do_read_transforms actually does the transforms.  This means that the
4658
    * code which effectively calculates this value is actually repeated in three
4659
    * separate places.  They must all match.  Innocent changes to the order of
4660
    * transformations can and will break libpng in a way that causes memory
4661
    * overwrites.
4662
    *
4663
    * TODO: fix this.
4664
    */
4665
46.5k
#ifdef PNG_READ_PACK_SUPPORTED
4666
46.5k
   if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8)
4667
28.2k
      max_pixel_depth = 8;
4668
46.5k
#endif
4669
4670
46.5k
#ifdef PNG_READ_EXPAND_SUPPORTED
4671
46.5k
   if ((png_ptr->transformations & PNG_EXPAND) != 0)
4672
0
   {
4673
0
      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4674
0
      {
4675
0
         if (png_ptr->num_trans != 0)
4676
0
            max_pixel_depth = 32;
4677
4678
0
         else
4679
0
            max_pixel_depth = 24;
4680
0
      }
4681
4682
0
      else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4683
0
      {
4684
0
         if (max_pixel_depth < 8)
4685
0
            max_pixel_depth = 8;
4686
4687
0
         if (png_ptr->num_trans != 0)
4688
0
            max_pixel_depth *= 2;
4689
0
      }
4690
4691
0
      else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
4692
0
      {
4693
0
         if (png_ptr->num_trans != 0)
4694
0
         {
4695
0
            max_pixel_depth *= 4;
4696
0
            max_pixel_depth /= 3;
4697
0
         }
4698
0
      }
4699
0
   }
4700
46.5k
#endif
4701
4702
46.5k
#ifdef PNG_READ_EXPAND_16_SUPPORTED
4703
46.5k
   if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
4704
0
   {
4705
0
#  ifdef PNG_READ_EXPAND_SUPPORTED
4706
      /* In fact it is an error if it isn't supported, but checking is
4707
       * the safe way.
4708
       */
4709
0
      if ((png_ptr->transformations & PNG_EXPAND) != 0)
4710
0
      {
4711
0
         if (png_ptr->bit_depth < 16)
4712
0
            max_pixel_depth *= 2;
4713
0
      }
4714
0
      else
4715
0
#  endif
4716
0
      png_ptr->transformations &= ~PNG_EXPAND_16;
4717
0
   }
4718
46.5k
#endif
4719
4720
46.5k
#ifdef PNG_READ_FILLER_SUPPORTED
4721
46.5k
   if ((png_ptr->transformations & (PNG_FILLER)) != 0)
4722
0
   {
4723
0
      if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
4724
0
      {
4725
0
         if (max_pixel_depth <= 8)
4726
0
            max_pixel_depth = 16;
4727
4728
0
         else
4729
0
            max_pixel_depth = 32;
4730
0
      }
4731
4732
0
      else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB ||
4733
0
         png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
4734
0
      {
4735
0
         if (max_pixel_depth <= 32)
4736
0
            max_pixel_depth = 32;
4737
4738
0
         else
4739
0
            max_pixel_depth = 64;
4740
0
      }
4741
0
   }
4742
46.5k
#endif
4743
4744
46.5k
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
4745
46.5k
   if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0)
4746
0
   {
4747
0
      if (
4748
0
#ifdef PNG_READ_EXPAND_SUPPORTED
4749
0
          (png_ptr->num_trans != 0 &&
4750
0
          (png_ptr->transformations & PNG_EXPAND) != 0) ||
4751
0
#endif
4752
0
#ifdef PNG_READ_FILLER_SUPPORTED
4753
0
          (png_ptr->transformations & (PNG_FILLER)) != 0 ||
4754
0
#endif
4755
0
          png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
4756
0
      {
4757
0
         if (max_pixel_depth <= 16)
4758
0
            max_pixel_depth = 32;
4759
4760
0
         else
4761
0
            max_pixel_depth = 64;
4762
0
      }
4763
4764
0
      else
4765
0
      {
4766
0
         if (max_pixel_depth <= 8)
4767
0
         {
4768
0
            if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4769
0
               max_pixel_depth = 32;
4770
4771
0
            else
4772
0
               max_pixel_depth = 24;
4773
0
         }
4774
4775
0
         else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
4776
0
            max_pixel_depth = 64;
4777
4778
0
         else
4779
0
            max_pixel_depth = 48;
4780
0
      }
4781
0
   }
4782
46.5k
#endif
4783
4784
46.5k
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
4785
46.5k
defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
4786
46.5k
   if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
4787
0
   {
4788
0
      unsigned int user_pixel_depth = png_ptr->user_transform_depth *
4789
0
         png_ptr->user_transform_channels;
4790
4791
0
      if (user_pixel_depth > max_pixel_depth)
4792
0
         max_pixel_depth = user_pixel_depth;
4793
0
   }
4794
46.5k
#endif
4795
4796
   /* This value is stored in png_struct and double checked in the row read
4797
    * code.
4798
    */
4799
46.5k
   png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth;
4800
46.5k
   png_ptr->transformed_pixel_depth = 0; /* calculated on demand */
4801
4802
   /* Align the width on the next larger 8 pixels.  Mainly used
4803
    * for interlacing
4804
    */
4805
46.5k
   row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
4806
   /* Calculate the maximum bytes needed, adding a byte and a pixel
4807
    * for safety's sake
4808
    */
4809
46.5k
   row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) +
4810
46.5k
       1 + ((max_pixel_depth + 7) >> 3U);
4811
4812
#ifdef PNG_MAX_MALLOC_64K
4813
   if (row_bytes > (png_uint_32)65536L)
4814
      png_error(png_ptr, "This image requires a row greater than 64KB");
4815
#endif
4816
4817
46.5k
   if (row_bytes + 48 > png_ptr->old_big_row_buf_size)
4818
46.5k
   {
4819
46.5k
      png_free(png_ptr, png_ptr->big_row_buf);
4820
46.5k
      png_free(png_ptr, png_ptr->big_prev_row);
4821
4822
46.5k
      if (png_ptr->interlaced != 0)
4823
25.1k
         png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr,
4824
25.1k
             row_bytes + 48);
4825
4826
21.3k
      else
4827
21.3k
         png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4828
4829
46.5k
      png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48);
4830
4831
46.5k
#if PNG_TARGET_ROW_ALIGNMENT > 1
4832
      /* Use 16-byte aligned memory for row_buf with at least 16 bytes
4833
       * of padding before and after row_buf; treat prev_row similarly.
4834
       * NOTE: the alignment is to the start of the pixels, one beyond the start
4835
       * of the buffer, because of the filter byte.  Prior to libpng 1.5.6 this
4836
       * was incorrect; the filter byte was aligned, which had the exact
4837
       * opposite effect of that intended.
4838
       */
4839
46.5k
      {
4840
46.5k
         png_bytep temp = png_ptr->big_row_buf + 32;
4841
46.5k
         size_t extra = (size_t)temp & 0x0f;
4842
46.5k
         png_ptr->row_buf = temp - extra - 1/*filter byte*/;
4843
4844
46.5k
         temp = png_ptr->big_prev_row + 32;
4845
46.5k
         extra = (size_t)temp & 0x0f;
4846
46.5k
         png_ptr->prev_row = temp - extra - 1/*filter byte*/;
4847
46.5k
      }
4848
#else
4849
      /* Use 31 bytes of padding before and 17 bytes after row_buf. */
4850
      png_ptr->row_buf = png_ptr->big_row_buf + 31;
4851
      png_ptr->prev_row = png_ptr->big_prev_row + 31;
4852
#endif
4853
46.5k
      png_ptr->old_big_row_buf_size = row_bytes + 48;
4854
46.5k
   }
4855
4856
#ifdef PNG_MAX_MALLOC_64K
4857
   if (png_ptr->rowbytes > 65535)
4858
      png_error(png_ptr, "This image requires a row greater than 64KB");
4859
4860
#endif
4861
46.5k
   if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1))
4862
0
      png_error(png_ptr, "Row has too many bytes to allocate in memory");
4863
4864
46.5k
   memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4865
4866
46.5k
   png_debug1(3, "width = %u,", png_ptr->width);
4867
46.5k
   png_debug1(3, "height = %u,", png_ptr->height);
4868
46.5k
   png_debug1(3, "iwidth = %u,", png_ptr->iwidth);
4869
46.5k
   png_debug1(3, "num_rows = %u,", png_ptr->num_rows);
4870
46.5k
   png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes);
4871
46.5k
   png_debug1(3, "irowbytes = %lu",
4872
46.5k
       (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1);
4873
4874
   /* The sequential reader needs a buffer for IDAT, but the progressive reader
4875
    * does not, so free the read buffer now regardless; the sequential reader
4876
    * reallocates it on demand.
4877
    */
4878
46.5k
   if (png_ptr->read_buffer != NULL)
4879
2.34k
   {
4880
2.34k
      png_bytep buffer = png_ptr->read_buffer;
4881
4882
2.34k
      png_ptr->read_buffer_size = 0;
4883
2.34k
      png_ptr->read_buffer = NULL;
4884
2.34k
      png_free(png_ptr, buffer);
4885
2.34k
   }
4886
4887
   /* Finally claim the zstream for the inflate of the IDAT data, use the bits
4888
    * value from the stream (note that this will result in a fatal error if the
4889
    * IDAT stream has a bogus deflate header window_bits value, but this should
4890
    * not be happening any longer!)
4891
    */
4892
46.5k
   if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK)
4893
0
      png_error(png_ptr, png_ptr->zstream.msg);
4894
4895
46.5k
   png_ptr->flags |= PNG_FLAG_ROW_INIT;
4896
46.5k
}
4897
4898
#ifdef PNG_READ_APNG_SUPPORTED
4899
/* This function should be called after the main IDAT sequence has been read
4900
 * and before a new fdAT is about to be read. It resets some parts of png_ptr
4901
 * to make them usable by the read functions again.
4902
 */
4903
void /* PRIVATE */
4904
png_read_reset(png_structp png_ptr)
4905
0
{
4906
0
   png_ptr->mode &= ~PNG_HAVE_IDAT;
4907
0
   png_ptr->mode &= ~PNG_AFTER_IDAT;
4908
0
   png_ptr->row_number = 0;
4909
0
   png_ptr->pass = 0;
4910
0
}
4911
4912
void /* PRIVATE */
4913
png_read_reinit(png_structp png_ptr, png_infop info_ptr)
4914
0
{
4915
0
   png_ptr->width = info_ptr->next_frame_width;
4916
0
   png_ptr->height = info_ptr->next_frame_height;
4917
0
   png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
4918
0
   if (png_ptr->info_rowbytes != 0)
4919
0
      png_ptr->info_rowbytes = info_ptr->rowbytes =
4920
0
         PNG_ROWBYTES(info_ptr->pixel_depth, png_ptr->width);
4921
0
   if (png_ptr->prev_row)
4922
0
      memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
4923
0
}
4924
4925
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
4926
/* Same as png_read_reset(), but for the progressive reader. */
4927
void /* PRIVATE */
4928
png_progressive_read_reset(png_structp png_ptr)
4929
0
{
4930
0
#ifdef PNG_READ_INTERLACING_SUPPORTED
4931
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
4932
4933
0
   if (png_ptr->interlaced)
4934
0
   {
4935
0
      if (!(png_ptr->transformations & PNG_INTERLACE))
4936
0
         png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
4937
0
                              png_pass_ystart[0]) /
4938
0
                             png_pass_yinc[0];
4939
0
      else
4940
0
         png_ptr->num_rows = png_ptr->height;
4941
4942
0
      png_ptr->iwidth = (png_ptr->width +
4943
0
                         png_pass_inc[png_ptr->pass] - 1 -
4944
0
                         png_pass_start[png_ptr->pass]) /
4945
0
                        png_pass_inc[png_ptr->pass];
4946
0
   }
4947
0
   else
4948
0
#endif /* PNG_READ_INTERLACING_SUPPORTED */
4949
0
   {
4950
0
      png_ptr->num_rows = png_ptr->height;
4951
0
      png_ptr->iwidth = png_ptr->width;
4952
0
   }
4953
0
   png_ptr->flags &= ~PNG_FLAG_ZSTREAM_ENDED;
4954
0
   if (inflateReset(&(png_ptr->zstream)) != Z_OK)
4955
0
      png_error(png_ptr, "inflateReset failed");
4956
0
   png_ptr->zstream.avail_in = 0;
4957
0
   png_ptr->zstream.next_in = 0;
4958
0
   png_ptr->zstream.next_out = png_ptr->row_buf;
4959
0
   png_ptr->zstream.avail_out =
4960
0
      (uInt)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1;
4961
0
}
4962
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
4963
#endif /* PNG_READ_APNG_SUPPORTED */
4964
#endif /* READ */