(root)/
libpng-1.6.40/
pngset.c
       1  
       2  /* pngset.c - storage of image information into info struct
       3   *
       4   * Copyright (c) 2018-2023 Cosmin Truta
       5   * Copyright (c) 1998-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   * The functions here are used during reads to store data from the file
      14   * into the info struct, and during writes to store application data
      15   * into the info struct for writing into the file.  This abstracts the
      16   * info struct and allows us to change the structure in the future.
      17   */
      18  
      19  #include "pngpriv.h"
      20  
      21  #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
      22  
      23  #ifdef PNG_bKGD_SUPPORTED
      24  void PNGAPI
      25  png_set_bKGD(png_const_structrp png_ptr, png_inforp info_ptr,
      26      png_const_color_16p background)
      27  {
      28     png_debug1(1, "in %s storage function", "bKGD");
      29  
      30     if (png_ptr == NULL || info_ptr == NULL || background == NULL)
      31        return;
      32  
      33     info_ptr->background = *background;
      34     info_ptr->valid |= PNG_INFO_bKGD;
      35  }
      36  #endif
      37  
      38  #ifdef PNG_cHRM_SUPPORTED
      39  void PNGFAPI
      40  png_set_cHRM_fixed(png_const_structrp png_ptr, png_inforp info_ptr,
      41      png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
      42      png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
      43      png_fixed_point blue_x, png_fixed_point blue_y)
      44  {
      45     png_xy xy;
      46  
      47     png_debug1(1, "in %s storage function", "cHRM fixed");
      48  
      49     if (png_ptr == NULL || info_ptr == NULL)
      50        return;
      51  
      52     xy.redx = red_x;
      53     xy.redy = red_y;
      54     xy.greenx = green_x;
      55     xy.greeny = green_y;
      56     xy.bluex = blue_x;
      57     xy.bluey = blue_y;
      58     xy.whitex = white_x;
      59     xy.whitey = white_y;
      60  
      61     if (png_colorspace_set_chromaticities(png_ptr, &info_ptr->colorspace, &xy,
      62         2/* override with app values*/) != 0)
      63        info_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
      64  
      65     png_colorspace_sync_info(png_ptr, info_ptr);
      66  }
      67  
      68  void PNGFAPI
      69  png_set_cHRM_XYZ_fixed(png_const_structrp png_ptr, png_inforp info_ptr,
      70      png_fixed_point int_red_X, png_fixed_point int_red_Y,
      71      png_fixed_point int_red_Z, png_fixed_point int_green_X,
      72      png_fixed_point int_green_Y, png_fixed_point int_green_Z,
      73      png_fixed_point int_blue_X, png_fixed_point int_blue_Y,
      74      png_fixed_point int_blue_Z)
      75  {
      76     png_XYZ XYZ;
      77  
      78     png_debug1(1, "in %s storage function", "cHRM XYZ fixed");
      79  
      80     if (png_ptr == NULL || info_ptr == NULL)
      81        return;
      82  
      83     XYZ.red_X = int_red_X;
      84     XYZ.red_Y = int_red_Y;
      85     XYZ.red_Z = int_red_Z;
      86     XYZ.green_X = int_green_X;
      87     XYZ.green_Y = int_green_Y;
      88     XYZ.green_Z = int_green_Z;
      89     XYZ.blue_X = int_blue_X;
      90     XYZ.blue_Y = int_blue_Y;
      91     XYZ.blue_Z = int_blue_Z;
      92  
      93     if (png_colorspace_set_endpoints(png_ptr, &info_ptr->colorspace,
      94         &XYZ, 2) != 0)
      95        info_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM;
      96  
      97     png_colorspace_sync_info(png_ptr, info_ptr);
      98  }
      99  
     100  #  ifdef PNG_FLOATING_POINT_SUPPORTED
     101  void PNGAPI
     102  png_set_cHRM(png_const_structrp png_ptr, png_inforp info_ptr,
     103      double white_x, double white_y, double red_x, double red_y,
     104      double green_x, double green_y, double blue_x, double blue_y)
     105  {
     106     png_set_cHRM_fixed(png_ptr, info_ptr,
     107         png_fixed(png_ptr, white_x, "cHRM White X"),
     108         png_fixed(png_ptr, white_y, "cHRM White Y"),
     109         png_fixed(png_ptr, red_x, "cHRM Red X"),
     110         png_fixed(png_ptr, red_y, "cHRM Red Y"),
     111         png_fixed(png_ptr, green_x, "cHRM Green X"),
     112         png_fixed(png_ptr, green_y, "cHRM Green Y"),
     113         png_fixed(png_ptr, blue_x, "cHRM Blue X"),
     114         png_fixed(png_ptr, blue_y, "cHRM Blue Y"));
     115  }
     116  
     117  void PNGAPI
     118  png_set_cHRM_XYZ(png_const_structrp png_ptr, png_inforp info_ptr, double red_X,
     119      double red_Y, double red_Z, double green_X, double green_Y, double green_Z,
     120      double blue_X, double blue_Y, double blue_Z)
     121  {
     122     png_set_cHRM_XYZ_fixed(png_ptr, info_ptr,
     123         png_fixed(png_ptr, red_X, "cHRM Red X"),
     124         png_fixed(png_ptr, red_Y, "cHRM Red Y"),
     125         png_fixed(png_ptr, red_Z, "cHRM Red Z"),
     126         png_fixed(png_ptr, green_X, "cHRM Green X"),
     127         png_fixed(png_ptr, green_Y, "cHRM Green Y"),
     128         png_fixed(png_ptr, green_Z, "cHRM Green Z"),
     129         png_fixed(png_ptr, blue_X, "cHRM Blue X"),
     130         png_fixed(png_ptr, blue_Y, "cHRM Blue Y"),
     131         png_fixed(png_ptr, blue_Z, "cHRM Blue Z"));
     132  }
     133  #  endif /* FLOATING_POINT */
     134  
     135  #endif /* cHRM */
     136  
     137  #ifdef PNG_eXIf_SUPPORTED
     138  void PNGAPI
     139  png_set_eXIf(png_const_structrp png_ptr, png_inforp info_ptr,
     140      png_bytep exif)
     141  {
     142    png_warning(png_ptr, "png_set_eXIf does not work; use png_set_eXIf_1");
     143    PNG_UNUSED(info_ptr)
     144    PNG_UNUSED(exif)
     145  }
     146  
     147  void PNGAPI
     148  png_set_eXIf_1(png_const_structrp png_ptr, png_inforp info_ptr,
     149      png_uint_32 num_exif, png_bytep exif)
     150  {
     151     png_bytep new_exif;
     152  
     153     png_debug1(1, "in %s storage function", "eXIf");
     154  
     155     if (png_ptr == NULL || info_ptr == NULL ||
     156         (png_ptr->mode & PNG_WROTE_eXIf) != 0)
     157        return;
     158  
     159     new_exif = png_voidcast(png_bytep, png_malloc_warn(png_ptr, num_exif));
     160  
     161     if (new_exif == NULL)
     162     {
     163        png_warning(png_ptr, "Insufficient memory for eXIf chunk data");
     164        return;
     165     }
     166  
     167     memcpy(new_exif, exif, (size_t)num_exif);
     168  
     169     png_free_data(png_ptr, info_ptr, PNG_FREE_EXIF, 0);
     170  
     171     info_ptr->num_exif = num_exif;
     172     info_ptr->exif = new_exif;
     173     info_ptr->free_me |= PNG_FREE_EXIF;
     174     info_ptr->valid |= PNG_INFO_eXIf;
     175  }
     176  #endif /* eXIf */
     177  
     178  #ifdef PNG_gAMA_SUPPORTED
     179  void PNGFAPI
     180  png_set_gAMA_fixed(png_const_structrp png_ptr, png_inforp info_ptr,
     181      png_fixed_point file_gamma)
     182  {
     183     png_debug1(1, "in %s storage function", "gAMA");
     184  
     185     if (png_ptr == NULL || info_ptr == NULL)
     186        return;
     187  
     188     png_colorspace_set_gamma(png_ptr, &info_ptr->colorspace, file_gamma);
     189     png_colorspace_sync_info(png_ptr, info_ptr);
     190  }
     191  
     192  #  ifdef PNG_FLOATING_POINT_SUPPORTED
     193  void PNGAPI
     194  png_set_gAMA(png_const_structrp png_ptr, png_inforp info_ptr, double file_gamma)
     195  {
     196     png_set_gAMA_fixed(png_ptr, info_ptr, png_fixed(png_ptr, file_gamma,
     197         "png_set_gAMA"));
     198  }
     199  #  endif
     200  #endif
     201  
     202  #ifdef PNG_hIST_SUPPORTED
     203  void PNGAPI
     204  png_set_hIST(png_const_structrp png_ptr, png_inforp info_ptr,
     205      png_const_uint_16p hist)
     206  {
     207     int i;
     208  
     209     png_debug1(1, "in %s storage function", "hIST");
     210  
     211     if (png_ptr == NULL || info_ptr == NULL)
     212        return;
     213  
     214     if (info_ptr->num_palette == 0 || info_ptr->num_palette
     215         > PNG_MAX_PALETTE_LENGTH)
     216     {
     217        png_warning(png_ptr,
     218            "Invalid palette size, hIST allocation skipped");
     219  
     220        return;
     221     }
     222  
     223     png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
     224  
     225     /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in
     226      * version 1.2.1
     227      */
     228     info_ptr->hist = png_voidcast(png_uint_16p, png_malloc_warn(png_ptr,
     229         PNG_MAX_PALETTE_LENGTH * (sizeof (png_uint_16))));
     230  
     231     if (info_ptr->hist == NULL)
     232     {
     233        png_warning(png_ptr, "Insufficient memory for hIST chunk data");
     234        return;
     235     }
     236  
     237     for (i = 0; i < info_ptr->num_palette; i++)
     238        info_ptr->hist[i] = hist[i];
     239  
     240     info_ptr->free_me |= PNG_FREE_HIST;
     241     info_ptr->valid |= PNG_INFO_hIST;
     242  }
     243  #endif
     244  
     245  void PNGAPI
     246  png_set_IHDR(png_const_structrp png_ptr, png_inforp info_ptr,
     247      png_uint_32 width, png_uint_32 height, int bit_depth,
     248      int color_type, int interlace_type, int compression_type,
     249      int filter_type)
     250  {
     251     png_debug1(1, "in %s storage function", "IHDR");
     252  
     253     if (png_ptr == NULL || info_ptr == NULL)
     254        return;
     255  
     256     info_ptr->width = width;
     257     info_ptr->height = height;
     258     info_ptr->bit_depth = (png_byte)bit_depth;
     259     info_ptr->color_type = (png_byte)color_type;
     260     info_ptr->compression_type = (png_byte)compression_type;
     261     info_ptr->filter_type = (png_byte)filter_type;
     262     info_ptr->interlace_type = (png_byte)interlace_type;
     263  
     264     png_check_IHDR (png_ptr, info_ptr->width, info_ptr->height,
     265         info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type,
     266         info_ptr->compression_type, info_ptr->filter_type);
     267  
     268     if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
     269        info_ptr->channels = 1;
     270  
     271     else if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
     272        info_ptr->channels = 3;
     273  
     274     else
     275        info_ptr->channels = 1;
     276  
     277     if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
     278        info_ptr->channels++;
     279  
     280     info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
     281  
     282     info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width);
     283  }
     284  
     285  #ifdef PNG_oFFs_SUPPORTED
     286  void PNGAPI
     287  png_set_oFFs(png_const_structrp png_ptr, png_inforp info_ptr,
     288      png_int_32 offset_x, png_int_32 offset_y, int unit_type)
     289  {
     290     png_debug1(1, "in %s storage function", "oFFs");
     291  
     292     if (png_ptr == NULL || info_ptr == NULL)
     293        return;
     294  
     295     info_ptr->x_offset = offset_x;
     296     info_ptr->y_offset = offset_y;
     297     info_ptr->offset_unit_type = (png_byte)unit_type;
     298     info_ptr->valid |= PNG_INFO_oFFs;
     299  }
     300  #endif
     301  
     302  #ifdef PNG_pCAL_SUPPORTED
     303  void PNGAPI
     304  png_set_pCAL(png_const_structrp png_ptr, png_inforp info_ptr,
     305      png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type,
     306      int nparams, png_const_charp units, png_charpp params)
     307  {
     308     size_t length;
     309     int i;
     310  
     311     png_debug1(1, "in %s storage function", "pCAL");
     312  
     313     if (png_ptr == NULL || info_ptr == NULL || purpose == NULL || units == NULL
     314         || (nparams > 0 && params == NULL))
     315        return;
     316  
     317     length = strlen(purpose) + 1;
     318     png_debug1(3, "allocating purpose for info (%lu bytes)",
     319         (unsigned long)length);
     320  
     321     /* TODO: validate format of calibration name and unit name */
     322  
     323     /* Check that the type matches the specification. */
     324     if (type < 0 || type > 3)
     325     {
     326        png_chunk_report(png_ptr, "Invalid pCAL equation type",
     327              PNG_CHUNK_WRITE_ERROR);
     328        return;
     329     }
     330  
     331     if (nparams < 0 || nparams > 255)
     332     {
     333        png_chunk_report(png_ptr, "Invalid pCAL parameter count",
     334              PNG_CHUNK_WRITE_ERROR);
     335        return;
     336     }
     337  
     338     /* Validate params[nparams] */
     339     for (i=0; i<nparams; ++i)
     340     {
     341        if (params[i] == NULL ||
     342            !png_check_fp_string(params[i], strlen(params[i])))
     343        {
     344           png_chunk_report(png_ptr, "Invalid format for pCAL parameter",
     345                 PNG_CHUNK_WRITE_ERROR);
     346           return;
     347        }
     348     }
     349  
     350     info_ptr->pcal_purpose = png_voidcast(png_charp,
     351         png_malloc_warn(png_ptr, length));
     352  
     353     if (info_ptr->pcal_purpose == NULL)
     354     {
     355        png_chunk_report(png_ptr, "Insufficient memory for pCAL purpose",
     356              PNG_CHUNK_WRITE_ERROR);
     357        return;
     358     }
     359  
     360     memcpy(info_ptr->pcal_purpose, purpose, length);
     361  
     362     info_ptr->free_me |= PNG_FREE_PCAL;
     363  
     364     png_debug(3, "storing X0, X1, type, and nparams in info");
     365     info_ptr->pcal_X0 = X0;
     366     info_ptr->pcal_X1 = X1;
     367     info_ptr->pcal_type = (png_byte)type;
     368     info_ptr->pcal_nparams = (png_byte)nparams;
     369  
     370     length = strlen(units) + 1;
     371     png_debug1(3, "allocating units for info (%lu bytes)",
     372         (unsigned long)length);
     373  
     374     info_ptr->pcal_units = png_voidcast(png_charp,
     375         png_malloc_warn(png_ptr, length));
     376  
     377     if (info_ptr->pcal_units == NULL)
     378     {
     379        png_warning(png_ptr, "Insufficient memory for pCAL units");
     380        return;
     381     }
     382  
     383     memcpy(info_ptr->pcal_units, units, length);
     384  
     385     info_ptr->pcal_params = png_voidcast(png_charpp, png_malloc_warn(png_ptr,
     386         (size_t)(((unsigned int)nparams + 1) * (sizeof (png_charp)))));
     387  
     388     if (info_ptr->pcal_params == NULL)
     389     {
     390        png_warning(png_ptr, "Insufficient memory for pCAL params");
     391        return;
     392     }
     393  
     394     memset(info_ptr->pcal_params, 0, ((unsigned int)nparams + 1) *
     395         (sizeof (png_charp)));
     396  
     397     for (i = 0; i < nparams; i++)
     398     {
     399        length = strlen(params[i]) + 1;
     400        png_debug2(3, "allocating parameter %d for info (%lu bytes)", i,
     401            (unsigned long)length);
     402  
     403        info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
     404  
     405        if (info_ptr->pcal_params[i] == NULL)
     406        {
     407           png_warning(png_ptr, "Insufficient memory for pCAL parameter");
     408           return;
     409        }
     410  
     411        memcpy(info_ptr->pcal_params[i], params[i], length);
     412     }
     413  
     414     info_ptr->valid |= PNG_INFO_pCAL;
     415  }
     416  #endif
     417  
     418  #ifdef PNG_sCAL_SUPPORTED
     419  void PNGAPI
     420  png_set_sCAL_s(png_const_structrp png_ptr, png_inforp info_ptr,
     421      int unit, png_const_charp swidth, png_const_charp sheight)
     422  {
     423     size_t lengthw = 0, lengthh = 0;
     424  
     425     png_debug1(1, "in %s storage function", "sCAL");
     426  
     427     if (png_ptr == NULL || info_ptr == NULL)
     428        return;
     429  
     430     /* Double check the unit (should never get here with an invalid
     431      * unit unless this is an API call.)
     432      */
     433     if (unit != 1 && unit != 2)
     434        png_error(png_ptr, "Invalid sCAL unit");
     435  
     436     if (swidth == NULL || (lengthw = strlen(swidth)) == 0 ||
     437         swidth[0] == 45 /* '-' */ || !png_check_fp_string(swidth, lengthw))
     438        png_error(png_ptr, "Invalid sCAL width");
     439  
     440     if (sheight == NULL || (lengthh = strlen(sheight)) == 0 ||
     441         sheight[0] == 45 /* '-' */ || !png_check_fp_string(sheight, lengthh))
     442        png_error(png_ptr, "Invalid sCAL height");
     443  
     444     info_ptr->scal_unit = (png_byte)unit;
     445  
     446     ++lengthw;
     447  
     448     png_debug1(3, "allocating unit for info (%u bytes)", (unsigned int)lengthw);
     449  
     450     info_ptr->scal_s_width = png_voidcast(png_charp,
     451         png_malloc_warn(png_ptr, lengthw));
     452  
     453     if (info_ptr->scal_s_width == NULL)
     454     {
     455        png_warning(png_ptr, "Memory allocation failed while processing sCAL");
     456  
     457        return;
     458     }
     459  
     460     memcpy(info_ptr->scal_s_width, swidth, lengthw);
     461  
     462     ++lengthh;
     463  
     464     png_debug1(3, "allocating unit for info (%u bytes)", (unsigned int)lengthh);
     465  
     466     info_ptr->scal_s_height = png_voidcast(png_charp,
     467         png_malloc_warn(png_ptr, lengthh));
     468  
     469     if (info_ptr->scal_s_height == NULL)
     470     {
     471        png_free(png_ptr, info_ptr->scal_s_width);
     472        info_ptr->scal_s_width = NULL;
     473  
     474        png_warning(png_ptr, "Memory allocation failed while processing sCAL");
     475        return;
     476     }
     477  
     478     memcpy(info_ptr->scal_s_height, sheight, lengthh);
     479  
     480     info_ptr->free_me |= PNG_FREE_SCAL;
     481     info_ptr->valid |= PNG_INFO_sCAL;
     482  }
     483  
     484  #  ifdef PNG_FLOATING_POINT_SUPPORTED
     485  void PNGAPI
     486  png_set_sCAL(png_const_structrp png_ptr, png_inforp info_ptr, int unit,
     487      double width, double height)
     488  {
     489     png_debug1(1, "in %s storage function", "sCAL");
     490  
     491     /* Check the arguments. */
     492     if (width <= 0)
     493        png_warning(png_ptr, "Invalid sCAL width ignored");
     494  
     495     else if (height <= 0)
     496        png_warning(png_ptr, "Invalid sCAL height ignored");
     497  
     498     else
     499     {
     500        /* Convert 'width' and 'height' to ASCII. */
     501        char swidth[PNG_sCAL_MAX_DIGITS+1];
     502        char sheight[PNG_sCAL_MAX_DIGITS+1];
     503  
     504        png_ascii_from_fp(png_ptr, swidth, (sizeof swidth), width,
     505            PNG_sCAL_PRECISION);
     506        png_ascii_from_fp(png_ptr, sheight, (sizeof sheight), height,
     507            PNG_sCAL_PRECISION);
     508  
     509        png_set_sCAL_s(png_ptr, info_ptr, unit, swidth, sheight);
     510     }
     511  }
     512  #  endif
     513  
     514  #  ifdef PNG_FIXED_POINT_SUPPORTED
     515  void PNGAPI
     516  png_set_sCAL_fixed(png_const_structrp png_ptr, png_inforp info_ptr, int unit,
     517      png_fixed_point width, png_fixed_point height)
     518  {
     519     png_debug1(1, "in %s storage function", "sCAL");
     520  
     521     /* Check the arguments. */
     522     if (width <= 0)
     523        png_warning(png_ptr, "Invalid sCAL width ignored");
     524  
     525     else if (height <= 0)
     526        png_warning(png_ptr, "Invalid sCAL height ignored");
     527  
     528     else
     529     {
     530        /* Convert 'width' and 'height' to ASCII. */
     531        char swidth[PNG_sCAL_MAX_DIGITS+1];
     532        char sheight[PNG_sCAL_MAX_DIGITS+1];
     533  
     534        png_ascii_from_fixed(png_ptr, swidth, (sizeof swidth), width);
     535        png_ascii_from_fixed(png_ptr, sheight, (sizeof sheight), height);
     536  
     537        png_set_sCAL_s(png_ptr, info_ptr, unit, swidth, sheight);
     538     }
     539  }
     540  #  endif
     541  #endif
     542  
     543  #ifdef PNG_pHYs_SUPPORTED
     544  void PNGAPI
     545  png_set_pHYs(png_const_structrp png_ptr, png_inforp info_ptr,
     546      png_uint_32 res_x, png_uint_32 res_y, int unit_type)
     547  {
     548     png_debug1(1, "in %s storage function", "pHYs");
     549  
     550     if (png_ptr == NULL || info_ptr == NULL)
     551        return;
     552  
     553     info_ptr->x_pixels_per_unit = res_x;
     554     info_ptr->y_pixels_per_unit = res_y;
     555     info_ptr->phys_unit_type = (png_byte)unit_type;
     556     info_ptr->valid |= PNG_INFO_pHYs;
     557  }
     558  #endif
     559  
     560  void PNGAPI
     561  png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr,
     562      png_const_colorp palette, int num_palette)
     563  {
     564  
     565     png_uint_32 max_palette_length;
     566  
     567     png_debug1(1, "in %s storage function", "PLTE");
     568  
     569     if (png_ptr == NULL || info_ptr == NULL)
     570        return;
     571  
     572     max_palette_length = (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
     573        (1 << info_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
     574  
     575     if (num_palette < 0 || num_palette > (int) max_palette_length)
     576     {
     577        if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
     578           png_error(png_ptr, "Invalid palette length");
     579  
     580        else
     581        {
     582           png_warning(png_ptr, "Invalid palette length");
     583  
     584           return;
     585        }
     586     }
     587  
     588     if ((num_palette > 0 && palette == NULL) ||
     589        (num_palette == 0
     590  #        ifdef PNG_MNG_FEATURES_SUPPORTED
     591              && (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0
     592  #        endif
     593        ))
     594     {
     595        png_error(png_ptr, "Invalid palette");
     596     }
     597  
     598     /* It may not actually be necessary to set png_ptr->palette here;
     599      * we do it for backward compatibility with the way the png_handle_tRNS
     600      * function used to do the allocation.
     601      *
     602      * 1.6.0: the above statement appears to be incorrect; something has to set
     603      * the palette inside png_struct on read.
     604      */
     605     png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
     606  
     607     /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
     608      * of num_palette entries, in case of an invalid PNG file or incorrect
     609      * call to png_set_PLTE() with too-large sample values.
     610      */
     611     png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr,
     612         PNG_MAX_PALETTE_LENGTH * (sizeof (png_color))));
     613  
     614     if (num_palette > 0)
     615        memcpy(png_ptr->palette, palette, (unsigned int)num_palette *
     616            (sizeof (png_color)));
     617  
     618     info_ptr->palette = png_ptr->palette;
     619     info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
     620     info_ptr->free_me |= PNG_FREE_PLTE;
     621     info_ptr->valid |= PNG_INFO_PLTE;
     622  }
     623  
     624  #ifdef PNG_sBIT_SUPPORTED
     625  void PNGAPI
     626  png_set_sBIT(png_const_structrp png_ptr, png_inforp info_ptr,
     627      png_const_color_8p sig_bit)
     628  {
     629     png_debug1(1, "in %s storage function", "sBIT");
     630  
     631     if (png_ptr == NULL || info_ptr == NULL || sig_bit == NULL)
     632        return;
     633  
     634     info_ptr->sig_bit = *sig_bit;
     635     info_ptr->valid |= PNG_INFO_sBIT;
     636  }
     637  #endif
     638  
     639  #ifdef PNG_sRGB_SUPPORTED
     640  void PNGAPI
     641  png_set_sRGB(png_const_structrp png_ptr, png_inforp info_ptr, int srgb_intent)
     642  {
     643     png_debug1(1, "in %s storage function", "sRGB");
     644  
     645     if (png_ptr == NULL || info_ptr == NULL)
     646        return;
     647  
     648     (void)png_colorspace_set_sRGB(png_ptr, &info_ptr->colorspace, srgb_intent);
     649     png_colorspace_sync_info(png_ptr, info_ptr);
     650  }
     651  
     652  void PNGAPI
     653  png_set_sRGB_gAMA_and_cHRM(png_const_structrp png_ptr, png_inforp info_ptr,
     654      int srgb_intent)
     655  {
     656     png_debug1(1, "in %s storage function", "sRGB_gAMA_and_cHRM");
     657  
     658     if (png_ptr == NULL || info_ptr == NULL)
     659        return;
     660  
     661     if (png_colorspace_set_sRGB(png_ptr, &info_ptr->colorspace,
     662         srgb_intent) != 0)
     663     {
     664        /* This causes the gAMA and cHRM to be written too */
     665        info_ptr->colorspace.flags |=
     666           PNG_COLORSPACE_FROM_gAMA|PNG_COLORSPACE_FROM_cHRM;
     667     }
     668  
     669     png_colorspace_sync_info(png_ptr, info_ptr);
     670  }
     671  #endif /* sRGB */
     672  
     673  
     674  #ifdef PNG_iCCP_SUPPORTED
     675  void PNGAPI
     676  png_set_iCCP(png_const_structrp png_ptr, png_inforp info_ptr,
     677      png_const_charp name, int compression_type,
     678      png_const_bytep profile, png_uint_32 proflen)
     679  {
     680     png_charp new_iccp_name;
     681     png_bytep new_iccp_profile;
     682     size_t length;
     683  
     684     png_debug1(1, "in %s storage function", "iCCP");
     685  
     686     if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
     687        return;
     688  
     689     if (compression_type != PNG_COMPRESSION_TYPE_BASE)
     690        png_app_error(png_ptr, "Invalid iCCP compression method");
     691  
     692     /* Set the colorspace first because this validates the profile; do not
     693      * override previously set app cHRM or gAMA here (because likely as not the
     694      * application knows better than libpng what the correct values are.)  Pass
     695      * the info_ptr color_type field to png_colorspace_set_ICC because in the
     696      * write case it has not yet been stored in png_ptr.
     697      */
     698     {
     699        int result = png_colorspace_set_ICC(png_ptr, &info_ptr->colorspace, name,
     700            proflen, profile, info_ptr->color_type);
     701  
     702        png_colorspace_sync_info(png_ptr, info_ptr);
     703  
     704        /* Don't do any of the copying if the profile was bad, or inconsistent. */
     705        if (result == 0)
     706           return;
     707  
     708        /* But do write the gAMA and cHRM chunks from the profile. */
     709        info_ptr->colorspace.flags |=
     710           PNG_COLORSPACE_FROM_gAMA|PNG_COLORSPACE_FROM_cHRM;
     711     }
     712  
     713     length = strlen(name)+1;
     714     new_iccp_name = png_voidcast(png_charp, png_malloc_warn(png_ptr, length));
     715  
     716     if (new_iccp_name == NULL)
     717     {
     718        png_benign_error(png_ptr, "Insufficient memory to process iCCP chunk");
     719  
     720        return;
     721     }
     722  
     723     memcpy(new_iccp_name, name, length);
     724     new_iccp_profile = png_voidcast(png_bytep,
     725         png_malloc_warn(png_ptr, proflen));
     726  
     727     if (new_iccp_profile == NULL)
     728     {
     729        png_free(png_ptr, new_iccp_name);
     730        png_benign_error(png_ptr,
     731            "Insufficient memory to process iCCP profile");
     732  
     733        return;
     734     }
     735  
     736     memcpy(new_iccp_profile, profile, proflen);
     737  
     738     png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
     739  
     740     info_ptr->iccp_proflen = proflen;
     741     info_ptr->iccp_name = new_iccp_name;
     742     info_ptr->iccp_profile = new_iccp_profile;
     743     info_ptr->free_me |= PNG_FREE_ICCP;
     744     info_ptr->valid |= PNG_INFO_iCCP;
     745  }
     746  #endif
     747  
     748  #ifdef PNG_TEXT_SUPPORTED
     749  void PNGAPI
     750  png_set_text(png_const_structrp png_ptr, png_inforp info_ptr,
     751      png_const_textp text_ptr, int num_text)
     752  {
     753     int ret;
     754     ret = png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
     755  
     756     if (ret != 0)
     757        png_error(png_ptr, "Insufficient memory to store text");
     758  }
     759  
     760  int /* PRIVATE */
     761  png_set_text_2(png_const_structrp png_ptr, png_inforp info_ptr,
     762      png_const_textp text_ptr, int num_text)
     763  {
     764     int i;
     765  
     766     png_debug1(1, "in %lx storage function", png_ptr == NULL ? 0xabadca11U :
     767        (unsigned long)png_ptr->chunk_name);
     768  
     769     if (png_ptr == NULL || info_ptr == NULL || num_text <= 0 || text_ptr == NULL)
     770        return(0);
     771  
     772     /* Make sure we have enough space in the "text" array in info_struct
     773      * to hold all of the incoming text_ptr objects.  This compare can't overflow
     774      * because max_text >= num_text (anyway, subtract of two positive integers
     775      * can't overflow in any case.)
     776      */
     777     if (num_text > info_ptr->max_text - info_ptr->num_text)
     778     {
     779        int old_num_text = info_ptr->num_text;
     780        int max_text;
     781        png_textp new_text = NULL;
     782  
     783        /* Calculate an appropriate max_text, checking for overflow. */
     784        max_text = old_num_text;
     785        if (num_text <= INT_MAX - max_text)
     786        {
     787           max_text += num_text;
     788  
     789           /* Round up to a multiple of 8 */
     790           if (max_text < INT_MAX-8)
     791              max_text = (max_text + 8) & ~0x7;
     792  
     793           else
     794              max_text = INT_MAX;
     795  
     796           /* Now allocate a new array and copy the old members in; this does all
     797            * the overflow checks.
     798            */
     799           new_text = png_voidcast(png_textp,png_realloc_array(png_ptr,
     800               info_ptr->text, old_num_text, max_text-old_num_text,
     801               sizeof *new_text));
     802        }
     803  
     804        if (new_text == NULL)
     805        {
     806           png_chunk_report(png_ptr, "too many text chunks",
     807               PNG_CHUNK_WRITE_ERROR);
     808  
     809           return 1;
     810        }
     811  
     812        png_free(png_ptr, info_ptr->text);
     813  
     814        info_ptr->text = new_text;
     815        info_ptr->free_me |= PNG_FREE_TEXT;
     816        info_ptr->max_text = max_text;
     817        /* num_text is adjusted below as the entries are copied in */
     818  
     819        png_debug1(3, "allocated %d entries for info_ptr->text", max_text);
     820     }
     821  
     822     for (i = 0; i < num_text; i++)
     823     {
     824        size_t text_length, key_len;
     825        size_t lang_len, lang_key_len;
     826        png_textp textp = &(info_ptr->text[info_ptr->num_text]);
     827  
     828        if (text_ptr[i].key == NULL)
     829            continue;
     830  
     831        if (text_ptr[i].compression < PNG_TEXT_COMPRESSION_NONE ||
     832            text_ptr[i].compression >= PNG_TEXT_COMPRESSION_LAST)
     833        {
     834           png_chunk_report(png_ptr, "text compression mode is out of range",
     835               PNG_CHUNK_WRITE_ERROR);
     836           continue;
     837        }
     838  
     839        key_len = strlen(text_ptr[i].key);
     840  
     841        if (text_ptr[i].compression <= 0)
     842        {
     843           lang_len = 0;
     844           lang_key_len = 0;
     845        }
     846  
     847        else
     848  #  ifdef PNG_iTXt_SUPPORTED
     849        {
     850           /* Set iTXt data */
     851  
     852           if (text_ptr[i].lang != NULL)
     853              lang_len = strlen(text_ptr[i].lang);
     854  
     855           else
     856              lang_len = 0;
     857  
     858           if (text_ptr[i].lang_key != NULL)
     859              lang_key_len = strlen(text_ptr[i].lang_key);
     860  
     861           else
     862              lang_key_len = 0;
     863        }
     864  #  else /* iTXt */
     865        {
     866           png_chunk_report(png_ptr, "iTXt chunk not supported",
     867               PNG_CHUNK_WRITE_ERROR);
     868           continue;
     869        }
     870  #  endif
     871  
     872        if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
     873        {
     874           text_length = 0;
     875  #  ifdef PNG_iTXt_SUPPORTED
     876           if (text_ptr[i].compression > 0)
     877              textp->compression = PNG_ITXT_COMPRESSION_NONE;
     878  
     879           else
     880  #  endif
     881              textp->compression = PNG_TEXT_COMPRESSION_NONE;
     882        }
     883  
     884        else
     885        {
     886           text_length = strlen(text_ptr[i].text);
     887           textp->compression = text_ptr[i].compression;
     888        }
     889  
     890        textp->key = png_voidcast(png_charp,png_malloc_base(png_ptr,
     891            key_len + text_length + lang_len + lang_key_len + 4));
     892  
     893        if (textp->key == NULL)
     894        {
     895           png_chunk_report(png_ptr, "text chunk: out of memory",
     896               PNG_CHUNK_WRITE_ERROR);
     897  
     898           return 1;
     899        }
     900  
     901        png_debug2(2, "Allocated %lu bytes at %p in png_set_text",
     902            (unsigned long)(png_uint_32)
     903            (key_len + lang_len + lang_key_len + text_length + 4),
     904            textp->key);
     905  
     906        memcpy(textp->key, text_ptr[i].key, key_len);
     907        *(textp->key + key_len) = '\0';
     908  
     909        if (text_ptr[i].compression > 0)
     910        {
     911           textp->lang = textp->key + key_len + 1;
     912           memcpy(textp->lang, text_ptr[i].lang, lang_len);
     913           *(textp->lang + lang_len) = '\0';
     914           textp->lang_key = textp->lang + lang_len + 1;
     915           memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
     916           *(textp->lang_key + lang_key_len) = '\0';
     917           textp->text = textp->lang_key + lang_key_len + 1;
     918        }
     919  
     920        else
     921        {
     922           textp->lang=NULL;
     923           textp->lang_key=NULL;
     924           textp->text = textp->key + key_len + 1;
     925        }
     926  
     927        if (text_length != 0)
     928           memcpy(textp->text, text_ptr[i].text, text_length);
     929  
     930        *(textp->text + text_length) = '\0';
     931  
     932  #  ifdef PNG_iTXt_SUPPORTED
     933        if (textp->compression > 0)
     934        {
     935           textp->text_length = 0;
     936           textp->itxt_length = text_length;
     937        }
     938  
     939        else
     940  #  endif
     941        {
     942           textp->text_length = text_length;
     943           textp->itxt_length = 0;
     944        }
     945  
     946        info_ptr->num_text++;
     947        png_debug1(3, "transferred text chunk %d", info_ptr->num_text);
     948     }
     949  
     950     return(0);
     951  }
     952  #endif
     953  
     954  #ifdef PNG_tIME_SUPPORTED
     955  void PNGAPI
     956  png_set_tIME(png_const_structrp png_ptr, png_inforp info_ptr,
     957      png_const_timep mod_time)
     958  {
     959     png_debug1(1, "in %s storage function", "tIME");
     960  
     961     if (png_ptr == NULL || info_ptr == NULL || mod_time == NULL ||
     962         (png_ptr->mode & PNG_WROTE_tIME) != 0)
     963        return;
     964  
     965     if (mod_time->month == 0   || mod_time->month > 12  ||
     966         mod_time->day   == 0   || mod_time->day   > 31  ||
     967         mod_time->hour  > 23   || mod_time->minute > 59 ||
     968         mod_time->second > 60)
     969     {
     970        png_warning(png_ptr, "Ignoring invalid time value");
     971  
     972        return;
     973     }
     974  
     975     info_ptr->mod_time = *mod_time;
     976     info_ptr->valid |= PNG_INFO_tIME;
     977  }
     978  #endif
     979  
     980  #ifdef PNG_tRNS_SUPPORTED
     981  void PNGAPI
     982  png_set_tRNS(png_structrp png_ptr, png_inforp info_ptr,
     983      png_const_bytep trans_alpha, int num_trans, png_const_color_16p trans_color)
     984  {
     985     png_debug1(1, "in %s storage function", "tRNS");
     986  
     987     if (png_ptr == NULL || info_ptr == NULL)
     988  
     989        return;
     990  
     991     if (trans_alpha != NULL)
     992     {
     993         /* It may not actually be necessary to set png_ptr->trans_alpha here;
     994          * we do it for backward compatibility with the way the png_handle_tRNS
     995          * function used to do the allocation.
     996          *
     997          * 1.6.0: The above statement is incorrect; png_handle_tRNS effectively
     998          * relies on png_set_tRNS storing the information in png_struct
     999          * (otherwise it won't be there for the code in pngrtran.c).
    1000          */
    1001  
    1002         png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
    1003  
    1004         if (num_trans > 0 && num_trans <= PNG_MAX_PALETTE_LENGTH)
    1005         {
    1006           /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
    1007            info_ptr->trans_alpha = png_voidcast(png_bytep,
    1008                png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH));
    1009            memcpy(info_ptr->trans_alpha, trans_alpha, (size_t)num_trans);
    1010  
    1011            info_ptr->free_me |= PNG_FREE_TRNS;
    1012            info_ptr->valid |= PNG_INFO_tRNS;
    1013         }
    1014         png_ptr->trans_alpha = info_ptr->trans_alpha;
    1015     }
    1016  
    1017     if (trans_color != NULL)
    1018     {
    1019  #ifdef PNG_WARNINGS_SUPPORTED
    1020        if (info_ptr->bit_depth < 16)
    1021        {
    1022           int sample_max = (1 << info_ptr->bit_depth) - 1;
    1023  
    1024           if ((info_ptr->color_type == PNG_COLOR_TYPE_GRAY &&
    1025               trans_color->gray > sample_max) ||
    1026               (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
    1027               (trans_color->red > sample_max ||
    1028               trans_color->green > sample_max ||
    1029               trans_color->blue > sample_max)))
    1030              png_warning(png_ptr,
    1031                  "tRNS chunk has out-of-range samples for bit_depth");
    1032        }
    1033  #endif
    1034  
    1035        info_ptr->trans_color = *trans_color;
    1036  
    1037        if (num_trans == 0)
    1038           num_trans = 1;
    1039     }
    1040  
    1041     info_ptr->num_trans = (png_uint_16)num_trans;
    1042  
    1043     if (num_trans != 0)
    1044     {
    1045        info_ptr->free_me |= PNG_FREE_TRNS;
    1046        info_ptr->valid |= PNG_INFO_tRNS;
    1047     }
    1048  }
    1049  #endif
    1050  
    1051  #ifdef PNG_sPLT_SUPPORTED
    1052  void PNGAPI
    1053  png_set_sPLT(png_const_structrp png_ptr,
    1054      png_inforp info_ptr, png_const_sPLT_tp entries, int nentries)
    1055  /*
    1056   *  entries        - array of png_sPLT_t structures
    1057   *                   to be added to the list of palettes
    1058   *                   in the info structure.
    1059   *
    1060   *  nentries       - number of palette structures to be
    1061   *                   added.
    1062   */
    1063  {
    1064     png_sPLT_tp np;
    1065  
    1066     if (png_ptr == NULL || info_ptr == NULL || nentries <= 0 || entries == NULL)
    1067        return;
    1068  
    1069     /* Use the internal realloc function, which checks for all the possible
    1070      * overflows.  Notice that the parameters are (int) and (size_t)
    1071      */
    1072     np = png_voidcast(png_sPLT_tp,png_realloc_array(png_ptr,
    1073         info_ptr->splt_palettes, info_ptr->splt_palettes_num, nentries,
    1074         sizeof *np));
    1075  
    1076     if (np == NULL)
    1077     {
    1078        /* Out of memory or too many chunks */
    1079        png_chunk_report(png_ptr, "too many sPLT chunks", PNG_CHUNK_WRITE_ERROR);
    1080        return;
    1081     }
    1082  
    1083     png_free(png_ptr, info_ptr->splt_palettes);
    1084  
    1085     info_ptr->splt_palettes = np;
    1086     info_ptr->free_me |= PNG_FREE_SPLT;
    1087  
    1088     np += info_ptr->splt_palettes_num;
    1089  
    1090     do
    1091     {
    1092        size_t length;
    1093  
    1094        /* Skip invalid input entries */
    1095        if (entries->name == NULL || entries->entries == NULL)
    1096        {
    1097           /* png_handle_sPLT doesn't do this, so this is an app error */
    1098           png_app_error(png_ptr, "png_set_sPLT: invalid sPLT");
    1099           /* Just skip the invalid entry */
    1100           continue;
    1101        }
    1102  
    1103        np->depth = entries->depth;
    1104  
    1105        /* In the event of out-of-memory just return - there's no point keeping
    1106         * on trying to add sPLT chunks.
    1107         */
    1108        length = strlen(entries->name) + 1;
    1109        np->name = png_voidcast(png_charp, png_malloc_base(png_ptr, length));
    1110  
    1111        if (np->name == NULL)
    1112           break;
    1113  
    1114        memcpy(np->name, entries->name, length);
    1115  
    1116        /* IMPORTANT: we have memory now that won't get freed if something else
    1117         * goes wrong; this code must free it.  png_malloc_array produces no
    1118         * warnings; use a png_chunk_report (below) if there is an error.
    1119         */
    1120        np->entries = png_voidcast(png_sPLT_entryp, png_malloc_array(png_ptr,
    1121            entries->nentries, sizeof (png_sPLT_entry)));
    1122  
    1123        if (np->entries == NULL)
    1124        {
    1125           png_free(png_ptr, np->name);
    1126           np->name = NULL;
    1127           break;
    1128        }
    1129  
    1130        np->nentries = entries->nentries;
    1131        /* This multiply can't overflow because png_malloc_array has already
    1132         * checked it when doing the allocation.
    1133         */
    1134        memcpy(np->entries, entries->entries,
    1135            (unsigned int)entries->nentries * sizeof (png_sPLT_entry));
    1136  
    1137        /* Note that 'continue' skips the advance of the out pointer and out
    1138         * count, so an invalid entry is not added.
    1139         */
    1140        info_ptr->valid |= PNG_INFO_sPLT;
    1141        ++(info_ptr->splt_palettes_num);
    1142        ++np;
    1143        ++entries;
    1144     }
    1145     while (--nentries);
    1146  
    1147     if (nentries > 0)
    1148        png_chunk_report(png_ptr, "sPLT out of memory", PNG_CHUNK_WRITE_ERROR);
    1149  }
    1150  #endif /* sPLT */
    1151  
    1152  #ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
    1153  static png_byte
    1154  check_location(png_const_structrp png_ptr, int location)
    1155  {
    1156     location &= (PNG_HAVE_IHDR|PNG_HAVE_PLTE|PNG_AFTER_IDAT);
    1157  
    1158     /* New in 1.6.0; copy the location and check it.  This is an API
    1159      * change; previously the app had to use the
    1160      * png_set_unknown_chunk_location API below for each chunk.
    1161      */
    1162     if (location == 0 && (png_ptr->mode & PNG_IS_READ_STRUCT) == 0)
    1163     {
    1164        /* Write struct, so unknown chunks come from the app */
    1165        png_app_warning(png_ptr,
    1166            "png_set_unknown_chunks now expects a valid location");
    1167        /* Use the old behavior */
    1168        location = (png_byte)(png_ptr->mode &
    1169            (PNG_HAVE_IHDR|PNG_HAVE_PLTE|PNG_AFTER_IDAT));
    1170     }
    1171  
    1172     /* This need not be an internal error - if the app calls
    1173      * png_set_unknown_chunks on a read pointer it must get the location right.
    1174      */
    1175     if (location == 0)
    1176        png_error(png_ptr, "invalid location in png_set_unknown_chunks");
    1177  
    1178     /* Now reduce the location to the top-most set bit by removing each least
    1179      * significant bit in turn.
    1180      */
    1181     while (location != (location & -location))
    1182        location &= ~(location & -location);
    1183  
    1184     /* The cast is safe because 'location' is a bit mask and only the low four
    1185      * bits are significant.
    1186      */
    1187     return (png_byte)location;
    1188  }
    1189  
    1190  void PNGAPI
    1191  png_set_unknown_chunks(png_const_structrp png_ptr,
    1192      png_inforp info_ptr, png_const_unknown_chunkp unknowns, int num_unknowns)
    1193  {
    1194     png_unknown_chunkp np;
    1195  
    1196     if (png_ptr == NULL || info_ptr == NULL || num_unknowns <= 0 ||
    1197         unknowns == NULL)
    1198        return;
    1199  
    1200     /* Check for the failure cases where support has been disabled at compile
    1201      * time.  This code is hardly ever compiled - it's here because
    1202      * STORE_UNKNOWN_CHUNKS is set by both read and write code (compiling in this
    1203      * code) but may be meaningless if the read or write handling of unknown
    1204      * chunks is not compiled in.
    1205      */
    1206  #  if !defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) && \
    1207        defined(PNG_READ_SUPPORTED)
    1208        if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0)
    1209        {
    1210           png_app_error(png_ptr, "no unknown chunk support on read");
    1211  
    1212           return;
    1213        }
    1214  #  endif
    1215  #  if !defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED) && \
    1216        defined(PNG_WRITE_SUPPORTED)
    1217        if ((png_ptr->mode & PNG_IS_READ_STRUCT) == 0)
    1218        {
    1219           png_app_error(png_ptr, "no unknown chunk support on write");
    1220  
    1221           return;
    1222        }
    1223  #  endif
    1224  
    1225     /* Prior to 1.6.0 this code used png_malloc_warn; however, this meant that
    1226      * unknown critical chunks could be lost with just a warning resulting in
    1227      * undefined behavior.  Now png_chunk_report is used to provide behavior
    1228      * appropriate to read or write.
    1229      */
    1230     np = png_voidcast(png_unknown_chunkp, png_realloc_array(png_ptr,
    1231         info_ptr->unknown_chunks, info_ptr->unknown_chunks_num, num_unknowns,
    1232         sizeof *np));
    1233  
    1234     if (np == NULL)
    1235     {
    1236        png_chunk_report(png_ptr, "too many unknown chunks",
    1237            PNG_CHUNK_WRITE_ERROR);
    1238        return;
    1239     }
    1240  
    1241     png_free(png_ptr, info_ptr->unknown_chunks);
    1242  
    1243     info_ptr->unknown_chunks = np; /* safe because it is initialized */
    1244     info_ptr->free_me |= PNG_FREE_UNKN;
    1245  
    1246     np += info_ptr->unknown_chunks_num;
    1247  
    1248     /* Increment unknown_chunks_num each time round the loop to protect the
    1249      * just-allocated chunk data.
    1250      */
    1251     for (; num_unknowns > 0; --num_unknowns, ++unknowns)
    1252     {
    1253        memcpy(np->name, unknowns->name, (sizeof np->name));
    1254        np->name[(sizeof np->name)-1] = '\0';
    1255        np->location = check_location(png_ptr, unknowns->location);
    1256  
    1257        if (unknowns->size == 0)
    1258        {
    1259           np->data = NULL;
    1260           np->size = 0;
    1261        }
    1262  
    1263        else
    1264        {
    1265           np->data = png_voidcast(png_bytep,
    1266               png_malloc_base(png_ptr, unknowns->size));
    1267  
    1268           if (np->data == NULL)
    1269           {
    1270              png_chunk_report(png_ptr, "unknown chunk: out of memory",
    1271                  PNG_CHUNK_WRITE_ERROR);
    1272              /* But just skip storing the unknown chunk */
    1273              continue;
    1274           }
    1275  
    1276           memcpy(np->data, unknowns->data, unknowns->size);
    1277           np->size = unknowns->size;
    1278        }
    1279  
    1280        /* These increments are skipped on out-of-memory for the data - the
    1281         * unknown chunk entry gets overwritten if the png_chunk_report returns.
    1282         * This is correct in the read case (the chunk is just dropped.)
    1283         */
    1284        ++np;
    1285        ++(info_ptr->unknown_chunks_num);
    1286     }
    1287  }
    1288  
    1289  void PNGAPI
    1290  png_set_unknown_chunk_location(png_const_structrp png_ptr, png_inforp info_ptr,
    1291      int chunk, int location)
    1292  {
    1293     /* This API is pretty pointless in 1.6.0 because the location can be set
    1294      * before the call to png_set_unknown_chunks.
    1295      *
    1296      * TODO: add a png_app_warning in 1.7
    1297      */
    1298     if (png_ptr != NULL && info_ptr != NULL && chunk >= 0 &&
    1299        chunk < info_ptr->unknown_chunks_num)
    1300     {
    1301        if ((location & (PNG_HAVE_IHDR|PNG_HAVE_PLTE|PNG_AFTER_IDAT)) == 0)
    1302        {
    1303           png_app_error(png_ptr, "invalid unknown chunk location");
    1304           /* Fake out the pre 1.6.0 behavior: */
    1305           if (((unsigned int)location & PNG_HAVE_IDAT) != 0) /* undocumented! */
    1306              location = PNG_AFTER_IDAT;
    1307  
    1308           else
    1309              location = PNG_HAVE_IHDR; /* also undocumented */
    1310        }
    1311  
    1312        info_ptr->unknown_chunks[chunk].location =
    1313           check_location(png_ptr, location);
    1314     }
    1315  }
    1316  #endif /* STORE_UNKNOWN_CHUNKS */
    1317  
    1318  #ifdef PNG_MNG_FEATURES_SUPPORTED
    1319  png_uint_32 PNGAPI
    1320  png_permit_mng_features(png_structrp png_ptr, png_uint_32 mng_features)
    1321  {
    1322     png_debug(1, "in png_permit_mng_features");
    1323  
    1324     if (png_ptr == NULL)
    1325        return 0;
    1326  
    1327     png_ptr->mng_features_permitted = mng_features & PNG_ALL_MNG_FEATURES;
    1328  
    1329     return png_ptr->mng_features_permitted;
    1330  }
    1331  #endif
    1332  
    1333  #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
    1334  static unsigned int
    1335  add_one_chunk(png_bytep list, unsigned int count, png_const_bytep add, int keep)
    1336  {
    1337     unsigned int i;
    1338  
    1339     /* Utility function: update the 'keep' state of a chunk if it is already in
    1340      * the list, otherwise add it to the list.
    1341      */
    1342     for (i=0; i<count; ++i, list += 5)
    1343     {
    1344        if (memcmp(list, add, 4) == 0)
    1345        {
    1346           list[4] = (png_byte)keep;
    1347  
    1348           return count;
    1349        }
    1350     }
    1351  
    1352     if (keep != PNG_HANDLE_CHUNK_AS_DEFAULT)
    1353     {
    1354        ++count;
    1355        memcpy(list, add, 4);
    1356        list[4] = (png_byte)keep;
    1357     }
    1358  
    1359     return count;
    1360  }
    1361  
    1362  void PNGAPI
    1363  png_set_keep_unknown_chunks(png_structrp png_ptr, int keep,
    1364      png_const_bytep chunk_list, int num_chunks_in)
    1365  {
    1366     png_bytep new_list;
    1367     unsigned int num_chunks, old_num_chunks;
    1368  
    1369     if (png_ptr == NULL)
    1370        return;
    1371  
    1372     if (keep < 0 || keep >= PNG_HANDLE_CHUNK_LAST)
    1373     {
    1374        png_app_error(png_ptr, "png_set_keep_unknown_chunks: invalid keep");
    1375  
    1376        return;
    1377     }
    1378  
    1379     if (num_chunks_in <= 0)
    1380     {
    1381        png_ptr->unknown_default = keep;
    1382  
    1383        /* '0' means just set the flags, so stop here */
    1384        if (num_chunks_in == 0)
    1385          return;
    1386     }
    1387  
    1388     if (num_chunks_in < 0)
    1389     {
    1390        /* Ignore all unknown chunks and all chunks recognized by
    1391         * libpng except for IHDR, PLTE, tRNS, IDAT, and IEND
    1392         */
    1393        static const png_byte chunks_to_ignore[] = {
    1394           98,  75,  71,  68, '\0',  /* bKGD */
    1395           99,  72,  82,  77, '\0',  /* cHRM */
    1396          101,  88,  73, 102, '\0',  /* eXIf */
    1397          103,  65,  77,  65, '\0',  /* gAMA */
    1398          104,  73,  83,  84, '\0',  /* hIST */
    1399          105,  67,  67,  80, '\0',  /* iCCP */
    1400          105,  84,  88, 116, '\0',  /* iTXt */
    1401          111,  70,  70, 115, '\0',  /* oFFs */
    1402          112,  67,  65,  76, '\0',  /* pCAL */
    1403          112,  72,  89, 115, '\0',  /* pHYs */
    1404          115,  66,  73,  84, '\0',  /* sBIT */
    1405          115,  67,  65,  76, '\0',  /* sCAL */
    1406          115,  80,  76,  84, '\0',  /* sPLT */
    1407          115,  84,  69,  82, '\0',  /* sTER */
    1408          115,  82,  71,  66, '\0',  /* sRGB */
    1409          116,  69,  88, 116, '\0',  /* tEXt */
    1410          116,  73,  77,  69, '\0',  /* tIME */
    1411          122,  84,  88, 116, '\0'   /* zTXt */
    1412        };
    1413  
    1414        chunk_list = chunks_to_ignore;
    1415        num_chunks = (unsigned int)/*SAFE*/(sizeof chunks_to_ignore)/5U;
    1416     }
    1417  
    1418     else /* num_chunks_in > 0 */
    1419     {
    1420        if (chunk_list == NULL)
    1421        {
    1422           /* Prior to 1.6.0 this was silently ignored, now it is an app_error
    1423            * which can be switched off.
    1424            */
    1425           png_app_error(png_ptr, "png_set_keep_unknown_chunks: no chunk list");
    1426  
    1427           return;
    1428        }
    1429  
    1430        num_chunks = (unsigned int)num_chunks_in;
    1431     }
    1432  
    1433     old_num_chunks = png_ptr->num_chunk_list;
    1434     if (png_ptr->chunk_list == NULL)
    1435        old_num_chunks = 0;
    1436  
    1437     /* Since num_chunks is always restricted to UINT_MAX/5 this can't overflow.
    1438      */
    1439     if (num_chunks + old_num_chunks > UINT_MAX/5)
    1440     {
    1441        png_app_error(png_ptr, "png_set_keep_unknown_chunks: too many chunks");
    1442  
    1443        return;
    1444     }
    1445  
    1446     /* If these chunks are being reset to the default then no more memory is
    1447      * required because add_one_chunk above doesn't extend the list if the 'keep'
    1448      * parameter is the default.
    1449      */
    1450     if (keep != 0)
    1451     {
    1452        new_list = png_voidcast(png_bytep, png_malloc(png_ptr,
    1453            5 * (num_chunks + old_num_chunks)));
    1454  
    1455        if (old_num_chunks > 0)
    1456           memcpy(new_list, png_ptr->chunk_list, 5*old_num_chunks);
    1457     }
    1458  
    1459     else if (old_num_chunks > 0)
    1460        new_list = png_ptr->chunk_list;
    1461  
    1462     else
    1463        new_list = NULL;
    1464  
    1465     /* Add the new chunks together with each one's handling code.  If the chunk
    1466      * already exists the code is updated, otherwise the chunk is added to the
    1467      * end.  (In libpng 1.6.0 order no longer matters because this code enforces
    1468      * the earlier convention that the last setting is the one that is used.)
    1469      */
    1470     if (new_list != NULL)
    1471     {
    1472        png_const_bytep inlist;
    1473        png_bytep outlist;
    1474        unsigned int i;
    1475  
    1476        for (i=0; i<num_chunks; ++i)
    1477        {
    1478           old_num_chunks = add_one_chunk(new_list, old_num_chunks,
    1479               chunk_list+5*i, keep);
    1480        }
    1481  
    1482        /* Now remove any spurious 'default' entries. */
    1483        num_chunks = 0;
    1484        for (i=0, inlist=outlist=new_list; i<old_num_chunks; ++i, inlist += 5)
    1485        {
    1486           if (inlist[4])
    1487           {
    1488              if (outlist != inlist)
    1489                 memcpy(outlist, inlist, 5);
    1490              outlist += 5;
    1491              ++num_chunks;
    1492           }
    1493        }
    1494  
    1495        /* This means the application has removed all the specialized handling. */
    1496        if (num_chunks == 0)
    1497        {
    1498           if (png_ptr->chunk_list != new_list)
    1499              png_free(png_ptr, new_list);
    1500  
    1501           new_list = NULL;
    1502        }
    1503     }
    1504  
    1505     else
    1506        num_chunks = 0;
    1507  
    1508     png_ptr->num_chunk_list = num_chunks;
    1509  
    1510     if (png_ptr->chunk_list != new_list)
    1511     {
    1512        if (png_ptr->chunk_list != NULL)
    1513           png_free(png_ptr, png_ptr->chunk_list);
    1514  
    1515        png_ptr->chunk_list = new_list;
    1516     }
    1517  }
    1518  #endif
    1519  
    1520  #ifdef PNG_READ_USER_CHUNKS_SUPPORTED
    1521  void PNGAPI
    1522  png_set_read_user_chunk_fn(png_structrp png_ptr, png_voidp user_chunk_ptr,
    1523      png_user_chunk_ptr read_user_chunk_fn)
    1524  {
    1525     png_debug(1, "in png_set_read_user_chunk_fn");
    1526  
    1527     if (png_ptr == NULL)
    1528        return;
    1529  
    1530     png_ptr->read_user_chunk_fn = read_user_chunk_fn;
    1531     png_ptr->user_chunk_ptr = user_chunk_ptr;
    1532  }
    1533  #endif
    1534  
    1535  #ifdef PNG_INFO_IMAGE_SUPPORTED
    1536  void PNGAPI
    1537  png_set_rows(png_const_structrp png_ptr, png_inforp info_ptr,
    1538      png_bytepp row_pointers)
    1539  {
    1540     png_debug1(1, "in %s storage function", "rows");
    1541  
    1542     if (png_ptr == NULL || info_ptr == NULL)
    1543        return;
    1544  
    1545     if (info_ptr->row_pointers != NULL &&
    1546         (info_ptr->row_pointers != row_pointers))
    1547        png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
    1548  
    1549     info_ptr->row_pointers = row_pointers;
    1550  
    1551     if (row_pointers != NULL)
    1552        info_ptr->valid |= PNG_INFO_IDAT;
    1553  }
    1554  #endif
    1555  
    1556  void PNGAPI
    1557  png_set_compression_buffer_size(png_structrp png_ptr, size_t size)
    1558  {
    1559     if (png_ptr == NULL)
    1560        return;
    1561  
    1562     if (size == 0 || size > PNG_UINT_31_MAX)
    1563        png_error(png_ptr, "invalid compression buffer size");
    1564  
    1565  #  ifdef PNG_SEQUENTIAL_READ_SUPPORTED
    1566     if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0)
    1567     {
    1568        png_ptr->IDAT_read_size = (png_uint_32)size; /* checked above */
    1569        return;
    1570     }
    1571  #  endif
    1572  
    1573  #  ifdef PNG_WRITE_SUPPORTED
    1574     if ((png_ptr->mode & PNG_IS_READ_STRUCT) == 0)
    1575     {
    1576        if (png_ptr->zowner != 0)
    1577        {
    1578           png_warning(png_ptr,
    1579               "Compression buffer size cannot be changed because it is in use");
    1580  
    1581           return;
    1582        }
    1583  
    1584  #ifndef __COVERITY__
    1585        /* Some compilers complain that this is always false.  However, it
    1586         * can be true when integer overflow happens.
    1587         */
    1588        if (size > ZLIB_IO_MAX)
    1589        {
    1590           png_warning(png_ptr,
    1591               "Compression buffer size limited to system maximum");
    1592           size = ZLIB_IO_MAX; /* must fit */
    1593        }
    1594  #endif
    1595  
    1596        if (size < 6)
    1597        {
    1598           /* Deflate will potentially go into an infinite loop on a SYNC_FLUSH
    1599            * if this is permitted.
    1600            */
    1601           png_warning(png_ptr,
    1602               "Compression buffer size cannot be reduced below 6");
    1603  
    1604           return;
    1605        }
    1606  
    1607        if (png_ptr->zbuffer_size != size)
    1608        {
    1609           png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
    1610           png_ptr->zbuffer_size = (uInt)size;
    1611        }
    1612     }
    1613  #  endif
    1614  }
    1615  
    1616  void PNGAPI
    1617  png_set_invalid(png_const_structrp png_ptr, png_inforp info_ptr, int mask)
    1618  {
    1619     if (png_ptr != NULL && info_ptr != NULL)
    1620        info_ptr->valid &= (unsigned int)(~mask);
    1621  }
    1622  
    1623  
    1624  #ifdef PNG_SET_USER_LIMITS_SUPPORTED
    1625  /* This function was added to libpng 1.2.6 */
    1626  void PNGAPI
    1627  png_set_user_limits(png_structrp png_ptr, png_uint_32 user_width_max,
    1628      png_uint_32 user_height_max)
    1629  {
    1630     /* Images with dimensions larger than these limits will be
    1631      * rejected by png_set_IHDR().  To accept any PNG datastream
    1632      * regardless of dimensions, set both limits to 0x7fffffff.
    1633      */
    1634     if (png_ptr == NULL)
    1635        return;
    1636  
    1637     png_ptr->user_width_max = user_width_max;
    1638     png_ptr->user_height_max = user_height_max;
    1639  }
    1640  
    1641  /* This function was added to libpng 1.4.0 */
    1642  void PNGAPI
    1643  png_set_chunk_cache_max(png_structrp png_ptr, png_uint_32 user_chunk_cache_max)
    1644  {
    1645     if (png_ptr != NULL)
    1646        png_ptr->user_chunk_cache_max = user_chunk_cache_max;
    1647  }
    1648  
    1649  /* This function was added to libpng 1.4.1 */
    1650  void PNGAPI
    1651  png_set_chunk_malloc_max(png_structrp png_ptr,
    1652      png_alloc_size_t user_chunk_malloc_max)
    1653  {
    1654     if (png_ptr != NULL)
    1655        png_ptr->user_chunk_malloc_max = user_chunk_malloc_max;
    1656  }
    1657  #endif /* ?SET_USER_LIMITS */
    1658  
    1659  
    1660  #ifdef PNG_BENIGN_ERRORS_SUPPORTED
    1661  void PNGAPI
    1662  png_set_benign_errors(png_structrp png_ptr, int allowed)
    1663  {
    1664     png_debug(1, "in png_set_benign_errors");
    1665  
    1666     /* If allowed is 1, png_benign_error() is treated as a warning.
    1667      *
    1668      * If allowed is 0, png_benign_error() is treated as an error (which
    1669      * is the default behavior if png_set_benign_errors() is not called).
    1670      */
    1671  
    1672     if (allowed != 0)
    1673        png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN |
    1674           PNG_FLAG_APP_WARNINGS_WARN | PNG_FLAG_APP_ERRORS_WARN;
    1675  
    1676     else
    1677        png_ptr->flags &= ~(PNG_FLAG_BENIGN_ERRORS_WARN |
    1678           PNG_FLAG_APP_WARNINGS_WARN | PNG_FLAG_APP_ERRORS_WARN);
    1679  }
    1680  #endif /* BENIGN_ERRORS */
    1681  
    1682  #ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
    1683     /* Whether to report invalid palette index; added at libng-1.5.10.
    1684      * It is possible for an indexed (color-type==3) PNG file to contain
    1685      * pixels with invalid (out-of-range) indexes if the PLTE chunk has
    1686      * fewer entries than the image's bit-depth would allow. We recover
    1687      * from this gracefully by filling any incomplete palette with zeros
    1688      * (opaque black).  By default, when this occurs libpng will issue
    1689      * a benign error.  This API can be used to override that behavior.
    1690      */
    1691  void PNGAPI
    1692  png_set_check_for_invalid_index(png_structrp png_ptr, int allowed)
    1693  {
    1694     png_debug(1, "in png_set_check_for_invalid_index");
    1695  
    1696     if (allowed > 0)
    1697        png_ptr->num_palette_max = 0;
    1698  
    1699     else
    1700        png_ptr->num_palette_max = -1;
    1701  }
    1702  #endif
    1703  
    1704  #if defined(PNG_TEXT_SUPPORTED) || defined(PNG_pCAL_SUPPORTED) || \
    1705      defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
    1706  /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
    1707   * and if invalid, correct the keyword rather than discarding the entire
    1708   * chunk.  The PNG 1.0 specification requires keywords 1-79 characters in
    1709   * length, forbids leading or trailing whitespace, multiple internal spaces,
    1710   * and the non-break space (0x80) from ISO 8859-1.  Returns keyword length.
    1711   *
    1712   * The 'new_key' buffer must be 80 characters in size (for the keyword plus a
    1713   * trailing '\0').  If this routine returns 0 then there was no keyword, or a
    1714   * valid one could not be generated, and the caller must png_error.
    1715   */
    1716  png_uint_32 /* PRIVATE */
    1717  png_check_keyword(png_structrp png_ptr, png_const_charp key, png_bytep new_key)
    1718  {
    1719  #ifdef PNG_WARNINGS_SUPPORTED
    1720     png_const_charp orig_key = key;
    1721  #endif
    1722     png_uint_32 key_len = 0;
    1723     int bad_character = 0;
    1724     int space = 1;
    1725  
    1726     png_debug(1, "in png_check_keyword");
    1727  
    1728     if (key == NULL)
    1729     {
    1730        *new_key = 0;
    1731        return 0;
    1732     }
    1733  
    1734     while (*key && key_len < 79)
    1735     {
    1736        png_byte ch = (png_byte)*key++;
    1737  
    1738        if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/))
    1739        {
    1740           *new_key++ = ch; ++key_len; space = 0;
    1741        }
    1742  
    1743        else if (space == 0)
    1744        {
    1745           /* A space or an invalid character when one wasn't seen immediately
    1746            * before; output just a space.
    1747            */
    1748           *new_key++ = 32; ++key_len; space = 1;
    1749  
    1750           /* If the character was not a space then it is invalid. */
    1751           if (ch != 32)
    1752              bad_character = ch;
    1753        }
    1754  
    1755        else if (bad_character == 0)
    1756           bad_character = ch; /* just skip it, record the first error */
    1757     }
    1758  
    1759     if (key_len > 0 && space != 0) /* trailing space */
    1760     {
    1761        --key_len; --new_key;
    1762        if (bad_character == 0)
    1763           bad_character = 32;
    1764     }
    1765  
    1766     /* Terminate the keyword */
    1767     *new_key = 0;
    1768  
    1769     if (key_len == 0)
    1770        return 0;
    1771  
    1772  #ifdef PNG_WARNINGS_SUPPORTED
    1773     /* Try to only output one warning per keyword: */
    1774     if (*key != 0) /* keyword too long */
    1775        png_warning(png_ptr, "keyword truncated");
    1776  
    1777     else if (bad_character != 0)
    1778     {
    1779        PNG_WARNING_PARAMETERS(p)
    1780  
    1781        png_warning_parameter(p, 1, orig_key);
    1782        png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_02x, bad_character);
    1783  
    1784        png_formatted_warning(png_ptr, p, "keyword \"@1\": bad character '0x@2'");
    1785     }
    1786  #else /* !WARNINGS */
    1787     PNG_UNUSED(png_ptr)
    1788  #endif /* !WARNINGS */
    1789  
    1790     return key_len;
    1791  }
    1792  #endif /* TEXT || pCAL || iCCP || sPLT */
    1793  #endif /* READ || WRITE */