Coverage Report

Created: 2025-12-31 07:15

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