Coverage Report

Created: 2018-09-25 14:53

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