< prev index next >

src/java.desktop/share/native/libsplashscreen/libpng/png.c

Print this page




  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /* png.c - location for general purpose libpng functions
  26  *
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file and, per its terms, should not be removed:
  31  *
  32  * Last changed in libpng 1.6.28 [January 5, 2017]
  33  * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson
  34  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  35  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  36  *
  37  * This code is released under the libpng license.
  38  * For conditions of distribution and use, see the disclaimer
  39  * and license in png.h
  40  */
  41 
  42 #include "pngpriv.h"
  43 
  44 /* Generate a compiler error if there is an old png.h in the search path. */
  45 typedef png_libpng_version_1_6_28 Your_png_h_is_not_version_1_6_28;




















  46 
  47 /* Tells libpng that we have already handled the first "num_bytes" bytes
  48  * of the PNG file signature.  If the PNG data is embedded into another
  49  * stream we can set num_bytes = 8 so that libpng will not attempt to read
  50  * or write any of the magic bytes before it starts on the IHDR.
  51  */
  52 
  53 #ifdef PNG_READ_SUPPORTED
  54 void PNGAPI
  55 png_set_sig_bytes(png_structrp png_ptr, int num_bytes)
  56 {
  57    unsigned int nb = (unsigned int)num_bytes;
  58 
  59    png_debug(1, "in png_set_sig_bytes");
  60 
  61    if (png_ptr == NULL)
  62       return;
  63 
  64    if (num_bytes < 0)
  65       nb = 0;


 606       if (num != -1)
 607       {
 608           png_free(png_ptr, info_ptr->unknown_chunks[num].data);
 609           info_ptr->unknown_chunks[num].data = NULL;
 610       }
 611 
 612       else
 613       {
 614          int i;
 615 
 616          for (i = 0; i < info_ptr->unknown_chunks_num; i++)
 617             png_free(png_ptr, info_ptr->unknown_chunks[i].data);
 618 
 619          png_free(png_ptr, info_ptr->unknown_chunks);
 620          info_ptr->unknown_chunks = NULL;
 621          info_ptr->unknown_chunks_num = 0;
 622       }
 623    }
 624 #endif
 625 




















 626 #ifdef PNG_hIST_SUPPORTED
 627    /* Free any hIST entry */
 628    if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)
 629    {
 630       png_free(png_ptr, info_ptr->hist);
 631       info_ptr->hist = NULL;
 632       info_ptr->valid &= ~PNG_INFO_hIST;
 633    }
 634 #endif
 635 
 636    /* Free any PLTE entry that was internally allocated */
 637    if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)
 638    {
 639       png_free(png_ptr, info_ptr->palette);
 640       info_ptr->palette = NULL;
 641       info_ptr->valid &= ~PNG_INFO_PLTE;
 642       info_ptr->num_palette = 0;
 643    }
 644 
 645 #ifdef PNG_INFO_IMAGE_SUPPORTED


 787       else
 788          return png_ptr->time_buffer;
 789    }
 790 
 791    return NULL;
 792 }
 793 #    endif /* LIBPNG_VER < 10700 */
 794 #  endif /* TIME_RFC1123 */
 795 
 796 #endif /* READ || WRITE */
 797 
 798 png_const_charp PNGAPI
 799 png_get_copyright(png_const_structrp png_ptr)
 800 {
 801    PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
 802 #ifdef PNG_STRING_COPYRIGHT
 803    return PNG_STRING_COPYRIGHT
 804 #else
 805 #  ifdef __STDC__
 806    return PNG_STRING_NEWLINE \
 807       "libpng version 1.6.28 - January 5, 2017" PNG_STRING_NEWLINE \
 808       "Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson" \
 809       PNG_STRING_NEWLINE \
 810       "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
 811       "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
 812       PNG_STRING_NEWLINE;
 813 #  else
 814    return "libpng version 1.6.28 - January 5, 2017\
 815       Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson\
 816       Copyright (c) 1996-1997 Andreas Dilger\
 817       Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
 818 #  endif
 819 #endif
 820 }
 821 
 822 /* The following return the library version as a short string in the
 823  * format 1.0.0 through 99.99.99zz.  To get the version of *.h files
 824  * used with your application, print out PNG_LIBPNG_VER_STRING, which
 825  * is defined in png.h.
 826  * Note: now there is no difference between png_get_libpng_ver() and
 827  * png_get_header_ver().  Due to the version_nn_nn_nn typedef guard,
 828  * it is guaranteed that png.c uses the correct version of png.h.
 829  */
 830 png_const_charp PNGAPI
 831 png_get_libpng_ver(png_const_structrp png_ptr)
 832 {
 833    /* Version of *.c files used when building libpng */
 834    return png_get_header_ver(png_ptr);


1884       /* red   */ 41239, 21264,  1933,
1885       /* green */ 35758, 71517, 11919,
1886       /* blue  */ 18048,  7219, 95053
1887    };
1888 
1889    /* Do nothing if the colorspace is already invalidated. */
1890    if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)
1891       return 0;
1892 
1893    /* Check the intent, then check for existing settings.  It is valid for the
1894     * PNG file to have cHRM or gAMA chunks along with sRGB, but the values must
1895     * be consistent with the correct values.  If, however, this function is
1896     * called below because an iCCP chunk matches sRGB then it is quite
1897     * conceivable that an older app recorded incorrect gAMA and cHRM because of
1898     * an incorrect calculation based on the values in the profile - this does
1899     * *not* invalidate the profile (though it still produces an error, which can
1900     * be ignored.)
1901     */
1902    if (intent < 0 || intent >= PNG_sRGB_INTENT_LAST)
1903       return png_icc_profile_error(png_ptr, colorspace, "sRGB",
1904           (unsigned)intent, "invalid sRGB rendering intent");
1905 
1906    if ((colorspace->flags & PNG_COLORSPACE_HAVE_INTENT) != 0 &&
1907        colorspace->rendering_intent != intent)
1908       return png_icc_profile_error(png_ptr, colorspace, "sRGB",
1909          (unsigned)intent, "inconsistent rendering intents");
1910 
1911    if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0)
1912    {
1913       png_benign_error(png_ptr, "duplicate sRGB information ignored");
1914       return 0;
1915    }
1916 
1917    /* If the standard sRGB cHRM chunk does not match the one from the PNG file
1918     * warn but overwrite the value with the correct one.
1919     */
1920    if ((colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0 &&
1921        !png_colorspace_endpoints_match(&sRGB_xy, &colorspace->end_points_xy,
1922        100))
1923       png_chunk_report(png_ptr, "cHRM chunk does not match sRGB",
1924          PNG_CHUNK_ERROR);
1925 
1926    /* This check is just done for the error reporting - the routine always
1927     * returns true when the 'from' argument corresponds to sRGB (2).
1928     */
1929    (void)png_colorspace_check_gamma(png_ptr, colorspace, PNG_GAMMA_sRGB_INVERSE,


1950    return 1; /* set */
1951 }
1952 #endif /* sRGB */
1953 
1954 #ifdef PNG_iCCP_SUPPORTED
1955 /* Encoded value of D50 as an ICC XYZNumber.  From the ICC 2010 spec the value
1956  * is XYZ(0.9642,1.0,0.8249), which scales to:
1957  *
1958  *    (63189.8112, 65536, 54060.6464)
1959  */
1960 static const png_byte D50_nCIEXYZ[12] =
1961    { 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };
1962 
1963 static int /* bool */
1964 icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,
1965     png_const_charp name, png_uint_32 profile_length)
1966 {
1967    if (profile_length < 132)
1968       return png_icc_profile_error(png_ptr, colorspace, name, profile_length,
1969           "too short");
1970 
1971    return 1;
1972 }
1973 
1974 #ifdef PNG_READ_iCCP_SUPPORTED
1975 int /* PRIVATE */
1976 png_icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,
1977     png_const_charp name, png_uint_32 profile_length)
1978 {
1979    if (!icc_check_length(png_ptr, colorspace, name, profile_length))
1980       return 0;
1981 
1982    /* This needs to be here because the 'normal' check is in
1983     * png_decompress_chunk, yet this happens after the attempt to
1984     * png_malloc_base the required data.  We only need this on read; on write
1985     * the caller supplies the profile buffer so libpng doesn't allocate it.  See
1986     * the call to icc_check_length below (the write case).
1987     */
1988 #  ifdef PNG_SET_USER_LIMITS_SUPPORTED
1989       else if (png_ptr->user_chunk_malloc_max > 0 &&
1990                png_ptr->user_chunk_malloc_max < profile_length)


2195 {
2196    png_uint_32 tag_count = png_get_uint_32(profile+128);
2197    png_uint_32 itag;
2198    png_const_bytep tag = profile+132; /* The first tag */
2199 
2200    /* First scan all the tags in the table and add bits to the icc_info value
2201     * (temporarily in 'tags').
2202     */
2203    for (itag=0; itag < tag_count; ++itag, tag += 12)
2204    {
2205       png_uint_32 tag_id = png_get_uint_32(tag+0);
2206       png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */
2207       png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */
2208 
2209       /* The ICC specification does not exclude zero length tags, therefore the
2210        * start might actually be anywhere if there is no data, but this would be
2211        * a clear abuse of the intent of the standard so the start is checked for
2212        * being in range.  All defined tag types have an 8 byte header - a 4 byte
2213        * type signature then 0.
2214        */








2215       if ((tag_start & 3) != 0)
2216       {
2217          /* CNHP730S.icc shipped with Microsoft Windows 64 violates this, it is
2218           * only a warning here because libpng does not care about the
2219           * alignment.
2220           */
2221          (void)png_icc_profile_error(png_ptr, NULL, name, tag_id,
2222              "ICC profile tag start not a multiple of 4");
2223       }
2224 
2225       /* This is a hard error; potentially it can cause read outside the
2226        * profile.
2227        */
2228       if (tag_start > profile_length || tag_length > profile_length - tag_start)
2229          return png_icc_profile_error(png_ptr, colorspace, name, tag_id,
2230              "ICC profile tag outside profile");
2231    }
2232 
2233    return 1; /* success, maybe with warnings */
2234 }
2235 
2236 #ifdef PNG_sRGB_SUPPORTED
2237 #if PNG_sRGB_PROFILE_CHECKS >= 0
2238 /* Information about the known ICC sRGB profiles */
2239 static const struct
2240 {
2241    png_uint_32 adler, crc, length;
2242    png_uint_32 md5[4];
2243    png_byte    have_md5;
2244    png_byte    is_broken;
2245    png_uint_16 intent;
2246 
2247 #  define PNG_MD5(a,b,c,d) { a, b, c, d }, (a!=0)||(b!=0)||(c!=0)||(d!=0)
2248 #  define PNG_ICC_CHECKSUM(adler, crc, md5, intent, broke, date, length, fname)\
2249       { adler, crc, length, md5, broke, intent },
2250 


2843 }
2844 #endif /* pCAL || sCAL */
2845 
2846 #ifdef PNG_sCAL_SUPPORTED
2847 #  ifdef PNG_FLOATING_POINT_SUPPORTED
2848 /* Utility used below - a simple accurate power of ten from an integral
2849  * exponent.
2850  */
2851 static double
2852 png_pow10(int power)
2853 {
2854    int recip = 0;
2855    double d = 1;
2856 
2857    /* Handle negative exponent with a reciprocal at the end because
2858     * 10 is exact whereas .1 is inexact in base 2
2859     */
2860    if (power < 0)
2861    {
2862       if (power < DBL_MIN_10_EXP) return 0;
2863       recip = 1, power = -power;
2864    }
2865 
2866    if (power > 0)
2867    {
2868       /* Decompose power bitwise. */
2869       double mult = 10;
2870       do
2871       {
2872          if (power & 1) d *= mult;
2873          mult *= mult;
2874          power >>= 1;
2875       }
2876       while (power > 0);
2877 
2878       if (recip != 0) d = 1/d;
2879    }
2880    /* else power is 0 and d is 1 */
2881 
2882    return d;
2883 }
2884 
2885 /* Function to format a floating point value in ASCII with a given
2886  * precision.
2887  */








2888 void /* PRIVATE */
2889 png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
2890     double fp, unsigned int precision)
2891 {
2892    /* We use standard functions from math.h, but not printf because
2893     * that would require stdio.  The caller must supply a buffer of
2894     * sufficient size or we will png_error.  The tests on size and
2895     * the space in ascii[] consumed are indicated below.
2896     */
2897    if (precision < 1)
2898       precision = DBL_DIG;
2899 
2900    /* Enforce the limit of the implementation precision too. */
2901    if (precision > DBL_DIG+1)
2902       precision = DBL_DIG+1;
2903 
2904    /* Basic sanity checks */
2905    if (size >= precision+5) /* See the requirements below. */
2906    {
2907       if (fp < 0)


2921           * from base 2 to base 10 (multiply by log10(2) -
2922           * 0.3010, but 77/256 is 0.3008, so exp_b10 needs to
2923           * be increased.  Note that the arithmetic shift
2924           * performs a floor() unlike C arithmetic - using a
2925           * C multiply would break the following for negative
2926           * exponents.
2927           */
2928          (void)frexp(fp, &exp_b10); /* exponent to base 2 */
2929 
2930          exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
2931 
2932          /* Avoid underflow here. */
2933          base = png_pow10(exp_b10); /* May underflow */
2934 
2935          while (base < DBL_MIN || base < fp)
2936          {
2937             /* And this may overflow. */
2938             double test = png_pow10(exp_b10+1);
2939 
2940             if (test <= DBL_MAX)
2941                ++exp_b10, base = test;


2942 
2943             else
2944                break;
2945          }
2946 
2947          /* Normalize fp and correct exp_b10, after this fp is in the
2948           * range [.1,1) and exp_b10 is both the exponent and the digit
2949           * *before* which the decimal point should be inserted
2950           * (starting with 0 for the first digit).  Note that this
2951           * works even if 10^exp_b10 is out of range because of the
2952           * test on DBL_MAX above.
2953           */
2954          fp /= base;
2955          while (fp >= 1) fp /= 10, ++exp_b10;



2956 
2957          /* Because of the code above fp may, at this point, be
2958           * less than .1, this is ok because the code below can
2959           * handle the leading zeros this generates, so no attempt
2960           * is made to correct that here.
2961           */
2962 
2963          {
2964             unsigned int czero, clead, cdigits;
2965             char exponent[10];
2966 
2967             /* Allow up to two leading zeros - this will not lengthen
2968              * the number compared to using E-n.
2969              */
2970             if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
2971             {
2972                czero = (unsigned int)(-exp_b10); /* PLUS 2 digits: TOTAL 3 */
2973                exp_b10 = 0;      /* Dot added below before first output. */
2974             }
2975             else
2976                czero = 0;    /* No zeros to add */
2977 
2978             /* Generate the digit list, stripping trailing zeros and
2979              * inserting a '.' before a digit if the exponent is 0.
2980              */
2981             clead = czero; /* Count of leading zeros */
2982             cdigits = 0;   /* Count of digits in list. */
2983 
2984             do
2985             {
2986                double d;
2987 
2988                fp *= 10;
2989                /* Use modf here, not floor and subtract, so that
2990                 * the separation is done in one step.  At the end
2991                 * of the loop don't break the number into parts so
2992                 * that the final digit is rounded.
2993                 */
2994                if (cdigits+czero+1 < precision+clead)
2995                   fp = modf(fp, &d);
2996 
2997                else
2998                {
2999                   d = floor(fp + .5);
3000 
3001                   if (d > 9)
3002                   {
3003                      /* Rounding up to 10, handle that here. */
3004                      if (czero > 0)
3005                      {
3006                         --czero, d = 1;
3007                         if (cdigits == 0) --clead;
3008                      }
3009                      else
3010                      {
3011                         while (cdigits > 0 && d > 9)
3012                         {
3013                            int ch = *--ascii;
3014 
3015                            if (exp_b10 != (-1))
3016                               ++exp_b10;
3017 
3018                            else if (ch == 46)
3019                            {
3020                               ch = *--ascii, ++size;
3021                               /* Advance exp_b10 to '1', so that the
3022                                * decimal point happens after the
3023                                * previous digit.
3024                                */
3025                               exp_b10 = 1;
3026                            }
3027 
3028                            --cdigits;
3029                            d = ch - 47;  /* I.e. 1+(ch-48) */
3030                         }
3031 
3032                         /* Did we reach the beginning? If so adjust the
3033                          * exponent but take into account the leading
3034                          * decimal point.
3035                          */
3036                         if (d > 9)  /* cdigits == 0 */
3037                         {
3038                            if (exp_b10 == (-1))
3039                            {
3040                               /* Leading decimal point (plus zeros?), if
3041                                * we lose the decimal point here it must
3042                                * be reentered below.
3043                                */
3044                               int ch = *--ascii;
3045 
3046                               if (ch == 46)
3047                                  ++size, exp_b10 = 1;


3048 
3049                               /* Else lost a leading zero, so 'exp_b10' is
3050                                * still ok at (-1)
3051                                */
3052                            }
3053                            else
3054                               ++exp_b10;
3055 
3056                            /* In all cases we output a '1' */
3057                            d = 1;
3058                         }
3059                      }
3060                   }
3061                   fp = 0; /* Guarantees termination below. */
3062                }
3063 
3064                if (d == 0)
3065                {
3066                   ++czero;
3067                   if (cdigits == 0) ++clead;
3068                }
3069                else
3070                {
3071                   /* Included embedded zeros in the digit count. */
3072                   cdigits += czero - clead;
3073                   clead = 0;
3074 
3075                   while (czero > 0)
3076                   {
3077                      /* exp_b10 == (-1) means we just output the decimal
3078                       * place - after the DP don't adjust 'exp_b10' any
3079                       * more!
3080                       */
3081                      if (exp_b10 != (-1))
3082                      {
3083                         if (exp_b10 == 0) *ascii++ = 46, --size;



3084                         /* PLUS 1: TOTAL 4 */
3085                         --exp_b10;
3086                      }
3087                      *ascii++ = 48, --czero;
3088                   }
3089 
3090                   if (exp_b10 != (-1))
3091                   {
3092                      if (exp_b10 == 0)
3093                         *ascii++ = 46, --size; /* counted above */


3094 
3095                      --exp_b10;
3096                   }
3097                   *ascii++ = (char)(48 + (int)d), ++cdigits;
3098                }
3099             }
3100             while (cdigits+czero < precision+clead && fp > DBL_MIN);
3101 
3102             /* The total output count (max) is now 4+precision */
3103 
3104             /* Check for an exponent, if we don't need one we are
3105              * done and just need to terminate the string.  At
3106              * this point exp_b10==(-1) is effectively if flag - it got
3107              * to '-1' because of the decrement after outputting
3108              * the decimal point above (the exponent required is
3109              * *not* -1!)
3110              */
3111             if (exp_b10 >= (-1) && exp_b10 <= 2)
3112             {
3113                /* The following only happens if we didn't output the
3114                 * leading zeros above for negative exponent, so this
3115                 * doesn't add to the digit requirement.  Note that the
3116                 * two zeros here can only be output if the two leading
3117                 * zeros were *not* output, so this doesn't increase
3118                 * the output count.
3119                 */
3120                while (--exp_b10 >= 0) *ascii++ = 48;
3121 
3122                *ascii = 0;
3123 
3124                /* Total buffer requirement (including the '\0') is
3125                 * 5+precision - see check at the start.
3126                 */
3127                return;
3128             }
3129 
3130             /* Here if an exponent is required, adjust size for
3131              * the digits we output but did not count.  The total
3132              * digit output here so far is at most 1+precision - no
3133              * decimal point and no leading or trailing zeros have
3134              * been output.
3135              */
3136             size -= cdigits;
3137 
3138             *ascii++ = 69, --size;    /* 'E': PLUS 1 TOTAL 2+precision */
3139 
3140             /* The following use of an unsigned temporary avoids ambiguities in
3141              * the signed arithmetic on exp_b10 and permits GCC at least to do
3142              * better optimization.
3143              */
3144             {
3145                unsigned int uexp_b10;
3146 
3147                if (exp_b10 < 0)
3148                {
3149                   *ascii++ = 45, --size; /* '-': PLUS 1 TOTAL 3+precision */
3150                   uexp_b10 = (unsigned int)(-exp_b10);
3151                }
3152 
3153                else
3154                   uexp_b10 = (unsigned int)exp_b10;
3155 
3156                cdigits = 0;
3157 
3158                while (uexp_b10 > 0)
3159                {
3160                   exponent[cdigits++] = (char)(48 + uexp_b10 % 10);
3161                   uexp_b10 /= 10;
3162                }
3163             }
3164 
3165             /* Need another size check here for the exponent digits, so
3166              * this need not be considered above.
3167              */
3168             if (size > cdigits)
3169             {
3170                while (cdigits > 0) *ascii++ = exponent[--cdigits];
3171 
3172                *ascii = 0;
3173 
3174                return;


3177       }
3178       else if (!(fp >= DBL_MIN))
3179       {
3180          *ascii++ = 48; /* '0' */
3181          *ascii = 0;
3182          return;
3183       }
3184       else
3185       {
3186          *ascii++ = 105; /* 'i' */
3187          *ascii++ = 110; /* 'n' */
3188          *ascii++ = 102; /* 'f' */
3189          *ascii = 0;
3190          return;
3191       }
3192    }
3193 
3194    /* Here on buffer too small. */
3195    png_error(png_ptr, "ASCII conversion buffer too small");
3196 }



3197 
3198 #  endif /* FLOATING_POINT */
3199 
3200 #  ifdef PNG_FIXED_POINT_SUPPORTED
3201 /* Function to format a fixed point value in ASCII.
3202  */
3203 void /* PRIVATE */
3204 png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
3205     png_size_t size, png_fixed_point fp)
3206 {
3207    /* Require space for 10 decimal digits, a decimal point, a minus sign and a
3208     * trailing \0, 13 characters:
3209     */
3210    if (size > 12)
3211    {
3212       png_uint_32 num;
3213 
3214       /* Avoid overflow here on the minimum integer. */
3215       if (fp < 0)
3216          *ascii++ = 45, num = (png_uint_32)(-fp);


3217       else
3218          num = (png_uint_32)fp;
3219 
3220       if (num <= 0x80000000) /* else overflowed */
3221       {
3222          unsigned int ndigits = 0, first = 16 /* flag value */;
3223          char digits[10];
3224 
3225          while (num)
3226          {
3227             /* Split the low digit off num: */
3228             unsigned int tmp = num/10;
3229             num -= tmp*10;
3230             digits[ndigits++] = (char)(48 + num);
3231             /* Record the first non-zero digit, note that this is a number
3232              * starting at 1, it's not actually the array index.
3233              */
3234             if (first == 16 && num > 0)
3235                first = ndigits;
3236             num = tmp;
3237          }
3238 
3239          if (ndigits > 0)
3240          {
3241             while (ndigits > 5) *ascii++ = digits[--ndigits];
3242             /* The remaining digits are fractional digits, ndigits is '5' or
3243              * smaller at this point.  It is certainly not zero.  Check for a
3244              * non-zero fractional digit:
3245              */
3246             if (first <= 5)
3247             {
3248                unsigned int i;
3249                *ascii++ = 46; /* decimal point */
3250                /* ndigits may be <5 for small numbers, output leading zeros
3251                 * then ndigits digits to first:
3252                 */
3253                i = 5;
3254                while (ndigits < i) *ascii++ = 48, --i;



3255                while (ndigits >= first) *ascii++ = digits[--ndigits];
3256                /* Don't output the trailing zeros! */
3257             }
3258          }
3259          else
3260             *ascii++ = 48;
3261 
3262          /* And null terminate the string: */
3263          *ascii = 0;
3264          return;
3265       }
3266    }
3267 
3268    /* Here on buffer too small. */
3269    png_error(png_ptr, "ASCII conversion buffer too small");
3270 }
3271 #   endif /* FIXED_POINT */
3272 #endif /* SCAL */
3273 
3274 #if defined(PNG_FLOATING_POINT_SUPPORTED) && \


3285 
3286    if (r > 2147483647. || r < -2147483648.)
3287       png_fixed_error(png_ptr, text);
3288 
3289 #  ifndef PNG_ERROR_TEXT_SUPPORTED
3290    PNG_UNUSED(text)
3291 #  endif
3292 
3293    return (png_fixed_point)r;
3294 }
3295 #endif
3296 
3297 #if defined(PNG_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\
3298     defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)
3299 /* muldiv functions */
3300 /* This API takes signed arguments and rounds the result to the nearest
3301  * integer (or, for a fixed point number - the standard argument - to
3302  * the nearest .00001).  Overflow and divide by zero are signalled in
3303  * the result, a boolean - true on success, false on overflow.
3304  */









