Coverage Report

Created: 2026-04-09 11:41

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