Coverage Report

Created: 2026-05-16 06:16

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