Coverage Report

Created: 2022-11-20 06:11

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