3305 int
3306 png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
3307     png_int_32 divisor)
3308 {
3309    /* Return a * times / divisor, rounded. */
3310    if (divisor != 0)
3311    {
3312       if (a == 0 || times == 0)
3313       {
3314          *res = 0;
3315          return 1;
3316       }
3317       else
3318       {
3319 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
3320          double r = a;
3321          r *= times;
3322          r /= divisor;
3323          r = floor(r+.5);
3324 


3399             if (s00 >= (D >> 1))
3400                ++result;
3401 
3402             if (negative != 0)
3403                result = -result;
3404 
3405             /* Check for overflow. */
3406             if ((negative != 0 && result <= 0) ||
3407                 (negative == 0 && result >= 0))
3408             {
3409                *res = result;
3410                return 1;
3411             }
3412          }
3413 #endif
3414       }
3415    }
3416 
3417    return 0;
3418 }



3419 #endif /* READ_GAMMA || INCH_CONVERSIONS */
3420 
3421 #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
3422 /* The following is for when the caller doesn't much care about the
3423  * result.
3424  */
3425 png_fixed_point
3426 png_muldiv_warn(png_const_structrp png_ptr, png_fixed_point a, png_int_32 times,
3427     png_int_32 divisor)
3428 {
3429    png_fixed_point result;
3430 
3431    if (png_muldiv(&result, a, times, divisor) != 0)
3432       return result;
3433 
3434    png_warning(png_ptr, "fixed point overflow ignored");
3435    return 0;
3436 }
3437 #endif
3438 


