Coverage Report

Created: 2026-10-14 08:19

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