Coverage Report

Created: 2025-12-03 08:24

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