CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

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