Coverage Report

Created: 2026-10-28 06:56

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