• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* pngread.c - read a PNG file
3  *
4  * Copyright (c) 2018-2019 Cosmin Truta
5  * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
6  * Copyright (c) 1996-1997 Andreas Dilger
7  * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
8  *
9  * This code is released under the libpng license.
10  * For conditions of distribution and use, see the disclaimer
11  * and license in png.h
12  *
13  * This file contains routines that an application calls directly to
14  * read a PNG file or stream.
15  */
16 
17 #include "pngpriv.h"
18 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
19 #  include <errno.h>
20 #endif
21 
22 #ifdef PNG_READ_SUPPORTED
23 
24 /* Create a PNG structure for reading, and allocate any memory needed. */
25 PNG_FUNCTION(png_structp,PNGAPI
26 png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
27     png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
28 {
29 #ifndef PNG_USER_MEM_SUPPORTED
30    png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
31         error_fn, warn_fn, NULL, NULL, NULL);
32 #else
33    return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
34         warn_fn, NULL, NULL, NULL);
35 }
36 
37 /* Alternate create PNG structure for reading, and allocate any memory
38  * needed.
39  */
40 PNG_FUNCTION(png_structp,PNGAPI
41 png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
42     png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
43     png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
44 {
45    png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
46        error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
47 #endif /* USER_MEM */
48 
49    if (png_ptr != NULL)
50    {
51       png_ptr->mode = PNG_IS_READ_STRUCT;
52 
53       /* Added in libpng-1.6.0; this can be used to detect a read structure if
54        * required (it will be zero in a write structure.)
55        */
56 #     ifdef PNG_SEQUENTIAL_READ_SUPPORTED
57 #ifdef PNG_MULTY_LINE_ENABLE
58          // OH ISSUE: png optimize
59          png_ptr->IDAT_read_size = PNG_INFLATE_MAX_SIZE;
60 #else
61          png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
62 #endif
63 #     endif
64 
65 #     ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
66          png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
67 
68          /* In stable builds only warn if an application error can be completely
69           * handled.
70           */
71 #        if PNG_RELEASE_BUILD
72             png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
73 #        endif
74 #     endif
75 
76       /* TODO: delay this, it can be done in png_init_io (if the app doesn't
77        * do it itself) avoiding setting the default function if it is not
78        * required.
79        */
80       png_set_read_fn(png_ptr, NULL, NULL);
81    }
82 
83    return png_ptr;
84 }
85 
86 
87 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
88 /* Read the information before the actual image data.  This has been
89  * changed in v0.90 to allow reading a file that already has the magic
90  * bytes read from the stream.  You can tell libpng how many bytes have
91  * been read from the beginning of the stream (up to the maximum of 8)
92  * via png_set_sig_bytes(), and we will only check the remaining bytes
93  * here.  The application can then have access to the signature bytes we
94  * read if it is determined that this isn't a valid PNG file.
95  */
96 void PNGAPI
png_read_info(png_structrp png_ptr,png_inforp info_ptr)97 png_read_info(png_structrp png_ptr, png_inforp info_ptr)
98 {
99 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
100    int keep;
101 #endif
102 
103    png_debug(1, "in png_read_info");
104 
105    if (png_ptr == NULL || info_ptr == NULL)
106       return;
107 
108    /* Read and check the PNG file signature. */
109    png_read_sig(png_ptr, info_ptr);
110 
111    for (;;)
112    {
113       png_uint_32 length = png_read_chunk_header(png_ptr);
114       png_uint_32 chunk_name = png_ptr->chunk_name;
115 
116       /* IDAT logic needs to happen here to simplify getting the two flags
117        * right.
118        */
119       if (chunk_name == png_IDAT)
120       {
121          if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
122             png_chunk_error(png_ptr, "Missing IHDR before IDAT");
123 
124          else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
125              (png_ptr->mode & PNG_HAVE_PLTE) == 0)
126             png_chunk_error(png_ptr, "Missing PLTE before IDAT");
127 
128          else if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
129             png_chunk_benign_error(png_ptr, "Too many IDATs found");
130 
131          png_ptr->mode |= PNG_HAVE_IDAT;
132       }
133 
134       else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
135       {
136          png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
137          png_ptr->mode |= PNG_AFTER_IDAT;
138       }
139 
140       /* This should be a binary subdivision search or a hash for
141        * matching the chunk name rather than a linear search.
142        */
143       if (chunk_name == png_IHDR)
144          png_handle_IHDR(png_ptr, info_ptr, length);
145 
146       else if (chunk_name == png_IEND)
147          png_handle_IEND(png_ptr, info_ptr, length);
148 
149 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
150       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
151       {
152          png_handle_unknown(png_ptr, info_ptr, length, keep);
153 
154          if (chunk_name == png_PLTE)
155             png_ptr->mode |= PNG_HAVE_PLTE;
156 
157          else if (chunk_name == png_IDAT)
158          {
159             png_ptr->idat_size = 0; /* It has been consumed */
160             break;
161          }
162       }
163 #endif
164       else if (chunk_name == png_PLTE)
165          png_handle_PLTE(png_ptr, info_ptr, length);
166 
167       else if (chunk_name == png_IDAT)
168       {
169          png_ptr->idat_size = length;
170          break;
171       }
172 
173 #ifdef PNG_READ_bKGD_SUPPORTED
174       else if (chunk_name == png_bKGD)
175          png_handle_bKGD(png_ptr, info_ptr, length);
176 #endif
177 
178 #ifdef PNG_READ_cHRM_SUPPORTED
179       else if (chunk_name == png_cHRM)
180          png_handle_cHRM(png_ptr, info_ptr, length);
181 #endif
182 
183 #ifdef PNG_READ_eXIf_SUPPORTED
184       else if (chunk_name == png_eXIf)
185          png_handle_eXIf(png_ptr, info_ptr, length);
186 #endif
187 
188 #ifdef PNG_READ_gAMA_SUPPORTED
189       else if (chunk_name == png_gAMA)
190          png_handle_gAMA(png_ptr, info_ptr, length);
191 #endif
192 
193 #ifdef PNG_READ_hIST_SUPPORTED
194       else if (chunk_name == png_hIST)
195          png_handle_hIST(png_ptr, info_ptr, length);
196 #endif
197 
198 #ifdef PNG_READ_oFFs_SUPPORTED
199       else if (chunk_name == png_oFFs)
200          png_handle_oFFs(png_ptr, info_ptr, length);
201 #endif
202 
203 #ifdef PNG_READ_pCAL_SUPPORTED
204       else if (chunk_name == png_pCAL)
205          png_handle_pCAL(png_ptr, info_ptr, length);
206 #endif
207 
208 #ifdef PNG_READ_sCAL_SUPPORTED
209       else if (chunk_name == png_sCAL)
210          png_handle_sCAL(png_ptr, info_ptr, length);
211 #endif
212 
213 #ifdef PNG_READ_pHYs_SUPPORTED
214       else if (chunk_name == png_pHYs)
215          png_handle_pHYs(png_ptr, info_ptr, length);
216 #endif
217 
218 #ifdef PNG_READ_sBIT_SUPPORTED
219       else if (chunk_name == png_sBIT)
220          png_handle_sBIT(png_ptr, info_ptr, length);
221 #endif
222 
223 #ifdef PNG_READ_sRGB_SUPPORTED
224       else if (chunk_name == png_sRGB)
225          png_handle_sRGB(png_ptr, info_ptr, length);
226 #endif
227 
228 #ifdef PNG_READ_iCCP_SUPPORTED
229       else if (chunk_name == png_iCCP)
230          png_handle_iCCP(png_ptr, info_ptr, length);
231 #endif
232 
233 #ifdef PNG_READ_sPLT_SUPPORTED
234       else if (chunk_name == png_sPLT)
235          png_handle_sPLT(png_ptr, info_ptr, length);
236 #endif
237 
238 #ifdef PNG_READ_tEXt_SUPPORTED
239       else if (chunk_name == png_tEXt)
240          png_handle_tEXt(png_ptr, info_ptr, length);
241 #endif
242 
243 #ifdef PNG_READ_tIME_SUPPORTED
244       else if (chunk_name == png_tIME)
245          png_handle_tIME(png_ptr, info_ptr, length);
246 #endif
247 
248 #ifdef PNG_READ_tRNS_SUPPORTED
249       else if (chunk_name == png_tRNS)
250          png_handle_tRNS(png_ptr, info_ptr, length);
251 #endif
252 
253 #ifdef PNG_READ_zTXt_SUPPORTED
254       else if (chunk_name == png_zTXt)
255          png_handle_zTXt(png_ptr, info_ptr, length);
256 #endif
257 
258 #ifdef PNG_READ_iTXt_SUPPORTED
259       else if (chunk_name == png_iTXt)
260          png_handle_iTXt(png_ptr, info_ptr, length);
261 #endif
262 
263       else
264          png_handle_unknown(png_ptr, info_ptr, length,
265              PNG_HANDLE_CHUNK_AS_DEFAULT);
266    }
267 }
268 #endif /* SEQUENTIAL_READ */
269 
270 /* Optional call to update the users info_ptr structure */
271 void PNGAPI
png_read_update_info(png_structrp png_ptr,png_inforp info_ptr)272 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
273 {
274    png_debug(1, "in png_read_update_info");
275 
276    if (png_ptr != NULL)
277    {
278       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
279       {
280          png_read_start_row(png_ptr);
281 
282 #        ifdef PNG_READ_TRANSFORMS_SUPPORTED
283             png_read_transform_info(png_ptr, info_ptr);
284 #        else
285             PNG_UNUSED(info_ptr)
286 #        endif
287       }
288 
289       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
290       else
291          png_app_error(png_ptr,
292              "png_read_update_info/png_start_read_image: duplicate call");
293    }
294 }
295 
296 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
297 /* Initialize palette, background, etc, after transformations
298  * are set, but before any reading takes place.  This allows
299  * the user to obtain a gamma-corrected palette, for example.
300  * If the user doesn't call this, we will do it ourselves.
301  */
302 void PNGAPI
png_start_read_image(png_structrp png_ptr)303 png_start_read_image(png_structrp png_ptr)
304 {
305    png_debug(1, "in png_start_read_image");
306 
307    if (png_ptr != NULL)
308    {
309       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
310          png_read_start_row(png_ptr);
311 
312       /* New in 1.6.0 this avoids the bug of doing the initializations twice */
313       else
314          png_app_error(png_ptr,
315              "png_start_read_image/png_read_update_info: duplicate call");
316    }
317 }
318 #endif /* SEQUENTIAL_READ */
319 
320 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
321 #ifdef PNG_MNG_FEATURES_SUPPORTED
322 /* Undoes intrapixel differencing,
323  * NOTE: this is apparently only supported in the 'sequential' reader.
324  */
325 static void
png_do_read_intrapixel(png_row_infop row_info,png_bytep row)326 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
327 {
328    png_debug(1, "in png_do_read_intrapixel");
329 
330    if (
331        (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
332    {
333       int bytes_per_pixel;
334       png_uint_32 row_width = row_info->width;
335 
336       if (row_info->bit_depth == 8)
337       {
338          png_bytep rp;
339          png_uint_32 i;
340 
341          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
342             bytes_per_pixel = 3;
343 
344          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
345             bytes_per_pixel = 4;
346 
347          else
348             return;
349 
350          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
351          {
352             *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
353             *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
354          }
355       }
356       else if (row_info->bit_depth == 16)
357       {
358          png_bytep rp;
359          png_uint_32 i;
360 
361          if (row_info->color_type == PNG_COLOR_TYPE_RGB)
362             bytes_per_pixel = 6;
363 
364          else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
365             bytes_per_pixel = 8;
366 
367          else
368             return;
369 
370          for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
371          {
372             png_uint_32 s0   = (png_uint_32)(*(rp    ) << 8) | *(rp + 1);
373             png_uint_32 s1   = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
374             png_uint_32 s2   = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
375             png_uint_32 red  = (s0 + s1 + 65536) & 0xffff;
376             png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
377             *(rp    ) = (png_byte)((red >> 8) & 0xff);
378             *(rp + 1) = (png_byte)(red & 0xff);
379             *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
380             *(rp + 5) = (png_byte)(blue & 0xff);
381          }
382       }
383    }
384 }
385 #endif /* MNG_FEATURES */
386 
387 void PNGAPI
png_read_row(png_structrp png_ptr,png_bytep row,png_bytep dsp_row)388 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
389 {
390    png_row_info row_info;
391 
392    if (png_ptr == NULL)
393       return;
394 
395    png_debug2(1, "in png_read_row (row %lu, pass %d)",
396        (unsigned long)png_ptr->row_number, png_ptr->pass);
397 
398    /* png_read_start_row sets the information (in particular iwidth) for this
399     * interlace pass.
400     */
401    if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
402       png_read_start_row(png_ptr);
403 
404    /* 1.5.6: row_info moved out of png_struct to a local here. */
405    row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
406    row_info.color_type = png_ptr->color_type;
407    row_info.bit_depth = png_ptr->bit_depth;
408    row_info.channels = png_ptr->channels;
409    row_info.pixel_depth = png_ptr->pixel_depth;
410    row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
411 
412 #ifdef PNG_WARNINGS_SUPPORTED
413    if (png_ptr->row_number == 0 && png_ptr->pass == 0)
414    {
415    /* Check for transforms that have been set but were defined out */
416 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
417    if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
418       png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
419 #endif
420 
421 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
422    if ((png_ptr->transformations & PNG_FILLER) != 0)
423       png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
424 #endif
425 
426 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
427     !defined(PNG_READ_PACKSWAP_SUPPORTED)
428    if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
429       png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
430 #endif
431 
432 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
433    if ((png_ptr->transformations & PNG_PACK) != 0)
434       png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
435 #endif
436 
437 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
438    if ((png_ptr->transformations & PNG_SHIFT) != 0)
439       png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
440 #endif
441 
442 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
443    if ((png_ptr->transformations & PNG_BGR) != 0)
444       png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
445 #endif
446 
447 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
448    if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
449       png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
450 #endif
451    }
452 #endif /* WARNINGS */
453 
454 #ifdef PNG_READ_INTERLACING_SUPPORTED
455    /* If interlaced and we do not need a new row, combine row and return.
456     * Notice that the pixels we have from previous rows have been transformed
457     * already; we can only combine like with like (transformed or
458     * untransformed) and, because of the libpng API for interlaced images, this
459     * means we must transform before de-interlacing.
460     */
461    if (png_ptr->interlaced != 0 &&
462        (png_ptr->transformations & PNG_INTERLACE) != 0)
463    {
464       switch (png_ptr->pass)
465       {
466          case 0:
467             if (png_ptr->row_number & 0x07)
468             {
469                if (dsp_row != NULL)
470                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
471                png_read_finish_row(png_ptr);
472                return;
473             }
474             break;
475 
476          case 1:
477             if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
478             {
479                if (dsp_row != NULL)
480                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
481 
482                png_read_finish_row(png_ptr);
483                return;
484             }
485             break;
486 
487          case 2:
488             if ((png_ptr->row_number & 0x07) != 4)
489             {
490                if (dsp_row != NULL && (png_ptr->row_number & 4))
491                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
492 
493                png_read_finish_row(png_ptr);
494                return;
495             }
496             break;
497 
498          case 3:
499             if ((png_ptr->row_number & 3) || png_ptr->width < 3)
500             {
501                if (dsp_row != NULL)
502                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
503 
504                png_read_finish_row(png_ptr);
505                return;
506             }
507             break;
508 
509          case 4:
510             if ((png_ptr->row_number & 3) != 2)
511             {
512                if (dsp_row != NULL && (png_ptr->row_number & 2))
513                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
514 
515                png_read_finish_row(png_ptr);
516                return;
517             }
518             break;
519 
520          case 5:
521             if ((png_ptr->row_number & 1) || png_ptr->width < 2)
522             {
523                if (dsp_row != NULL)
524                   png_combine_row(png_ptr, dsp_row, 1/*display*/);
525 
526                png_read_finish_row(png_ptr);
527                return;
528             }
529             break;
530 
531          default:
532          case 6:
533             if ((png_ptr->row_number & 1) == 0)
534             {
535                png_read_finish_row(png_ptr);
536                return;
537             }
538             break;
539       }
540    }
541 #endif
542 
543    if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
544       png_error(png_ptr, "Invalid attempt to read row data");
545 
546    /* Fill the row with IDAT data: */
547    png_ptr->row_buf[0]=255; /* to force error if no data was found */
548    png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
549 
550    if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
551    {
552       if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
553          png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
554              png_ptr->prev_row + 1, png_ptr->row_buf[0]);
555       else
556          png_error(png_ptr, "bad adaptive filter value");
557    }
558 
559    /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
560     * 1.5.6, while the buffer really is this big in current versions of libpng
561     * it may not be in the future, so this was changed just to copy the
562     * interlaced count:
563     */
564    memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
565 
566 #ifdef PNG_MNG_FEATURES_SUPPORTED
567    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
568        (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
569    {
570       /* Intrapixel differencing */
571       png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
572    }
573 #endif
574 
575 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
576    if (png_ptr->transformations)
577       png_do_read_transformations(png_ptr, &row_info);
578 #endif
579 
580    /* The transformed pixel depth should match the depth now in row_info. */
581    if (png_ptr->transformed_pixel_depth == 0)
582    {
583       png_ptr->transformed_pixel_depth = row_info.pixel_depth;
584       if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
585          png_error(png_ptr, "sequential row overflow");
586    }
587 
588    else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
589       png_error(png_ptr, "internal sequential row size calculation error");
590 
591 #ifdef PNG_READ_INTERLACING_SUPPORTED
592    /* Expand interlaced rows to full size */
593    if (png_ptr->interlaced != 0 &&
594       (png_ptr->transformations & PNG_INTERLACE) != 0)
595    {
596       if (png_ptr->pass < 6)
597          png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
598              png_ptr->transformations);
599 
600       if (dsp_row != NULL)
601          png_combine_row(png_ptr, dsp_row, 1/*display*/);
602 
603       if (row != NULL)
604          png_combine_row(png_ptr, row, 0/*row*/);
605    }
606 
607    else
608 #endif
609    {
610       if (row != NULL)
611          png_combine_row(png_ptr, row, -1/*ignored*/);
612 
613       if (dsp_row != NULL)
614          png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
615    }
616    png_read_finish_row(png_ptr);
617 
618    if (png_ptr->read_row_fn != NULL)
619       (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
620 
621 }
622 #endif /* SEQUENTIAL_READ */
623 
624 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
625 /* Read one or more rows of image data.  If the image is interlaced,
626  * and png_set_interlace_handling() has been called, the rows need to
627  * contain the contents of the rows from the previous pass.  If the
628  * image has alpha or transparency, and png_handle_alpha()[*] has been
629  * called, the rows contents must be initialized to the contents of the
630  * screen.
631  *
632  * "row" holds the actual image, and pixels are placed in it
633  * as they arrive.  If the image is displayed after each pass, it will
634  * appear to "sparkle" in.  "display_row" can be used to display a
635  * "chunky" progressive image, with finer detail added as it becomes
636  * available.  If you do not want this "chunky" display, you may pass
637  * NULL for display_row.  If you do not want the sparkle display, and
638  * you have not called png_handle_alpha(), you may pass NULL for rows.
639  * If you have called png_handle_alpha(), and the image has either an
640  * alpha channel or a transparency chunk, you must provide a buffer for
641  * rows.  In this case, you do not have to provide a display_row buffer
642  * also, but you may.  If the image is not interlaced, or if you have
643  * not called png_set_interlace_handling(), the display_row buffer will
644  * be ignored, so pass NULL to it.
645  *
646  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
647  */
648 
649 void PNGAPI
png_read_rows(png_structrp png_ptr,png_bytepp row,png_bytepp display_row,png_uint_32 num_rows)650 png_read_rows(png_structrp png_ptr, png_bytepp row,
651     png_bytepp display_row, png_uint_32 num_rows)
652 {
653    png_uint_32 i;
654    png_bytepp rp;
655    png_bytepp dp;
656 
657    png_debug(1, "in png_read_rows");
658 
659    if (png_ptr == NULL)
660       return;
661 
662    rp = row;
663    dp = display_row;
664    if (rp != NULL && dp != NULL)
665       for (i = 0; i < num_rows; i++)
666       {
667          png_bytep rptr = *rp++;
668          png_bytep dptr = *dp++;
669 
670          png_read_row(png_ptr, rptr, dptr);
671       }
672 
673    else if (rp != NULL)
674       for (i = 0; i < num_rows; i++)
675       {
676          png_bytep rptr = *rp;
677          png_read_row(png_ptr, rptr, NULL);
678          rp++;
679       }
680 
681    else if (dp != NULL)
682       for (i = 0; i < num_rows; i++)
683       {
684          png_bytep dptr = *dp;
685          png_read_row(png_ptr, NULL, dptr);
686          dp++;
687       }
688 }
689 #endif /* SEQUENTIAL_READ */
690 
691 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
692 
693 #ifdef PNG_MULTY_LINE_ENABLE
694 // OH ISSUE: png optimize
png_read_two_rows(png_structrp png_ptr,png_bytepp rows,png_uint_32 i,png_row_info row_info)695 static void png_read_two_rows(png_structrp png_ptr, png_bytepp rows, png_uint_32 i,
696                          png_row_info row_info)
697 {
698    png_debug1(1, "in png_read_two_rows %d", png_ptr->row_buf[0]);
699    png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
700       png_ptr->prev_row + 1, png_ptr->row_buf[0] + 4); // 4 is the increment of x2_filter
701 
702 #ifdef PNG_MNG_FEATURES_SUPPORTED
703    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
704       (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
705    {
706       /* Intrapixel differencing */
707       png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
708    }
709 #endif
710 
711 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
712    if (png_ptr->transformations
713 #       ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
714          || png_ptr->num_palette_max >= 0
715 #       endif
716       )
717       png_do_read_transformations(png_ptr, &row_info);
718 #endif
719 
720    /* The transformed pixel depth should match the depth now in row_info. */
721    if (png_ptr->transformed_pixel_depth == 0)
722    {
723       png_ptr->transformed_pixel_depth = row_info.pixel_depth;
724       if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
725          png_error(png_ptr, "sequential row overflow");
726    }
727 
728    else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
729       png_error(png_ptr, "internal sequential row size calculation error");
730 
731    if (rows[i] != NULL)
732       png_combine_row(png_ptr, rows[i], -1);
733 
734    png_read_finish_row(png_ptr);
735 
736    if (png_ptr->read_row_fn != NULL)
737       (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
738 
739    png_ptr->row_buf = png_ptr->row_buf + row_info.rowbytes + 1;
740 
741    // do again next line
742    memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
743 
744 #ifdef PNG_MNG_FEATURES_SUPPORTED
745    if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
746       (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
747    {
748       /* Intrapixel differencing */
749       png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
750    }
751 #endif
752 
753 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
754    if (png_ptr->transformations
755 #       ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
756          || png_ptr->num_palette_max >= 0
757 #       endif
758       )
759       png_do_read_transformations(png_ptr, &row_info);
760 #endif
761 
762    /* The transformed pixel depth should match the depth now in row_info. */
763    if (png_ptr->transformed_pixel_depth == 0)
764    {
765       png_ptr->transformed_pixel_depth = row_info.pixel_depth;
766       if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
767          png_error(png_ptr, "sequential row overflow");
768    }
769 
770    else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
771       png_error(png_ptr, "internal sequential row size calculation error");
772 
773    if (rows[i+1] != NULL)
774       png_combine_row(png_ptr, rows[i+1], -1);
775 
776    png_read_finish_row(png_ptr);
777 
778    if (png_ptr->read_row_fn != NULL)
779       (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
780 
781    png_ptr->row_buf = png_ptr->row_buf + row_info.rowbytes + 1;
782 }
783 
png_read_muilty_rows(png_structrp png_ptr,png_bytepp rows,png_uint_32 row_num,png_row_info row_info_in)784 static void png_read_muilty_rows(png_structrp png_ptr, png_bytepp rows,
785    png_uint_32 row_num, png_row_info row_info_in)
786 {
787    if (png_ptr == NULL)
788       return;
789 
790    png_debug2(1, "in png_read_muilty_rows (row %lu, pass %d)",
791        (unsigned long)png_ptr->row_number, png_ptr->pass);
792 
793    if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
794          png_error(png_ptr, "Invalid attempt to read row data");
795 
796    /* Fill the row with IDAT data: */
797    uInt row_bytes =  row_info_in.rowbytes;
798    png_ptr->row_buf[0]=255; /* 255 to force error if no data was found */
799    png_read_IDAT_data(png_ptr, png_ptr->row_buf, (row_bytes + 1) * row_num);
800    png_bytep temp_row = png_ptr->row_buf;
801 
802    for (png_uint_32 i = 0; i < row_num; i++) {
803       png_row_info row_info = row_info_in;
804       // check if the x2_filter is effective: only supports channels 3 or 4
805       if ((row_info_in.channels == 3 || row_info_in.channels == 4) &&
806           i < row_num -1 && png_ptr->row_buf[0] > PNG_FILTER_VALUE_SUB &&
807           png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST &&
808           png_ptr->row_buf[0] == png_ptr->row_buf[row_info_in.rowbytes + 1])
809       {
810          png_read_two_rows(png_ptr, rows, i, row_info);
811          i++;
812          continue;
813       }
814       if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
815       {
816          if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
817             png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
818                png_ptr->prev_row + 1, png_ptr->row_buf[0]);
819          else
820             png_debug1(1, "bad adaptive filter value %d", png_ptr->row_buf[0]);
821       }
822 
823       memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info_in.rowbytes + 1);
824 
825 #ifdef PNG_MNG_FEATURES_SUPPORTED
826       if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
827          (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
828       {
829          /* Intrapixel differencing */
830          png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
831       }
832 #endif
833 
834 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
835       if (png_ptr->transformations
836 #        ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
837             || png_ptr->num_palette_max >= 0
838 #        endif
839          )
840          png_do_read_transformations(png_ptr, &row_info);
841 #endif
842 
843       /* The transformed pixel depth should match the depth now in row_info. */
844       if (png_ptr->transformed_pixel_depth == 0)
845       {
846          png_ptr->transformed_pixel_depth = row_info.pixel_depth;
847          if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
848             png_error(png_ptr, "sequential row overflow");
849       }
850 
851       else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
852          png_error(png_ptr, "internal sequential row size calculation error");
853 
854       if (rows[i] != NULL)
855          png_combine_row(png_ptr, rows[i], -1);
856 
857       png_read_finish_row(png_ptr);
858 
859       if (png_ptr->read_row_fn != NULL)
860          (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
861 
862       png_ptr->row_buf = png_ptr->row_buf + row_bytes + 1;
863    }
864    png_ptr->row_buf = temp_row;
865 }
866 
png_warn_check(png_structrp png_ptr)867 static void png_warn_check(png_structrp png_ptr)
868 {
869 #ifdef PNG_WARNINGS_SUPPORTED
870    /* Check for transforms that have been set but were defined out */
871 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
872    if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
873       png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
874 #endif
875 
876 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
877    if ((png_ptr->transformations & PNG_FILLER) != 0)
878       png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
879 #endif
880 
881 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
882     !defined(PNG_READ_PACKSWAP_SUPPORTED)
883    if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
884       png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
885 #endif
886 
887 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
888    if ((png_ptr->transformations & PNG_PACK) != 0)
889       png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
890 #endif
891 
892 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
893    if ((png_ptr->transformations & PNG_SHIFT) != 0)
894       png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
895 #endif
896 
897 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
898    if ((png_ptr->transformations & PNG_BGR) != 0)
899       png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
900 #endif
901 
902 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
903    if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
904       png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
905 #endif
906 #endif /* WARNINGS */
907 }
908 #endif // PNG_MULTY_LINE_ENABLE
909 
910 /* Read the entire image.  If the image has an alpha channel or a tRNS
911  * chunk, and you have called png_handle_alpha()[*], you will need to
912  * initialize the image to the current image that PNG will be overlaying.
913  * We set the num_rows again here, in case it was incorrectly set in
914  * png_read_start_row() by a call to png_read_update_info() or
915  * png_start_read_image() if png_set_interlace_handling() wasn't called
916  * prior to either of these functions like it should have been.  You can
917  * only call this function once.  If you desire to have an image for
918  * each pass of a interlaced image, use png_read_rows() instead.
919  *
920  * [*] png_handle_alpha() does not exist yet, as of this version of libpng
921  */
922 void PNGAPI
png_read_image(png_structrp png_ptr,png_bytepp image)923 png_read_image(png_structrp png_ptr, png_bytepp image)
924 {
925    png_uint_32 i, image_height;
926    int pass, j;
927    png_bytepp rp;
928 
929    png_debug(1, "in png_read_image");
930 
931    if (png_ptr == NULL)
932       return;
933 
934 #ifdef PNG_READ_INTERLACING_SUPPORTED
935    if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
936    {
937       pass = png_set_interlace_handling(png_ptr);
938       /* And make sure transforms are initialized. */
939       png_start_read_image(png_ptr);
940    }
941    else
942    {
943       if (png_ptr->interlaced != 0 &&
944           (png_ptr->transformations & PNG_INTERLACE) == 0)
945       {
946          /* Caller called png_start_read_image or png_read_update_info without
947           * first turning on the PNG_INTERLACE transform.  We can fix this here,
948           * but the caller should do it!
949           */
950          png_warning(png_ptr, "Interlace handling should be turned on when "
951              "using png_read_image");
952          /* Make sure this is set correctly */
953          png_ptr->num_rows = png_ptr->height;
954       }
955 
956       /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
957        * the above error case.
958        */
959       pass = png_set_interlace_handling(png_ptr);
960    }
961 #else
962    if (png_ptr->interlaced)
963       png_error(png_ptr,
964           "Cannot read interlaced image -- interlace handler disabled");
965 
966    pass = 1;
967 #endif
968 
969    image_height=png_ptr->height;
970 
971 #ifdef PNG_MULTY_LINE_ENABLE
972    // OH ISSUE: png optimize
973    if (png_ptr->interlaced == 0 && png_ptr->bit_depth == 8 && // 8 is 1 pixel 8 bytes
974        (png_ptr->transformations & PNG_CHECK) == 0) {
975       if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
976          png_read_start_row(png_ptr);
977 
978       png_warn_check(png_ptr);
979       png_row_info row_info;
980       row_info.width = png_ptr->iwidth;
981       row_info.color_type = png_ptr->color_type;
982       row_info.bit_depth = png_ptr->bit_depth;
983       row_info.channels = png_ptr->channels;
984       row_info.pixel_depth = png_ptr->pixel_depth;
985       row_info.rowbytes = png_ptr->rowbytes;
986 
987       rp = image;
988       int row_num = PNG_INFLATE_ROWS;
989       for (i = 0; i < image_height; i += PNG_INFLATE_ROWS)
990       {
991          if (image_height - i < PNG_INFLATE_ROWS)
992          {
993             row_num = image_height - i;
994          }
995          png_read_muilty_rows(png_ptr, rp, row_num, row_info);
996          rp += row_num;
997       }
998    }
999    else
1000 #endif
1001    {
1002       for (j = 0; j < pass; j++)
1003       {
1004          rp = image;
1005          for (i = 0; i < image_height; i++)
1006          {
1007             png_read_row(png_ptr, *rp, NULL);
1008             rp++;
1009          }
1010       }
1011    }
1012 }
1013 #endif /* SEQUENTIAL_READ */
1014 
1015 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1016 /* Read the end of the PNG file.  Will not read past the end of the
1017  * file, will verify the end is accurate, and will read any comments
1018  * or time information at the end of the file, if info is not NULL.
1019  */
1020 void PNGAPI
png_read_end(png_structrp png_ptr,png_inforp info_ptr)1021 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
1022 {
1023 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1024    int keep;
1025 #endif
1026 
1027    png_debug(1, "in png_read_end");
1028 
1029    if (png_ptr == NULL)
1030       return;
1031 
1032    /* If png_read_end is called in the middle of reading the rows there may
1033     * still be pending IDAT data and an owned zstream.  Deal with this here.
1034     */
1035 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1036    if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
1037 #endif
1038       png_read_finish_IDAT(png_ptr);
1039 
1040 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
1041    /* Report invalid palette index; added at libng-1.5.10 */
1042    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
1043        png_ptr->num_palette_max > png_ptr->num_palette)
1044       png_benign_error(png_ptr, "Read palette index exceeding num_palette");
1045 #endif
1046 
1047    do
1048    {
1049       png_uint_32 length = png_read_chunk_header(png_ptr);
1050       png_uint_32 chunk_name = png_ptr->chunk_name;
1051 
1052       if (chunk_name != png_IDAT)
1053          png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
1054 
1055       if (chunk_name == png_IEND)
1056          png_handle_IEND(png_ptr, info_ptr, length);
1057 
1058       else if (chunk_name == png_IHDR)
1059          png_handle_IHDR(png_ptr, info_ptr, length);
1060 
1061       else if (info_ptr == NULL)
1062          png_crc_finish(png_ptr, length);
1063 
1064 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1065       else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
1066       {
1067          if (chunk_name == png_IDAT)
1068          {
1069             if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
1070                 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
1071                png_benign_error(png_ptr, ".Too many IDATs found");
1072          }
1073          png_handle_unknown(png_ptr, info_ptr, length, keep);
1074          if (chunk_name == png_PLTE)
1075             png_ptr->mode |= PNG_HAVE_PLTE;
1076       }
1077 #endif
1078 
1079       else if (chunk_name == png_IDAT)
1080       {
1081          /* Zero length IDATs are legal after the last IDAT has been
1082           * read, but not after other chunks have been read.  1.6 does not
1083           * always read all the deflate data; specifically it cannot be relied
1084           * upon to read the Adler32 at the end.  If it doesn't ignore IDAT
1085           * chunks which are longer than zero as well:
1086           */
1087          if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
1088              || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
1089             png_benign_error(png_ptr, "..Too many IDATs found");
1090 
1091          png_crc_finish(png_ptr, length);
1092       }
1093       else if (chunk_name == png_PLTE)
1094          png_handle_PLTE(png_ptr, info_ptr, length);
1095 
1096 #ifdef PNG_READ_bKGD_SUPPORTED
1097       else if (chunk_name == png_bKGD)
1098          png_handle_bKGD(png_ptr, info_ptr, length);
1099 #endif
1100 
1101 #ifdef PNG_READ_cHRM_SUPPORTED
1102       else if (chunk_name == png_cHRM)
1103          png_handle_cHRM(png_ptr, info_ptr, length);
1104 #endif
1105 
1106 #ifdef PNG_READ_eXIf_SUPPORTED
1107       else if (chunk_name == png_eXIf)
1108          png_handle_eXIf(png_ptr, info_ptr, length);
1109 #endif
1110 
1111 #ifdef PNG_READ_gAMA_SUPPORTED
1112       else if (chunk_name == png_gAMA)
1113          png_handle_gAMA(png_ptr, info_ptr, length);
1114 #endif
1115 
1116 #ifdef PNG_READ_hIST_SUPPORTED
1117       else if (chunk_name == png_hIST)
1118          png_handle_hIST(png_ptr, info_ptr, length);
1119 #endif
1120 
1121 #ifdef PNG_READ_oFFs_SUPPORTED
1122       else if (chunk_name == png_oFFs)
1123          png_handle_oFFs(png_ptr, info_ptr, length);
1124 #endif
1125 
1126 #ifdef PNG_READ_pCAL_SUPPORTED
1127       else if (chunk_name == png_pCAL)
1128          png_handle_pCAL(png_ptr, info_ptr, length);
1129 #endif
1130 
1131 #ifdef PNG_READ_sCAL_SUPPORTED
1132       else if (chunk_name == png_sCAL)
1133          png_handle_sCAL(png_ptr, info_ptr, length);
1134 #endif
1135 
1136 #ifdef PNG_READ_pHYs_SUPPORTED
1137       else if (chunk_name == png_pHYs)
1138          png_handle_pHYs(png_ptr, info_ptr, length);
1139 #endif
1140 
1141 #ifdef PNG_READ_sBIT_SUPPORTED
1142       else if (chunk_name == png_sBIT)
1143          png_handle_sBIT(png_ptr, info_ptr, length);
1144 #endif
1145 
1146 #ifdef PNG_READ_sRGB_SUPPORTED
1147       else if (chunk_name == png_sRGB)
1148          png_handle_sRGB(png_ptr, info_ptr, length);
1149 #endif
1150 
1151 #ifdef PNG_READ_iCCP_SUPPORTED
1152       else if (chunk_name == png_iCCP)
1153          png_handle_iCCP(png_ptr, info_ptr, length);
1154 #endif
1155 
1156 #ifdef PNG_READ_sPLT_SUPPORTED
1157       else if (chunk_name == png_sPLT)
1158          png_handle_sPLT(png_ptr, info_ptr, length);
1159 #endif
1160 
1161 #ifdef PNG_READ_tEXt_SUPPORTED
1162       else if (chunk_name == png_tEXt)
1163          png_handle_tEXt(png_ptr, info_ptr, length);
1164 #endif
1165 
1166 #ifdef PNG_READ_tIME_SUPPORTED
1167       else if (chunk_name == png_tIME)
1168          png_handle_tIME(png_ptr, info_ptr, length);
1169 #endif
1170 
1171 #ifdef PNG_READ_tRNS_SUPPORTED
1172       else if (chunk_name == png_tRNS)
1173          png_handle_tRNS(png_ptr, info_ptr, length);
1174 #endif
1175 
1176 #ifdef PNG_READ_zTXt_SUPPORTED
1177       else if (chunk_name == png_zTXt)
1178          png_handle_zTXt(png_ptr, info_ptr, length);
1179 #endif
1180 
1181 #ifdef PNG_READ_iTXt_SUPPORTED
1182       else if (chunk_name == png_iTXt)
1183          png_handle_iTXt(png_ptr, info_ptr, length);
1184 #endif
1185 
1186       else
1187          png_handle_unknown(png_ptr, info_ptr, length,
1188              PNG_HANDLE_CHUNK_AS_DEFAULT);
1189    } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
1190 }
1191 #endif /* SEQUENTIAL_READ */
1192 
1193 /* Free all memory used in the read struct */
1194 static void
png_read_destroy(png_structrp png_ptr)1195 png_read_destroy(png_structrp png_ptr)
1196 {
1197    png_debug(1, "in png_read_destroy");
1198 
1199 #ifdef PNG_READ_GAMMA_SUPPORTED
1200    png_destroy_gamma_table(png_ptr);
1201 #endif
1202 
1203    png_free(png_ptr, png_ptr->big_row_buf);
1204    png_ptr->big_row_buf = NULL;
1205    png_free(png_ptr, png_ptr->big_prev_row);
1206    png_ptr->big_prev_row = NULL;
1207    png_free(png_ptr, png_ptr->read_buffer);
1208    png_ptr->read_buffer = NULL;
1209 
1210 #ifdef PNG_READ_QUANTIZE_SUPPORTED
1211    png_free(png_ptr, png_ptr->palette_lookup);
1212    png_ptr->palette_lookup = NULL;
1213    png_free(png_ptr, png_ptr->quantize_index);
1214    png_ptr->quantize_index = NULL;
1215 #endif
1216 
1217    if ((png_ptr->free_me & PNG_FREE_PLTE) != 0)
1218    {
1219       png_zfree(png_ptr, png_ptr->palette);
1220       png_ptr->palette = NULL;
1221    }
1222    png_ptr->free_me &= ~PNG_FREE_PLTE;
1223 
1224 #if defined(PNG_tRNS_SUPPORTED) || \
1225     defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
1226    if ((png_ptr->free_me & PNG_FREE_TRNS) != 0)
1227    {
1228       png_free(png_ptr, png_ptr->trans_alpha);
1229       png_ptr->trans_alpha = NULL;
1230    }
1231    png_ptr->free_me &= ~PNG_FREE_TRNS;
1232 #endif
1233 
1234    inflateEnd(&png_ptr->zstream);
1235 
1236 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
1237    png_free(png_ptr, png_ptr->save_buffer);
1238    png_ptr->save_buffer = NULL;
1239 #endif
1240 
1241 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
1242    defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
1243    png_free(png_ptr, png_ptr->unknown_chunk.data);
1244    png_ptr->unknown_chunk.data = NULL;
1245 #endif
1246 
1247 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
1248    png_free(png_ptr, png_ptr->chunk_list);
1249    png_ptr->chunk_list = NULL;
1250 #endif
1251 
1252 #if defined(PNG_READ_EXPAND_SUPPORTED) && \
1253     defined(PNG_ARM_NEON_IMPLEMENTATION)
1254    png_free(png_ptr, png_ptr->riffled_palette);
1255    png_ptr->riffled_palette = NULL;
1256 #endif
1257 
1258    /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
1259     * callbacks are still set at this point.  They are required to complete the
1260     * destruction of the png_struct itself.
1261     */
1262 }
1263 
1264 /* Free all memory used by the read */
1265 void PNGAPI
png_destroy_read_struct(png_structpp png_ptr_ptr,png_infopp info_ptr_ptr,png_infopp end_info_ptr_ptr)1266 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
1267     png_infopp end_info_ptr_ptr)
1268 {
1269    png_structrp png_ptr = NULL;
1270 
1271    png_debug(1, "in png_destroy_read_struct");
1272 
1273    if (png_ptr_ptr != NULL)
1274       png_ptr = *png_ptr_ptr;
1275 
1276    if (png_ptr == NULL)
1277       return;
1278 
1279    /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
1280     * behavior.  Prior to 1.6.0 libpng did extra 'info' destruction in this API.
1281     * The extra was, apparently, unnecessary yet this hides memory leak bugs.
1282     */
1283    png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
1284    png_destroy_info_struct(png_ptr, info_ptr_ptr);
1285 
1286    *png_ptr_ptr = NULL;
1287    png_read_destroy(png_ptr);
1288    png_destroy_png_struct(png_ptr);
1289 }
1290 
1291 void PNGAPI
png_set_read_status_fn(png_structrp png_ptr,png_read_status_ptr read_row_fn)1292 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
1293 {
1294    if (png_ptr == NULL)
1295       return;
1296 
1297    png_ptr->read_row_fn = read_row_fn;
1298 }
1299 
1300 
1301 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1302 #ifdef PNG_INFO_IMAGE_SUPPORTED
1303 void PNGAPI
png_read_png(png_structrp png_ptr,png_inforp info_ptr,int transforms,voidp params)1304 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1305     int transforms, voidp params)
1306 {
1307    if (png_ptr == NULL || info_ptr == NULL)
1308       return;
1309 
1310    /* png_read_info() gives us all of the information from the
1311     * PNG file before the first IDAT (image data chunk).
1312     */
1313    png_read_info(png_ptr, info_ptr);
1314    if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1315       png_error(png_ptr, "Image is too high to process with png_read_png()");
1316 
1317    /* -------------- image transformations start here ------------------- */
1318    /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
1319     * is not implemented.  This will only happen in de-configured (non-default)
1320     * libpng builds.  The results can be unexpected - png_read_png may return
1321     * short or mal-formed rows because the transform is skipped.
1322     */
1323 
1324    /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1325     */
1326    if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
1327       /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1328        * did in earlier versions, while "scale_16" is now more accurate.
1329        */
1330 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1331       png_set_scale_16(png_ptr);
1332 #else
1333       png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
1334 #endif
1335 
1336    /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1337     * latter by doing SCALE first.  This is ok and allows apps not to check for
1338     * which is supported to get the right answer.
1339     */
1340    if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
1341 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1342       png_set_strip_16(png_ptr);
1343 #else
1344       png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
1345 #endif
1346 
1347    /* Strip alpha bytes from the input data without combining with
1348     * the background (not recommended).
1349     */
1350    if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1351 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1352       png_set_strip_alpha(png_ptr);
1353 #else
1354       png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1355 #endif
1356 
1357    /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1358     * byte into separate bytes (useful for paletted and grayscale images).
1359     */
1360    if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1361 #ifdef PNG_READ_PACK_SUPPORTED
1362       png_set_packing(png_ptr);
1363 #else
1364       png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1365 #endif
1366 
1367    /* Change the order of packed pixels to least significant bit first
1368     * (not useful if you are using png_set_packing).
1369     */
1370    if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1371 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1372       png_set_packswap(png_ptr);
1373 #else
1374       png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1375 #endif
1376 
1377    /* Expand paletted colors into true RGB triplets
1378     * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1379     * Expand paletted or RGB images with transparency to full alpha
1380     * channels so the data will be available as RGBA quartets.
1381     */
1382    if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1383 #ifdef PNG_READ_EXPAND_SUPPORTED
1384       png_set_expand(png_ptr);
1385 #else
1386       png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1387 #endif
1388 
1389    /* We don't handle background color or gamma transformation or quantizing.
1390     */
1391 
1392    /* Invert monochrome files to have 0 as white and 1 as black
1393     */
1394    if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1395 #ifdef PNG_READ_INVERT_SUPPORTED
1396       png_set_invert_mono(png_ptr);
1397 #else
1398       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1399 #endif
1400 
1401    /* If you want to shift the pixel values from the range [0,255] or
1402     * [0,65535] to the original [0,7] or [0,31], or whatever range the
1403     * colors were originally in:
1404     */
1405    if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1406 #ifdef PNG_READ_SHIFT_SUPPORTED
1407       if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1408          png_set_shift(png_ptr, &info_ptr->sig_bit);
1409 #else
1410       png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1411 #endif
1412 
1413    /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1414    if ((transforms & PNG_TRANSFORM_BGR) != 0)
1415 #ifdef PNG_READ_BGR_SUPPORTED
1416       png_set_bgr(png_ptr);
1417 #else
1418       png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1419 #endif
1420 
1421    /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1422    if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1423 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1424       png_set_swap_alpha(png_ptr);
1425 #else
1426       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1427 #endif
1428 
1429    /* Swap bytes of 16-bit files to least significant byte first */
1430    if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1431 #ifdef PNG_READ_SWAP_SUPPORTED
1432       png_set_swap(png_ptr);
1433 #else
1434       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1435 #endif
1436 
1437 /* Added at libpng-1.2.41 */
1438    /* Invert the alpha channel from opacity to transparency */
1439    if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1440 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1441       png_set_invert_alpha(png_ptr);
1442 #else
1443       png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1444 #endif
1445 
1446 /* Added at libpng-1.2.41 */
1447    /* Expand grayscale image to RGB */
1448    if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1449 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1450       png_set_gray_to_rgb(png_ptr);
1451 #else
1452       png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1453 #endif
1454 
1455 /* Added at libpng-1.5.4 */
1456    if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1457 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1458       png_set_expand_16(png_ptr);
1459 #else
1460       png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1461 #endif
1462 
1463    /* We don't handle adding filler bytes */
1464 
1465    /* We use png_read_image and rely on that for interlace handling, but we also
1466     * call png_read_update_info therefore must turn on interlace handling now:
1467     */
1468    (void)png_set_interlace_handling(png_ptr);
1469 
1470    /* Optional call to gamma correct and add the background to the palette
1471     * and update info structure.  REQUIRED if you are expecting libpng to
1472     * update the palette for you (i.e., you selected such a transform above).
1473     */
1474    png_read_update_info(png_ptr, info_ptr);
1475 
1476    /* -------------- image transformations end here ------------------- */
1477 
1478    png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1479    if (info_ptr->row_pointers == NULL)
1480    {
1481       png_uint_32 iptr;
1482 
1483       info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1484           info_ptr->height * (sizeof (png_bytep))));
1485 
1486       for (iptr=0; iptr<info_ptr->height; iptr++)
1487          info_ptr->row_pointers[iptr] = NULL;
1488 
1489       info_ptr->free_me |= PNG_FREE_ROWS;
1490 
1491       for (iptr = 0; iptr < info_ptr->height; iptr++)
1492          info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1493              png_malloc(png_ptr, info_ptr->rowbytes));
1494    }
1495 
1496    png_read_image(png_ptr, info_ptr->row_pointers);
1497    info_ptr->valid |= PNG_INFO_IDAT;
1498 
1499    /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1500    png_read_end(png_ptr, info_ptr);
1501 
1502    PNG_UNUSED(params)
1503 }
1504 #endif /* INFO_IMAGE */
1505 #endif /* SEQUENTIAL_READ */
1506 
1507 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1508 /* SIMPLIFIED READ
1509  *
1510  * This code currently relies on the sequential reader, though it could easily
1511  * be made to work with the progressive one.
1512  */
1513 /* Arguments to png_image_finish_read: */
1514 
1515 /* Encoding of PNG data (used by the color-map code) */
1516 #  define P_NOTSET  0 /* File encoding not yet known */
1517 #  define P_sRGB    1 /* 8-bit encoded to sRGB gamma */
1518 #  define P_LINEAR  2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1519 #  define P_FILE    3 /* 8-bit encoded to file gamma, not sRGB or linear */
1520 #  define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1521 
1522 /* Color-map processing: after libpng has run on the PNG image further
1523  * processing may be needed to convert the data to color-map indices.
1524  */
1525 #define PNG_CMAP_NONE      0
1526 #define PNG_CMAP_GA        1 /* Process GA data to a color-map with alpha */
1527 #define PNG_CMAP_TRANS     2 /* Process GA data to a background index */
1528 #define PNG_CMAP_RGB       3 /* Process RGB data */
1529 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1530 
1531 /* The following document where the background is for each processing case. */
1532 #define PNG_CMAP_NONE_BACKGROUND      256
1533 #define PNG_CMAP_GA_BACKGROUND        231
1534 #define PNG_CMAP_TRANS_BACKGROUND     254
1535 #define PNG_CMAP_RGB_BACKGROUND       256
1536 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1537 
1538 typedef struct
1539 {
1540    /* Arguments: */
1541    png_imagep image;
1542    png_voidp  buffer;
1543    png_int_32 row_stride;
1544    png_voidp  colormap;
1545    png_const_colorp background;
1546    /* Local variables: */
1547    png_voidp       local_row;
1548    png_voidp       first_row;
1549    ptrdiff_t       row_bytes;           /* step between rows */
1550    int             file_encoding;       /* E_ values above */
1551    png_fixed_point gamma_to_linear;     /* For P_FILE, reciprocal of gamma */
1552    int             colormap_processing; /* PNG_CMAP_ values above */
1553 } png_image_read_control;
1554 
1555 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1556  * called, so setting up the jmp_buf is not required.  This means that anything
1557  * called from here must *not* call png_malloc - it has to call png_malloc_warn
1558  * instead so that control is returned safely back to this routine.
1559  */
1560 static int
png_image_read_init(png_imagep image)1561 png_image_read_init(png_imagep image)
1562 {
1563    if (image->opaque == NULL)
1564    {
1565       png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1566           png_safe_error, png_safe_warning);
1567 
1568       /* And set the rest of the structure to NULL to ensure that the various
1569        * fields are consistent.
1570        */
1571       memset(image, 0, (sizeof *image));
1572       image->version = PNG_IMAGE_VERSION;
1573 
1574       if (png_ptr != NULL)
1575       {
1576          png_infop info_ptr = png_create_info_struct(png_ptr);
1577 
1578          if (info_ptr != NULL)
1579          {
1580             png_controlp control = png_voidcast(png_controlp,
1581                 png_malloc_warn(png_ptr, (sizeof *control)));
1582 
1583             if (control != NULL)
1584             {
1585                memset(control, 0, (sizeof *control));
1586 
1587                control->png_ptr = png_ptr;
1588                control->info_ptr = info_ptr;
1589                control->for_write = 0;
1590 
1591                image->opaque = control;
1592                return 1;
1593             }
1594 
1595             /* Error clean up */
1596             png_destroy_info_struct(png_ptr, &info_ptr);
1597          }
1598 
1599          png_destroy_read_struct(&png_ptr, NULL, NULL);
1600       }
1601 
1602       return png_image_error(image, "png_image_read: out of memory");
1603    }
1604 
1605    return png_image_error(image, "png_image_read: opaque pointer not NULL");
1606 }
1607 
1608 /* Utility to find the base format of a PNG file from a png_struct. */
1609 static png_uint_32
png_image_format(png_structrp png_ptr)1610 png_image_format(png_structrp png_ptr)
1611 {
1612    png_uint_32 format = 0;
1613 
1614    if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1615       format |= PNG_FORMAT_FLAG_COLOR;
1616 
1617    if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1618       format |= PNG_FORMAT_FLAG_ALPHA;
1619 
1620    /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1621     * sets the png_struct fields; that's all we are interested in here.  The
1622     * precise interaction with an app call to png_set_tRNS and PNG file reading
1623     * is unclear.
1624     */
1625    else if (png_ptr->num_trans > 0)
1626       format |= PNG_FORMAT_FLAG_ALPHA;
1627 
1628    if (png_ptr->bit_depth == 16)
1629       format |= PNG_FORMAT_FLAG_LINEAR;
1630 
1631    if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1632       format |= PNG_FORMAT_FLAG_COLORMAP;
1633 
1634    return format;
1635 }
1636 
1637 /* Is the given gamma significantly different from sRGB?  The test is the same
1638  * one used in pngrtran.c when deciding whether to do gamma correction.  The
1639  * arithmetic optimizes the division by using the fact that the inverse of the
1640  * file sRGB gamma is 2.2
1641  */
1642 static int
png_gamma_not_sRGB(png_fixed_point g)1643 png_gamma_not_sRGB(png_fixed_point g)
1644 {
1645    if (g < PNG_FP_1)
1646    {
1647       /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1648       if (g == 0)
1649          return 0;
1650 
1651       return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1652    }
1653 
1654    return 1;
1655 }
1656 
1657 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1658  * header and fill in all the information.  This is executed in a safe context,
1659  * unlike the init routine above.
1660  */
1661 static int
png_image_read_header(png_voidp argument)1662 png_image_read_header(png_voidp argument)
1663 {
1664    png_imagep image = png_voidcast(png_imagep, argument);
1665    png_structrp png_ptr = image->opaque->png_ptr;
1666    png_inforp info_ptr = image->opaque->info_ptr;
1667 
1668 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
1669    png_set_benign_errors(png_ptr, 1/*warn*/);
1670 #endif
1671    png_read_info(png_ptr, info_ptr);
1672 
1673    /* Do this the fast way; just read directly out of png_struct. */
1674    image->width = png_ptr->width;
1675    image->height = png_ptr->height;
1676 
1677    {
1678       png_uint_32 format = png_image_format(png_ptr);
1679 
1680       image->format = format;
1681 
1682 #ifdef PNG_COLORSPACE_SUPPORTED
1683       /* Does the colorspace match sRGB?  If there is no color endpoint
1684        * (colorant) information assume yes, otherwise require the
1685        * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set.  If the
1686        * colorspace has been determined to be invalid ignore it.
1687        */
1688       if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1689          & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1690             PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1691          image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1692 #endif
1693    }
1694 
1695    /* We need the maximum number of entries regardless of the format the
1696     * application sets here.
1697     */
1698    {
1699       png_uint_32 cmap_entries;
1700 
1701       switch (png_ptr->color_type)
1702       {
1703          case PNG_COLOR_TYPE_GRAY:
1704             cmap_entries = 1U << png_ptr->bit_depth;
1705             break;
1706 
1707          case PNG_COLOR_TYPE_PALETTE:
1708             cmap_entries = (png_uint_32)png_ptr->num_palette;
1709             break;
1710 
1711          default:
1712             cmap_entries = 256;
1713             break;
1714       }
1715 
1716       if (cmap_entries > 256)
1717          cmap_entries = 256;
1718 
1719       image->colormap_entries = cmap_entries;
1720    }
1721 
1722    return 1;
1723 }
1724 
1725 #ifdef PNG_STDIO_SUPPORTED
1726 int PNGAPI
png_image_begin_read_from_stdio(png_imagep image,FILE * file)1727 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1728 {
1729    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1730    {
1731       if (file != NULL)
1732       {
1733          if (png_image_read_init(image) != 0)
1734          {
1735             /* This is slightly evil, but png_init_io doesn't do anything other
1736              * than this and we haven't changed the standard IO functions so
1737              * this saves a 'safe' function.
1738              */
1739             image->opaque->png_ptr->io_ptr = file;
1740             return png_safe_execute(image, png_image_read_header, image);
1741          }
1742       }
1743 
1744       else
1745          return png_image_error(image,
1746              "png_image_begin_read_from_stdio: invalid argument");
1747    }
1748 
1749    else if (image != NULL)
1750       return png_image_error(image,
1751           "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1752 
1753    return 0;
1754 }
1755 
1756 int PNGAPI
png_image_begin_read_from_file(png_imagep image,const char * file_name)1757 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1758 {
1759    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1760    {
1761       if (file_name != NULL)
1762       {
1763          FILE *fp = fopen(file_name, "rb");
1764 
1765          if (fp != NULL)
1766          {
1767             if (png_image_read_init(image) != 0)
1768             {
1769                image->opaque->png_ptr->io_ptr = fp;
1770                image->opaque->owned_file = 1;
1771                return png_safe_execute(image, png_image_read_header, image);
1772             }
1773 
1774             /* Clean up: just the opened file. */
1775             (void)fclose(fp);
1776          }
1777 
1778          else
1779             return png_image_error(image, strerror(errno));
1780       }
1781 
1782       else
1783          return png_image_error(image,
1784              "png_image_begin_read_from_file: invalid argument");
1785    }
1786 
1787    else if (image != NULL)
1788       return png_image_error(image,
1789           "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1790 
1791    return 0;
1792 }
1793 #endif /* STDIO */
1794 
1795 static void PNGCBAPI
png_image_memory_read(png_structp png_ptr,png_bytep out,size_t need)1796 png_image_memory_read(png_structp png_ptr, png_bytep out, size_t need)
1797 {
1798    if (png_ptr != NULL)
1799    {
1800       png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1801       if (image != NULL)
1802       {
1803          png_controlp cp = image->opaque;
1804          if (cp != NULL)
1805          {
1806             png_const_bytep memory = cp->memory;
1807             size_t size = cp->size;
1808 
1809             if (memory != NULL && size >= need)
1810             {
1811                memcpy(out, memory, need);
1812                cp->memory = memory + need;
1813                cp->size = size - need;
1814                return;
1815             }
1816 
1817             png_error(png_ptr, "read beyond end of data");
1818          }
1819       }
1820 
1821       png_error(png_ptr, "invalid memory read");
1822    }
1823 }
1824 
png_image_begin_read_from_memory(png_imagep image,png_const_voidp memory,size_t size)1825 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1826     png_const_voidp memory, size_t size)
1827 {
1828    if (image != NULL && image->version == PNG_IMAGE_VERSION)
1829    {
1830       if (memory != NULL && size > 0)
1831       {
1832          if (png_image_read_init(image) != 0)
1833          {
1834             /* Now set the IO functions to read from the memory buffer and
1835              * store it into io_ptr.  Again do this in-place to avoid calling a
1836              * libpng function that requires error handling.
1837              */
1838             image->opaque->memory = png_voidcast(png_const_bytep, memory);
1839             image->opaque->size = size;
1840             image->opaque->png_ptr->io_ptr = image;
1841             image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1842 
1843             return png_safe_execute(image, png_image_read_header, image);
1844          }
1845       }
1846 
1847       else
1848          return png_image_error(image,
1849              "png_image_begin_read_from_memory: invalid argument");
1850    }
1851 
1852    else if (image != NULL)
1853       return png_image_error(image,
1854           "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1855 
1856    return 0;
1857 }
1858 
1859 /* Utility function to skip chunks that are not used by the simplified image
1860  * read functions and an appropriate macro to call it.
1861  */
1862 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1863 static void
png_image_skip_unused_chunks(png_structrp png_ptr)1864 png_image_skip_unused_chunks(png_structrp png_ptr)
1865 {
1866    /* Prepare the reader to ignore all recognized chunks whose data will not
1867     * be used, i.e., all chunks recognized by libpng except for those
1868     * involved in basic image reading:
1869     *
1870     *    IHDR, PLTE, IDAT, IEND
1871     *
1872     * Or image data handling:
1873     *
1874     *    tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1875     *
1876     * This provides a small performance improvement and eliminates any
1877     * potential vulnerability to security problems in the unused chunks.
1878     *
1879     * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1880     * too.  This allows the simplified API to be compiled without iCCP support,
1881     * however if the support is there the chunk is still checked to detect
1882     * errors (which are unfortunately quite common.)
1883     */
1884    {
1885          static const png_byte chunks_to_process[] = {
1886             98,  75,  71,  68, '\0',  /* bKGD */
1887             99,  72,  82,  77, '\0',  /* cHRM */
1888            103,  65,  77,  65, '\0',  /* gAMA */
1889 #        ifdef PNG_READ_iCCP_SUPPORTED
1890            105,  67,  67,  80, '\0',  /* iCCP */
1891 #        endif
1892            115,  66,  73,  84, '\0',  /* sBIT */
1893            115,  82,  71,  66, '\0',  /* sRGB */
1894            };
1895 
1896        /* Ignore unknown chunks and all other chunks except for the
1897         * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1898         */
1899        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1900            NULL, -1);
1901 
1902        /* But do not ignore image data handling chunks */
1903        png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1904            chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1905    }
1906 }
1907 
1908 #  define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1909 #else
1910 #  define PNG_SKIP_CHUNKS(p) ((void)0)
1911 #endif /* HANDLE_AS_UNKNOWN */
1912 
1913 /* The following macro gives the exact rounded answer for all values in the
1914  * range 0..255 (it actually divides by 51.2, but the rounding still generates
1915  * the correct numbers 0..5
1916  */
1917 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1918 
1919 /* Utility functions to make particular color-maps */
1920 static void
set_file_encoding(png_image_read_control * display)1921 set_file_encoding(png_image_read_control *display)
1922 {
1923    png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1924    if (png_gamma_significant(g) != 0)
1925    {
1926       if (png_gamma_not_sRGB(g) != 0)
1927       {
1928          display->file_encoding = P_FILE;
1929          display->gamma_to_linear = png_reciprocal(g);
1930       }
1931 
1932       else
1933          display->file_encoding = P_sRGB;
1934    }
1935 
1936    else
1937       display->file_encoding = P_LINEAR8;
1938 }
1939 
1940 static unsigned int
decode_gamma(png_image_read_control * display,png_uint_32 value,int encoding)1941 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1942 {
1943    if (encoding == P_FILE) /* double check */
1944       encoding = display->file_encoding;
1945 
1946    if (encoding == P_NOTSET) /* must be the file encoding */
1947    {
1948       set_file_encoding(display);
1949       encoding = display->file_encoding;
1950    }
1951 
1952    switch (encoding)
1953    {
1954       case P_FILE:
1955          value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1956          break;
1957 
1958       case P_sRGB:
1959          value = png_sRGB_table[value];
1960          break;
1961 
1962       case P_LINEAR:
1963          break;
1964 
1965       case P_LINEAR8:
1966          value *= 257;
1967          break;
1968 
1969 #ifdef __GNUC__
1970       default:
1971          png_error(display->image->opaque->png_ptr,
1972              "unexpected encoding (internal error)");
1973 #endif
1974    }
1975 
1976    return value;
1977 }
1978 
1979 static png_uint_32
png_colormap_compose(png_image_read_control * display,png_uint_32 foreground,int foreground_encoding,png_uint_32 alpha,png_uint_32 background,int encoding)1980 png_colormap_compose(png_image_read_control *display,
1981     png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1982     png_uint_32 background, int encoding)
1983 {
1984    /* The file value is composed on the background, the background has the given
1985     * encoding and so does the result, the file is encoded with P_FILE and the
1986     * file and alpha are 8-bit values.  The (output) encoding will always be
1987     * P_LINEAR or P_sRGB.
1988     */
1989    png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1990    png_uint_32 b = decode_gamma(display, background, encoding);
1991 
1992    /* The alpha is always an 8-bit value (it comes from the palette), the value
1993     * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1994     */
1995    f = f * alpha + b * (255-alpha);
1996 
1997    if (encoding == P_LINEAR)
1998    {
1999       /* Scale to 65535; divide by 255, approximately (in fact this is extremely
2000        * accurate, it divides by 255.00000005937181414556, with no overflow.)
2001        */
2002       f *= 257; /* Now scaled by 65535 */
2003       f += f >> 16;
2004       f = (f+32768) >> 16;
2005    }
2006 
2007    else /* P_sRGB */
2008       f = PNG_sRGB_FROM_LINEAR(f);
2009 
2010    return f;
2011 }
2012 
2013 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
2014  * be 8-bit.
2015  */
2016 static void
png_create_colormap_entry(png_image_read_control * display,png_uint_32 ip,png_uint_32 red,png_uint_32 green,png_uint_32 blue,png_uint_32 alpha,int encoding)2017 png_create_colormap_entry(png_image_read_control *display,
2018     png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
2019     png_uint_32 alpha, int encoding)
2020 {
2021    png_imagep image = display->image;
2022    int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2023        P_LINEAR : P_sRGB;
2024    int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
2025        (red != green || green != blue);
2026 
2027    if (ip > 255)
2028       png_error(image->opaque->png_ptr, "color-map index out of range");
2029 
2030    /* Update the cache with whether the file gamma is significantly different
2031     * from sRGB.
2032     */
2033    if (encoding == P_FILE)
2034    {
2035       if (display->file_encoding == P_NOTSET)
2036          set_file_encoding(display);
2037 
2038       /* Note that the cached value may be P_FILE too, but if it is then the
2039        * gamma_to_linear member has been set.
2040        */
2041       encoding = display->file_encoding;
2042    }
2043 
2044    if (encoding == P_FILE)
2045    {
2046       png_fixed_point g = display->gamma_to_linear;
2047 
2048       red = png_gamma_16bit_correct(red*257, g);
2049       green = png_gamma_16bit_correct(green*257, g);
2050       blue = png_gamma_16bit_correct(blue*257, g);
2051 
2052       if (convert_to_Y != 0 || output_encoding == P_LINEAR)
2053       {
2054          alpha *= 257;
2055          encoding = P_LINEAR;
2056       }
2057 
2058       else
2059       {
2060          red = PNG_sRGB_FROM_LINEAR(red * 255);
2061          green = PNG_sRGB_FROM_LINEAR(green * 255);
2062          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
2063          encoding = P_sRGB;
2064       }
2065    }
2066 
2067    else if (encoding == P_LINEAR8)
2068    {
2069       /* This encoding occurs quite frequently in test cases because PngSuite
2070        * includes a gAMA 1.0 chunk with most images.
2071        */
2072       red *= 257;
2073       green *= 257;
2074       blue *= 257;
2075       alpha *= 257;
2076       encoding = P_LINEAR;
2077    }
2078 
2079    else if (encoding == P_sRGB &&
2080        (convert_to_Y  != 0 || output_encoding == P_LINEAR))
2081    {
2082       /* The values are 8-bit sRGB values, but must be converted to 16-bit
2083        * linear.
2084        */
2085       red = png_sRGB_table[red];
2086       green = png_sRGB_table[green];
2087       blue = png_sRGB_table[blue];
2088       alpha *= 257;
2089       encoding = P_LINEAR;
2090    }
2091 
2092    /* This is set if the color isn't gray but the output is. */
2093    if (encoding == P_LINEAR)
2094    {
2095       if (convert_to_Y != 0)
2096       {
2097          /* NOTE: these values are copied from png_do_rgb_to_gray */
2098          png_uint_32 y = (png_uint_32)6968 * red  + (png_uint_32)23434 * green +
2099             (png_uint_32)2366 * blue;
2100 
2101          if (output_encoding == P_LINEAR)
2102             y = (y + 16384) >> 15;
2103 
2104          else
2105          {
2106             /* y is scaled by 32768, we need it scaled by 255: */
2107             y = (y + 128) >> 8;
2108             y *= 255;
2109             y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
2110             alpha = PNG_DIV257(alpha);
2111             encoding = P_sRGB;
2112          }
2113 
2114          blue = red = green = y;
2115       }
2116 
2117       else if (output_encoding == P_sRGB)
2118       {
2119          red = PNG_sRGB_FROM_LINEAR(red * 255);
2120          green = PNG_sRGB_FROM_LINEAR(green * 255);
2121          blue = PNG_sRGB_FROM_LINEAR(blue * 255);
2122          alpha = PNG_DIV257(alpha);
2123          encoding = P_sRGB;
2124       }
2125    }
2126 
2127    if (encoding != output_encoding)
2128       png_error(image->opaque->png_ptr, "bad encoding (internal error)");
2129 
2130    /* Store the value. */
2131    {
2132 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
2133          int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
2134             (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
2135 #     else
2136 #        define afirst 0
2137 #     endif
2138 #     ifdef PNG_FORMAT_BGR_SUPPORTED
2139          int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
2140 #     else
2141 #        define bgr 0
2142 #     endif
2143 
2144       if (output_encoding == P_LINEAR)
2145       {
2146          png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
2147 
2148          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
2149 
2150          /* The linear 16-bit values must be pre-multiplied by the alpha channel
2151           * value, if less than 65535 (this is, effectively, composite on black
2152           * if the alpha channel is removed.)
2153           */
2154          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
2155          {
2156             case 4:
2157                entry[afirst ? 0 : 3] = (png_uint_16)alpha;
2158                /* FALLTHROUGH */
2159 
2160             case 3:
2161                if (alpha < 65535)
2162                {
2163                   if (alpha > 0)
2164                   {
2165                      blue = (blue * alpha + 32767U)/65535U;
2166                      green = (green * alpha + 32767U)/65535U;
2167                      red = (red * alpha + 32767U)/65535U;
2168                   }
2169 
2170                   else
2171                      red = green = blue = 0;
2172                }
2173                entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
2174                entry[afirst + 1] = (png_uint_16)green;
2175                entry[afirst + bgr] = (png_uint_16)red;
2176                break;
2177 
2178             case 2:
2179                entry[1 ^ afirst] = (png_uint_16)alpha;
2180                /* FALLTHROUGH */
2181 
2182             case 1:
2183                if (alpha < 65535)
2184                {
2185                   if (alpha > 0)
2186                      green = (green * alpha + 32767U)/65535U;
2187 
2188                   else
2189                      green = 0;
2190                }
2191                entry[afirst] = (png_uint_16)green;
2192                break;
2193 
2194             default:
2195                break;
2196          }
2197       }
2198 
2199       else /* output encoding is P_sRGB */
2200       {
2201          png_bytep entry = png_voidcast(png_bytep, display->colormap);
2202 
2203          entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
2204 
2205          switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
2206          {
2207             case 4:
2208                entry[afirst ? 0 : 3] = (png_byte)alpha;
2209                /* FALLTHROUGH */
2210             case 3:
2211                entry[afirst + (2 ^ bgr)] = (png_byte)blue;
2212                entry[afirst + 1] = (png_byte)green;
2213                entry[afirst + bgr] = (png_byte)red;
2214                break;
2215 
2216             case 2:
2217                entry[1 ^ afirst] = (png_byte)alpha;
2218                /* FALLTHROUGH */
2219             case 1:
2220                entry[afirst] = (png_byte)green;
2221                break;
2222 
2223             default:
2224                break;
2225          }
2226       }
2227 
2228 #     ifdef afirst
2229 #        undef afirst
2230 #     endif
2231 #     ifdef bgr
2232 #        undef bgr
2233 #     endif
2234    }
2235 }
2236 
2237 static int
make_gray_file_colormap(png_image_read_control * display)2238 make_gray_file_colormap(png_image_read_control *display)
2239 {
2240    unsigned int i;
2241 
2242    for (i=0; i<256; ++i)
2243       png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
2244 
2245    return (int)i;
2246 }
2247 
2248 static int
make_gray_colormap(png_image_read_control * display)2249 make_gray_colormap(png_image_read_control *display)
2250 {
2251    unsigned int i;
2252 
2253    for (i=0; i<256; ++i)
2254       png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
2255 
2256    return (int)i;
2257 }
2258 #define PNG_GRAY_COLORMAP_ENTRIES 256
2259 
2260 static int
make_ga_colormap(png_image_read_control * display)2261 make_ga_colormap(png_image_read_control *display)
2262 {
2263    unsigned int i, a;
2264 
2265    /* Alpha is retained, the output will be a color-map with entries
2266     * selected by six levels of alpha.  One transparent entry, 6 gray
2267     * levels for all the intermediate alpha values, leaving 230 entries
2268     * for the opaque grays.  The color-map entries are the six values
2269     * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
2270     * relevant entry.
2271     *
2272     * if (alpha > 229) // opaque
2273     * {
2274     *    // The 231 entries are selected to make the math below work:
2275     *    base = 0;
2276     *    entry = (231 * gray + 128) >> 8;
2277     * }
2278     * else if (alpha < 26) // transparent
2279     * {
2280     *    base = 231;
2281     *    entry = 0;
2282     * }
2283     * else // partially opaque
2284     * {
2285     *    base = 226 + 6 * PNG_DIV51(alpha);
2286     *    entry = PNG_DIV51(gray);
2287     * }
2288     */
2289    i = 0;
2290    while (i < 231)
2291    {
2292       unsigned int gray = (i * 256 + 115) / 231;
2293       png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
2294    }
2295 
2296    /* 255 is used here for the component values for consistency with the code
2297     * that undoes premultiplication in pngwrite.c.
2298     */
2299    png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
2300 
2301    for (a=1; a<5; ++a)
2302    {
2303       unsigned int g;
2304 
2305       for (g=0; g<6; ++g)
2306          png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
2307              P_sRGB);
2308    }
2309 
2310    return (int)i;
2311 }
2312 
2313 #define PNG_GA_COLORMAP_ENTRIES 256
2314 
2315 static int
make_rgb_colormap(png_image_read_control * display)2316 make_rgb_colormap(png_image_read_control *display)
2317 {
2318    unsigned int i, r;
2319 
2320    /* Build a 6x6x6 opaque RGB cube */
2321    for (i=r=0; r<6; ++r)
2322    {
2323       unsigned int g;
2324 
2325       for (g=0; g<6; ++g)
2326       {
2327          unsigned int b;
2328 
2329          for (b=0; b<6; ++b)
2330             png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
2331                 P_sRGB);
2332       }
2333    }
2334 
2335    return (int)i;
2336 }
2337 
2338 #define PNG_RGB_COLORMAP_ENTRIES 216
2339 
2340 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2341 #define PNG_RGB_INDEX(r,g,b) \
2342    ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2343 
2344 static int
png_image_read_colormap(png_voidp argument)2345 png_image_read_colormap(png_voidp argument)
2346 {
2347    png_image_read_control *display =
2348       png_voidcast(png_image_read_control*, argument);
2349    png_imagep image = display->image;
2350 
2351    png_structrp png_ptr = image->opaque->png_ptr;
2352    png_uint_32 output_format = image->format;
2353    int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2354       P_LINEAR : P_sRGB;
2355 
2356    unsigned int cmap_entries;
2357    unsigned int output_processing;        /* Output processing option */
2358    unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2359 
2360    /* Background information; the background color and the index of this color
2361     * in the color-map if it exists (else 256).
2362     */
2363    unsigned int background_index = 256;
2364    png_uint_32 back_r, back_g, back_b;
2365 
2366    /* Flags to accumulate things that need to be done to the input. */
2367    int expand_tRNS = 0;
2368 
2369    /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2370     * very difficult to do, the results look awful, and it is difficult to see
2371     * what possible use it is because the application can't control the
2372     * color-map.
2373     */
2374    if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2375          png_ptr->num_trans > 0) /* alpha in input */ &&
2376       ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2377    {
2378       if (output_encoding == P_LINEAR) /* compose on black */
2379          back_b = back_g = back_r = 0;
2380 
2381       else if (display->background == NULL /* no way to remove it */)
2382          png_error(png_ptr,
2383              "background color must be supplied to remove alpha/transparency");
2384 
2385       /* Get a copy of the background color (this avoids repeating the checks
2386        * below.)  The encoding is 8-bit sRGB or 16-bit linear, depending on the
2387        * output format.
2388        */
2389       else
2390       {
2391          back_g = display->background->green;
2392          if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2393          {
2394             back_r = display->background->red;
2395             back_b = display->background->blue;
2396          }
2397          else
2398             back_b = back_r = back_g;
2399       }
2400    }
2401 
2402    else if (output_encoding == P_LINEAR)
2403       back_b = back_r = back_g = 65535;
2404 
2405    else
2406       back_b = back_r = back_g = 255;
2407 
2408    /* Default the input file gamma if required - this is necessary because
2409     * libpng assumes that if no gamma information is present the data is in the
2410     * output format, but the simplified API deduces the gamma from the input
2411     * format.
2412     */
2413    if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2414    {
2415       /* Do this directly, not using the png_colorspace functions, to ensure
2416        * that it happens even if the colorspace is invalid (though probably if
2417        * it is the setting will be ignored)  Note that the same thing can be
2418        * achieved at the application interface with png_set_gAMA.
2419        */
2420       if (png_ptr->bit_depth == 16 &&
2421          (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2422          png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2423 
2424       else
2425          png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2426 
2427       png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2428    }
2429 
2430    /* Decide what to do based on the PNG color type of the input data.  The
2431     * utility function png_create_colormap_entry deals with most aspects of the
2432     * output transformations; this code works out how to produce bytes of
2433     * color-map entries from the original format.
2434     */
2435    switch (png_ptr->color_type)
2436    {
2437       case PNG_COLOR_TYPE_GRAY:
2438          if (png_ptr->bit_depth <= 8)
2439          {
2440             /* There at most 256 colors in the output, regardless of
2441              * transparency.
2442              */
2443             unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2444 
2445             cmap_entries = 1U << png_ptr->bit_depth;
2446             if (cmap_entries > image->colormap_entries)
2447                png_error(png_ptr, "gray[8] color-map: too few entries");
2448 
2449             step = 255 / (cmap_entries - 1);
2450             output_processing = PNG_CMAP_NONE;
2451 
2452             /* If there is a tRNS chunk then this either selects a transparent
2453              * value or, if the output has no alpha, the background color.
2454              */
2455             if (png_ptr->num_trans > 0)
2456             {
2457                trans = png_ptr->trans_color.gray;
2458 
2459                if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2460                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2461             }
2462 
2463             /* png_create_colormap_entry just takes an RGBA and writes the
2464              * corresponding color-map entry using the format from 'image',
2465              * including the required conversion to sRGB or linear as
2466              * appropriate.  The input values are always either sRGB (if the
2467              * gamma correction flag is 0) or 0..255 scaled file encoded values
2468              * (if the function must gamma correct them).
2469              */
2470             for (i=val=0; i<cmap_entries; ++i, val += step)
2471             {
2472                /* 'i' is a file value.  While this will result in duplicated
2473                 * entries for 8-bit non-sRGB encoded files it is necessary to
2474                 * have non-gamma corrected values to do tRNS handling.
2475                 */
2476                if (i != trans)
2477                   png_create_colormap_entry(display, i, val, val, val, 255,
2478                       P_FILE/*8-bit with file gamma*/);
2479 
2480                /* Else this entry is transparent.  The colors don't matter if
2481                 * there is an alpha channel (back_alpha == 0), but it does no
2482                 * harm to pass them in; the values are not set above so this
2483                 * passes in white.
2484                 *
2485                 * NOTE: this preserves the full precision of the application
2486                 * supplied background color when it is used.
2487                 */
2488                else
2489                   png_create_colormap_entry(display, i, back_r, back_g, back_b,
2490                       back_alpha, output_encoding);
2491             }
2492 
2493             /* We need libpng to preserve the original encoding. */
2494             data_encoding = P_FILE;
2495 
2496             /* The rows from libpng, while technically gray values, are now also
2497              * color-map indices; however, they may need to be expanded to 1
2498              * byte per pixel.  This is what png_set_packing does (i.e., it
2499              * unpacks the bit values into bytes.)
2500              */
2501             if (png_ptr->bit_depth < 8)
2502                png_set_packing(png_ptr);
2503          }
2504 
2505          else /* bit depth is 16 */
2506          {
2507             /* The 16-bit input values can be converted directly to 8-bit gamma
2508              * encoded values; however, if a tRNS chunk is present 257 color-map
2509              * entries are required.  This means that the extra entry requires
2510              * special processing; add an alpha channel, sacrifice gray level
2511              * 254 and convert transparent (alpha==0) entries to that.
2512              *
2513              * Use libpng to chop the data to 8 bits.  Convert it to sRGB at the
2514              * same time to minimize quality loss.  If a tRNS chunk is present
2515              * this means libpng must handle it too; otherwise it is impossible
2516              * to do the exact match on the 16-bit value.
2517              *
2518              * If the output has no alpha channel *and* the background color is
2519              * gray then it is possible to let libpng handle the substitution by
2520              * ensuring that the corresponding gray level matches the background
2521              * color exactly.
2522              */
2523             data_encoding = P_sRGB;
2524 
2525             if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2526                png_error(png_ptr, "gray[16] color-map: too few entries");
2527 
2528             cmap_entries = (unsigned int)make_gray_colormap(display);
2529 
2530             if (png_ptr->num_trans > 0)
2531             {
2532                unsigned int back_alpha;
2533 
2534                if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2535                   back_alpha = 0;
2536 
2537                else
2538                {
2539                   if (back_r == back_g && back_g == back_b)
2540                   {
2541                      /* Background is gray; no special processing will be
2542                       * required.
2543                       */
2544                      png_color_16 c;
2545                      png_uint_32 gray = back_g;
2546 
2547                      if (output_encoding == P_LINEAR)
2548                      {
2549                         gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2550 
2551                         /* And make sure the corresponding palette entry
2552                          * matches.
2553                          */
2554                         png_create_colormap_entry(display, gray, back_g, back_g,
2555                             back_g, 65535, P_LINEAR);
2556                      }
2557 
2558                      /* The background passed to libpng, however, must be the
2559                       * sRGB value.
2560                       */
2561                      c.index = 0; /*unused*/
2562                      c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2563 
2564                      /* NOTE: does this work without expanding tRNS to alpha?
2565                       * It should be the color->gray case below apparently
2566                       * doesn't.
2567                       */
2568                      png_set_background_fixed(png_ptr, &c,
2569                          PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2570                          0/*gamma: not used*/);
2571 
2572                      output_processing = PNG_CMAP_NONE;
2573                      break;
2574                   }
2575 #ifdef __COVERITY__
2576                  /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2577                   * here.
2578                   */
2579                   back_alpha = 255;
2580 #else
2581                   back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2582 #endif
2583                }
2584 
2585                /* output_processing means that the libpng-processed row will be
2586                 * 8-bit GA and it has to be processing to single byte color-map
2587                 * values.  Entry 254 is replaced by either a completely
2588                 * transparent entry or by the background color at full
2589                 * precision (and the background color is not a simple gray
2590                 * level in this case.)
2591                 */
2592                expand_tRNS = 1;
2593                output_processing = PNG_CMAP_TRANS;
2594                background_index = 254;
2595 
2596                /* And set (overwrite) color-map entry 254 to the actual
2597                 * background color at full precision.
2598                 */
2599                png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2600                    back_alpha, output_encoding);
2601             }
2602 
2603             else
2604                output_processing = PNG_CMAP_NONE;
2605          }
2606          break;
2607 
2608       case PNG_COLOR_TYPE_GRAY_ALPHA:
2609          /* 8-bit or 16-bit PNG with two channels - gray and alpha.  A minimum
2610           * of 65536 combinations.  If, however, the alpha channel is to be
2611           * removed there are only 256 possibilities if the background is gray.
2612           * (Otherwise there is a subset of the 65536 possibilities defined by
2613           * the triangle between black, white and the background color.)
2614           *
2615           * Reduce 16-bit files to 8-bit and sRGB encode the result.  No need to
2616           * worry about tRNS matching - tRNS is ignored if there is an alpha
2617           * channel.
2618           */
2619          data_encoding = P_sRGB;
2620 
2621          if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2622          {
2623             if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2624                png_error(png_ptr, "gray+alpha color-map: too few entries");
2625 
2626             cmap_entries = (unsigned int)make_ga_colormap(display);
2627 
2628             background_index = PNG_CMAP_GA_BACKGROUND;
2629             output_processing = PNG_CMAP_GA;
2630          }
2631 
2632          else /* alpha is removed */
2633          {
2634             /* Alpha must be removed as the PNG data is processed when the
2635              * background is a color because the G and A channels are
2636              * independent and the vector addition (non-parallel vectors) is a
2637              * 2-D problem.
2638              *
2639              * This can be reduced to the same algorithm as above by making a
2640              * colormap containing gray levels (for the opaque grays), a
2641              * background entry (for a transparent pixel) and a set of four six
2642              * level color values, one set for each intermediate alpha value.
2643              * See the comments in make_ga_colormap for how this works in the
2644              * per-pixel processing.
2645              *
2646              * If the background is gray, however, we only need a 256 entry gray
2647              * level color map.  It is sufficient to make the entry generated
2648              * for the background color be exactly the color specified.
2649              */
2650             if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2651                (back_r == back_g && back_g == back_b))
2652             {
2653                /* Background is gray; no special processing will be required. */
2654                png_color_16 c;
2655                png_uint_32 gray = back_g;
2656 
2657                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2658                   png_error(png_ptr, "gray-alpha color-map: too few entries");
2659 
2660                cmap_entries = (unsigned int)make_gray_colormap(display);
2661 
2662                if (output_encoding == P_LINEAR)
2663                {
2664                   gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2665 
2666                   /* And make sure the corresponding palette entry matches. */
2667                   png_create_colormap_entry(display, gray, back_g, back_g,
2668                       back_g, 65535, P_LINEAR);
2669                }
2670 
2671                /* The background passed to libpng, however, must be the sRGB
2672                 * value.
2673                 */
2674                c.index = 0; /*unused*/
2675                c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2676 
2677                png_set_background_fixed(png_ptr, &c,
2678                    PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2679                    0/*gamma: not used*/);
2680 
2681                output_processing = PNG_CMAP_NONE;
2682             }
2683 
2684             else
2685             {
2686                png_uint_32 i, a;
2687 
2688                /* This is the same as png_make_ga_colormap, above, except that
2689                 * the entries are all opaque.
2690                 */
2691                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2692                   png_error(png_ptr, "ga-alpha color-map: too few entries");
2693 
2694                i = 0;
2695                while (i < 231)
2696                {
2697                   png_uint_32 gray = (i * 256 + 115) / 231;
2698                   png_create_colormap_entry(display, i++, gray, gray, gray,
2699                       255, P_sRGB);
2700                }
2701 
2702                /* NOTE: this preserves the full precision of the application
2703                 * background color.
2704                 */
2705                background_index = i;
2706                png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2707 #ifdef __COVERITY__
2708                    /* Coverity claims that output_encoding
2709                     * cannot be 2 (P_LINEAR) here.
2710                     */ 255U,
2711 #else
2712                     output_encoding == P_LINEAR ? 65535U : 255U,
2713 #endif
2714                     output_encoding);
2715 
2716                /* For non-opaque input composite on the sRGB background - this
2717                 * requires inverting the encoding for each component.  The input
2718                 * is still converted to the sRGB encoding because this is a
2719                 * reasonable approximate to the logarithmic curve of human
2720                 * visual sensitivity, at least over the narrow range which PNG
2721                 * represents.  Consequently 'G' is always sRGB encoded, while
2722                 * 'A' is linear.  We need the linear background colors.
2723                 */
2724                if (output_encoding == P_sRGB) /* else already linear */
2725                {
2726                   /* This may produce a value not exactly matching the
2727                    * background, but that's ok because these numbers are only
2728                    * used when alpha != 0
2729                    */
2730                   back_r = png_sRGB_table[back_r];
2731                   back_g = png_sRGB_table[back_g];
2732                   back_b = png_sRGB_table[back_b];
2733                }
2734 
2735                for (a=1; a<5; ++a)
2736                {
2737                   unsigned int g;
2738 
2739                   /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2740                    * by an 8-bit alpha value (0..255).
2741                    */
2742                   png_uint_32 alpha = 51 * a;
2743                   png_uint_32 back_rx = (255-alpha) * back_r;
2744                   png_uint_32 back_gx = (255-alpha) * back_g;
2745                   png_uint_32 back_bx = (255-alpha) * back_b;
2746 
2747                   for (g=0; g<6; ++g)
2748                   {
2749                      png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2750 
2751                      png_create_colormap_entry(display, i++,
2752                          PNG_sRGB_FROM_LINEAR(gray + back_rx),
2753                          PNG_sRGB_FROM_LINEAR(gray + back_gx),
2754                          PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2755                   }
2756                }
2757 
2758                cmap_entries = i;
2759                output_processing = PNG_CMAP_GA;
2760             }
2761          }
2762          break;
2763 
2764       case PNG_COLOR_TYPE_RGB:
2765       case PNG_COLOR_TYPE_RGB_ALPHA:
2766          /* Exclude the case where the output is gray; we can always handle this
2767           * with the cases above.
2768           */
2769          if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2770          {
2771             /* The color-map will be grayscale, so we may as well convert the
2772              * input RGB values to a simple grayscale and use the grayscale
2773              * code above.
2774              *
2775              * NOTE: calling this apparently damages the recognition of the
2776              * transparent color in background color handling; call
2777              * png_set_tRNS_to_alpha before png_set_background_fixed.
2778              */
2779             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2780                 -1);
2781             data_encoding = P_sRGB;
2782 
2783             /* The output will now be one or two 8-bit gray or gray+alpha
2784              * channels.  The more complex case arises when the input has alpha.
2785              */
2786             if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2787                png_ptr->num_trans > 0) &&
2788                (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2789             {
2790                /* Both input and output have an alpha channel, so no background
2791                 * processing is required; just map the GA bytes to the right
2792                 * color-map entry.
2793                 */
2794                expand_tRNS = 1;
2795 
2796                if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2797                   png_error(png_ptr, "rgb[ga] color-map: too few entries");
2798 
2799                cmap_entries = (unsigned int)make_ga_colormap(display);
2800                background_index = PNG_CMAP_GA_BACKGROUND;
2801                output_processing = PNG_CMAP_GA;
2802             }
2803 
2804             else
2805             {
2806                /* Either the input or the output has no alpha channel, so there
2807                 * will be no non-opaque pixels in the color-map; it will just be
2808                 * grayscale.
2809                 */
2810                if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2811                   png_error(png_ptr, "rgb[gray] color-map: too few entries");
2812 
2813                /* Ideally this code would use libpng to do the gamma correction,
2814                 * but if an input alpha channel is to be removed we will hit the
2815                 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2816                 * correction bug).  Fix this by dropping the gamma correction in
2817                 * this case and doing it in the palette; this will result in
2818                 * duplicate palette entries, but that's better than the
2819                 * alternative of double gamma correction.
2820                 */
2821                if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2822                   png_ptr->num_trans > 0) &&
2823                   png_gamma_not_sRGB(png_ptr->colorspace.gamma) != 0)
2824                {
2825                   cmap_entries = (unsigned int)make_gray_file_colormap(display);
2826                   data_encoding = P_FILE;
2827                }
2828 
2829                else
2830                   cmap_entries = (unsigned int)make_gray_colormap(display);
2831 
2832                /* But if the input has alpha or transparency it must be removed
2833                 */
2834                if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2835                   png_ptr->num_trans > 0)
2836                {
2837                   png_color_16 c;
2838                   png_uint_32 gray = back_g;
2839 
2840                   /* We need to ensure that the application background exists in
2841                    * the colormap and that completely transparent pixels map to
2842                    * it.  Achieve this simply by ensuring that the entry
2843                    * selected for the background really is the background color.
2844                    */
2845                   if (data_encoding == P_FILE) /* from the fixup above */
2846                   {
2847                      /* The app supplied a gray which is in output_encoding, we
2848                       * need to convert it to a value of the input (P_FILE)
2849                       * encoding then set this palette entry to the required
2850                       * output encoding.
2851                       */
2852                      if (output_encoding == P_sRGB)
2853                         gray = png_sRGB_table[gray]; /* now P_LINEAR */
2854 
2855                      gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2856                          png_ptr->colorspace.gamma)); /* now P_FILE */
2857 
2858                      /* And make sure the corresponding palette entry contains
2859                       * exactly the required sRGB value.
2860                       */
2861                      png_create_colormap_entry(display, gray, back_g, back_g,
2862                          back_g, 0/*unused*/, output_encoding);
2863                   }
2864 
2865                   else if (output_encoding == P_LINEAR)
2866                   {
2867                      gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2868 
2869                      /* And make sure the corresponding palette entry matches.
2870                       */
2871                      png_create_colormap_entry(display, gray, back_g, back_g,
2872                         back_g, 0/*unused*/, P_LINEAR);
2873                   }
2874 
2875                   /* The background passed to libpng, however, must be the
2876                    * output (normally sRGB) value.
2877                    */
2878                   c.index = 0; /*unused*/
2879                   c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2880 
2881                   /* NOTE: the following is apparently a bug in libpng. Without
2882                    * it the transparent color recognition in
2883                    * png_set_background_fixed seems to go wrong.
2884                    */
2885                   expand_tRNS = 1;
2886                   png_set_background_fixed(png_ptr, &c,
2887                       PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2888                       0/*gamma: not used*/);
2889                }
2890 
2891                output_processing = PNG_CMAP_NONE;
2892             }
2893          }
2894 
2895          else /* output is color */
2896          {
2897             /* We could use png_quantize here so long as there is no transparent
2898              * color or alpha; png_quantize ignores alpha.  Easier overall just
2899              * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2900              * Consequently we always want libpng to produce sRGB data.
2901              */
2902             data_encoding = P_sRGB;
2903 
2904             /* Is there any transparency or alpha? */
2905             if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2906                png_ptr->num_trans > 0)
2907             {
2908                /* Is there alpha in the output too?  If so all four channels are
2909                 * processed into a special RGB cube with alpha support.
2910                 */
2911                if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2912                {
2913                   png_uint_32 r;
2914 
2915                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2916                      png_error(png_ptr, "rgb+alpha color-map: too few entries");
2917 
2918                   cmap_entries = (unsigned int)make_rgb_colormap(display);
2919 
2920                   /* Add a transparent entry. */
2921                   png_create_colormap_entry(display, cmap_entries, 255, 255,
2922                       255, 0, P_sRGB);
2923 
2924                   /* This is stored as the background index for the processing
2925                    * algorithm.
2926                    */
2927                   background_index = cmap_entries++;
2928 
2929                   /* Add 27 r,g,b entries each with alpha 0.5. */
2930                   for (r=0; r<256; r = (r << 1) | 0x7f)
2931                   {
2932                      png_uint_32 g;
2933 
2934                      for (g=0; g<256; g = (g << 1) | 0x7f)
2935                      {
2936                         png_uint_32 b;
2937 
2938                         /* This generates components with the values 0, 127 and
2939                          * 255
2940                          */
2941                         for (b=0; b<256; b = (b << 1) | 0x7f)
2942                            png_create_colormap_entry(display, cmap_entries++,
2943                                r, g, b, 128, P_sRGB);
2944                      }
2945                   }
2946 
2947                   expand_tRNS = 1;
2948                   output_processing = PNG_CMAP_RGB_ALPHA;
2949                }
2950 
2951                else
2952                {
2953                   /* Alpha/transparency must be removed.  The background must
2954                    * exist in the color map (achieved by setting adding it after
2955                    * the 666 color-map).  If the standard processing code will
2956                    * pick up this entry automatically that's all that is
2957                    * required; libpng can be called to do the background
2958                    * processing.
2959                    */
2960                   unsigned int sample_size =
2961                      PNG_IMAGE_SAMPLE_SIZE(output_format);
2962                   png_uint_32 r, g, b; /* sRGB background */
2963 
2964                   if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2965                      png_error(png_ptr, "rgb-alpha color-map: too few entries");
2966 
2967                   cmap_entries = (unsigned int)make_rgb_colormap(display);
2968 
2969                   png_create_colormap_entry(display, cmap_entries, back_r,
2970                       back_g, back_b, 0/*unused*/, output_encoding);
2971 
2972                   if (output_encoding == P_LINEAR)
2973                   {
2974                      r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2975                      g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2976                      b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2977                   }
2978 
2979                   else
2980                   {
2981                      r = back_r;
2982                      g = back_g;
2983                      b = back_g;
2984                   }
2985 
2986                   /* Compare the newly-created color-map entry with the one the
2987                    * PNG_CMAP_RGB algorithm will use.  If the two entries don't
2988                    * match, add the new one and set this as the background
2989                    * index.
2990                    */
2991                   if (memcmp((png_const_bytep)display->colormap +
2992                       sample_size * cmap_entries,
2993                       (png_const_bytep)display->colormap +
2994                           sample_size * PNG_RGB_INDEX(r,g,b),
2995                      sample_size) != 0)
2996                   {
2997                      /* The background color must be added. */
2998                      background_index = cmap_entries++;
2999 
3000                      /* Add 27 r,g,b entries each with created by composing with
3001                       * the background at alpha 0.5.
3002                       */
3003                      for (r=0; r<256; r = (r << 1) | 0x7f)
3004                      {
3005                         for (g=0; g<256; g = (g << 1) | 0x7f)
3006                         {
3007                            /* This generates components with the values 0, 127
3008                             * and 255
3009                             */
3010                            for (b=0; b<256; b = (b << 1) | 0x7f)
3011                               png_create_colormap_entry(display, cmap_entries++,
3012                                   png_colormap_compose(display, r, P_sRGB, 128,
3013                                       back_r, output_encoding),
3014                                   png_colormap_compose(display, g, P_sRGB, 128,
3015                                       back_g, output_encoding),
3016                                   png_colormap_compose(display, b, P_sRGB, 128,
3017                                       back_b, output_encoding),
3018                                   0/*unused*/, output_encoding);
3019                         }
3020                      }
3021 
3022                      expand_tRNS = 1;
3023                      output_processing = PNG_CMAP_RGB_ALPHA;
3024                   }
3025 
3026                   else /* background color is in the standard color-map */
3027                   {
3028                      png_color_16 c;
3029 
3030                      c.index = 0; /*unused*/
3031                      c.red = (png_uint_16)back_r;
3032                      c.gray = c.green = (png_uint_16)back_g;
3033                      c.blue = (png_uint_16)back_b;
3034 
3035                      png_set_background_fixed(png_ptr, &c,
3036                          PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3037                          0/*gamma: not used*/);
3038 
3039                      output_processing = PNG_CMAP_RGB;
3040                   }
3041                }
3042             }
3043 
3044             else /* no alpha or transparency in the input */
3045             {
3046                /* Alpha in the output is irrelevant, simply map the opaque input
3047                 * pixels to the 6x6x6 color-map.
3048                 */
3049                if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
3050                   png_error(png_ptr, "rgb color-map: too few entries");
3051 
3052                cmap_entries = (unsigned int)make_rgb_colormap(display);
3053                output_processing = PNG_CMAP_RGB;
3054             }
3055          }
3056          break;
3057 
3058       case PNG_COLOR_TYPE_PALETTE:
3059          /* It's already got a color-map.  It may be necessary to eliminate the
3060           * tRNS entries though.
3061           */
3062          {
3063             unsigned int num_trans = png_ptr->num_trans;
3064             png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
3065             png_const_colorp colormap = png_ptr->palette;
3066             int do_background = trans != NULL &&
3067                (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
3068             unsigned int i;
3069 
3070             /* Just in case: */
3071             if (trans == NULL)
3072                num_trans = 0;
3073 
3074             output_processing = PNG_CMAP_NONE;
3075             data_encoding = P_FILE; /* Don't change from color-map indices */
3076             cmap_entries = (unsigned int)png_ptr->num_palette;
3077             if (cmap_entries > 256)
3078                cmap_entries = 256;
3079 
3080             if (cmap_entries > (unsigned int)image->colormap_entries)
3081                png_error(png_ptr, "palette color-map: too few entries");
3082 
3083             for (i=0; i < cmap_entries; ++i)
3084             {
3085                if (do_background != 0 && i < num_trans && trans[i] < 255)
3086                {
3087                   if (trans[i] == 0)
3088                      png_create_colormap_entry(display, i, back_r, back_g,
3089                          back_b, 0, output_encoding);
3090 
3091                   else
3092                   {
3093                      /* Must compose the PNG file color in the color-map entry
3094                       * on the sRGB color in 'back'.
3095                       */
3096                      png_create_colormap_entry(display, i,
3097                          png_colormap_compose(display, colormap[i].red,
3098                              P_FILE, trans[i], back_r, output_encoding),
3099                          png_colormap_compose(display, colormap[i].green,
3100                              P_FILE, trans[i], back_g, output_encoding),
3101                          png_colormap_compose(display, colormap[i].blue,
3102                              P_FILE, trans[i], back_b, output_encoding),
3103                          output_encoding == P_LINEAR ? trans[i] * 257U :
3104                              trans[i],
3105                          output_encoding);
3106                   }
3107                }
3108 
3109                else
3110                   png_create_colormap_entry(display, i, colormap[i].red,
3111                       colormap[i].green, colormap[i].blue,
3112                       i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
3113             }
3114 
3115             /* The PNG data may have indices packed in fewer than 8 bits, it
3116              * must be expanded if so.
3117              */
3118             if (png_ptr->bit_depth < 8)
3119                png_set_packing(png_ptr);
3120          }
3121          break;
3122 
3123       default:
3124          png_error(png_ptr, "invalid PNG color type");
3125          /*NOT REACHED*/
3126    }
3127 
3128    /* Now deal with the output processing */
3129    if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
3130        (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
3131       png_set_tRNS_to_alpha(png_ptr);
3132 
3133    switch (data_encoding)
3134    {
3135       case P_sRGB:
3136          /* Change to 8-bit sRGB */
3137          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
3138          /* FALLTHROUGH */
3139 
3140       case P_FILE:
3141          if (png_ptr->bit_depth > 8)
3142             png_set_scale_16(png_ptr);
3143          break;
3144 
3145 #ifdef __GNUC__
3146       default:
3147          png_error(png_ptr, "bad data option (internal error)");
3148 #endif
3149    }
3150 
3151    if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
3152       png_error(png_ptr, "color map overflow (BAD internal error)");
3153 
3154    image->colormap_entries = cmap_entries;
3155 
3156    /* Double check using the recorded background index */
3157    switch (output_processing)
3158    {
3159       case PNG_CMAP_NONE:
3160          if (background_index != PNG_CMAP_NONE_BACKGROUND)
3161             goto bad_background;
3162          break;
3163 
3164       case PNG_CMAP_GA:
3165          if (background_index != PNG_CMAP_GA_BACKGROUND)
3166             goto bad_background;
3167          break;
3168 
3169       case PNG_CMAP_TRANS:
3170          if (background_index >= cmap_entries ||
3171             background_index != PNG_CMAP_TRANS_BACKGROUND)
3172             goto bad_background;
3173          break;
3174 
3175       case PNG_CMAP_RGB:
3176          if (background_index != PNG_CMAP_RGB_BACKGROUND)
3177             goto bad_background;
3178          break;
3179 
3180       case PNG_CMAP_RGB_ALPHA:
3181          if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
3182             goto bad_background;
3183          break;
3184 
3185       default:
3186          png_error(png_ptr, "bad processing option (internal error)");
3187 
3188       bad_background:
3189          png_error(png_ptr, "bad background index (internal error)");
3190    }
3191 
3192    display->colormap_processing = (int)output_processing;
3193 
3194    return 1/*ok*/;
3195 }
3196 
3197 /* The final part of the color-map read called from png_image_finish_read. */
3198 static int
png_image_read_and_map(png_voidp argument)3199 png_image_read_and_map(png_voidp argument)
3200 {
3201    png_image_read_control *display = png_voidcast(png_image_read_control*,
3202        argument);
3203    png_imagep image = display->image;
3204    png_structrp png_ptr = image->opaque->png_ptr;
3205    int passes;
3206 
3207    /* Called when the libpng data must be transformed into the color-mapped
3208     * form.  There is a local row buffer in display->local and this routine must
3209     * do the interlace handling.
3210     */
3211    switch (png_ptr->interlaced)
3212    {
3213       case PNG_INTERLACE_NONE:
3214          passes = 1;
3215          break;
3216 
3217       case PNG_INTERLACE_ADAM7:
3218          passes = PNG_INTERLACE_ADAM7_PASSES;
3219          break;
3220 
3221       default:
3222          png_error(png_ptr, "unknown interlace type");
3223    }
3224 
3225    {
3226       png_uint_32  height = image->height;
3227       png_uint_32  width = image->width;
3228       int          proc = display->colormap_processing;
3229       png_bytep    first_row = png_voidcast(png_bytep, display->first_row);
3230       ptrdiff_t    step_row = display->row_bytes;
3231       int pass;
3232 
3233       for (pass = 0; pass < passes; ++pass)
3234       {
3235          unsigned int     startx, stepx, stepy;
3236          png_uint_32      y;
3237 
3238          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3239          {
3240             /* The row may be empty for a short image: */
3241             if (PNG_PASS_COLS(width, pass) == 0)
3242                continue;
3243 
3244             startx = PNG_PASS_START_COL(pass);
3245             stepx = PNG_PASS_COL_OFFSET(pass);
3246             y = PNG_PASS_START_ROW(pass);
3247             stepy = PNG_PASS_ROW_OFFSET(pass);
3248          }
3249 
3250          else
3251          {
3252             y = 0;
3253             startx = 0;
3254             stepx = stepy = 1;
3255          }
3256 
3257          for (; y<height; y += stepy)
3258          {
3259             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3260             png_bytep outrow = first_row + y * step_row;
3261             png_const_bytep end_row = outrow + width;
3262 
3263             /* Read read the libpng data into the temporary buffer. */
3264             png_read_row(png_ptr, inrow, NULL);
3265 
3266             /* Now process the row according to the processing option, note
3267              * that the caller verifies that the format of the libpng output
3268              * data is as required.
3269              */
3270             outrow += startx;
3271             switch (proc)
3272             {
3273                case PNG_CMAP_GA:
3274                   for (; outrow < end_row; outrow += stepx)
3275                   {
3276                      /* The data is always in the PNG order */
3277                      unsigned int gray = *inrow++;
3278                      unsigned int alpha = *inrow++;
3279                      unsigned int entry;
3280 
3281                      /* NOTE: this code is copied as a comment in
3282                       * make_ga_colormap above.  Please update the
3283                       * comment if you change this code!
3284                       */
3285                      if (alpha > 229) /* opaque */
3286                      {
3287                         entry = (231 * gray + 128) >> 8;
3288                      }
3289                      else if (alpha < 26) /* transparent */
3290                      {
3291                         entry = 231;
3292                      }
3293                      else /* partially opaque */
3294                      {
3295                         entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
3296                      }
3297 
3298                      *outrow = (png_byte)entry;
3299                   }
3300                   break;
3301 
3302                case PNG_CMAP_TRANS:
3303                   for (; outrow < end_row; outrow += stepx)
3304                   {
3305                      png_byte gray = *inrow++;
3306                      png_byte alpha = *inrow++;
3307 
3308                      if (alpha == 0)
3309                         *outrow = PNG_CMAP_TRANS_BACKGROUND;
3310 
3311                      else if (gray != PNG_CMAP_TRANS_BACKGROUND)
3312                         *outrow = gray;
3313 
3314                      else
3315                         *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
3316                   }
3317                   break;
3318 
3319                case PNG_CMAP_RGB:
3320                   for (; outrow < end_row; outrow += stepx)
3321                   {
3322                      *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
3323                      inrow += 3;
3324                   }
3325                   break;
3326 
3327                case PNG_CMAP_RGB_ALPHA:
3328                   for (; outrow < end_row; outrow += stepx)
3329                   {
3330                      unsigned int alpha = inrow[3];
3331 
3332                      /* Because the alpha entries only hold alpha==0.5 values
3333                       * split the processing at alpha==0.25 (64) and 0.75
3334                       * (196).
3335                       */
3336 
3337                      if (alpha >= 196)
3338                         *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
3339                             inrow[2]);
3340 
3341                      else if (alpha < 64)
3342                         *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
3343 
3344                      else
3345                      {
3346                         /* Likewise there are three entries for each of r, g
3347                          * and b.  We could select the entry by popcount on
3348                          * the top two bits on those architectures that
3349                          * support it, this is what the code below does,
3350                          * crudely.
3351                          */
3352                         unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3353 
3354                         /* Here are how the values map:
3355                          *
3356                          * 0x00 .. 0x3f -> 0
3357                          * 0x40 .. 0xbf -> 1
3358                          * 0xc0 .. 0xff -> 2
3359                          *
3360                          * So, as above with the explicit alpha checks, the
3361                          * breakpoints are at 64 and 196.
3362                          */
3363                         if (inrow[0] & 0x80) back_i += 9; /* red */
3364                         if (inrow[0] & 0x40) back_i += 9;
3365                         if (inrow[0] & 0x80) back_i += 3; /* green */
3366                         if (inrow[0] & 0x40) back_i += 3;
3367                         if (inrow[0] & 0x80) back_i += 1; /* blue */
3368                         if (inrow[0] & 0x40) back_i += 1;
3369 
3370                         *outrow = (png_byte)back_i;
3371                      }
3372 
3373                      inrow += 4;
3374                   }
3375                   break;
3376 
3377                default:
3378                   break;
3379             }
3380          }
3381       }
3382    }
3383 
3384    return 1;
3385 }
3386 
3387 static int
png_image_read_colormapped(png_voidp argument)3388 png_image_read_colormapped(png_voidp argument)
3389 {
3390    png_image_read_control *display = png_voidcast(png_image_read_control*,
3391        argument);
3392    png_imagep image = display->image;
3393    png_controlp control = image->opaque;
3394    png_structrp png_ptr = control->png_ptr;
3395    png_inforp info_ptr = control->info_ptr;
3396 
3397    int passes = 0; /* As a flag */
3398 
3399    PNG_SKIP_CHUNKS(png_ptr);
3400 
3401    /* Update the 'info' structure and make sure the result is as required; first
3402     * make sure to turn on the interlace handling if it will be required
3403     * (because it can't be turned on *after* the call to png_read_update_info!)
3404     */
3405    if (display->colormap_processing == PNG_CMAP_NONE)
3406       passes = png_set_interlace_handling(png_ptr);
3407 
3408    png_read_update_info(png_ptr, info_ptr);
3409 
3410    /* The expected output can be deduced from the colormap_processing option. */
3411    switch (display->colormap_processing)
3412    {
3413       case PNG_CMAP_NONE:
3414          /* Output must be one channel and one byte per pixel, the output
3415           * encoding can be anything.
3416           */
3417          if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3418             info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3419             info_ptr->bit_depth == 8)
3420             break;
3421 
3422          goto bad_output;
3423 
3424       case PNG_CMAP_TRANS:
3425       case PNG_CMAP_GA:
3426          /* Output must be two channels and the 'G' one must be sRGB, the latter
3427           * can be checked with an exact number because it should have been set
3428           * to this number above!
3429           */
3430          if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3431             info_ptr->bit_depth == 8 &&
3432             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3433             image->colormap_entries == 256)
3434             break;
3435 
3436          goto bad_output;
3437 
3438       case PNG_CMAP_RGB:
3439          /* Output must be 8-bit sRGB encoded RGB */
3440          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3441             info_ptr->bit_depth == 8 &&
3442             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3443             image->colormap_entries == 216)
3444             break;
3445 
3446          goto bad_output;
3447 
3448       case PNG_CMAP_RGB_ALPHA:
3449          /* Output must be 8-bit sRGB encoded RGBA */
3450          if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3451             info_ptr->bit_depth == 8 &&
3452             png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3453             image->colormap_entries == 244 /* 216 + 1 + 27 */)
3454             break;
3455 
3456          goto bad_output;
3457 
3458       default:
3459       bad_output:
3460          png_error(png_ptr, "bad color-map processing (internal error)");
3461    }
3462 
3463    /* Now read the rows.  Do this here if it is possible to read directly into
3464     * the output buffer, otherwise allocate a local row buffer of the maximum
3465     * size libpng requires and call the relevant processing routine safely.
3466     */
3467    {
3468       png_voidp first_row = display->buffer;
3469       ptrdiff_t row_bytes = display->row_stride;
3470 
3471       /* The following expression is designed to work correctly whether it gives
3472        * a signed or an unsigned result.
3473        */
3474       if (row_bytes < 0)
3475       {
3476          char *ptr = png_voidcast(char*, first_row);
3477          ptr += (image->height-1) * (-row_bytes);
3478          first_row = png_voidcast(png_voidp, ptr);
3479       }
3480 
3481       display->first_row = first_row;
3482       display->row_bytes = row_bytes;
3483    }
3484 
3485    if (passes == 0)
3486    {
3487       int result;
3488       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3489 
3490       display->local_row = row;
3491       result = png_safe_execute(image, png_image_read_and_map, display);
3492       display->local_row = NULL;
3493       png_free(png_ptr, row);
3494 
3495       return result;
3496    }
3497 
3498    else
3499    {
3500       png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
3501 
3502       while (--passes >= 0)
3503       {
3504          png_uint_32      y = image->height;
3505          png_bytep        row = png_voidcast(png_bytep, display->first_row);
3506 
3507          for (; y > 0; --y)
3508          {
3509             png_read_row(png_ptr, row, NULL);
3510             row += row_bytes;
3511          }
3512       }
3513 
3514       return 1;
3515    }
3516 }
3517 
3518 /* Just the row reading part of png_image_read. */
3519 static int
png_image_read_composite(png_voidp argument)3520 png_image_read_composite(png_voidp argument)
3521 {
3522    png_image_read_control *display = png_voidcast(png_image_read_control*,
3523        argument);
3524    png_imagep image = display->image;
3525    png_structrp png_ptr = image->opaque->png_ptr;
3526    int passes;
3527 
3528    switch (png_ptr->interlaced)
3529    {
3530       case PNG_INTERLACE_NONE:
3531          passes = 1;
3532          break;
3533 
3534       case PNG_INTERLACE_ADAM7:
3535          passes = PNG_INTERLACE_ADAM7_PASSES;
3536          break;
3537 
3538       default:
3539          png_error(png_ptr, "unknown interlace type");
3540    }
3541 
3542    {
3543       png_uint_32  height = image->height;
3544       png_uint_32  width = image->width;
3545       ptrdiff_t    step_row = display->row_bytes;
3546       unsigned int channels =
3547           (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
3548       int pass;
3549 
3550       for (pass = 0; pass < passes; ++pass)
3551       {
3552          unsigned int     startx, stepx, stepy;
3553          png_uint_32      y;
3554 
3555          if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3556          {
3557             /* The row may be empty for a short image: */
3558             if (PNG_PASS_COLS(width, pass) == 0)
3559                continue;
3560 
3561             startx = PNG_PASS_START_COL(pass) * channels;
3562             stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3563             y = PNG_PASS_START_ROW(pass);
3564             stepy = PNG_PASS_ROW_OFFSET(pass);
3565          }
3566 
3567          else
3568          {
3569             y = 0;
3570             startx = 0;
3571             stepx = channels;
3572             stepy = 1;
3573          }
3574 
3575          for (; y<height; y += stepy)
3576          {
3577             png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3578             png_bytep outrow;
3579             png_const_bytep end_row;
3580 
3581             /* Read the row, which is packed: */
3582             png_read_row(png_ptr, inrow, NULL);
3583 
3584             outrow = png_voidcast(png_bytep, display->first_row);
3585             outrow += y * step_row;
3586             end_row = outrow + width * channels;
3587 
3588             /* Now do the composition on each pixel in this row. */
3589             outrow += startx;
3590             for (; outrow < end_row; outrow += stepx)
3591             {
3592                png_byte alpha = inrow[channels];
3593 
3594                if (alpha > 0) /* else no change to the output */
3595                {
3596                   unsigned int c;
3597 
3598                   for (c=0; c<channels; ++c)
3599                   {
3600                      png_uint_32 component = inrow[c];
3601 
3602                      if (alpha < 255) /* else just use component */
3603                      {
3604                         /* This is PNG_OPTIMIZED_ALPHA, the component value
3605                          * is a linear 8-bit value.  Combine this with the
3606                          * current outrow[c] value which is sRGB encoded.
3607                          * Arithmetic here is 16-bits to preserve the output
3608                          * values correctly.
3609                          */
3610                         component *= 257*255; /* =65535 */
3611                         component += (255-alpha)*png_sRGB_table[outrow[c]];
3612 
3613                         /* So 'component' is scaled by 255*65535 and is
3614                          * therefore appropriate for the sRGB to linear
3615                          * conversion table.
3616                          */
3617                         component = PNG_sRGB_FROM_LINEAR(component);
3618                      }
3619 
3620                      outrow[c] = (png_byte)component;
3621                   }
3622                }
3623 
3624                inrow += channels+1; /* components and alpha channel */
3625             }
3626          }
3627       }
3628    }
3629 
3630    return 1;
3631 }
3632 
3633 /* The do_local_background case; called when all the following transforms are to
3634  * be done:
3635  *
3636  * PNG_RGB_TO_GRAY
3637  * PNG_COMPOSITE
3638  * PNG_GAMMA
3639  *
3640  * This is a work-around for the fact that both the PNG_RGB_TO_GRAY and
3641  * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3642  * correction.  The fix-up is to prevent the PNG_COMPOSITE operation from
3643  * happening inside libpng, so this routine sees an 8 or 16-bit gray+alpha
3644  * row and handles the removal or pre-multiplication of the alpha channel.
3645  */
3646 static int
png_image_read_background(png_voidp argument)3647 png_image_read_background(png_voidp argument)
3648 {
3649    png_image_read_control *display = png_voidcast(png_image_read_control*,
3650        argument);
3651    png_imagep image = display->image;
3652    png_structrp png_ptr = image->opaque->png_ptr;
3653    png_inforp info_ptr = image->opaque->info_ptr;
3654    png_uint_32 height = image->height;
3655    png_uint_32 width = image->width;
3656    int pass, passes;
3657 
3658    /* Double check the convoluted logic below.  We expect to get here with
3659     * libpng doing rgb to gray and gamma correction but background processing
3660     * left to the png_image_read_background function.  The rows libpng produce
3661     * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3662     */
3663    if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3664       png_error(png_ptr, "lost rgb to gray");
3665 
3666    if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3667       png_error(png_ptr, "unexpected compose");
3668 
3669    if (png_get_channels(png_ptr, info_ptr) != 2)
3670       png_error(png_ptr, "lost/gained channels");
3671 
3672    /* Expect the 8-bit case to always remove the alpha channel */
3673    if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3674       (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3675       png_error(png_ptr, "unexpected 8-bit transformation");
3676 
3677    switch (png_ptr->interlaced)
3678    {
3679       case PNG_INTERLACE_NONE:
3680          passes = 1;
3681          break;
3682 
3683       case PNG_INTERLACE_ADAM7:
3684          passes = PNG_INTERLACE_ADAM7_PASSES;
3685          break;
3686 
3687       default:
3688          png_error(png_ptr, "unknown interlace type");
3689    }
3690 
3691    /* Use direct access to info_ptr here because otherwise the simplified API
3692     * would require PNG_EASY_ACCESS_SUPPORTED (just for this.)  Note this is
3693     * checking the value after libpng expansions, not the original value in the
3694     * PNG.
3695     */
3696    switch (info_ptr->bit_depth)
3697    {
3698       case 8:
3699          /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3700           * to be removed by composing on a background: either the row if
3701           * display->background is NULL or display->background->green if not.
3702           * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3703           */
3704          {
3705             png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3706             ptrdiff_t step_row = display->row_bytes;
3707 
3708             for (pass = 0; pass < passes; ++pass)
3709             {
3710                png_bytep row = png_voidcast(png_bytep, display->first_row);
3711                unsigned int     startx, stepx, stepy;
3712                png_uint_32      y;
3713 
3714                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3715                {
3716                   /* The row may be empty for a short image: */
3717                   if (PNG_PASS_COLS(width, pass) == 0)
3718                      continue;
3719 
3720                   startx = PNG_PASS_START_COL(pass);
3721                   stepx = PNG_PASS_COL_OFFSET(pass);
3722                   y = PNG_PASS_START_ROW(pass);
3723                   stepy = PNG_PASS_ROW_OFFSET(pass);
3724                }
3725 
3726                else
3727                {
3728                   y = 0;
3729                   startx = 0;
3730                   stepx = stepy = 1;
3731                }
3732 
3733                if (display->background == NULL)
3734                {
3735                   for (; y<height; y += stepy)
3736                   {
3737                      png_bytep inrow = png_voidcast(png_bytep,
3738                          display->local_row);
3739                      png_bytep outrow = first_row + y * step_row;
3740                      png_const_bytep end_row = outrow + width;
3741 
3742                      /* Read the row, which is packed: */
3743                      png_read_row(png_ptr, inrow, NULL);
3744 
3745                      /* Now do the composition on each pixel in this row. */
3746                      outrow += startx;
3747                      for (; outrow < end_row; outrow += stepx)
3748                      {
3749                         png_byte alpha = inrow[1];
3750 
3751                         if (alpha > 0) /* else no change to the output */
3752                         {
3753                            png_uint_32 component = inrow[0];
3754 
3755                            if (alpha < 255) /* else just use component */
3756                            {
3757                               /* Since PNG_OPTIMIZED_ALPHA was not set it is
3758                                * necessary to invert the sRGB transfer
3759                                * function and multiply the alpha out.
3760                                */
3761                               component = png_sRGB_table[component] * alpha;
3762                               component += png_sRGB_table[outrow[0]] *
3763                                  (255-alpha);
3764                               component = PNG_sRGB_FROM_LINEAR(component);
3765                            }
3766 
3767                            outrow[0] = (png_byte)component;
3768                         }
3769 
3770                         inrow += 2; /* gray and alpha channel */
3771                      }
3772                   }
3773                }
3774 
3775                else /* constant background value */
3776                {
3777                   png_byte background8 = display->background->green;
3778                   png_uint_16 background = png_sRGB_table[background8];
3779 
3780                   for (; y<height; y += stepy)
3781                   {
3782                      png_bytep inrow = png_voidcast(png_bytep,
3783                          display->local_row);
3784                      png_bytep outrow = first_row + y * step_row;
3785                      png_const_bytep end_row = outrow + width;
3786 
3787                      /* Read the row, which is packed: */
3788                      png_read_row(png_ptr, inrow, NULL);
3789 
3790                      /* Now do the composition on each pixel in this row. */
3791                      outrow += startx;
3792                      for (; outrow < end_row; outrow += stepx)
3793                      {
3794                         png_byte alpha = inrow[1];
3795 
3796                         if (alpha > 0) /* else use background */
3797                         {
3798                            png_uint_32 component = inrow[0];
3799 
3800                            if (alpha < 255) /* else just use component */
3801                            {
3802                               component = png_sRGB_table[component] * alpha;
3803                               component += background * (255-alpha);
3804                               component = PNG_sRGB_FROM_LINEAR(component);
3805                            }
3806 
3807                            outrow[0] = (png_byte)component;
3808                         }
3809 
3810                         else
3811                            outrow[0] = background8;
3812 
3813                         inrow += 2; /* gray and alpha channel */
3814                      }
3815 
3816                      row += display->row_bytes;
3817                   }
3818                }
3819             }
3820          }
3821          break;
3822 
3823       case 16:
3824          /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3825           * still be done and, maybe, the alpha channel removed.  This code also
3826           * handles the alpha-first option.
3827           */
3828          {
3829             png_uint_16p first_row = png_voidcast(png_uint_16p,
3830                 display->first_row);
3831             /* The division by two is safe because the caller passed in a
3832              * stride which was multiplied by 2 (below) to get row_bytes.
3833              */
3834             ptrdiff_t    step_row = display->row_bytes / 2;
3835             unsigned int preserve_alpha = (image->format &
3836                 PNG_FORMAT_FLAG_ALPHA) != 0;
3837             unsigned int outchannels = 1U+preserve_alpha;
3838             int swap_alpha = 0;
3839 
3840 #           ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3841                if (preserve_alpha != 0 &&
3842                    (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3843                   swap_alpha = 1;
3844 #           endif
3845 
3846             for (pass = 0; pass < passes; ++pass)
3847             {
3848                unsigned int     startx, stepx, stepy;
3849                png_uint_32      y;
3850 
3851                /* The 'x' start and step are adjusted to output components here.
3852                 */
3853                if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3854                {
3855                   /* The row may be empty for a short image: */
3856                   if (PNG_PASS_COLS(width, pass) == 0)
3857                      continue;
3858 
3859                   startx = PNG_PASS_START_COL(pass) * outchannels;
3860                   stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3861                   y = PNG_PASS_START_ROW(pass);
3862                   stepy = PNG_PASS_ROW_OFFSET(pass);
3863                }
3864 
3865                else
3866                {
3867                   y = 0;
3868                   startx = 0;
3869                   stepx = outchannels;
3870                   stepy = 1;
3871                }
3872 
3873                for (; y<height; y += stepy)
3874                {
3875                   png_const_uint_16p inrow;
3876                   png_uint_16p outrow = first_row + y*step_row;
3877                   png_uint_16p end_row = outrow + width * outchannels;
3878 
3879                   /* Read the row, which is packed: */
3880                   png_read_row(png_ptr, png_voidcast(png_bytep,
3881                       display->local_row), NULL);
3882                   inrow = png_voidcast(png_const_uint_16p, display->local_row);
3883 
3884                   /* Now do the pre-multiplication on each pixel in this row.
3885                    */
3886                   outrow += startx;
3887                   for (; outrow < end_row; outrow += stepx)
3888                   {
3889                      png_uint_32 component = inrow[0];
3890                      png_uint_16 alpha = inrow[1];
3891 
3892                      if (alpha > 0) /* else 0 */
3893                      {
3894                         if (alpha < 65535) /* else just use component */
3895                         {
3896                            component *= alpha;
3897                            component += 32767;
3898                            component /= 65535;
3899                         }
3900                      }
3901 
3902                      else
3903                         component = 0;
3904 
3905                      outrow[swap_alpha] = (png_uint_16)component;
3906                      if (preserve_alpha != 0)
3907                         outrow[1 ^ swap_alpha] = alpha;
3908 
3909                      inrow += 2; /* components and alpha channel */
3910                   }
3911                }
3912             }
3913          }
3914          break;
3915 
3916 #ifdef __GNUC__
3917       default:
3918          png_error(png_ptr, "unexpected bit depth");
3919 #endif
3920    }
3921 
3922    return 1;
3923 }
3924 
3925 /* The guts of png_image_finish_read as a png_safe_execute callback. */
3926 static int
png_image_read_direct(png_voidp argument)3927 png_image_read_direct(png_voidp argument)
3928 {
3929    png_image_read_control *display = png_voidcast(png_image_read_control*,
3930        argument);
3931    png_imagep image = display->image;
3932    png_structrp png_ptr = image->opaque->png_ptr;
3933    png_inforp info_ptr = image->opaque->info_ptr;
3934 
3935    png_uint_32 format = image->format;
3936    int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3937    int do_local_compose = 0;
3938    int do_local_background = 0; /* to avoid double gamma correction bug */
3939    int passes = 0;
3940 
3941    /* Add transforms to ensure the correct output format is produced then check
3942     * that the required implementation support is there.  Always expand; always
3943     * need 8 bits minimum, no palette and expanded tRNS.
3944     */
3945    png_set_expand(png_ptr);
3946 
3947    /* Now check the format to see if it was modified. */
3948    {
3949       png_uint_32 base_format = png_image_format(png_ptr) &
3950          ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3951       png_uint_32 change = format ^ base_format;
3952       png_fixed_point output_gamma;
3953       int mode; /* alpha mode */
3954 
3955       /* Do this first so that we have a record if rgb to gray is happening. */
3956       if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3957       {
3958          /* gray<->color transformation required. */
3959          if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3960             png_set_gray_to_rgb(png_ptr);
3961 
3962          else
3963          {
3964             /* libpng can't do both rgb to gray and
3965              * background/pre-multiplication if there is also significant gamma
3966              * correction, because both operations require linear colors and
3967              * the code only supports one transform doing the gamma correction.
3968              * Handle this by doing the pre-multiplication or background
3969              * operation in this code, if necessary.
3970              *
3971              * TODO: fix this by rewriting pngrtran.c (!)
3972              *
3973              * For the moment (given that fixing this in pngrtran.c is an
3974              * enormous change) 'do_local_background' is used to indicate that
3975              * the problem exists.
3976              */
3977             if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3978                do_local_background = 1/*maybe*/;
3979 
3980             png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3981                 PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3982          }
3983 
3984          change &= ~PNG_FORMAT_FLAG_COLOR;
3985       }
3986 
3987       /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3988        */
3989       {
3990          png_fixed_point input_gamma_default;
3991 
3992          if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3993              (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3994             input_gamma_default = PNG_GAMMA_LINEAR;
3995          else
3996             input_gamma_default = PNG_DEFAULT_sRGB;
3997 
3998          /* Call png_set_alpha_mode to set the default for the input gamma; the
3999           * output gamma is set by a second call below.
4000           */
4001          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
4002       }
4003 
4004       if (linear != 0)
4005       {
4006          /* If there *is* an alpha channel in the input it must be multiplied
4007           * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
4008           */
4009          if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
4010             mode = PNG_ALPHA_STANDARD; /* associated alpha */
4011 
4012          else
4013             mode = PNG_ALPHA_PNG;
4014 
4015          output_gamma = PNG_GAMMA_LINEAR;
4016       }
4017 
4018       else
4019       {
4020          mode = PNG_ALPHA_PNG;
4021          output_gamma = PNG_DEFAULT_sRGB;
4022       }
4023 
4024       if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0)
4025       {
4026          mode = PNG_ALPHA_OPTIMIZED;
4027          change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
4028       }
4029 
4030       /* If 'do_local_background' is set check for the presence of gamma
4031        * correction; this is part of the work-round for the libpng bug
4032        * described above.
4033        *
4034        * TODO: fix libpng and remove this.
4035        */
4036       if (do_local_background != 0)
4037       {
4038          png_fixed_point gtest;
4039 
4040          /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
4041           * gamma correction, the screen gamma hasn't been set on png_struct
4042           * yet; it's set below.  png_struct::gamma, however, is set to the
4043           * final value.
4044           */
4045          if (png_muldiv(&gtest, output_gamma, png_ptr->colorspace.gamma,
4046              PNG_FP_1) != 0 && png_gamma_significant(gtest) == 0)
4047             do_local_background = 0;
4048 
4049          else if (mode == PNG_ALPHA_STANDARD)
4050          {
4051             do_local_background = 2/*required*/;
4052             mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
4053          }
4054 
4055          /* else leave as 1 for the checks below */
4056       }
4057 
4058       /* If the bit-depth changes then handle that here. */
4059       if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
4060       {
4061          if (linear != 0 /*16-bit output*/)
4062             png_set_expand_16(png_ptr);
4063 
4064          else /* 8-bit output */
4065             png_set_scale_16(png_ptr);
4066 
4067          change &= ~PNG_FORMAT_FLAG_LINEAR;
4068       }
4069 
4070       /* Now the background/alpha channel changes. */
4071       if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
4072       {
4073          /* Removing an alpha channel requires composition for the 8-bit
4074           * formats; for the 16-bit it is already done, above, by the
4075           * pre-multiplication and the channel just needs to be stripped.
4076           */
4077          if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
4078          {
4079             /* If RGB->gray is happening the alpha channel must be left and the
4080              * operation completed locally.
4081              *
4082              * TODO: fix libpng and remove this.
4083              */
4084             if (do_local_background != 0)
4085                do_local_background = 2/*required*/;
4086 
4087             /* 16-bit output: just remove the channel */
4088             else if (linear != 0) /* compose on black (well, pre-multiply) */
4089                png_set_strip_alpha(png_ptr);
4090 
4091             /* 8-bit output: do an appropriate compose */
4092             else if (display->background != NULL)
4093             {
4094                png_color_16 c;
4095 
4096                c.index = 0; /*unused*/
4097                c.red = display->background->red;
4098                c.green = display->background->green;
4099                c.blue = display->background->blue;
4100                c.gray = display->background->green;
4101 
4102                /* This is always an 8-bit sRGB value, using the 'green' channel
4103                 * for gray is much better than calculating the luminance here;
4104                 * we can get off-by-one errors in that calculation relative to
4105                 * the app expectations and that will show up in transparent
4106                 * pixels.
4107                 */
4108                png_set_background_fixed(png_ptr, &c,
4109                    PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
4110                    0/*gamma: not used*/);
4111             }
4112 
4113             else /* compose on row: implemented below. */
4114             {
4115                do_local_compose = 1;
4116                /* This leaves the alpha channel in the output, so it has to be
4117                 * removed by the code below.  Set the encoding to the 'OPTIMIZE'
4118                 * one so the code only has to hack on the pixels that require
4119                 * composition.
4120                 */
4121                mode = PNG_ALPHA_OPTIMIZED;
4122             }
4123          }
4124 
4125          else /* output needs an alpha channel */
4126          {
4127             /* This is tricky because it happens before the swap operation has
4128              * been accomplished; however, the swap does *not* swap the added
4129              * alpha channel (weird API), so it must be added in the correct
4130              * place.
4131              */
4132             png_uint_32 filler; /* opaque filler */
4133             int where;
4134 
4135             if (linear != 0)
4136                filler = 65535;
4137 
4138             else
4139                filler = 255;
4140 
4141 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4142             if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4143             {
4144                where = PNG_FILLER_BEFORE;
4145                change &= ~PNG_FORMAT_FLAG_AFIRST;
4146             }
4147 
4148             else
4149 #endif
4150             where = PNG_FILLER_AFTER;
4151 
4152             png_set_add_alpha(png_ptr, filler, where);
4153          }
4154 
4155          /* This stops the (irrelevant) call to swap_alpha below. */
4156          change &= ~PNG_FORMAT_FLAG_ALPHA;
4157       }
4158 
4159       /* Now set the alpha mode correctly; this is always done, even if there is
4160        * no alpha channel in either the input or the output because it correctly
4161        * sets the output gamma.
4162        */
4163       png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
4164 
4165 #     ifdef PNG_FORMAT_BGR_SUPPORTED
4166          if ((change & PNG_FORMAT_FLAG_BGR) != 0)
4167          {
4168             /* Check only the output format; PNG is never BGR; don't do this if
4169              * the output is gray, but fix up the 'format' value in that case.
4170              */
4171             if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
4172                png_set_bgr(png_ptr);
4173 
4174             else
4175                format &= ~PNG_FORMAT_FLAG_BGR;
4176 
4177             change &= ~PNG_FORMAT_FLAG_BGR;
4178          }
4179 #     endif
4180 
4181 #     ifdef PNG_FORMAT_AFIRST_SUPPORTED
4182          if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
4183          {
4184             /* Only relevant if there is an alpha channel - it's particularly
4185              * important to handle this correctly because do_local_compose may
4186              * be set above and then libpng will keep the alpha channel for this
4187              * code to remove.
4188              */
4189             if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
4190             {
4191                /* Disable this if doing a local background,
4192                 * TODO: remove this when local background is no longer required.
4193                 */
4194                if (do_local_background != 2)
4195                   png_set_swap_alpha(png_ptr);
4196             }
4197 
4198             else
4199                format &= ~PNG_FORMAT_FLAG_AFIRST;
4200 
4201             change &= ~PNG_FORMAT_FLAG_AFIRST;
4202          }
4203 #     endif
4204 
4205       /* If the *output* is 16-bit then we need to check for a byte-swap on this
4206        * architecture.
4207        */
4208       if (linear != 0)
4209       {
4210          png_uint_16 le = 0x0001;
4211 
4212          if ((*(png_const_bytep) & le) != 0)
4213             png_set_swap(png_ptr);
4214       }
4215 
4216       /* If change is not now 0 some transformation is missing - error out. */
4217       if (change != 0)
4218          png_error(png_ptr, "png_read_image: unsupported transformation");
4219    }
4220 
4221    PNG_SKIP_CHUNKS(png_ptr);
4222 
4223    /* Update the 'info' structure and make sure the result is as required; first
4224     * make sure to turn on the interlace handling if it will be required
4225     * (because it can't be turned on *after* the call to png_read_update_info!)
4226     *
4227     * TODO: remove the do_local_background fixup below.
4228     */
4229    if (do_local_compose == 0 && do_local_background != 2)
4230       passes = png_set_interlace_handling(png_ptr);
4231 
4232    png_read_update_info(png_ptr, info_ptr);
4233 
4234    {
4235       png_uint_32 info_format = 0;
4236 
4237       if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
4238          info_format |= PNG_FORMAT_FLAG_COLOR;
4239 
4240       if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
4241       {
4242          /* do_local_compose removes this channel below. */
4243          if (do_local_compose == 0)
4244          {
4245             /* do_local_background does the same if required. */
4246             if (do_local_background != 2 ||
4247                (format & PNG_FORMAT_FLAG_ALPHA) != 0)
4248                info_format |= PNG_FORMAT_FLAG_ALPHA;
4249          }
4250       }
4251 
4252       else if (do_local_compose != 0) /* internal error */
4253          png_error(png_ptr, "png_image_read: alpha channel lost");
4254 
4255       if ((format & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) {
4256          info_format |= PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
4257       }
4258 
4259       if (info_ptr->bit_depth == 16)
4260          info_format |= PNG_FORMAT_FLAG_LINEAR;
4261 
4262 #ifdef PNG_FORMAT_BGR_SUPPORTED
4263       if ((png_ptr->transformations & PNG_BGR) != 0)
4264          info_format |= PNG_FORMAT_FLAG_BGR;
4265 #endif
4266 
4267 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4268          if (do_local_background == 2)
4269          {
4270             if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4271                info_format |= PNG_FORMAT_FLAG_AFIRST;
4272          }
4273 
4274          if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
4275             ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
4276             (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
4277          {
4278             if (do_local_background == 2)
4279                png_error(png_ptr, "unexpected alpha swap transformation");
4280 
4281             info_format |= PNG_FORMAT_FLAG_AFIRST;
4282          }
4283 #     endif
4284 
4285       /* This is actually an internal error. */
4286       if (info_format != format)
4287          png_error(png_ptr, "png_read_image: invalid transformations");
4288    }
4289 
4290    /* Now read the rows.  If do_local_compose is set then it is necessary to use
4291     * a local row buffer.  The output will be GA, RGBA or BGRA and must be
4292     * converted to G, RGB or BGR as appropriate.  The 'local_row' member of the
4293     * display acts as a flag.
4294     */
4295    {
4296       png_voidp first_row = display->buffer;
4297       ptrdiff_t row_bytes = display->row_stride;
4298 
4299       if (linear != 0)
4300          row_bytes *= 2;
4301 
4302       /* The following expression is designed to work correctly whether it gives
4303        * a signed or an unsigned result.
4304        */
4305       if (row_bytes < 0)
4306       {
4307          char *ptr = png_voidcast(char*, first_row);
4308          ptr += (image->height-1) * (-row_bytes);
4309          first_row = png_voidcast(png_voidp, ptr);
4310       }
4311 
4312       display->first_row = first_row;
4313       display->row_bytes = row_bytes;
4314    }
4315 
4316    if (do_local_compose != 0)
4317    {
4318       int result;
4319       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4320 
4321       display->local_row = row;
4322       result = png_safe_execute(image, png_image_read_composite, display);
4323       display->local_row = NULL;
4324       png_free(png_ptr, row);
4325 
4326       return result;
4327    }
4328 
4329    else if (do_local_background == 2)
4330    {
4331       int result;
4332       png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4333 
4334       display->local_row = row;
4335       result = png_safe_execute(image, png_image_read_background, display);
4336       display->local_row = NULL;
4337       png_free(png_ptr, row);
4338 
4339       return result;
4340    }
4341 
4342    else
4343    {
4344       png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
4345 
4346       while (--passes >= 0)
4347       {
4348          png_uint_32      y = image->height;
4349          png_bytep        row = png_voidcast(png_bytep, display->first_row);
4350 
4351          for (; y > 0; --y)
4352          {
4353             png_read_row(png_ptr, row, NULL);
4354             row += row_bytes;
4355          }
4356       }
4357 
4358       return 1;
4359    }
4360 }
4361 
4362 int PNGAPI
png_image_finish_read(png_imagep image,png_const_colorp background,void * buffer,png_int_32 row_stride,void * colormap)4363 png_image_finish_read(png_imagep image, png_const_colorp background,
4364     void *buffer, png_int_32 row_stride, void *colormap)
4365 {
4366    if (image != NULL && image->version == PNG_IMAGE_VERSION)
4367    {
4368       /* Check for row_stride overflow.  This check is not performed on the
4369        * original PNG format because it may not occur in the output PNG format
4370        * and libpng deals with the issues of reading the original.
4371        */
4372       unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
4373 
4374       /* The following checks just the 'row_stride' calculation to ensure it
4375        * fits in a signed 32-bit value.  Because channels/components can be
4376        * either 1 or 2 bytes in size the length of a row can still overflow 32
4377        * bits; this is just to verify that the 'row_stride' argument can be
4378        * represented.
4379        */
4380       if (image->width <= 0x7fffffffU/channels) /* no overflow */
4381       {
4382          png_uint_32 check;
4383          png_uint_32 png_row_stride = image->width * channels;
4384 
4385          if (row_stride == 0)
4386             row_stride = (png_int_32)/*SAFE*/png_row_stride;
4387 
4388          if (row_stride < 0)
4389             check = (png_uint_32)(-row_stride);
4390 
4391          else
4392             check = (png_uint_32)row_stride;
4393 
4394          /* This verifies 'check', the absolute value of the actual stride
4395           * passed in and detects overflow in the application calculation (i.e.
4396           * if the app did actually pass in a non-zero 'row_stride'.
4397           */
4398          if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4399          {
4400             /* Now check for overflow of the image buffer calculation; this
4401              * limits the whole image size to 32 bits for API compatibility with
4402              * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
4403              *
4404              * The PNG_IMAGE_BUFFER_SIZE macro is:
4405              *
4406              *    (PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)*height*(row_stride))
4407              *
4408              * And the component size is always 1 or 2, so make sure that the
4409              * number of *bytes* that the application is saying are available
4410              * does actually fit into a 32-bit number.
4411              *
4412              * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
4413              * will be changed to use png_alloc_size_t; bigger images can be
4414              * accommodated on 64-bit systems.
4415              */
4416             if (image->height <=
4417                 0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4418             {
4419                if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4420                   (image->colormap_entries > 0 && colormap != NULL))
4421                {
4422                   int result;
4423                   png_image_read_control display;
4424 
4425                   memset(&display, 0, (sizeof display));
4426                   display.image = image;
4427                   display.buffer = buffer;
4428                   display.row_stride = row_stride;
4429                   display.colormap = colormap;
4430                   display.background = background;
4431                   display.local_row = NULL;
4432 
4433                   /* Choose the correct 'end' routine; for the color-map case
4434                    * all the setup has already been done.
4435                    */
4436                   if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4437                      result =
4438                          png_safe_execute(image,
4439                              png_image_read_colormap, &display) &&
4440                              png_safe_execute(image,
4441                              png_image_read_colormapped, &display);
4442 
4443                   else
4444                      result =
4445                         png_safe_execute(image,
4446                             png_image_read_direct, &display);
4447 
4448                   png_image_free(image);
4449                   return result;
4450                }
4451 
4452                else
4453                   return png_image_error(image,
4454                       "png_image_finish_read[color-map]: no color-map");
4455             }
4456 
4457             else
4458                return png_image_error(image,
4459                    "png_image_finish_read: image too large");
4460          }
4461 
4462          else
4463             return png_image_error(image,
4464                 "png_image_finish_read: invalid argument");
4465       }
4466 
4467       else
4468          return png_image_error(image,
4469              "png_image_finish_read: row_stride too large");
4470    }
4471 
4472    else if (image != NULL)
4473       return png_image_error(image,
4474           "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4475 
4476    return 0;
4477 }
4478 
4479 #endif /* SIMPLIFIED_READ */
4480 #endif /* READ */
4481