3692 
3693    else
3694       lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
3695 
3696    /* Safe, because the result can't have more than 20 bits: */
3697    return (png_int_32)((lg2 + 2048) >> 12);
3698 }
3699 #endif /* 16BIT */
3700 
3701 /* The 'exp()' case must invert the above, taking a 20-bit fixed point
3702  * logarithmic value and returning a 16 or 8-bit number as appropriate.  In
3703  * each case only the low 16 bits are relevant - the fraction - since the
3704  * integer bits (the top 4) simply determine a shift.
3705  *
3706  * The worst case is the 16-bit distinction between 65535 and 65534. This
3707  * requires perhaps spurious accuracy in the decoding of the logarithm to
3708  * distinguish log2(65535/65534.5) - 10^-5 or 17 bits.  There is little chance
3709  * of getting this accuracy in practice.
3710  *
3711  * To deal with this the following exp() function works out the exponent of the
3712  * frational part of the logarithm by using an accurate 32-bit value from the
3713  * top four fractional bits then multiplying in the remaining bits.
3714  */
3715 static const png_uint_32
3716 png_32bit_exp[16] =
3717 {
3718    /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
3719    4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
3720    3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
3721    2553802834U, 2445529972U, 2341847524U, 2242560872U
3722 };
3723 
3724 /* Adjustment table; provided to explain the numbers in the code below. */
3725 #if 0
3726 for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
3727    11 44937.64284865548751208448
3728    10 45180.98734845585101160448
3729     9 45303.31936980687359311872
3730     8 45364.65110595323018870784
3731     7 45395.35850361789624614912
3732     6 45410.72259715102037508096


