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