Coverage Report

Created: 2026-08-14 09:29

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