4271           * TODO: fix this.
4272           */
4273          png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
4274              png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
4275              png_ptr->colorspace.gamma/* Probably doing rgb_to_gray */);
4276       }
4277 #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
4278    }
4279 #endif /* 16BIT */
4280 }
4281 #endif /* READ_GAMMA */
4282 
4283 /* HARDWARE OR SOFTWARE OPTION SUPPORT */
4284 #ifdef PNG_SET_OPTION_SUPPORTED
4285 int PNGAPI
4286 png_set_option(png_structrp png_ptr, int option, int onoff)
4287 {
4288    if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
4289       (option & 1) == 0)
4290    {
4291       png_uint_32 mask = 3 << option;
4292       png_uint_32 setting = (2 + (onoff != 0)) << option;
4293       png_uint_32 current = png_ptr->options;
4294 
4295       png_ptr->options = (png_uint_32)(((current & ~mask) | setting) & 0xff);
4296 
4297       return (current & mask) >> option;
4298    }
4299 
4300    return PNG_OPTION_INVALID;
4301 }
4302 #endif
4303 
4304 /* sRGB support */
4305 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
4306    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
4307 /* sRGB conversion tables; these are machine generated with the code in
4308  * contrib/tools/makesRGB.c.  The actual sRGB transfer curve defined in the
4309  * specification (see the article at http://en.wikipedia.org/wiki/SRGB)
4310  * is used, not the gamma=1/2.2 approximation use elsewhere in libpng.
4311  * The sRGB to linear table is exact (to the nearest 16-bit linear fraction).
4312  * The inverse (linear to sRGB) table has accuracies as follows:
4313  *
4314  * For all possible (255*65535+1) input values:
4315  *
4316  *    error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact
4317  *
4318  * For the input values corresponding to the 65536 16-bit values:
4319  *
4320  *    error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact
4321  *
4322  * In all cases the inexact readings are only off by one.
4323  */
4324 
4325 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
4326 /* The convert-to-sRGB table is only currently required for read. */
4327 const png_uint_16 png_sRGB_table[256] =
4328 {
4329    0,20,40,60,80,99,119,139,




  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /* png.c - location for general purpose libpng functions
  26  *
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file and, per its terms, should not be removed:
  31  *
  32  * Last changed in libpng 1.6.33 [September 28, 2017]
  33  * Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson
  34  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  35  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  36  *
  37  * This code is released under the libpng license.
  38  * For conditions of distribution and use, see the disclaimer
  39  * and license in png.h
  40  */
  41 
  42 #include "pngpriv.h"
  43 
  44 /* Generate a compiler error if there is an old png.h in the search path. */
  45 typedef png_libpng_version_1_6_34 Your_png_h_is_not_version_1_6_34;
  46 
  47 #ifdef __GNUC__
  48 /* The version tests may need to be added to, but the problem warning has
  49  * consistently been fixed in GCC versions which obtain wide-spread release.
  50  * The problem is that many versions of GCC rearrange comparison expressions in
  51  * the optimizer in such a way that the results of the comparison will change
  52  * if signed integer overflow occurs.  Such comparisons are not permitted in
  53  * ANSI C90, however GCC isn't clever enough to work out that that do not occur
  54  * below in png_ascii_from_fp and png_muldiv, so it produces a warning with
  55  * -Wextra.  Unfortunately this is highly dependent on the optimizer and the
  56  * machine architecture so the warning comes and goes unpredictably and is
  57  * impossible to "fix", even were that a good idea.
  58  */
  59 #if __GNUC__ == 7 && __GNUC_MINOR__ == 1
  60 #define GCC_STRICT_OVERFLOW 1
  61 #endif /* GNU 7.1.x */
  62 #endif /* GNU */
  63 #ifndef GCC_STRICT_OVERFLOW
  64 #define GCC_STRICT_OVERFLOW 0
  65 #endif
  66 
  67 /* Tells libpng that we have already handled the first "num_bytes" bytes
  68  * of the PNG file signature.  If the PNG data is embedded into another
  69  * stream we can set num_bytes = 8 so that libpng will not attempt to read
  70  * or write any of the magic bytes before it starts on the IHDR.
  71  */
  72 
  73 #ifdef PNG_READ_SUPPORTED
  74 void PNGAPI
  75 png_set_sig_bytes(png_structrp png_ptr, int num_bytes)
  76 {
  77    unsigned int nb = (unsigned int)num_bytes;
  78 
  79    png_debug(1, "in png_set_sig_bytes");
  80 
  81    if (png_ptr == NULL)
  82       return;
  83 
  84    if (num_bytes < 0)
  85       nb = 0;


 626       if (num != -1)
 627       {
 628           png_free(png_ptr, info_ptr->unknown_chunks[num].data);
 629           info_ptr->unknown_chunks[num].data = NULL;
 630       }
 631 
 632       else
 633       {
 634          int i;
 635 
 636          for (i = 0; i < info_ptr->unknown_chunks_num; i++)
 637             png_free(png_ptr, info_ptr->unknown_chunks[i].data);
 638 
 639          png_free(png_ptr, info_ptr->unknown_chunks);
 640          info_ptr->unknown_chunks = NULL;
 641          info_ptr->unknown_chunks_num = 0;
 642       }
 643    }
 644 #endif
 645 
 646 #ifdef PNG_eXIf_SUPPORTED
 647    /* Free any eXIf entry */
 648    if (((mask & PNG_FREE_EXIF) & info_ptr->free_me) != 0)
 649    {
 650 # ifdef PNG_READ_eXIf_SUPPORTED
 651       if (info_ptr->eXIf_buf)
 652       {
 653          png_free(png_ptr, info_ptr->eXIf_buf);
 654          info_ptr->eXIf_buf = NULL;
 655       }
 656 # endif
 657       if (info_ptr->exif)
 658       {
 659          png_free(png_ptr, info_ptr->exif);
 660          info_ptr->exif = NULL;
 661       }
 662       info_ptr->valid &= ~PNG_INFO_eXIf;
 663    }
 664 #endif
 665 
 666 #ifdef PNG_hIST_SUPPORTED
 667    /* Free any hIST entry */
 668    if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)
 669    {
 670       png_free(png_ptr, info_ptr->hist);
 671       info_ptr->hist = NULL;
 672       info_ptr->valid &= ~PNG_INFO_hIST;
 673    }
 674 #endif
 675 
 676    /* Free any PLTE entry that was internally allocated */
 677    if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)
 678    {
 679       png_free(png_ptr, info_ptr->palette);
 680       info_ptr->palette = NULL;
 681       info_ptr->valid &= ~PNG_INFO_PLTE;
 682       info_ptr->num_palette = 0;
 683    }
 684 
 685 #ifdef PNG_INFO_IMAGE_SUPPORTED


 827       else
 828          return png_ptr->time_buffer;
 829    }
 830 
 831    return NULL;
 832 }
 833 #    endif /* LIBPNG_VER < 10700 */
 834 #  endif /* TIME_RFC1123 */
 835 
 836 #endif /* READ || WRITE */
 837 
 838 png_const_charp PNGAPI
 839 png_get_copyright(png_const_structrp png_ptr)
 840 {
 841    PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
 842 #ifdef PNG_STRING_COPYRIGHT
 843    return PNG_STRING_COPYRIGHT
 844 #else
 845 #  ifdef __STDC__
 846    return PNG_STRING_NEWLINE \
 847       "libpng version 1.6.34 - September 29, 2017" PNG_STRING_NEWLINE \
 848       "Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson" \
 849       PNG_STRING_NEWLINE \
 850       "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
 851       "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
 852       PNG_STRING_NEWLINE;
 853 #  else
 854    return "libpng version 1.6.34 - September 29, 2017\
 855       Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson\
 856       Copyright (c) 1996-1997 Andreas Dilger\
 857       Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
 858 #  endif
 859 #endif
 860 }
 861 
 862 /* The following return the library version as a short string in the
 863  * format 1.0.0 through 99.99.99zz.  To get the version of *.h files
 864  * used with your application, print out PNG_LIBPNG_VER_STRING, which
 865  * is defined in png.h.
 866  * Note: now there is no difference between png_get_libpng_ver() and
 867  * png_get_header_ver().  Due to the version_nn_nn_nn typedef guard,
 868  * it is guaranteed that png.c uses the correct version of png.h.
 869  */
 870 png_const_charp PNGAPI
 871 png_get_libpng_ver(png_const_structrp png_ptr)
 872 {
 873    /* Version of *.c files used when building libpng */
 874    return png_get_header_ver(png_ptr);


1924       /* red   */ 41239, 21264,  1933,
1925       /* green */ 35758, 71517, 11919,
1926       /* blue  */ 18048,  7219, 95053
1927    };
1928 
1929    /* Do nothing if the colorspace is already invalidated. */
1930    if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)
1931       return 0;
1932 
1933    /* Check the intent, then check for existing settings.  It is valid for the
1934     * PNG file to have cHRM or gAMA chunks along with sRGB, but the values must
1935     * be consistent with the correct values.  If, however, this function is
1936     * called below because an iCCP chunk matches sRGB then it is quite
1937     * conceivable that an older app recorded incorrect gAMA and cHRM because of
1938     * an incorrect calculation based on the values in the profile - this does
1939     * *not* invalidate the profile (though it still produces an error, which can
1940     * be ignored.)
1941     */
1942    if (intent < 0 || intent >= PNG_sRGB_INTENT_LAST)
1943       return png_icc_profile_error(png_ptr, colorspace, "sRGB",
1944           (png_alloc_size_t)intent, "invalid sRGB rendering intent");
1945 
1946    if ((colorspace->flags & PNG_COLORSPACE_HAVE_INTENT) != 0 &&
1947        colorspace->rendering_intent != intent)
1948       return png_icc_profile_error(png_ptr, colorspace, "sRGB",
1949          (png_alloc_size_t)intent, "inconsistent rendering intents");
1950 
1951    if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0)
1952    {
1953       png_benign_error(png_ptr, "duplicate sRGB information ignored");
1954       return 0;
1955    }
1956 
1957    /* If the standard sRGB cHRM chunk does not match the one from the PNG file
1958     * warn but overwrite the value with the correct one.
1959     */
1960    if ((colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0 &&
1961        !png_colorspace_endpoints_match(&sRGB_xy, &colorspace->end_points_xy,
1962        100))
1963       png_chunk_report(png_ptr, "cHRM chunk does not match sRGB",
1964          PNG_CHUNK_ERROR);
1965 
1966    /* This check is just done for the error reporting - the routine always
1967     * returns true when the 'from' argument corresponds to sRGB (2).
1968     */
1969    (void)png_colorspace_check_gamma(png_ptr, colorspace, PNG_GAMMA_sRGB_INVERSE,


1990    return 1; /* set */
1991 }
1992 #endif /* sRGB */
1993 
1994 #ifdef PNG_iCCP_SUPPORTED
1995 /* Encoded value of D50 as an ICC XYZNumber.  From the ICC 2010 spec the value
1996  * is XYZ(0.9642,1.0,0.8249), which scales to:
1997  *
1998  *    (63189.8112, 65536, 54060.6464)
1999  */
2000 static const png_byte D50_nCIEXYZ[12] =
2001    { 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };
2002 
2003 static int /* bool */
2004 icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,
2005     png_const_charp name, png_uint_32 profile_length)
2006 {
2007    if (profile_length < 132)
2008       return png_icc_profile_error(png_ptr, colorspace, name, profile_length,
2009           "too short");

2010    return 1;
2011 }
2012 
2013 #ifdef PNG_READ_iCCP_SUPPORTED
2014 int /* PRIVATE */
2015 png_icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,
2016     png_const_charp name, png_uint_32 profile_length)
2017 {
2018    if (!icc_check_length(png_ptr, colorspace, name, profile_length))
2019       return 0;
2020 
2021    /* This needs to be here because the 'normal' check is in
2022     * png_decompress_chunk, yet this happens after the attempt to
2023     * png_malloc_base the required data.  We only need this on read; on write
2024     * the caller supplies the profile buffer so libpng doesn't allocate it.  See
2025     * the call to icc_check_length below (the write case).
2026     */
2027 #  ifdef PNG_SET_USER_LIMITS_SUPPORTED
2028       else if (png_ptr->user_chunk_malloc_max > 0 &&
2029                png_ptr->user_chunk_malloc_max < profile_length)


2234 {
2235    png_uint_32 tag_count = png_get_uint_32(profile+128);
2236    png_uint_32 itag;
2237    png_const_bytep tag = profile+132; /* The first tag */
2238 
2239    /* First scan all the tags in the table and add bits to the icc_info value
2240     * (temporarily in 'tags').
2241     */
2242    for (itag=0; itag < tag_count; ++itag, tag += 12)
2243    {
2244       png_uint_32 tag_id = png_get_uint_32(tag+0);
2245       png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */
2246       png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */
2247 
2248       /* The ICC specification does not exclude zero length tags, therefore the
2249        * start might actually be anywhere if there is no data, but this would be
2250        * a clear abuse of the intent of the standard so the start is checked for
2251        * being in range.  All defined tag types have an 8 byte header - a 4 byte
2252        * type signature then 0.
2253        */
2254 
2255       /* This is a hard error; potentially it can cause read outside the
2256        * profile.
2257        */
2258       if (tag_start > profile_length || tag_length > profile_length - tag_start)
2259          return png_icc_profile_error(png_ptr, colorspace, name, tag_id,
2260              "ICC profile tag outside profile");
2261 
2262       if ((tag_start & 3) != 0)
2263       {
2264          /* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is
2265           * only a warning here because libpng does not care about the
2266           * alignment.
2267           */
2268          (void)png_icc_profile_error(png_ptr, NULL, name, tag_id,
2269              "ICC profile tag start not a multiple of 4");
2270       }







2271    }
2272 
2273    return 1; /* success, maybe with warnings */
2274 }
2275 
2276 #ifdef PNG_sRGB_SUPPORTED
2277 #if PNG_sRGB_PROFILE_CHECKS >= 0
2278 /* Information about the known ICC sRGB profiles */
2279 static const struct
2280 {
2281    png_uint_32 adler, crc, length;
2282    png_uint_32 md5[4];
2283    png_byte    have_md5;
2284    png_byte    is_broken;
2285    png_uint_16 intent;
2286 
2287 #  define PNG_MD5(a,b,c,d) { a, b, c, d }, (a!=0)||(b!=0)||(c!=0)||(d!=0)
2288 #  define PNG_ICC_CHECKSUM(adler, crc, md5, intent, broke, date, length, fname)\
2289       { adler, crc, length, md5, broke, intent },
2290 


2883 }
2884 #endif /* pCAL || sCAL */
2885 
2886 #ifdef PNG_sCAL_SUPPORTED
2887 #  ifdef PNG_FLOATING_POINT_SUPPORTED
2888 /* Utility used below - a simple accurate power of ten from an integral
2889  * exponent.
2890  */
2891 static double
2892 png_pow10(int power)
2893 {
2894    int recip = 0;
2895    double d = 1;
2896 
2897    /* Handle negative exponent with a reciprocal at the end because
2898     * 10 is exact whereas .1 is inexact in base 2
2899     */
2900    if (power < 0)
2901    {
2902       if (power < DBL_MIN_10_EXP) return 0;
2903       recip = 1; power = -power;
2904    }
2905 
2906    if (power > 0)
2907    {
2908       /* Decompose power bitwise. */
2909       double mult = 10;
2910       do
2911       {
2912          if (power & 1) d *= mult;
2913          mult *= mult;
2914          power >>= 1;
2915       }
2916       while (power > 0);
2917 
2918       if (recip != 0) d = 1/d;
2919    }
2920    /* else power is 0 and d is 1 */
2921 
2922    return d;
2923 }
2924 
2925 /* Function to format a floating point value in ASCII with a given
2926  * precision.
2927  */
2928 #if GCC_STRICT_OVERFLOW
2929 #pragma GCC diagnostic push
2930 /* The problem arises below with exp_b10, which can never overflow because it
2931  * comes, originally, from frexp and is therefore limited to a range which is
2932  * typically +/-710 (log2(DBL_MAX)/log2(DBL_MIN)).
2933  */
2934 #pragma GCC diagnostic warning "-Wstrict-overflow=2"
2935 #endif /* GCC_STRICT_OVERFLOW */
2936 void /* PRIVATE */
2937 png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
2938     double fp, unsigned int precision)
2939 {
2940    /* We use standard functions from math.h, but not printf because
2941     * that would require stdio.  The caller must supply a buffer of
2942     * sufficient size or we will png_error.  The tests on size and
2943     * the space in ascii[] consumed are indicated below.
2944     */
2945    if (precision < 1)
2946       precision = DBL_DIG;
2947 
2948    /* Enforce the limit of the implementation precision too. */
2949    if (precision > DBL_DIG+1)
2950       precision = DBL_DIG+1;
2951 
2952    /* Basic sanity checks */
2953    if (size >= precision+5) /* See the requirements below. */
2954    {
2955       if (fp < 0)


2969           * from base 2 to base 10 (multiply by log10(2) -
2970           * 0.3010, but 77/256 is 0.3008, so exp_b10 needs to
2971           * be increased.  Note that the arithmetic shift
2972           * performs a floor() unlike C arithmetic - using a
2973           * C multiply would break the following for negative
2974           * exponents.
2975           */
2976          (void)frexp(fp, &exp_b10); /* exponent to base 2 */
2977 
2978          exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
2979 
2980          /* Avoid underflow here. */
2981          base = png_pow10(exp_b10); /* May underflow */
2982 
2983          while (base < DBL_MIN || base < fp)
2984          {
2985             /* And this may overflow. */
2986             double test = png_pow10(exp_b10+1);
2987 
2988             if (test <= DBL_MAX)
2989             {
2990                ++exp_b10; base = test;
2991             }
2992 
2993             else
2994                break;
2995          }
2996 
2997          /* Normalize fp and correct exp_b10, after this fp is in the
2998           * range [.1,1) and exp_b10 is both the exponent and the digit
2999           * *before* which the decimal point should be inserted
3000           * (starting with 0 for the first digit).  Note that this
3001           * works even if 10^exp_b10 is out of range because of the
3002           * test on DBL_MAX above.
3003           */
3004          fp /= base;
3005          while (fp >= 1)
3006          {
3007             fp /= 10; ++exp_b10;
3008          }
3009 
3010          /* Because of the code above fp may, at this point, be
3011           * less than .1, this is ok because the code below can
3012           * handle the leading zeros this generates, so no attempt
3013           * is made to correct that here.
3014           */
3015 
3016          {
3017             unsigned int czero, clead, cdigits;
3018             char exponent[10];
3019 
3020             /* Allow up to two leading zeros - this will not lengthen
3021              * the number compared to using E-n.
3022              */
3023             if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
3024             {
3025                czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */
3026                exp_b10 = 0;      /* Dot added below before first output. */
3027             }
3028             else
3029                czero = 0;    /* No zeros to add */
3030 
3031             /* Generate the digit list, stripping trailing zeros and
3032              * inserting a '.' before a digit if the exponent is 0.
3033              */
3034             clead = czero; /* Count of leading zeros */
3035             cdigits = 0;   /* Count of digits in list. */
3036 
3037             do
3038             {
3039                double d;
3040 
3041                fp *= 10;
3042                /* Use modf here, not floor and subtract, so that
3043                 * the separation is done in one step.  At the end
3044                 * of the loop don't break the number into parts so
3045                 * that the final digit is rounded.
3046                 */
3047                if (cdigits+czero+1 < precision+clead)
3048                   fp = modf(fp, &d);
3049 
3050                else
3051                {
3052                   d = floor(fp + .5);
3053 
3054                   if (d > 9)
3055                   {
3056                      /* Rounding up to 10, handle that here. */
3057                      if (czero > 0)
3058                      {
3059                         --czero; d = 1;
3060                         if (cdigits == 0) --clead;
3061                      }
3062                      else
3063                      {
3064                         while (cdigits > 0 && d > 9)
3065                         {
3066                            int ch = *--ascii;
3067 
3068                            if (exp_b10 != (-1))
3069                               ++exp_b10;
3070 
3071                            else if (ch == 46)
3072                            {
3073                               ch = *--ascii; ++size;
3074                               /* Advance exp_b10 to '1', so that the
3075                                * decimal point happens after the
3076                                * previous digit.
3077                                */
3078                               exp_b10 = 1;
3079                            }
3080 
3081                            --cdigits;
3082                            d = ch - 47;  /* I.e. 1+(ch-48) */
3083                         }
3084 
3085                         /* Did we reach the beginning? If so adjust the
3086                          * exponent but take into account the leading
3087                          * decimal point.
3088                          */
3089                         if (d > 9)  /* cdigits == 0 */
3090                         {
3091                            if (exp_b10 == (-1))
3092                            {
3093                               /* Leading decimal point (plus zeros?), if
3094                                * we lose the decimal point here it must
3095                                * be reentered below.
3096                                */
3097                               int ch = *--ascii;
3098 
3099                               if (ch == 46)
3100                               {
3101                                  ++size; exp_b10 = 1;
3102                               }
3103 
3104                               /* Else lost a leading zero, so 'exp_b10' is
3105                                * still ok at (-1)
3106                                */
3107                            }
3108                            else
3109                               ++exp_b10;
3110 
3111                            /* In all cases we output a '1' */
3112                            d = 1;
3113                         }
3114                      }
3115                   }
3116                   fp = 0; /* Guarantees termination below. */
3117                }
3118 
3119                if (d == 0)
3120                {
3121                   ++czero;
3122                   if (cdigits == 0) ++clead;
3123                }
3124                else
3125                {
3126                   /* Included embedded zeros in the digit count. */
3127                   cdigits += czero - clead;
3128                   clead = 0;
3129 
3130                   while (czero > 0)
3131                   {
3132                      /* exp_b10 == (-1) means we just output the decimal
3133                       * place - after the DP don't adjust 'exp_b10' any
3134                       * more!
3135                       */
3136                      if (exp_b10 != (-1))
3137                      {
3138                         if (exp_b10 == 0)
3139                         {
3140                            *ascii++ = 46; --size;
3141                         }
3142                         /* PLUS 1: TOTAL 4 */
3143                         --exp_b10;
3144                      }
3145                      *ascii++ = 48; --czero;
3146                   }
3147 
3148                   if (exp_b10 != (-1))
3149                   {
3150                      if (exp_b10 == 0)
3151                      {
3152                         *ascii++ = 46; --size; /* counted above */
3153                      }
3154 
3155                      --exp_b10;
3156                   }
3157                   *ascii++ = (char)(48 + (int)d); ++cdigits;
3158                }
3159             }
3160             while (cdigits+czero < precision+clead && fp > DBL_MIN);
3161 
3162             /* The total output count (max) is now 4+precision */
3163 
3164             /* Check for an exponent, if we don't need one we are
3165              * done and just need to terminate the string.  At
3166              * this point exp_b10==(-1) is effectively a flag - it got
3167              * to '-1' because of the decrement after outputting
3168              * the decimal point above (the exponent required is
3169              * *not* -1!)
3170              */
3171             if (exp_b10 >= (-1) && exp_b10 <= 2)
3172             {
3173                /* The following only happens if we didn't output the
3174                 * leading zeros above for negative exponent, so this
3175                 * doesn't add to the digit requirement.  Note that the
3176                 * two zeros here can only be output if the two leading
3177                 * zeros were *not* output, so this doesn't increase
3178                 * the output count.
3179                 */
3180                while (exp_b10-- > 0) *ascii++ = 48;
3181 
3182                *ascii = 0;
3183 
3184                /* Total buffer requirement (including the '\0') is
3185                 * 5+precision - see check at the start.
3186                 */
3187                return;
3188             }
3189 
3190             /* Here if an exponent is required, adjust size for
3191              * the digits we output but did not count.  The total
3192              * digit output here so far is at most 1+precision - no
3193              * decimal point and no leading or trailing zeros have
3194              * been output.
3195              */
3196             size -= cdigits;
3197 
3198             *ascii++ = 69; --size;    /* 'E': PLUS 1 TOTAL 2+precision */
3199 
3200             /* The following use of an unsigned temporary avoids ambiguities in
3201              * the signed arithmetic on exp_b10 and permits GCC at least to do
3202              * better optimization.
3203              */
3204             {
3205                unsigned int uexp_b10;
3206 
3207                if (exp_b10 < 0)
3208                {
3209                   *ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */
3210                   uexp_b10 = 0U-exp_b10;
3211                }
3212 
3213                else
3214                   uexp_b10 = 0U+exp_b10;
3215 
3216                cdigits = 0;
3217 
3218                while (uexp_b10 > 0)
3219                {
3220                   exponent[cdigits++] = (char)(48 + uexp_b10 % 10);
3221                   uexp_b10 /= 10;
3222                }
3223             }
3224 
3225             /* Need another size check here for the exponent digits, so
3226              * this need not be considered above.
3227              */
3228             if (size > cdigits)
3229             {
3230                while (cdigits > 0) *ascii++ = exponent[--cdigits];
3231 
3232                *ascii = 0;
3233 
3234                return;


3237       }
3238       else if (!(fp >= DBL_MIN))
3239       {
3240          *ascii++ = 48; /* '0' */
3241          *ascii = 0;
3242          return;
3243       }
3244       else
3245       {
3246          *ascii++ = 105; /* 'i' */
3247          *ascii++ = 110; /* 'n' */
3248          *ascii++ = 102; /* 'f' */
3249          *ascii = 0;
3250          return;
3251       }
3252    }
3253 
3254    /* Here on buffer too small. */
3255    png_error(png_ptr, "ASCII conversion buffer too small");
3256 }
3257 #if GCC_STRICT_OVERFLOW
3258 #pragma GCC diagnostic pop
3259 #endif /* GCC_STRICT_OVERFLOW */
3260 
3261 #  endif /* FLOATING_POINT */
3262 
3263 #  ifdef PNG_FIXED_POINT_SUPPORTED
3264 /* Function to format a fixed point value in ASCII.
3265  */
3266 void /* PRIVATE */
3267 png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
3268     png_size_t size, png_fixed_point fp)
3269 {
3270    /* Require space for 10 decimal digits, a decimal point, a minus sign and a
3271     * trailing \0, 13 characters:
3272     */
3273    if (size > 12)
3274    {
3275       png_uint_32 num;
3276 
3277       /* Avoid overflow here on the minimum integer. */
3278       if (fp < 0)
3279       {
3280          *ascii++ = 45; num = (png_uint_32)(-fp);
3281       }
3282       else
3283          num = (png_uint_32)fp;
3284 
3285       if (num <= 0x80000000) /* else overflowed */
3286       {
3287          unsigned int ndigits = 0, first = 16 /* flag value */;
3288          char digits[10];
3289 
3290          while (num)
3291          {
3292             /* Split the low digit off num: */
3293             unsigned int tmp = num/10;
3294             num -= tmp*10;
3295             digits[ndigits++] = (char)(48 + num);
3296             /* Record the first non-zero digit, note that this is a number
3297              * starting at 1, it's not actually the array index.
3298              */
3299             if (first == 16 && num > 0)
3300                first = ndigits;
3301             num = tmp;
3302          }
3303 
3304          if (ndigits > 0)
3305          {
3306             while (ndigits > 5) *ascii++ = digits[--ndigits];
3307             /* The remaining digits are fractional digits, ndigits is '5' or
3308              * smaller at this point.  It is certainly not zero.  Check for a
3309              * non-zero fractional digit:
3310              */
3311             if (first <= 5)
3312             {
3313                unsigned int i;
3314                *ascii++ = 46; /* decimal point */
3315                /* ndigits may be <5 for small numbers, output leading zeros
3316                 * then ndigits digits to first:
3317                 */
3318                i = 5;
3319                while (ndigits < i)
3320                {
3321                   *ascii++ = 48; --i;
3322                }
3323                while (ndigits >= first) *ascii++ = digits[--ndigits];
3324                /* Don't output the trailing zeros! */
3325             }
3326          }
3327          else
3328             *ascii++ = 48;
3329 
3330          /* And null terminate the string: */
3331          *ascii = 0;
3332          return;
3333       }
3334    }
3335 
3336    /* Here on buffer too small. */
3337    png_error(png_ptr, "ASCII conversion buffer too small");
3338 }
3339 #   endif /* FIXED_POINT */
3340 #endif /* SCAL */
3341 
3342 #if defined(PNG_FLOATING_POINT_SUPPORTED) && \


3353 
3354    if (r > 2147483647. || r < -2147483648.)
3355       png_fixed_error(png_ptr, text);
3356 
3357 #  ifndef PNG_ERROR_TEXT_SUPPORTED
3358    PNG_UNUSED(text)
3359 #  endif
3360 
3361    return (png_fixed_point)r;
3362 }
3363 #endif
3364 
3365 #if defined(PNG_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\
3366     defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)
3367 /* muldiv functions */
3368 /* This API takes signed arguments and rounds the result to the nearest
3369  * integer (or, for a fixed point number - the standard argument - to
3370  * the nearest .00001).  Overflow and divide by zero are signalled in
3371  * the result, a boolean - true on success, false on overflow.
3372  */
3373 #if GCC_STRICT_OVERFLOW /* from above */
3374 /* It is not obvious which comparison below gets optimized in such a way that
3375  * signed overflow would change the result; looking through the code does not
3376  * reveal any tests which have the form GCC complains about, so presumably the
3377  * optimizer is moving an add or subtract into the 'if' somewhere.
3378  */
3379 #pragma GCC diagnostic push
3380 #pragma GCC diagnostic warning "-Wstrict-overflow=2"
3381 #endif /* GCC_STRICT_OVERFLOW */
3382 int
3383 png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
3384     png_int_32 divisor)
3385 {
3386    /* Return a * times / divisor, rounded. */
3387    if (divisor != 0)
3388    {
3389       if (a == 0 || times == 0)
3390       {
3391          *res = 0;
3392          return 1;
3393       }
3394       else
3395       {
3396 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
3397          double r = a;
3398          r *= times;
3399          r /= divisor;
3400          r = floor(r+.5);
3401 


3476             if (s00 >= (D >> 1))
3477                ++result;
3478 
3479             if (negative != 0)
3480                result = -result;
3481 
3482             /* Check for overflow. */
3483             if ((negative != 0 && result <= 0) ||
3484                 (negative == 0 && result >= 0))
3485             {
3486                *res = result;
3487                return 1;
3488             }
3489          }
3490 #endif
3491       }
3492    }
3493 
3494    return 0;
3495 }
3496 #if GCC_STRICT_OVERFLOW
3497 #pragma GCC diagnostic pop
3498 #endif /* GCC_STRICT_OVERFLOW */
3499 #endif /* READ_GAMMA || INCH_CONVERSIONS */
3500 
3501 #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
3502 /* The following is for when the caller doesn't much care about the
3503  * result.
3504  */
3505 png_fixed_point
3506 png_muldiv_warn(png_const_structrp png_ptr, png_fixed_point a, png_int_32 times,
3507     png_int_32 divisor)
3508 {
3509    png_fixed_point result;
3510 
3511    if (png_muldiv(&result, a, times, divisor) != 0)
3512       return result;
3513 
3514    png_warning(png_ptr, "fixed point overflow ignored");
3515    return 0;
3516 }
3517 #endif
3518 


