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