Coverage Report

Created: 2025-11-16 06:41

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