3772 
3773    else
3774       lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
3775 
3776    /* Safe, because the result can't have more than 20 bits: */
3777    return (png_int_32)((lg2 + 2048) >> 12);
3778 }
3779 #endif /* 16BIT */
3780 
3781 /* The 'exp()' case must invert the above, taking a 20-bit fixed point
3782  * logarithmic value and returning a 16 or 8-bit number as appropriate.  In
3783  * each case only the low 16 bits are relevant - the fraction - since the
3784  * integer bits (the top 4) simply determine a shift.
3785  *
3786  * The worst case is the 16-bit distinction between 65535 and 65534. This
3787  * requires perhaps spurious accuracy in the decoding of the logarithm to
3788  * distinguish log2(65535/65534.5) - 10^-5 or 17 bits.  There is little chance
3789  * of getting this accuracy in practice.
3790  *
3791  * To deal with this the following exp() function works out the exponent of the
3792  * fractional part of the logarithm by using an accurate 32-bit value from the
3793  * top four fractional bits then multiplying in the remaining bits.
3794  */
3795 static const png_uint_32
3796 png_32bit_exp[16] =
3797 {
3798    /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
3799    4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
3800    3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
3801    2553802834U, 2445529972U, 2341847524U, 2242560872U
3802 };
3803 
3804 /* Adjustment table; provided to explain the numbers in the code below. */
3805 #if 0
3806 for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
3807    11 44937.64284865548751208448
3808    10 45180.98734845585101160448
3809     9 45303.31936980687359311872
3810     8 45364.65110595323018870784
3811     7 45395.35850361789624614912
3812     6 45410.72259715102037508096


