Coverage Report

Created: 2025-11-16 06:28

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