4351           * TODO: fix this.
4352           */
4353          png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
4354              png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
4355              png_ptr->colorspace.gamma/* Probably doing rgb_to_gray */);
4356       }
4357 #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
4358    }
4359 #endif /* 16BIT */
4360 }
4361 #endif /* READ_GAMMA */
4362 
4363 /* HARDWARE OR SOFTWARE OPTION SUPPORT */
4364 #ifdef PNG_SET_OPTION_SUPPORTED
4365 int PNGAPI
4366 png_set_option(png_structrp png_ptr, int option, int onoff)
4367 {
4368    if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
4369       (option & 1) == 0)
4370    {
4371       png_uint_32 mask = 3U << option;
4372       png_uint_32 setting = (2U + (onoff != 0)) << option;
4373       png_uint_32 current = png_ptr->options;
4374 
4375       png_ptr->options = (png_uint_32)(((current & ~mask) | setting) & 0xff);
4376 
4377       return (int)(current & mask) >> option;
4378    }
4379 
4380    return PNG_OPTION_INVALID;
4381 }
4382 #endif
4383 
4384 /* sRGB support */
4385 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
4386    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
4387 /* sRGB conversion tables; these are machine generated with the code in
4388  * contrib/tools/makesRGB.c.  The actual sRGB transfer curve defined in the
4389  * specification (see the article at https://en.wikipedia.org/wiki/SRGB)
4390  * is used, not the gamma=1/2.2 approximation use elsewhere in libpng.
4391  * The sRGB to linear table is exact (to the nearest 16-bit linear fraction).
4392  * The inverse (linear to sRGB) table has accuracies as follows:
4393  *
4394  * For all possible (255*65535+1) input values:
4395  *
4396  *    error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact
4397  *
4398  * For the input values corresponding to the 65536 16-bit values:
4399  *
4400  *    error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact
4401  *
4402  * In all cases the inexact readings are only off by one.
4403  */
4404 
4405 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
4406 /* The convert-to-sRGB table is only currently required for read. */
4407 const png_uint_16 png_sRGB_table[256] =
4408 {
4409    0,20,40,60,80,99,119,139,


< prev index next >