Coverage Report

Created: 2025-11-03 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libpng/png.c
Line
Count
Source
1
/* png.c - location for general purpose libpng functions
2
 *
3
 * Copyright (c) 2018-2025 Cosmin Truta
4
 * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
5
 * Copyright (c) 1996-1997 Andreas Dilger
6
 * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
7
 *
8
 * This code is released under the libpng license.
9
 * For conditions of distribution and use, see the disclaimer
10
 * and license in png.h
11
 */
12
13
#include "pngpriv.h"
14
15
/* Generate a compiler error if there is an old png.h in the search path. */
16
typedef png_libpng_version_1_6_51_git Your_png_h_is_not_version_1_6_51_git;
17
18
/* Sanity check the chunks definitions - PNG_KNOWN_CHUNKS from pngpriv.h and the
19
 * corresponding macro definitions.  This causes a compile time failure if
20
 * something is wrong but generates no code.
21
 *
22
 * (1) The first check is that the PNG_CHUNK(cHNK, index) 'index' values must
23
 * increment from 0 to the last value.
24
 */
25
#define PNG_CHUNK(cHNK, index) != (index) || ((index)+1)
26
27
#if 0 PNG_KNOWN_CHUNKS < 0
28
#  error PNG_KNOWN_CHUNKS chunk definitions are not in order
29
#endif
30
31
#undef PNG_CHUNK
32
33
/* (2) The chunk name macros, png_cHNK, must all be valid and defined.  Since
34
 * this is a preprocessor test undefined pp-tokens come out as zero and will
35
 * fail this test.
36
 */
37
#define PNG_CHUNK(cHNK, index) !PNG_CHUNK_NAME_VALID(png_ ## cHNK) ||
38
39
#if PNG_KNOWN_CHUNKS 0
40
#  error png_cHNK not defined for some known cHNK
41
#endif
42
43
#undef PNG_CHUNK
44
45
/* Tells libpng that we have already handled the first "num_bytes" bytes
46
 * of the PNG file signature.  If the PNG data is embedded into another
47
 * stream we can set num_bytes = 8 so that libpng will not attempt to read
48
 * or write any of the magic bytes before it starts on the IHDR.
49
 */
50
51
#ifdef PNG_READ_SUPPORTED
52
void PNGAPI
53
png_set_sig_bytes(png_structrp png_ptr, int num_bytes)
54
7.22k
{
55
7.22k
   unsigned int nb = (unsigned int)num_bytes;
56
57
7.22k
   png_debug(1, "in png_set_sig_bytes");
58
59
7.22k
   if (png_ptr == NULL)
60
0
      return;
61
62
7.22k
   if (num_bytes < 0)
63
0
      nb = 0;
64
65
7.22k
   if (nb > 8)
66
0
      png_error(png_ptr, "Too many bytes for PNG signature");
67
68
7.22k
   png_ptr->sig_bytes = (png_byte)nb;
69
7.22k
}
70
71
/* Checks whether the supplied bytes match the PNG signature.  We allow
72
 * checking less than the full 8-byte signature so that those apps that
73
 * already read the first few bytes of a file to determine the file type
74
 * can simply check the remaining bytes for extra assurance.  Returns
75
 * an integer less than, equal to, or greater than zero if sig is found,
76
 * respectively, to be less than, to match, or be greater than the correct
77
 * PNG signature (this is the same behavior as strcmp, memcmp, etc).
78
 */
79
int PNGAPI
80
png_sig_cmp(png_const_bytep sig, size_t start, size_t num_to_check)
81
8.16k
{
82
8.16k
   static const png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
83
84
8.16k
   if (num_to_check > 8)
85
0
      num_to_check = 8;
86
87
8.16k
   else if (num_to_check < 1)
88
0
      return -1;
89
90
8.16k
   if (start > 7)
91
0
      return -1;
92
93
8.16k
   if (start + num_to_check > 8)
94
0
      num_to_check = 8 - start;
95
96
8.16k
   return memcmp(&sig[start], &png_signature[start], num_to_check);
97
8.16k
}
98
99
#endif /* READ */
100
101
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
102
/* Function to allocate memory for zlib */
103
PNG_FUNCTION(voidpf /* PRIVATE */,
104
png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)
105
16.9k
{
106
16.9k
   png_alloc_size_t num_bytes = size;
107
108
16.9k
   if (png_ptr == NULL)
109
0
      return NULL;
110
111
   /* This check against overflow is vestigial, dating back from
112
    * the old times when png_zalloc used to be an exported function.
113
    * We're still keeping it here for now, as an extra-cautious
114
    * prevention against programming errors inside zlib, although it
115
    * should rather be a debug-time assertion instead.
116
    */
117
16.9k
   if (size != 0 && items >= (~(png_alloc_size_t)0) / size)
118
0
   {
119
0
      png_warning(png_voidcast(png_structrp, png_ptr),
120
0
                  "Potential overflow in png_zalloc()");
121
0
      return NULL;
122
0
   }
123
124
16.9k
   num_bytes *= items;
125
16.9k
   return png_malloc_warn(png_voidcast(png_structrp, png_ptr), num_bytes);
126
16.9k
}
127
128
/* Function to free memory for zlib */
129
void /* PRIVATE */
130
png_zfree(voidpf png_ptr, voidpf ptr)
131
16.9k
{
132
16.9k
   png_free(png_voidcast(png_const_structrp,png_ptr), ptr);
133
16.9k
}
134
135
/* Reset the CRC variable to 32 bits of 1's.  Care must be taken
136
 * in case CRC is > 32 bits to leave the top bits 0.
137
 */
138
void /* PRIVATE */
139
png_reset_crc(png_structrp png_ptr)
140
140k
{
141
   /* The cast is safe because the crc is a 32-bit value. */
142
140k
   png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);
143
140k
}
144
145
/* Calculate the CRC over a section of data.  We can only pass as
146
 * much data to this routine as the largest single buffer size.  We
147
 * also check that this data will actually be used before going to the
148
 * trouble of calculating it.
149
 */
150
void /* PRIVATE */
151
png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, size_t length)
152
284k
{
153
284k
   int need_crc = 1;
154
155
284k
   if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
156
254k
   {
157
254k
      if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
158
254k
          (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
159
195k
         need_crc = 0;
160
254k
   }
161
162
29.3k
   else /* critical */
163
29.3k
   {
164
29.3k
      if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
165
23.5k
         need_crc = 0;
166
29.3k
   }
167
168
   /* 'uLong' is defined in zlib.h as unsigned long; this means that on some
169
    * systems it is a 64-bit value.  crc32, however, returns 32 bits so the
170
    * following cast is safe.  'uInt' may be no more than 16 bits, so it is
171
    * necessary to perform a loop here.
172
    */
173
284k
   if (need_crc != 0 && length > 0)
174
65.6k
   {
175
65.6k
      uLong crc = png_ptr->crc; /* Should never issue a warning */
176
177
65.6k
      do
178
65.6k
      {
179
65.6k
         uInt safe_length = (uInt)length;
180
65.6k
#ifndef __COVERITY__
181
65.6k
         if (safe_length == 0)
182
0
            safe_length = (uInt)-1; /* evil, but safe */
183
65.6k
#endif
184
185
65.6k
         crc = crc32(crc, ptr, safe_length);
186
187
         /* The following should never issue compiler warnings; if they do the
188
          * target system has characteristics that will probably violate other
189
          * assumptions within the libpng code.
190
          */
191
65.6k
         ptr += safe_length;
192
65.6k
         length -= safe_length;
193
65.6k
      }
194
65.6k
      while (length > 0);
195
196
      /* And the following is always safe because the crc is only 32 bits. */
197
65.6k
      png_ptr->crc = (png_uint_32)crc;
198
65.6k
   }
199
284k
}
200
201
/* Check a user supplied version number, called from both read and write
202
 * functions that create a png_struct.
203
 */
204
int
205
png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)
206
8.09k
{
207
   /* Libpng versions 1.0.0 and later are binary compatible if the version
208
    * string matches through the second '.'; we must recompile any
209
    * applications that use any older library version.
210
    */
211
212
8.09k
   if (user_png_ver != NULL)
213
8.09k
   {
214
8.09k
      int i = -1;
215
8.09k
      int found_dots = 0;
216
217
8.09k
      do
218
32.3k
      {
219
32.3k
         i++;
220
32.3k
         if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])
221
0
            png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
222
32.3k
         if (user_png_ver[i] == '.')
223
16.1k
            found_dots++;
224
32.3k
      } while (found_dots < 2 && user_png_ver[i] != 0 &&
225
24.2k
            PNG_LIBPNG_VER_STRING[i] != 0);
226
8.09k
   }
227
228
0
   else
229
0
      png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
230
231
8.09k
   if ((png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) != 0)
232
0
   {
233
0
#ifdef PNG_WARNINGS_SUPPORTED
234
0
      size_t pos = 0;
235
0
      char m[128];
236
237
0
      pos = png_safecat(m, (sizeof m), pos,
238
0
          "Application built with libpng-");
239
0
      pos = png_safecat(m, (sizeof m), pos, user_png_ver);
240
0
      pos = png_safecat(m, (sizeof m), pos, " but running with ");
241
0
      pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);
242
0
      PNG_UNUSED(pos)
243
244
0
      png_warning(png_ptr, m);
245
0
#endif
246
247
0
      return 0;
248
0
   }
249
250
   /* Success return. */
251
8.09k
   return 1;
252
8.09k
}
253
254
/* Generic function to create a png_struct for either read or write - this
255
 * contains the common initialization.
256
 */
257
PNG_FUNCTION(png_structp /* PRIVATE */,
258
png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
259
    png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
260
    png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
261
8.09k
{
262
8.09k
   png_struct create_struct;
263
8.09k
#  ifdef PNG_SETJMP_SUPPORTED
264
8.09k
      jmp_buf create_jmp_buf;
265
8.09k
#  endif
266
267
   /* This temporary stack-allocated structure is used to provide a place to
268
    * build enough context to allow the user provided memory allocator (if any)
269
    * to be called.
270
    */
271
8.09k
   memset(&create_struct, 0, (sizeof create_struct));
272
273
8.09k
#  ifdef PNG_USER_LIMITS_SUPPORTED
274
8.09k
      create_struct.user_width_max = PNG_USER_WIDTH_MAX;
275
8.09k
      create_struct.user_height_max = PNG_USER_HEIGHT_MAX;
276
277
8.09k
#     ifdef PNG_USER_CHUNK_CACHE_MAX
278
8.09k
      create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;
279
8.09k
#     endif
280
281
8.09k
#     if PNG_USER_CHUNK_MALLOC_MAX > 0 /* default to compile-time limit */
282
8.09k
      create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;
283
284
      /* No compile-time limit, so initialize to the system limit: */
285
#     elif defined PNG_MAX_MALLOC_64K /* legacy system limit */
286
      create_struct.user_chunk_malloc_max = 65536U;
287
288
#     else /* modern system limit SIZE_MAX (C99) */
289
      create_struct.user_chunk_malloc_max = PNG_SIZE_MAX;
290
#     endif
291
8.09k
#  endif
292
293
   /* The following two API calls simply set fields in png_struct, so it is safe
294
    * to do them now even though error handling is not yet set up.
295
    */
296
8.09k
#  ifdef PNG_USER_MEM_SUPPORTED
297
8.09k
      png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn);
298
#  else
299
      PNG_UNUSED(mem_ptr)
300
      PNG_UNUSED(malloc_fn)
301
      PNG_UNUSED(free_fn)
302
#  endif
303
304
   /* (*error_fn) can return control to the caller after the error_ptr is set,
305
    * this will result in a memory leak unless the error_fn does something
306
    * extremely sophisticated.  The design lacks merit but is implicit in the
307
    * API.
308
    */
309
8.09k
   png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);
310
311
8.09k
#  ifdef PNG_SETJMP_SUPPORTED
312
8.09k
      if (!setjmp(create_jmp_buf))
313
8.09k
#  endif
314
8.09k
      {
315
8.09k
#  ifdef PNG_SETJMP_SUPPORTED
316
         /* Temporarily fake out the longjmp information until we have
317
          * successfully completed this function.  This only works if we have
318
          * setjmp() support compiled in, but it is safe - this stuff should
319
          * never happen.
320
          */
321
8.09k
         create_struct.jmp_buf_ptr = &create_jmp_buf;
322
8.09k
         create_struct.jmp_buf_size = 0; /*stack allocation*/
323
8.09k
         create_struct.longjmp_fn = longjmp;
324
8.09k
#  endif
325
         /* Call the general version checker (shared with read and write code):
326
          */
327
8.09k
         if (png_user_version_check(&create_struct, user_png_ver) != 0)
328
8.09k
         {
329
8.09k
            png_structrp png_ptr = png_voidcast(png_structrp,
330
8.09k
                png_malloc_warn(&create_struct, (sizeof *png_ptr)));
331
332
8.09k
            if (png_ptr != NULL)
333
8.09k
            {
334
               /* png_ptr->zstream holds a back-pointer to the png_struct, so
335
                * this can only be done now:
336
                */
337
8.09k
               create_struct.zstream.zalloc = png_zalloc;
338
8.09k
               create_struct.zstream.zfree = png_zfree;
339
8.09k
               create_struct.zstream.opaque = png_ptr;
340
341
8.09k
#              ifdef PNG_SETJMP_SUPPORTED
342
               /* Eliminate the local error handling: */
343
8.09k
               create_struct.jmp_buf_ptr = NULL;
344
8.09k
               create_struct.jmp_buf_size = 0;
345
8.09k
               create_struct.longjmp_fn = 0;
346
8.09k
#              endif
347
348
8.09k
               *png_ptr = create_struct;
349
350
               /* This is the successful return point */
351
8.09k
               return png_ptr;
352
8.09k
            }
353
8.09k
         }
354
8.09k
      }
355
356
   /* A longjmp because of a bug in the application storage allocator or a
357
    * simple failure to allocate the png_struct.
358
    */
359
0
   return NULL;
360
8.09k
}
361
362
/* Allocate the memory for an info_struct for the application. */
363
PNG_FUNCTION(png_infop,PNGAPI
364
png_create_info_struct,(png_const_structrp png_ptr),PNG_ALLOCATED)
365
15.3k
{
366
15.3k
   png_inforp info_ptr;
367
368
15.3k
   png_debug(1, "in png_create_info_struct");
369
370
15.3k
   if (png_ptr == NULL)
371
0
      return NULL;
372
373
   /* Use the internal API that does not (or at least should not) error out, so
374
    * that this call always returns ok.  The application typically sets up the
375
    * error handling *after* creating the info_struct because this is the way it
376
    * has always been done in 'example.c'.
377
    */
378
15.3k
   info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,
379
15.3k
       (sizeof *info_ptr)));
380
381
15.3k
   if (info_ptr != NULL)
382
15.3k
      memset(info_ptr, 0, (sizeof *info_ptr));
383
384
15.3k
   return info_ptr;
385
15.3k
}
386
387
/* This function frees the memory associated with a single info struct.
388
 * Normally, one would use either png_destroy_read_struct() or
389
 * png_destroy_write_struct() to free an info struct, but this may be
390
 * useful for some applications.  From libpng 1.6.0 this function is also used
391
 * internally to implement the png_info release part of the 'struct' destroy
392
 * APIs.  This ensures that all possible approaches free the same data (all of
393
 * it).
394
 */
395
void PNGAPI
396
png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)
397
16.1k
{
398
16.1k
   png_inforp info_ptr = NULL;
399
400
16.1k
   png_debug(1, "in png_destroy_info_struct");
401
402
16.1k
   if (png_ptr == NULL)
403
0
      return;
404
405
16.1k
   if (info_ptr_ptr != NULL)
406
15.3k
      info_ptr = *info_ptr_ptr;
407
408
16.1k
   if (info_ptr != NULL)
409
15.3k
   {
410
      /* Do this first in case of an error below; if the app implements its own
411
       * memory management this can lead to png_free calling png_error, which
412
       * will abort this routine and return control to the app error handler.
413
       * An infinite loop may result if it then tries to free the same info
414
       * ptr.
415
       */
416
15.3k
      *info_ptr_ptr = NULL;
417
418
15.3k
      png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
419
15.3k
      memset(info_ptr, 0, (sizeof *info_ptr));
420
15.3k
      png_free(png_ptr, info_ptr);
421
15.3k
   }
422
16.1k
}
423
424
/* Initialize the info structure.  This is now an internal function (0.89)
425
 * and applications using it are urged to use png_create_info_struct()
426
 * instead.  Use deprecated in 1.6.0, internal use removed (used internally it
427
 * is just a memset).
428
 *
429
 * NOTE: it is almost inconceivable that this API is used because it bypasses
430
 * the user-memory mechanism and the user error handling/warning mechanisms in
431
 * those cases where it does anything other than a memset.
432
 */
433
PNG_FUNCTION(void,PNGAPI
434
png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size),
435
    PNG_DEPRECATED)
436
0
{
437
0
   png_inforp info_ptr = *ptr_ptr;
438
439
0
   png_debug(1, "in png_info_init_3");
440
441
0
   if (info_ptr == NULL)
442
0
      return;
443
444
0
   if ((sizeof (png_info)) > png_info_struct_size)
445
0
   {
446
0
      *ptr_ptr = NULL;
447
      /* The following line is why this API should not be used: */
448
0
      free(info_ptr);
449
0
      info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,
450
0
          (sizeof *info_ptr)));
451
0
      if (info_ptr == NULL)
452
0
         return;
453
0
      *ptr_ptr = info_ptr;
454
0
   }
455
456
   /* Set everything to 0 */
457
0
   memset(info_ptr, 0, (sizeof *info_ptr));
458
0
}
459
460
void PNGAPI
461
png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr,
462
    int freer, png_uint_32 mask)
463
0
{
464
0
   png_debug(1, "in png_data_freer");
465
466
0
   if (png_ptr == NULL || info_ptr == NULL)
467
0
      return;
468
469
0
   if (freer == PNG_DESTROY_WILL_FREE_DATA)
470
0
      info_ptr->free_me |= mask;
471
472
0
   else if (freer == PNG_USER_WILL_FREE_DATA)
473
0
      info_ptr->free_me &= ~mask;
474
475
0
   else
476
0
      png_error(png_ptr, "Unknown freer parameter in png_data_freer");
477
0
}
478
479
void PNGAPI
480
png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,
481
    int num)
482
16.2k
{
483
16.2k
   png_debug(1, "in png_free_data");
484
485
16.2k
   if (png_ptr == NULL || info_ptr == NULL)
486
0
      return;
487
488
16.2k
#ifdef PNG_TEXT_SUPPORTED
489
   /* Free text item num or (if num == -1) all text items */
490
16.2k
   if (info_ptr->text != NULL &&
491
468
       ((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)
492
438
   {
493
438
      if (num != -1)
494
0
      {
495
0
         png_free(png_ptr, info_ptr->text[num].key);
496
0
         info_ptr->text[num].key = NULL;
497
0
      }
498
499
438
      else
500
438
      {
501
438
         int i;
502
503
45.4k
         for (i = 0; i < info_ptr->num_text; i++)
504
44.9k
            png_free(png_ptr, info_ptr->text[i].key);
505
506
438
         png_free(png_ptr, info_ptr->text);
507
438
         info_ptr->text = NULL;
508
438
         info_ptr->num_text = 0;
509
438
         info_ptr->max_text = 0;
510
438
      }
511
438
   }
512
16.2k
#endif
513
514
16.2k
#ifdef PNG_tRNS_SUPPORTED
515
   /* Free any tRNS entry */
516
16.2k
   if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)
517
469
   {
518
469
      info_ptr->valid &= ~PNG_INFO_tRNS;
519
469
      png_free(png_ptr, info_ptr->trans_alpha);
520
469
      info_ptr->trans_alpha = NULL;
521
469
      info_ptr->num_trans = 0;
522
469
   }
523
16.2k
#endif
524
525
16.2k
#ifdef PNG_sCAL_SUPPORTED
526
   /* Free any sCAL entry */
527
16.2k
   if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)
528
126
   {
529
126
      png_free(png_ptr, info_ptr->scal_s_width);
530
126
      png_free(png_ptr, info_ptr->scal_s_height);
531
126
      info_ptr->scal_s_width = NULL;
532
126
      info_ptr->scal_s_height = NULL;
533
126
      info_ptr->valid &= ~PNG_INFO_sCAL;
534
126
   }
535
16.2k
#endif
536
537
16.2k
#ifdef PNG_pCAL_SUPPORTED
538
   /* Free any pCAL entry */
539
16.2k
   if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)
540
19
   {
541
19
      png_free(png_ptr, info_ptr->pcal_purpose);
542
19
      png_free(png_ptr, info_ptr->pcal_units);
543
19
      info_ptr->pcal_purpose = NULL;
544
19
      info_ptr->pcal_units = NULL;
545
546
19
      if (info_ptr->pcal_params != NULL)
547
19
         {
548
19
            int i;
549
550
60
            for (i = 0; i < info_ptr->pcal_nparams; i++)
551
41
               png_free(png_ptr, info_ptr->pcal_params[i]);
552
553
19
            png_free(png_ptr, info_ptr->pcal_params);
554
19
            info_ptr->pcal_params = NULL;
555
19
         }
556
19
      info_ptr->valid &= ~PNG_INFO_pCAL;
557
19
   }
558
16.2k
#endif
559
560
16.2k
#ifdef PNG_iCCP_SUPPORTED
561
   /* Free any profile entry */
562
16.2k
   if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)
563
38
   {
564
38
      png_free(png_ptr, info_ptr->iccp_name);
565
38
      png_free(png_ptr, info_ptr->iccp_profile);
566
38
      info_ptr->iccp_name = NULL;
567
38
      info_ptr->iccp_profile = NULL;
568
38
      info_ptr->valid &= ~PNG_INFO_iCCP;
569
38
   }
570
16.2k
#endif
571
572
16.2k
#ifdef PNG_sPLT_SUPPORTED
573
   /* Free a given sPLT entry, or (if num == -1) all sPLT entries */
574
16.2k
   if (info_ptr->splt_palettes != NULL &&
575
204
       ((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)
576
186
   {
577
186
      if (num != -1)
578
0
      {
579
0
         png_free(png_ptr, info_ptr->splt_palettes[num].name);
580
0
         png_free(png_ptr, info_ptr->splt_palettes[num].entries);
581
0
         info_ptr->splt_palettes[num].name = NULL;
582
0
         info_ptr->splt_palettes[num].entries = NULL;
583
0
      }
584
585
186
      else
586
186
      {
587
186
         int i;
588
589
5.31k
         for (i = 0; i < info_ptr->splt_palettes_num; i++)
590
5.12k
         {
591
5.12k
            png_free(png_ptr, info_ptr->splt_palettes[i].name);
592
5.12k
            png_free(png_ptr, info_ptr->splt_palettes[i].entries);
593
5.12k
         }
594
595
186
         png_free(png_ptr, info_ptr->splt_palettes);
596
186
         info_ptr->splt_palettes = NULL;
597
186
         info_ptr->splt_palettes_num = 0;
598
186
         info_ptr->valid &= ~PNG_INFO_sPLT;
599
186
      }
600
186
   }
601
16.2k
#endif
602
603
16.2k
#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
604
16.2k
   if (info_ptr->unknown_chunks != NULL &&
605
0
       ((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)
606
0
   {
607
0
      if (num != -1)
608
0
      {
609
0
          png_free(png_ptr, info_ptr->unknown_chunks[num].data);
610
0
          info_ptr->unknown_chunks[num].data = NULL;
611
0
      }
612
613
0
      else
614
0
      {
615
0
         int i;
616
617
0
         for (i = 0; i < info_ptr->unknown_chunks_num; i++)
618
0
            png_free(png_ptr, info_ptr->unknown_chunks[i].data);
619
620
0
         png_free(png_ptr, info_ptr->unknown_chunks);
621
0
         info_ptr->unknown_chunks = NULL;
622
0
         info_ptr->unknown_chunks_num = 0;
623
0
      }
624
0
   }
625
16.2k
#endif
626
627
16.2k
#ifdef PNG_eXIf_SUPPORTED
628
   /* Free any eXIf entry */
629
16.2k
   if (((mask & PNG_FREE_EXIF) & info_ptr->free_me) != 0)
630
14
   {
631
14
      if (info_ptr->exif)
632
14
      {
633
14
         png_free(png_ptr, info_ptr->exif);
634
14
         info_ptr->exif = NULL;
635
14
      }
636
14
      info_ptr->valid &= ~PNG_INFO_eXIf;
637
14
   }
638
16.2k
#endif
639
640
16.2k
#ifdef PNG_hIST_SUPPORTED
641
   /* Free any hIST entry */
642
16.2k
   if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)
643
0
   {
644
0
      png_free(png_ptr, info_ptr->hist);
645
0
      info_ptr->hist = NULL;
646
0
      info_ptr->valid &= ~PNG_INFO_hIST;
647
0
   }
648
16.2k
#endif
649
650
   /* Free any PLTE entry that was internally allocated */
651
16.2k
   if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)
652
452
   {
653
452
      png_free(png_ptr, info_ptr->palette);
654
452
      info_ptr->palette = NULL;
655
452
      info_ptr->valid &= ~PNG_INFO_PLTE;
656
452
      info_ptr->num_palette = 0;
657
452
   }
658
659
16.2k
#ifdef PNG_INFO_IMAGE_SUPPORTED
660
   /* Free any image bits attached to the info structure */
661
16.2k
   if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)
662
0
   {
663
0
      if (info_ptr->row_pointers != NULL)
664
0
      {
665
0
         png_uint_32 row;
666
0
         for (row = 0; row < info_ptr->height; row++)
667
0
            png_free(png_ptr, info_ptr->row_pointers[row]);
668
669
0
         png_free(png_ptr, info_ptr->row_pointers);
670
0
         info_ptr->row_pointers = NULL;
671
0
      }
672
0
      info_ptr->valid &= ~PNG_INFO_IDAT;
673
0
   }
674
16.2k
#endif
675
676
16.2k
   if (num != -1)
677
973
      mask &= ~PNG_FREE_MUL;
678
679
16.2k
   info_ptr->free_me &= ~mask;
680
16.2k
}
681
#endif /* READ || WRITE */
682
683
/* This function returns a pointer to the io_ptr associated with the user
684
 * functions.  The application should free any memory associated with this
685
 * pointer before png_write_destroy() or png_read_destroy() are called.
686
 */
687
png_voidp PNGAPI
688
png_get_io_ptr(png_const_structrp png_ptr)
689
329k
{
690
329k
   if (png_ptr == NULL)
691
0
      return NULL;
692
693
329k
   return png_ptr->io_ptr;
694
329k
}
695
696
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
697
#  ifdef PNG_STDIO_SUPPORTED
698
/* Initialize the default input/output functions for the PNG file.  If you
699
 * use your own read or write routines, you can call either png_set_read_fn()
700
 * or png_set_write_fn() instead of png_init_io().  If you have defined
701
 * PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a
702
 * function of your own because "FILE *" isn't necessarily available.
703
 */
704
void PNGAPI
705
png_init_io(png_structrp png_ptr, FILE *fp)
706
{
707
   png_debug(1, "in png_init_io");
708
709
   if (png_ptr == NULL)
710
      return;
711
712
   png_ptr->io_ptr = (png_voidp)fp;
713
}
714
#  endif
715
716
#  ifdef PNG_SAVE_INT_32_SUPPORTED
717
/* PNG signed integers are saved in 32-bit 2's complement format.  ANSI C-90
718
 * defines a cast of a signed integer to an unsigned integer either to preserve
719
 * the value, if it is positive, or to calculate:
720
 *
721
 *     (UNSIGNED_MAX+1) + integer
722
 *
723
 * Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the
724
 * negative integral value is added the result will be an unsigned value
725
 * corresponding to the 2's complement representation.
726
 */
727
void PNGAPI
728
png_save_int_32(png_bytep buf, png_int_32 i)
729
{
730
   png_save_uint_32(buf, (png_uint_32)i);
731
}
732
#  endif
733
734
#  ifdef PNG_TIME_RFC1123_SUPPORTED
735
/* Convert the supplied time into an RFC 1123 string suitable for use in
736
 * a "Creation Time" or other text-based time string.
737
 */
738
int PNGAPI
739
png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)
740
0
{
741
0
   static const char short_months[12][4] =
742
0
        {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
743
0
         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
744
745
0
   if (out == NULL)
746
0
      return 0;
747
748
0
   if (ptime->year > 9999 /* RFC1123 limitation */ ||
749
0
       ptime->month == 0    ||  ptime->month > 12  ||
750
0
       ptime->day   == 0    ||  ptime->day   > 31  ||
751
0
       ptime->hour  > 23    ||  ptime->minute > 59 ||
752
0
       ptime->second > 60)
753
0
      return 0;
754
755
0
   {
756
0
      size_t pos = 0;
757
0
      char number_buf[5] = {0, 0, 0, 0, 0}; /* enough for a four-digit year */
758
759
0
#     define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string))
760
0
#     define APPEND_NUMBER(format, value)\
761
0
         APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))
762
0
#     define APPEND(ch) if (pos < 28) out[pos++] = (ch)
763
764
0
      APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);
765
0
      APPEND(' ');
766
0
      APPEND_STRING(short_months[(ptime->month - 1)]);
767
0
      APPEND(' ');
768
0
      APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);
769
0
      APPEND(' ');
770
0
      APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);
771
0
      APPEND(':');
772
0
      APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);
773
0
      APPEND(':');
774
0
      APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);
775
0
      APPEND_STRING(" +0000"); /* This reliably terminates the buffer */
776
0
      PNG_UNUSED (pos)
777
778
0
#     undef APPEND
779
0
#     undef APPEND_NUMBER
780
0
#     undef APPEND_STRING
781
0
   }
782
783
0
   return 1;
784
0
}
785
786
#    if PNG_LIBPNG_VER < 10700
787
/* To do: remove the following from libpng-1.7 */
788
/* Original API that uses a private buffer in png_struct.
789
 * Deprecated because it causes png_struct to carry a spurious temporary
790
 * buffer (png_struct::time_buffer), better to have the caller pass this in.
791
 */
792
png_const_charp PNGAPI
793
png_convert_to_rfc1123(png_structrp png_ptr, png_const_timep ptime)
794
0
{
795
0
   if (png_ptr != NULL)
796
0
   {
797
      /* The only failure above if png_ptr != NULL is from an invalid ptime */
798
0
      if (png_convert_to_rfc1123_buffer(png_ptr->time_buffer, ptime) == 0)
799
0
         png_warning(png_ptr, "Ignoring invalid time value");
800
801
0
      else
802
0
         return png_ptr->time_buffer;
803
0
   }
804
805
0
   return NULL;
806
0
}
807
#    endif /* LIBPNG_VER < 10700 */
808
#  endif /* TIME_RFC1123 */
809
810
#endif /* READ || WRITE */
811
812
png_const_charp PNGAPI
813
png_get_copyright(png_const_structrp png_ptr)
814
0
{
815
0
   PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
816
#ifdef PNG_STRING_COPYRIGHT
817
   return PNG_STRING_COPYRIGHT
818
#else
819
0
   return PNG_STRING_NEWLINE \
820
0
      "libpng version 1.6.51.git" PNG_STRING_NEWLINE \
821
0
      "Copyright (c) 2018-2025 Cosmin Truta" PNG_STRING_NEWLINE \
822
0
      "Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \
823
0
      PNG_STRING_NEWLINE \
824
0
      "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
825
0
      "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
826
0
      PNG_STRING_NEWLINE;
827
0
#endif
828
0
}
829
830
/* The following return the library version as a short string in the
831
 * format 1.0.0 through 99.99.99zz.  To get the version of *.h files
832
 * used with your application, print out PNG_LIBPNG_VER_STRING, which
833
 * is defined in png.h.
834
 * Note: now there is no difference between png_get_libpng_ver() and
835
 * png_get_header_ver().  Due to the version_nn_nn_nn typedef guard,
836
 * it is guaranteed that png.c uses the correct version of png.h.
837
 */
838
png_const_charp PNGAPI
839
png_get_libpng_ver(png_const_structrp png_ptr)
840
0
{
841
   /* Version of *.c files used when building libpng */
842
0
   return png_get_header_ver(png_ptr);
843
0
}
844
845
png_const_charp PNGAPI
846
png_get_header_ver(png_const_structrp png_ptr)
847
0
{
848
   /* Version of *.h files used when building libpng */
849
0
   PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
850
0
   return PNG_LIBPNG_VER_STRING;
851
0
}
852
853
png_const_charp PNGAPI
854
png_get_header_version(png_const_structrp png_ptr)
855
0
{
856
   /* Returns longer string containing both version and date */
857
0
   PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
858
0
#ifdef __STDC__
859
0
   return PNG_HEADER_VERSION_STRING
860
#  ifndef PNG_READ_SUPPORTED
861
      " (NO READ SUPPORT)"
862
#  endif
863
0
      PNG_STRING_NEWLINE;
864
#else
865
   return PNG_HEADER_VERSION_STRING;
866
#endif
867
0
}
868
869
#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED
870
/* NOTE: this routine is not used internally! */
871
/* Build a grayscale palette.  Palette is assumed to be 1 << bit_depth
872
 * large of png_color.  This lets grayscale images be treated as
873
 * paletted.  Most useful for gamma correction and simplification
874
 * of code.  This API is not used internally.
875
 */
876
void PNGAPI
877
png_build_grayscale_palette(int bit_depth, png_colorp palette)
878
0
{
879
0
   int num_palette;
880
0
   int color_inc;
881
0
   int i;
882
0
   int v;
883
884
0
   png_debug(1, "in png_do_build_grayscale_palette");
885
886
0
   if (palette == NULL)
887
0
      return;
888
889
0
   switch (bit_depth)
890
0
   {
891
0
      case 1:
892
0
         num_palette = 2;
893
0
         color_inc = 0xff;
894
0
         break;
895
896
0
      case 2:
897
0
         num_palette = 4;
898
0
         color_inc = 0x55;
899
0
         break;
900
901
0
      case 4:
902
0
         num_palette = 16;
903
0
         color_inc = 0x11;
904
0
         break;
905
906
0
      case 8:
907
0
         num_palette = 256;
908
0
         color_inc = 1;
909
0
         break;
910
911
0
      default:
912
0
         num_palette = 0;
913
0
         color_inc = 0;
914
0
         break;
915
0
   }
916
917
0
   for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
918
0
   {
919
0
      palette[i].red = (png_byte)(v & 0xff);
920
0
      palette[i].green = (png_byte)(v & 0xff);
921
0
      palette[i].blue = (png_byte)(v & 0xff);
922
0
   }
923
0
}
924
#endif
925
926
#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
927
int PNGAPI
928
png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)
929
132k
{
930
   /* Check chunk_name and return "keep" value if it's on the list, else 0 */
931
132k
   png_const_bytep p, p_end;
932
933
132k
   if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list == 0)
934
132k
      return PNG_HANDLE_CHUNK_AS_DEFAULT;
935
936
0
   p_end = png_ptr->chunk_list;
937
0
   p = p_end + png_ptr->num_chunk_list*5; /* beyond end */
938
939
   /* The code is the fifth byte after each four byte string.  Historically this
940
    * code was always searched from the end of the list, this is no longer
941
    * necessary because the 'set' routine handles duplicate entries correctly.
942
    */
943
0
   do /* num_chunk_list > 0, so at least one */
944
0
   {
945
0
      p -= 5;
946
947
0
      if (memcmp(chunk_name, p, 4) == 0)
948
0
         return p[4];
949
0
   }
950
0
   while (p > p_end);
951
952
   /* This means that known chunks should be processed and unknown chunks should
953
    * be handled according to the value of png_ptr->unknown_default; this can be
954
    * confusing because, as a result, there are two levels of defaulting for
955
    * unknown chunks.
956
    */
957
0
   return PNG_HANDLE_CHUNK_AS_DEFAULT;
958
0
}
959
960
#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) ||\
961
   defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)
962
int /* PRIVATE */
963
png_chunk_unknown_handling(png_const_structrp png_ptr, png_uint_32 chunk_name)
964
132k
{
965
132k
   png_byte chunk_string[5];
966
967
132k
   PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);
968
132k
   return png_handle_as_unknown(png_ptr, chunk_string);
969
132k
}
970
#endif /* READ_UNKNOWN_CHUNKS || HANDLE_AS_UNKNOWN */
971
#endif /* SET_UNKNOWN_CHUNKS */
972
973
#ifdef PNG_READ_SUPPORTED
974
/* This function, added to libpng-1.0.6g, is untested. */
975
int PNGAPI
976
png_reset_zstream(png_structrp png_ptr)
977
0
{
978
0
   if (png_ptr == NULL)
979
0
      return Z_STREAM_ERROR;
980
981
   /* WARNING: this resets the window bits to the maximum! */
982
0
   return inflateReset(&png_ptr->zstream);
983
0
}
984
#endif /* READ */
985
986
/* This function was added to libpng-1.0.7 */
987
png_uint_32 PNGAPI
988
png_access_version_number(void)
989
0
{
990
   /* Version of *.c files used when building libpng */
991
0
   return (png_uint_32)PNG_LIBPNG_VER;
992
0
}
993
994
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
995
/* Ensure that png_ptr->zstream.msg holds some appropriate error message string.
996
 * If it doesn't 'ret' is used to set it to something appropriate, even in cases
997
 * like Z_OK or Z_STREAM_END where the error code is apparently a success code.
998
 */
999
void /* PRIVATE */
1000
png_zstream_error(png_structrp png_ptr, int ret)
1001
29.0k
{
1002
   /* Translate 'ret' into an appropriate error string, priority is given to the
1003
    * one in zstream if set.  This always returns a string, even in cases like
1004
    * Z_OK or Z_STREAM_END where the error code is a success code.
1005
    */
1006
29.0k
   if (png_ptr->zstream.msg == NULL) switch (ret)
1007
16.1k
   {
1008
0
      default:
1009
10.0k
      case Z_OK:
1010
10.0k
         png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return code");
1011
10.0k
         break;
1012
1013
5.54k
      case Z_STREAM_END:
1014
         /* Normal exit */
1015
5.54k
         png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected end of LZ stream");
1016
5.54k
         break;
1017
1018
5
      case Z_NEED_DICT:
1019
         /* This means the deflate stream did not have a dictionary; this
1020
          * indicates a bogus PNG.
1021
          */
1022
5
         png_ptr->zstream.msg = PNGZ_MSG_CAST("missing LZ dictionary");
1023
5
         break;
1024
1025
0
      case Z_ERRNO:
1026
         /* gz APIs only: should not happen */
1027
0
         png_ptr->zstream.msg = PNGZ_MSG_CAST("zlib IO error");
1028
0
         break;
1029
1030
0
      case Z_STREAM_ERROR:
1031
         /* internal libpng error */
1032
0
         png_ptr->zstream.msg = PNGZ_MSG_CAST("bad parameters to zlib");
1033
0
         break;
1034
1035
0
      case Z_DATA_ERROR:
1036
0
         png_ptr->zstream.msg = PNGZ_MSG_CAST("damaged LZ stream");
1037
0
         break;
1038
1039
0
      case Z_MEM_ERROR:
1040
0
         png_ptr->zstream.msg = PNGZ_MSG_CAST("insufficient memory");
1041
0
         break;
1042
1043
552
      case Z_BUF_ERROR:
1044
         /* End of input or output; not a problem if the caller is doing
1045
          * incremental read or write.
1046
          */
1047
552
         png_ptr->zstream.msg = PNGZ_MSG_CAST("truncated");
1048
552
         break;
1049
1050
0
      case Z_VERSION_ERROR:
1051
0
         png_ptr->zstream.msg = PNGZ_MSG_CAST("unsupported zlib version");
1052
0
         break;
1053
1054
0
      case PNG_UNEXPECTED_ZLIB_RETURN:
1055
         /* Compile errors here mean that zlib now uses the value co-opted in
1056
          * pngpriv.h for PNG_UNEXPECTED_ZLIB_RETURN; update the switch above
1057
          * and change pngpriv.h.  Note that this message is "... return",
1058
          * whereas the default/Z_OK one is "... return code".
1059
          */
1060
0
         png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return");
1061
0
         break;
1062
16.1k
   }
1063
29.0k
}
1064
1065
#ifdef PNG_COLORSPACE_SUPPORTED
1066
static png_int_32
1067
png_fp_add(png_int_32 addend0, png_int_32 addend1, int *error)
1068
0
{
1069
   /* Safely add two fixed point values setting an error flag and returning 0.5
1070
    * on overflow.
1071
    * IMPLEMENTATION NOTE: ANSI requires signed overflow not to occur, therefore
1072
    * relying on addition of two positive values producing a negative one is not
1073
    * safe.
1074
    */
1075
0
   if (addend0 > 0)
1076
0
   {
1077
0
      if (0x7fffffff - addend0 >= addend1)
1078
0
         return addend0+addend1;
1079
0
   }
1080
0
   else if (addend0 < 0)
1081
0
   {
1082
0
      if (-0x7fffffff - addend0 <= addend1)
1083
0
         return addend0+addend1;
1084
0
   }
1085
0
   else
1086
0
      return addend1;
1087
1088
0
   *error = 1;
1089
0
   return PNG_FP_1/2;
1090
0
}
1091
1092
static png_int_32
1093
png_fp_sub(png_int_32 addend0, png_int_32 addend1, int *error)
1094
0
{
1095
   /* As above but calculate addend0-addend1. */
1096
0
   if (addend1 > 0)
1097
0
   {
1098
0
      if (-0x7fffffff + addend1 <= addend0)
1099
0
         return addend0-addend1;
1100
0
   }
1101
0
   else if (addend1 < 0)
1102
0
   {
1103
0
      if (0x7fffffff + addend1 >= addend0)
1104
0
         return addend0-addend1;
1105
0
   }
1106
0
   else
1107
0
      return addend0;
1108
1109
0
   *error = 1;
1110
0
   return PNG_FP_1/2;
1111
0
}
1112
1113
static int
1114
png_safe_add(png_int_32 *addend0_and_result, png_int_32 addend1,
1115
      png_int_32 addend2)
1116
0
{
1117
   /* Safely add three integers.  Returns 0 on success, 1 on overflow.  Does not
1118
    * set the result on overflow.
1119
    */
1120
0
   int error = 0;
1121
0
   int result = png_fp_add(*addend0_and_result,
1122
0
                           png_fp_add(addend1, addend2, &error),
1123
0
                           &error);
1124
0
   if (!error) *addend0_and_result = result;
1125
0
   return error;
1126
0
}
1127
1128
/* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for
1129
 * cHRM, as opposed to using chromaticities.  These internal APIs return
1130
 * non-zero on a parameter error.  The X, Y and Z values are required to be
1131
 * positive and less than 1.0.
1132
 */
1133
int /* PRIVATE */
1134
png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)
1135
0
{
1136
   /* NOTE: returns 0 on success, 1 means error. */
1137
0
   png_int_32 d, dred, dgreen, dblue, dwhite, whiteX, whiteY;
1138
1139
   /* 'd' in each of the blocks below is just X+Y+Z for each component,
1140
    * x, y and z are X,Y,Z/(X+Y+Z).
1141
    */
1142
0
   d = XYZ->red_X;
1143
0
   if (png_safe_add(&d, XYZ->red_Y, XYZ->red_Z))
1144
0
      return 1;
1145
0
   dred = d;
1146
0
   if (png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, dred) == 0)
1147
0
      return 1;
1148
0
   if (png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, dred) == 0)
1149
0
      return 1;
1150
1151
0
   d = XYZ->green_X;
1152
0
   if (png_safe_add(&d, XYZ->green_Y, XYZ->green_Z))
1153
0
      return 1;
1154
0
   dgreen = d;
1155
0
   if (png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, dgreen) == 0)
1156
0
      return 1;
1157
0
   if (png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, dgreen) == 0)
1158
0
      return 1;
1159
1160
0
   d = XYZ->blue_X;
1161
0
   if (png_safe_add(&d, XYZ->blue_Y, XYZ->blue_Z))
1162
0
      return 1;
1163
0
   dblue = d;
1164
0
   if (png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, dblue) == 0)
1165
0
      return 1;
1166
0
   if (png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, dblue) == 0)
1167
0
      return 1;
1168
1169
   /* The reference white is simply the sum of the end-point (X,Y,Z) vectors so
1170
    * the fillowing calculates (X+Y+Z) of the reference white (media white,
1171
    * encoding white) itself:
1172
    */
1173
0
   d = dblue;
1174
0
   if (png_safe_add(&d, dred, dgreen))
1175
0
      return 1;
1176
0
   dwhite = d;
1177
1178
   /* Find the white X,Y values from the sum of the red, green and blue X,Y
1179
    * values.
1180
    */
1181
0
   d = XYZ->red_X;
1182
0
   if (png_safe_add(&d, XYZ->green_X, XYZ->blue_X))
1183
0
      return 1;
1184
0
   whiteX = d;
1185
1186
0
   d = XYZ->red_Y;
1187
0
   if (png_safe_add(&d, XYZ->green_Y, XYZ->blue_Y))
1188
0
      return 1;
1189
0
   whiteY = d;
1190
1191
0
   if (png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite) == 0)
1192
0
      return 1;
1193
0
   if (png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite) == 0)
1194
0
      return 1;
1195
1196
0
   return 0;
1197
0
}
1198
1199
int /* PRIVATE */
1200
png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)
1201
0
{
1202
   /* NOTE: returns 0 on success, 1 means error. */
1203
0
   png_fixed_point red_inverse, green_inverse, blue_scale;
1204
0
   png_fixed_point left, right, denominator;
1205
1206
   /* Check xy and, implicitly, z.  Note that wide gamut color spaces typically
1207
    * have end points with 0 tristimulus values (these are impossible end
1208
    * points, but they are used to cover the possible colors).  We check
1209
    * xy->whitey against 5, not 0, to avoid a possible integer overflow.
1210
    *
1211
    * The limits here will *not* accept ACES AP0, where bluey is -7700
1212
    * (-0.0770) because the PNG spec itself requires the xy values to be
1213
    * unsigned.  whitey is also required to be 5 or more to avoid overflow.
1214
    *
1215
    * Instead the upper limits have been relaxed to accomodate ACES AP1 where
1216
    * redz ends up as -600 (-0.006).  ProPhotoRGB was already "in range."
1217
    * The new limit accomodates the AP0 and AP1 ranges for z but not AP0 redy.
1218
    */
1219
0
   const png_fixed_point fpLimit = PNG_FP_1+(PNG_FP_1/10);
1220
0
   if (xy->redx   < 0 || xy->redx > fpLimit) return 1;
1221
0
   if (xy->redy   < 0 || xy->redy > fpLimit-xy->redx) return 1;
1222
0
   if (xy->greenx < 0 || xy->greenx > fpLimit) return 1;
1223
0
   if (xy->greeny < 0 || xy->greeny > fpLimit-xy->greenx) return 1;
1224
0
   if (xy->bluex  < 0 || xy->bluex > fpLimit) return 1;
1225
0
   if (xy->bluey  < 0 || xy->bluey > fpLimit-xy->bluex) return 1;
1226
0
   if (xy->whitex < 0 || xy->whitex > fpLimit) return 1;
1227
0
   if (xy->whitey < 5 || xy->whitey > fpLimit-xy->whitex) return 1;
1228
1229
   /* The reverse calculation is more difficult because the original tristimulus
1230
    * value had 9 independent values (red,green,blue)x(X,Y,Z) however only 8
1231
    * derived values were recorded in the cHRM chunk;
1232
    * (red,green,blue,white)x(x,y).  This loses one degree of freedom and
1233
    * therefore an arbitrary ninth value has to be introduced to undo the
1234
    * original transformations.
1235
    *
1236
    * Think of the original end-points as points in (X,Y,Z) space.  The
1237
    * chromaticity values (c) have the property:
1238
    *
1239
    *           C
1240
    *   c = ---------
1241
    *       X + Y + Z
1242
    *
1243
    * For each c (x,y,z) from the corresponding original C (X,Y,Z).  Thus the
1244
    * three chromaticity values (x,y,z) for each end-point obey the
1245
    * relationship:
1246
    *
1247
    *   x + y + z = 1
1248
    *
1249
    * This describes the plane in (X,Y,Z) space that intersects each axis at the
1250
    * value 1.0; call this the chromaticity plane.  Thus the chromaticity
1251
    * calculation has scaled each end-point so that it is on the x+y+z=1 plane
1252
    * and chromaticity is the intersection of the vector from the origin to the
1253
    * (X,Y,Z) value with the chromaticity plane.
1254
    *
1255
    * To fully invert the chromaticity calculation we would need the three
1256
    * end-point scale factors, (red-scale, green-scale, blue-scale), but these
1257
    * were not recorded.  Instead we calculated the reference white (X,Y,Z) and
1258
    * recorded the chromaticity of this.  The reference white (X,Y,Z) would have
1259
    * given all three of the scale factors since:
1260
    *
1261
    *    color-C = color-c * color-scale
1262
    *    white-C = red-C + green-C + blue-C
1263
    *            = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
1264
    *
1265
    * But cHRM records only white-x and white-y, so we have lost the white scale
1266
    * factor:
1267
    *
1268
    *    white-C = white-c*white-scale
1269
    *
1270
    * To handle this the inverse transformation makes an arbitrary assumption
1271
    * about white-scale:
1272
    *
1273
    *    Assume: white-Y = 1.0
1274
    *    Hence:  white-scale = 1/white-y
1275
    *    Or:     red-Y + green-Y + blue-Y = 1.0
1276
    *
1277
    * Notice the last statement of the assumption gives an equation in three of
1278
    * the nine values we want to calculate.  8 more equations come from the
1279
    * above routine as summarised at the top above (the chromaticity
1280
    * calculation):
1281
    *
1282
    *    Given: color-x = color-X / (color-X + color-Y + color-Z)
1283
    *    Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 0
1284
    *
1285
    * This is 9 simultaneous equations in the 9 variables "color-C" and can be
1286
    * solved by Cramer's rule.  Cramer's rule requires calculating 10 9x9 matrix
1287
    * determinants, however this is not as bad as it seems because only 28 of
1288
    * the total of 90 terms in the various matrices are non-zero.  Nevertheless
1289
    * Cramer's rule is notoriously numerically unstable because the determinant
1290
    * calculation involves the difference of large, but similar, numbers.  It is
1291
    * difficult to be sure that the calculation is stable for real world values
1292
    * and it is certain that it becomes unstable where the end points are close
1293
    * together.
1294
    *
1295
    * So this code uses the perhaps slightly less optimal but more
1296
    * understandable and totally obvious approach of calculating color-scale.
1297
    *
1298
    * This algorithm depends on the precision in white-scale and that is
1299
    * (1/white-y), so we can immediately see that as white-y approaches 0 the
1300
    * accuracy inherent in the cHRM chunk drops off substantially.
1301
    *
1302
    * libpng arithmetic: a simple inversion of the above equations
1303
    * ------------------------------------------------------------
1304
    *
1305
    *    white_scale = 1/white-y
1306
    *    white-X = white-x * white-scale
1307
    *    white-Y = 1.0
1308
    *    white-Z = (1 - white-x - white-y) * white_scale
1309
    *
1310
    *    white-C = red-C + green-C + blue-C
1311
    *            = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
1312
    *
1313
    * This gives us three equations in (red-scale,green-scale,blue-scale) where
1314
    * all the coefficients are now known:
1315
    *
1316
    *    red-x*red-scale + green-x*green-scale + blue-x*blue-scale
1317
    *       = white-x/white-y
1318
    *    red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 1
1319
    *    red-z*red-scale + green-z*green-scale + blue-z*blue-scale
1320
    *       = (1 - white-x - white-y)/white-y
1321
    *
1322
    * In the last equation color-z is (1 - color-x - color-y) so we can add all
1323
    * three equations together to get an alternative third:
1324
    *
1325
    *    red-scale + green-scale + blue-scale = 1/white-y = white-scale
1326
    *
1327
    * So now we have a Cramer's rule solution where the determinants are just
1328
    * 3x3 - far more tractible.  Unfortunately 3x3 determinants still involve
1329
    * multiplication of three coefficients so we can't guarantee to avoid
1330
    * overflow in the libpng fixed point representation.  Using Cramer's rule in
1331
    * floating point is probably a good choice here, but it's not an option for
1332
    * fixed point.  Instead proceed to simplify the first two equations by
1333
    * eliminating what is likely to be the largest value, blue-scale:
1334
    *
1335
    *    blue-scale = white-scale - red-scale - green-scale
1336
    *
1337
    * Hence:
1338
    *
1339
    *    (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =
1340
    *                (white-x - blue-x)*white-scale
1341
    *
1342
    *    (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =
1343
    *                1 - blue-y*white-scale
1344
    *
1345
    * And now we can trivially solve for (red-scale,green-scale):
1346
    *
1347
    *    green-scale =
1348
    *                (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale
1349
    *                -----------------------------------------------------------
1350
    *                                  green-x - blue-x
1351
    *
1352
    *    red-scale =
1353
    *                1 - blue-y*white-scale - (green-y - blue-y) * green-scale
1354
    *                ---------------------------------------------------------
1355
    *                                  red-y - blue-y
1356
    *
1357
    * Hence:
1358
    *
1359
    *    red-scale =
1360
    *          ( (green-x - blue-x) * (white-y - blue-y) -
1361
    *            (green-y - blue-y) * (white-x - blue-x) ) / white-y
1362
    * -------------------------------------------------------------------------
1363
    *  (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
1364
    *
1365
    *    green-scale =
1366
    *          ( (red-y - blue-y) * (white-x - blue-x) -
1367
    *            (red-x - blue-x) * (white-y - blue-y) ) / white-y
1368
    * -------------------------------------------------------------------------
1369
    *  (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
1370
    *
1371
    * Accuracy:
1372
    * The input values have 5 decimal digits of accuracy.
1373
    *
1374
    * In the previous implementation the values were all in the range 0 < value
1375
    * < 1, so simple products are in the same range but may need up to 10
1376
    * decimal digits to preserve the original precision and avoid underflow.
1377
    * Because we are using a 32-bit signed representation we cannot match this;
1378
    * the best is a little over 9 decimal digits, less than 10.
1379
    *
1380
    * This range has now been extended to allow values up to 1.1, or 110,000 in
1381
    * fixed point.
1382
    *
1383
    * The approach used here is to preserve the maximum precision within the
1384
    * signed representation.  Because the red-scale calculation above uses the
1385
    * difference between two products of values that must be in the range
1386
    * -1.1..+1.1 it is sufficient to divide the product by 8;
1387
    * ceil(121,000/32767*2).  The factor is irrelevant in the calculation
1388
    * because it is applied to both numerator and denominator.
1389
    *
1390
    * Note that the values of the differences of the products of the
1391
    * chromaticities in the above equations tend to be small, for example for
1392
    * the sRGB chromaticities they are:
1393
    *
1394
    * red numerator:    -0.04751
1395
    * green numerator:  -0.08788
1396
    * denominator:      -0.2241 (without white-y multiplication)
1397
    *
1398
    *  The resultant Y coefficients from the chromaticities of some widely used
1399
    *  color space definitions are (to 15 decimal places):
1400
    *
1401
    *  sRGB
1402
    *    0.212639005871510 0.715168678767756 0.072192315360734
1403
    *  Kodak ProPhoto
1404
    *    0.288071128229293 0.711843217810102 0.000085653960605
1405
    *  Adobe RGB
1406
    *    0.297344975250536 0.627363566255466 0.075291458493998
1407
    *  Adobe Wide Gamut RGB
1408
    *    0.258728243040113 0.724682314948566 0.016589442011321
1409
    */
1410
0
   {
1411
0
      int error = 0;
1412
1413
      /* By the argument above overflow should be impossible here, however the
1414
       * code now simply returns a failure code.  The xy subtracts in the
1415
       * arguments to png_muldiv are *not* checked for overflow because the
1416
       * checks at the start guarantee they are in the range 0..110000 and
1417
       * png_fixed_point is a 32-bit signed number.
1418
       */
1419
0
      if (png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 8) == 0)
1420
0
         return 1;
1421
0
      if (png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 8) ==
1422
0
            0)
1423
0
         return 1;
1424
0
      denominator = png_fp_sub(left, right, &error);
1425
0
      if (error) return 1;
1426
1427
      /* Now find the red numerator. */
1428
0
      if (png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)
1429
0
         return 1;
1430
0
      if (png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 8) ==
1431
0
            0)
1432
0
         return 1;
1433
1434
      /* Overflow is possible here and it indicates an extreme set of PNG cHRM
1435
       * chunk values.  This calculation actually returns the reciprocal of the
1436
       * scale value because this allows us to delay the multiplication of
1437
       * white-y into the denominator, which tends to produce a small number.
1438
       */
1439
0
      if (png_muldiv(&red_inverse, xy->whitey, denominator,
1440
0
                     png_fp_sub(left, right, &error)) == 0 || error ||
1441
0
          red_inverse <= xy->whitey /* r+g+b scales = white scale */)
1442
0
         return 1;
1443
1444
      /* Similarly for green_inverse: */
1445
0
      if (png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 8) == 0)
1446
0
         return 1;
1447
0
      if (png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)
1448
0
         return 1;
1449
0
      if (png_muldiv(&green_inverse, xy->whitey, denominator,
1450
0
                     png_fp_sub(left, right, &error)) == 0 || error ||
1451
0
          green_inverse <= xy->whitey)
1452
0
         return 1;
1453
1454
      /* And the blue scale, the checks above guarantee this can't overflow but
1455
       * it can still produce 0 for extreme cHRM values.
1456
       */
1457
0
      blue_scale = png_fp_sub(png_fp_sub(png_reciprocal(xy->whitey),
1458
0
                                         png_reciprocal(red_inverse), &error),
1459
0
                              png_reciprocal(green_inverse), &error);
1460
0
      if (error || blue_scale <= 0)
1461
0
         return 1;
1462
0
   }
1463
1464
   /* And fill in the png_XYZ.  Again the subtracts are safe because of the
1465
    * checks on the xy values at the start (the subtracts just calculate the
1466
    * corresponding z values.)
1467
    */
1468
0
   if (png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse) == 0)
1469
0
      return 1;
1470
0
   if (png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse) == 0)
1471
0
      return 1;
1472
0
   if (png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,
1473
0
       red_inverse) == 0)
1474
0
      return 1;
1475
1476
0
   if (png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse) == 0)
1477
0
      return 1;
1478
0
   if (png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse) == 0)
1479
0
      return 1;
1480
0
   if (png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,
1481
0
       green_inverse) == 0)
1482
0
      return 1;
1483
1484
0
   if (png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1) == 0)
1485
0
      return 1;
1486
0
   if (png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1) == 0)
1487
0
      return 1;
1488
0
   if (png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,
1489
0
       PNG_FP_1) == 0)
1490
0
      return 1;
1491
1492
0
   return 0; /*success*/
1493
0
}
1494
#endif /* COLORSPACE */
1495
1496
#ifdef PNG_READ_iCCP_SUPPORTED
1497
/* Error message generation */
1498
static char
1499
png_icc_tag_char(png_uint_32 byte)
1500
27.0k
{
1501
27.0k
   byte &= 0xff;
1502
27.0k
   if (byte >= 32 && byte <= 126)
1503
27.0k
      return (char)byte;
1504
0
   else
1505
0
      return '?';
1506
27.0k
}
1507
1508
static void
1509
png_icc_tag_name(char *name, png_uint_32 tag)
1510
6.76k
{
1511
6.76k
   name[0] = '\'';
1512
6.76k
   name[1] = png_icc_tag_char(tag >> 24);
1513
6.76k
   name[2] = png_icc_tag_char(tag >> 16);
1514
6.76k
   name[3] = png_icc_tag_char(tag >>  8);
1515
6.76k
   name[4] = png_icc_tag_char(tag      );
1516
6.76k
   name[5] = '\'';
1517
6.76k
}
1518
1519
static int
1520
is_ICC_signature_char(png_alloc_size_t it)
1521
76.5k
{
1522
76.5k
   return it == 32 || (it >= 48 && it <= 57) || (it >= 65 && it <= 90) ||
1523
52.5k
      (it >= 97 && it <= 122);
1524
76.5k
}
1525
1526
static int
1527
is_ICC_signature(png_alloc_size_t it)
1528
33.1k
{
1529
33.1k
   return is_ICC_signature_char(it >> 24) /* checks all the top bits */ &&
1530
17.8k
      is_ICC_signature_char((it >> 16) & 0xff) &&
1531
15.5k
      is_ICC_signature_char((it >> 8) & 0xff) &&
1532
9.99k
      is_ICC_signature_char(it & 0xff);
1533
33.1k
}
1534
1535
static int
1536
png_icc_profile_error(png_const_structrp png_ptr, png_const_charp name,
1537
   png_alloc_size_t value, png_const_charp reason)
1538
33.1k
{
1539
33.1k
   size_t pos;
1540
33.1k
   char message[196]; /* see below for calculation */
1541
1542
33.1k
   pos = png_safecat(message, (sizeof message), 0, "profile '"); /* 9 chars */
1543
33.1k
   pos = png_safecat(message, pos+79, pos, name); /* Truncate to 79 chars */
1544
33.1k
   pos = png_safecat(message, (sizeof message), pos, "': "); /* +2 = 90 */
1545
33.1k
   if (is_ICC_signature(value) != 0)
1546
6.76k
   {
1547
      /* So 'value' is at most 4 bytes and the following cast is safe */
1548
6.76k
      png_icc_tag_name(message+pos, (png_uint_32)value);
1549
6.76k
      pos += 6; /* total +8; less than the else clause */
1550
6.76k
      message[pos++] = ':';
1551
6.76k
      message[pos++] = ' ';
1552
6.76k
   }
1553
26.3k
#  ifdef PNG_WARNINGS_SUPPORTED
1554
26.3k
   else
1555
26.3k
   {
1556
26.3k
      char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114 */
1557
1558
26.3k
      pos = png_safecat(message, (sizeof message), pos,
1559
26.3k
          png_format_number(number, number+(sizeof number),
1560
26.3k
          PNG_NUMBER_FORMAT_x, value));
1561
26.3k
      pos = png_safecat(message, (sizeof message), pos, "h: "); /* +2 = 116 */
1562
26.3k
   }
1563
33.1k
#  endif
1564
   /* The 'reason' is an arbitrary message, allow +79 maximum 195 */
1565
33.1k
   pos = png_safecat(message, (sizeof message), pos, reason);
1566
33.1k
   PNG_UNUSED(pos)
1567
1568
33.1k
   png_chunk_benign_error(png_ptr, message);
1569
1570
33.1k
   return 0;
1571
33.1k
}
1572
1573
/* Encoded value of D50 as an ICC XYZNumber.  From the ICC 2010 spec the value
1574
 * is XYZ(0.9642,1.0,0.8249), which scales to:
1575
 *
1576
 *    (63189.8112, 65536, 54060.6464)
1577
 */
1578
static const png_byte D50_nCIEXYZ[12] =
1579
   { 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };
1580
1581
static int /* bool */
1582
icc_check_length(png_const_structrp png_ptr, png_const_charp name,
1583
   png_uint_32 profile_length)
1584
10.0k
{
1585
10.0k
   if (profile_length < 132)
1586
290
      return png_icc_profile_error(png_ptr, name, profile_length, "too short");
1587
9.72k
   return 1;
1588
10.0k
}
1589
1590
int /* PRIVATE */
1591
png_icc_check_length(png_const_structrp png_ptr, png_const_charp name,
1592
   png_uint_32 profile_length)
1593
10.0k
{
1594
10.0k
   if (!icc_check_length(png_ptr, name, profile_length))
1595
290
      return 0;
1596
1597
   /* This needs to be here because the 'normal' check is in
1598
    * png_decompress_chunk, yet this happens after the attempt to
1599
    * png_malloc_base the required data.  We only need this on read; on write
1600
    * the caller supplies the profile buffer so libpng doesn't allocate it.  See
1601
    * the call to icc_check_length below (the write case).
1602
    */
1603
9.72k
   if (profile_length > png_chunk_max(png_ptr))
1604
481
      return png_icc_profile_error(png_ptr, name, profile_length,
1605
481
            "profile too long");
1606
1607
9.24k
   return 1;
1608
9.72k
}
1609
1610
int /* PRIVATE */
1611
png_icc_check_header(png_const_structrp png_ptr, png_const_charp name,
1612
   png_uint_32 profile_length,
1613
   png_const_bytep profile/* first 132 bytes only */, int color_type)
1614
9.24k
{
1615
9.24k
   png_uint_32 temp;
1616
1617
   /* Length check; this cannot be ignored in this code because profile_length
1618
    * is used later to check the tag table, so even if the profile seems over
1619
    * long profile_length from the caller must be correct.  The caller can fix
1620
    * this up on read or write by just passing in the profile header length.
1621
    */
1622
9.24k
   temp = png_get_uint_32(profile);
1623
9.24k
   if (temp != profile_length)
1624
0
      return png_icc_profile_error(png_ptr, name, temp,
1625
0
          "length does not match profile");
1626
1627
9.24k
   temp = (png_uint_32) (*(profile+8));
1628
9.24k
   if (temp > 3 && (profile_length & 3))
1629
97
      return png_icc_profile_error(png_ptr, name, profile_length,
1630
97
          "invalid length");
1631
1632
9.14k
   temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */
1633
9.14k
   if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */
1634
8.36k
      profile_length < 132+12*temp) /* truncated tag table */
1635
1.08k
      return png_icc_profile_error(png_ptr, name, temp,
1636
1.08k
          "tag count too large");
1637
1638
   /* The 'intent' must be valid or we can't store it, ICC limits the intent to
1639
    * 16 bits.
1640
    */
1641
8.06k
   temp = png_get_uint_32(profile+64);
1642
8.06k
   if (temp >= 0xffff) /* The ICC limit */
1643
419
      return png_icc_profile_error(png_ptr, name, temp,
1644
419
          "invalid rendering intent");
1645
1646
   /* This is just a warning because the profile may be valid in future
1647
    * versions.
1648
    */
1649
7.64k
   if (temp >= PNG_sRGB_INTENT_LAST)
1650
3.51k
      (void)png_icc_profile_error(png_ptr, name, temp,
1651
3.51k
          "intent outside defined range");
1652
1653
   /* At this point the tag table can't be checked because it hasn't necessarily
1654
    * been loaded; however, various header fields can be checked.  These checks
1655
    * are for values permitted by the PNG spec in an ICC profile; the PNG spec
1656
    * restricts the profiles that can be passed in an iCCP chunk (they must be
1657
    * appropriate to processing PNG data!)
1658
    */
1659
1660
   /* Data checks (could be skipped).  These checks must be independent of the
1661
    * version number; however, the version number doesn't accommodate changes in
1662
    * the header fields (just the known tags and the interpretation of the
1663
    * data.)
1664
    */
1665
7.64k
   temp = png_get_uint_32(profile+36); /* signature 'ascp' */
1666
7.64k
   if (temp != 0x61637370)
1667
862
      return png_icc_profile_error(png_ptr, name, temp,
1668
862
          "invalid signature");
1669
1670
   /* Currently the PCS illuminant/adopted white point (the computational
1671
    * white point) are required to be D50,
1672
    * however the profile contains a record of the illuminant so perhaps ICC
1673
    * expects to be able to change this in the future (despite the rationale in
1674
    * the introduction for using a fixed PCS adopted white.)  Consequently the
1675
    * following is just a warning.
1676
    */
1677
6.78k
   if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)
1678
6.57k
      (void)png_icc_profile_error(png_ptr, name, 0/*no tag value*/,
1679
6.57k
          "PCS illuminant is not D50");
1680
1681
   /* The PNG spec requires this:
1682
    * "If the iCCP chunk is present, the image samples conform to the colour
1683
    * space represented by the embedded ICC profile as defined by the
1684
    * International Color Consortium [ICC]. The colour space of the ICC profile
1685
    * shall be an RGB colour space for colour images (PNG colour types 2, 3, and
1686
    * 6), or a greyscale colour space for greyscale images (PNG colour types 0
1687
    * and 4)."
1688
    *
1689
    * This checking code ensures the embedded profile (on either read or write)
1690
    * conforms to the specification requirements.  Notice that an ICC 'gray'
1691
    * color-space profile contains the information to transform the monochrome
1692
    * data to XYZ or L*a*b (according to which PCS the profile uses) and this
1693
    * should be used in preference to the standard libpng K channel replication
1694
    * into R, G and B channels.
1695
    *
1696
    * Previously it was suggested that an RGB profile on grayscale data could be
1697
    * handled.  However it it is clear that using an RGB profile in this context
1698
    * must be an error - there is no specification of what it means.  Thus it is
1699
    * almost certainly more correct to ignore the profile.
1700
    */
1701
6.78k
   temp = png_get_uint_32(profile+16); /* data colour space field */
1702
6.78k
   switch (temp)
1703
6.78k
   {
1704
5.18k
      case 0x52474220: /* 'RGB ' */
1705
5.18k
         if ((color_type & PNG_COLOR_MASK_COLOR) == 0)
1706
425
            return png_icc_profile_error(png_ptr, name, temp,
1707
425
                "RGB color space not permitted on grayscale PNG");
1708
4.76k
         break;
1709
1710
4.76k
      case 0x47524159: /* 'GRAY' */
1711
1.04k
         if ((color_type & PNG_COLOR_MASK_COLOR) != 0)
1712
320
            return png_icc_profile_error(png_ptr, name, temp,
1713
320
                "Gray color space not permitted on RGB PNG");
1714
723
         break;
1715
1716
723
      default:
1717
552
         return png_icc_profile_error(png_ptr, name, temp,
1718
552
             "invalid ICC profile color space");
1719
6.78k
   }
1720
1721
   /* It is up to the application to check that the profile class matches the
1722
    * application requirements; the spec provides no guidance, but it's pretty
1723
    * weird if the profile is not scanner ('scnr'), monitor ('mntr'), printer
1724
    * ('prtr') or 'spac' (for generic color spaces).  Issue a warning in these
1725
    * cases.  Issue an error for device link or abstract profiles - these don't
1726
    * contain the records necessary to transform the color-space to anything
1727
    * other than the target device (and not even that for an abstract profile).
1728
    * Profiles of these classes may not be embedded in images.
1729
    */
1730
5.48k
   temp = png_get_uint_32(profile+12); /* profile/device class */
1731
5.48k
   switch (temp)
1732
5.48k
   {
1733
34
      case 0x73636e72: /* 'scnr' */
1734
246
      case 0x6d6e7472: /* 'mntr' */
1735
1.05k
      case 0x70727472: /* 'prtr' */
1736
1.78k
      case 0x73706163: /* 'spac' */
1737
         /* All supported */
1738
1.78k
         break;
1739
1740
66
      case 0x61627374: /* 'abst' */
1741
         /* May not be embedded in an image */
1742
66
         return png_icc_profile_error(png_ptr, name, temp,
1743
66
             "invalid embedded Abstract ICC profile");
1744
1745
280
      case 0x6c696e6b: /* 'link' */
1746
         /* DeviceLink profiles cannot be interpreted in a non-device specific
1747
          * fashion, if an app uses the AToB0Tag in the profile the results are
1748
          * undefined unless the result is sent to the intended device,
1749
          * therefore a DeviceLink profile should not be found embedded in a
1750
          * PNG.
1751
          */
1752
280
         return png_icc_profile_error(png_ptr, name, temp,
1753
280
             "unexpected DeviceLink ICC profile class");
1754
1755
599
      case 0x6e6d636c: /* 'nmcl' */
1756
         /* A NamedColor profile is also device specific, however it doesn't
1757
          * contain an AToB0 tag that is open to misinterpretation.  Almost
1758
          * certainly it will fail the tests below.
1759
          */
1760
599
         (void)png_icc_profile_error(png_ptr, name, temp,
1761
599
             "unexpected NamedColor ICC profile class");
1762
599
         break;
1763
1764
2.75k
      default:
1765
         /* To allow for future enhancements to the profile accept unrecognized
1766
          * profile classes with a warning, these then hit the test below on the
1767
          * tag content to ensure they are backward compatible with one of the
1768
          * understood profiles.
1769
          */
1770
2.75k
         (void)png_icc_profile_error(png_ptr, name, temp,
1771
2.75k
             "unrecognized ICC profile class");
1772
2.75k
         break;
1773
5.48k
   }
1774
1775
   /* For any profile other than a device link one the PCS must be encoded
1776
    * either in XYZ or Lab.
1777
    */
1778
5.13k
   temp = png_get_uint_32(profile+20);
1779
5.13k
   switch (temp)
1780
5.13k
   {
1781
1.68k
      case 0x58595a20: /* 'XYZ ' */
1782
4.45k
      case 0x4c616220: /* 'Lab ' */
1783
4.45k
         break;
1784
1785
679
      default:
1786
679
         return png_icc_profile_error(png_ptr, name, temp,
1787
679
             "unexpected ICC PCS encoding");
1788
5.13k
   }
1789
1790
4.45k
   return 1;
1791
5.13k
}
1792
1793
int /* PRIVATE */
1794
png_icc_check_tag_table(png_const_structrp png_ptr, png_const_charp name,
1795
   png_uint_32 profile_length,
1796
   png_const_bytep profile /* header plus whole tag table */)
1797
3.70k
{
1798
3.70k
   png_uint_32 tag_count = png_get_uint_32(profile+128);
1799
3.70k
   png_uint_32 itag;
1800
3.70k
   png_const_bytep tag = profile+132; /* The first tag */
1801
1802
   /* First scan all the tags in the table and add bits to the icc_info value
1803
    * (temporarily in 'tags').
1804
    */
1805
20.9k
   for (itag=0; itag < tag_count; ++itag, tag += 12)
1806
18.3k
   {
1807
18.3k
      png_uint_32 tag_id = png_get_uint_32(tag+0);
1808
18.3k
      png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */
1809
18.3k
      png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */
1810
1811
      /* The ICC specification does not exclude zero length tags, therefore the
1812
       * start might actually be anywhere if there is no data, but this would be
1813
       * a clear abuse of the intent of the standard so the start is checked for
1814
       * being in range.  All defined tag types have an 8 byte header - a 4 byte
1815
       * type signature then 0.
1816
       */
1817
1818
      /* This is a hard error; potentially it can cause read outside the
1819
       * profile.
1820
       */
1821
18.3k
      if (tag_start > profile_length || tag_length > profile_length - tag_start)
1822
1.14k
         return png_icc_profile_error(png_ptr, name, tag_id,
1823
1.14k
             "ICC profile tag outside profile");
1824
1825
17.2k
      if ((tag_start & 3) != 0)
1826
12.9k
      {
1827
         /* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is
1828
          * only a warning here because libpng does not care about the
1829
          * alignment.
1830
          */
1831
12.9k
         (void)png_icc_profile_error(png_ptr, name, tag_id,
1832
12.9k
             "ICC profile tag start not a multiple of 4");
1833
12.9k
      }
1834
17.2k
   }
1835
1836
2.55k
   return 1; /* success, maybe with warnings */
1837
3.70k
}
1838
#endif /* READ_iCCP */
1839
1840
#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1841
#if (defined PNG_READ_mDCV_SUPPORTED) || (defined PNG_READ_cHRM_SUPPORTED)
1842
static int
1843
have_chromaticities(png_const_structrp png_ptr)
1844
0
{
1845
   /* Handle new PNGv3 chunks and the precedence rules to determine whether
1846
    * png_struct::chromaticities must be processed.  Only required for RGB to
1847
    * gray.
1848
    *
1849
    * mDCV: this is the mastering colour space and it is independent of the
1850
    *       encoding so it needs to be used regardless of the encoded space.
1851
    *
1852
    * cICP: first in priority but not yet implemented - the chromaticities come
1853
    *       from the 'primaries'.
1854
    *
1855
    * iCCP: not supported by libpng (so ignored)
1856
    *
1857
    * sRGB: the defaults match sRGB
1858
    *
1859
    * cHRM: calculate the coefficients
1860
    */
1861
0
#  ifdef PNG_READ_mDCV_SUPPORTED
1862
0
      if (png_has_chunk(png_ptr, mDCV))
1863
0
         return 1;
1864
0
#     define check_chromaticities 1
1865
0
#  endif /*mDCV*/
1866
1867
0
#  ifdef PNG_READ_sRGB_SUPPORTED
1868
0
      if (png_has_chunk(png_ptr, sRGB))
1869
0
         return 0;
1870
0
#  endif /*sRGB*/
1871
1872
0
#  ifdef PNG_READ_cHRM_SUPPORTED
1873
0
      if (png_has_chunk(png_ptr, cHRM))
1874
0
         return 1;
1875
0
#     define check_chromaticities 1
1876
0
#  endif /*cHRM*/
1877
1878
0
   return 0; /* sRGB defaults */
1879
0
}
1880
#endif /* READ_mDCV || READ_cHRM */
1881
1882
void /* PRIVATE */
1883
png_set_rgb_coefficients(png_structrp png_ptr)
1884
0
{
1885
   /* Set the rgb_to_gray coefficients from the colorspace if available.  Note
1886
    * that '_set' means that png_rgb_to_gray was called **and** it successfully
1887
    * set up the coefficients.
1888
    */
1889
0
   if (png_ptr->rgb_to_gray_coefficients_set == 0)
1890
0
   {
1891
0
#  if check_chromaticities
1892
0
      png_XYZ xyz;
1893
1894
0
      if (have_chromaticities(png_ptr) &&
1895
0
          png_XYZ_from_xy(&xyz, &png_ptr->chromaticities) == 0)
1896
0
      {
1897
         /* png_set_rgb_to_gray has not set the coefficients, get them from the
1898
          * Y * values of the colorspace colorants.
1899
          */
1900
0
         png_fixed_point r = xyz.red_Y;
1901
0
         png_fixed_point g = xyz.green_Y;
1902
0
         png_fixed_point b = xyz.blue_Y;
1903
0
         png_fixed_point total = r+g+b;
1904
1905
0
         if (total > 0 &&
1906
0
            r >= 0 && png_muldiv(&r, r, 32768, total) && r >= 0 && r <= 32768 &&
1907
0
            g >= 0 && png_muldiv(&g, g, 32768, total) && g >= 0 && g <= 32768 &&
1908
0
            b >= 0 && png_muldiv(&b, b, 32768, total) && b >= 0 && b <= 32768 &&
1909
0
            r+g+b <= 32769)
1910
0
         {
1911
            /* We allow 0 coefficients here.  r+g+b may be 32769 if two or
1912
             * all of the coefficients were rounded up.  Handle this by
1913
             * reducing the *largest* coefficient by 1; this matches the
1914
             * approach used for the default coefficients in pngrtran.c
1915
             */
1916
0
            int add = 0;
1917
1918
0
            if (r+g+b > 32768)
1919
0
               add = -1;
1920
0
            else if (r+g+b < 32768)
1921
0
               add = 1;
1922
1923
0
            if (add != 0)
1924
0
            {
1925
0
               if (g >= r && g >= b)
1926
0
                  g += add;
1927
0
               else if (r >= g && r >= b)
1928
0
                  r += add;
1929
0
               else
1930
0
                  b += add;
1931
0
            }
1932
1933
            /* Check for an internal error. */
1934
0
            if (r+g+b != 32768)
1935
0
               png_error(png_ptr,
1936
0
                   "internal error handling cHRM coefficients");
1937
1938
0
            else
1939
0
            {
1940
0
               png_ptr->rgb_to_gray_red_coeff   = (png_uint_16)r;
1941
0
               png_ptr->rgb_to_gray_green_coeff = (png_uint_16)g;
1942
0
            }
1943
0
         }
1944
0
      }
1945
0
      else
1946
0
#  endif /* check_chromaticities */
1947
0
      {
1948
         /* Use the historical REC 709 (etc) values: */
1949
0
         png_ptr->rgb_to_gray_red_coeff   = 6968;
1950
0
         png_ptr->rgb_to_gray_green_coeff = 23434;
1951
         /* png_ptr->rgb_to_gray_blue_coeff  = 2366; */
1952
0
      }
1953
0
   }
1954
0
}
1955
#endif /* READ_RGB_TO_GRAY */
1956
1957
void /* PRIVATE */
1958
png_check_IHDR(png_const_structrp png_ptr,
1959
    png_uint_32 width, png_uint_32 height, int bit_depth,
1960
    int color_type, int interlace_type, int compression_type,
1961
    int filter_type)
1962
9.13k
{
1963
9.13k
   int error = 0;
1964
1965
   /* Check for width and height valid values */
1966
9.13k
   if (width == 0)
1967
4
   {
1968
4
      png_warning(png_ptr, "Image width is zero in IHDR");
1969
4
      error = 1;
1970
4
   }
1971
1972
9.13k
   if (width > PNG_UINT_31_MAX)
1973
0
   {
1974
0
      png_warning(png_ptr, "Invalid image width in IHDR");
1975
0
      error = 1;
1976
0
   }
1977
1978
   /* The bit mask on the first line below must be at least as big as a
1979
    * png_uint_32.  "~7U" is not adequate on 16-bit systems because it will
1980
    * be an unsigned 16-bit value.  Casting to (png_alloc_size_t) makes the
1981
    * type of the result at least as bit (in bits) as the RHS of the > operator
1982
    * which also avoids a common warning on 64-bit systems that the comparison
1983
    * of (png_uint_32) against the constant value on the RHS will always be
1984
    * false.
1985
    */
1986
9.13k
   if (((width + 7) & ~(png_alloc_size_t)7) >
1987
9.13k
       (((PNG_SIZE_MAX
1988
9.13k
           - 48        /* big_row_buf hack */
1989
9.13k
           - 1)        /* filter byte */
1990
9.13k
           / 8)        /* 8-byte RGBA pixels */
1991
9.13k
           - 1))       /* extra max_pixel_depth pad */
1992
0
   {
1993
      /* The size of the row must be within the limits of this architecture.
1994
       * Because the read code can perform arbitrary transformations the
1995
       * maximum size is checked here.  Because the code in png_read_start_row
1996
       * adds extra space "for safety's sake" in several places a conservative
1997
       * limit is used here.
1998
       *
1999
       * NOTE: it would be far better to check the size that is actually used,
2000
       * but the effect in the real world is minor and the changes are more
2001
       * extensive, therefore much more dangerous and much more difficult to
2002
       * write in a way that avoids compiler warnings.
2003
       */
2004
0
      png_warning(png_ptr, "Image width is too large for this architecture");
2005
0
      error = 1;
2006
0
   }
2007
2008
9.13k
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
2009
9.13k
   if (width > png_ptr->user_width_max)
2010
#else
2011
   if (width > PNG_USER_WIDTH_MAX)
2012
#endif
2013
78
   {
2014
78
      png_warning(png_ptr, "Image width exceeds user limit in IHDR");
2015
78
      error = 1;
2016
78
   }
2017
2018
9.13k
   if (height == 0)
2019
5
   {
2020
5
      png_warning(png_ptr, "Image height is zero in IHDR");
2021
5
      error = 1;
2022
5
   }
2023
2024
9.13k
   if (height > PNG_UINT_31_MAX)
2025
0
   {
2026
0
      png_warning(png_ptr, "Invalid image height in IHDR");
2027
0
      error = 1;
2028
0
   }
2029
2030
9.13k
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
2031
9.13k
   if (height > png_ptr->user_height_max)
2032
#else
2033
   if (height > PNG_USER_HEIGHT_MAX)
2034
#endif
2035
86
   {
2036
86
      png_warning(png_ptr, "Image height exceeds user limit in IHDR");
2037
86
      error = 1;
2038
86
   }
2039
2040
   /* Check other values */
2041
9.13k
   if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
2042
3.57k
       bit_depth != 8 && bit_depth != 16)
2043
110
   {
2044
110
      png_warning(png_ptr, "Invalid bit depth in IHDR");
2045
110
      error = 1;
2046
110
   }
2047
2048
9.13k
   if (color_type < 0 || color_type == 1 ||
2049
9.13k
       color_type == 5 || color_type > 6)
2050
86
   {
2051
86
      png_warning(png_ptr, "Invalid color type in IHDR");
2052
86
      error = 1;
2053
86
   }
2054
2055
9.13k
   if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
2056
9.13k
       ((color_type == PNG_COLOR_TYPE_RGB ||
2057
7.23k
         color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
2058
7.00k
         color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
2059
9
   {
2060
9
      png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");
2061
9
      error = 1;
2062
9
   }
2063
2064
9.13k
   if (interlace_type >= PNG_INTERLACE_LAST)
2065
92
   {
2066
92
      png_warning(png_ptr, "Unknown interlace method in IHDR");
2067
92
      error = 1;
2068
92
   }
2069
2070
9.13k
   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
2071
94
   {
2072
94
      png_warning(png_ptr, "Unknown compression method in IHDR");
2073
94
      error = 1;
2074
94
   }
2075
2076
9.13k
#ifdef PNG_MNG_FEATURES_SUPPORTED
2077
   /* Accept filter_method 64 (intrapixel differencing) only if
2078
    * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
2079
    * 2. Libpng did not read a PNG signature (this filter_method is only
2080
    *    used in PNG datastreams that are embedded in MNG datastreams) and
2081
    * 3. The application called png_permit_mng_features with a mask that
2082
    *    included PNG_FLAG_MNG_FILTER_64 and
2083
    * 4. The filter_method is 64 and
2084
    * 5. The color_type is RGB or RGBA
2085
    */
2086
9.13k
   if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 &&
2087
830
       png_ptr->mng_features_permitted != 0)
2088
0
      png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
2089
2090
9.13k
   if (filter_type != PNG_FILTER_TYPE_BASE)
2091
92
   {
2092
92
      if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
2093
0
          (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
2094
0
          ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
2095
0
          (color_type == PNG_COLOR_TYPE_RGB ||
2096
0
          color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
2097
92
      {
2098
92
         png_warning(png_ptr, "Unknown filter method in IHDR");
2099
92
         error = 1;
2100
92
      }
2101
2102
92
      if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0)
2103
0
      {
2104
0
         png_warning(png_ptr, "Invalid filter method in IHDR");
2105
0
         error = 1;
2106
0
      }
2107
92
   }
2108
2109
#else
2110
   if (filter_type != PNG_FILTER_TYPE_BASE)
2111
   {
2112
      png_warning(png_ptr, "Unknown filter method in IHDR");
2113
      error = 1;
2114
   }
2115
#endif
2116
2117
9.13k
   if (error == 1)
2118
128
      png_error(png_ptr, "Invalid IHDR data");
2119
9.13k
}
2120
2121
#if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
2122
/* ASCII to fp functions */
2123
/* Check an ASCII formatted floating point value, see the more detailed
2124
 * comments in pngpriv.h
2125
 */
2126
/* The following is used internally to preserve the sticky flags */
2127
98.2k
#define png_fp_add(state, flags) ((state) |= (flags))
2128
2.97k
#define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))
2129
2130
int /* PRIVATE */
2131
png_check_fp_number(png_const_charp string, size_t size, int *statep,
2132
    size_t *whereami)
2133
7.22k
{
2134
7.22k
   int state = *statep;
2135
7.22k
   size_t i = *whereami;
2136
2137
108k
   while (i < size)
2138
107k
   {
2139
107k
      int type;
2140
      /* First find the type of the next character */
2141
107k
      switch (string[i])
2142
107k
      {
2143
842
      case 43:  type = PNG_FP_SAW_SIGN;                   break;
2144
1.50k
      case 45:  type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;
2145
2.37k
      case 46:  type = PNG_FP_SAW_DOT;                    break;
2146
80.1k
      case 48:  type = PNG_FP_SAW_DIGIT;                  break;
2147
7.82k
      case 49: case 50: case 51: case 52:
2148
14.5k
      case 53: case 54: case 55: case 56:
2149
16.1k
      case 57:  type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;
2150
539
      case 69:
2151
2.57k
      case 101: type = PNG_FP_SAW_E;                      break;
2152
3.50k
      default:  goto PNG_FP_End;
2153
107k
      }
2154
2155
      /* Now deal with this type according to the current
2156
       * state, the type is arranged to not overlap the
2157
       * bits of the PNG_FP_STATE.
2158
       */
2159
103k
      switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))
2160
103k
      {
2161
1.28k
      case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:
2162
1.28k
         if ((state & PNG_FP_SAW_ANY) != 0)
2163
590
            goto PNG_FP_End; /* not a part of the number */
2164
2165
697
         png_fp_add(state, type);
2166
697
         break;
2167
2168
2.13k
      case PNG_FP_INTEGER + PNG_FP_SAW_DOT:
2169
         /* Ok as trailer, ok as lead of fraction. */
2170
2.13k
         if ((state & PNG_FP_SAW_DOT) != 0) /* two dots */
2171
390
            goto PNG_FP_End;
2172
2173
1.74k
         else if ((state & PNG_FP_SAW_DIGIT) != 0) /* trailing dot? */
2174
558
            png_fp_add(state, type);
2175
2176
1.18k
         else
2177
1.18k
            png_fp_set(state, PNG_FP_FRACTION | type);
2178
2179
1.74k
         break;
2180
2181
62.6k
      case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:
2182
62.6k
         if ((state & PNG_FP_SAW_DOT) != 0) /* delayed fraction */
2183
115
            png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);
2184
2185
62.6k
         png_fp_add(state, type | PNG_FP_WAS_VALID);
2186
2187
62.6k
         break;
2188
2189
1.61k
      case PNG_FP_INTEGER + PNG_FP_SAW_E:
2190
1.61k
         if ((state & PNG_FP_SAW_DIGIT) == 0)
2191
298
            goto PNG_FP_End;
2192
2193
1.31k
         png_fp_set(state, PNG_FP_EXPONENT);
2194
2195
1.31k
         break;
2196
2197
   /* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:
2198
         goto PNG_FP_End; ** no sign in fraction */
2199
2200
   /* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:
2201
         goto PNG_FP_End; ** Because SAW_DOT is always set */
2202
2203
32.1k
      case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:
2204
32.1k
         png_fp_add(state, type | PNG_FP_WAS_VALID);
2205
32.1k
         break;
2206
2207
552
      case PNG_FP_FRACTION + PNG_FP_SAW_E:
2208
         /* This is correct because the trailing '.' on an
2209
          * integer is handled above - so we can only get here
2210
          * with the sequence ".E" (with no preceding digits).
2211
          */
2212
552
         if ((state & PNG_FP_SAW_DIGIT) == 0)
2213
196
            goto PNG_FP_End;
2214
2215
356
         png_fp_set(state, PNG_FP_EXPONENT);
2216
2217
356
         break;
2218
2219
957
      case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:
2220
957
         if ((state & PNG_FP_SAW_ANY) != 0)
2221
316
            goto PNG_FP_End; /* not a part of the number */
2222
2223
641
         png_fp_add(state, PNG_FP_SAW_SIGN);
2224
2225
641
         break;
2226
2227
   /* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:
2228
         goto PNG_FP_End; */
2229
2230
1.47k
      case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:
2231
1.47k
         png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);
2232
2233
1.47k
         break;
2234
2235
   /* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:
2236
         goto PNG_FP_End; */
2237
2238
751
      default: goto PNG_FP_End; /* I.e. break 2 */
2239
103k
      }
2240
2241
      /* The character seems ok, continue. */
2242
101k
      ++i;
2243
101k
   }
2244
2245
7.22k
PNG_FP_End:
2246
   /* Here at the end, update the state and return the correct
2247
    * return code.
2248
    */
2249
7.22k
   *statep = state;
2250
7.22k
   *whereami = i;
2251
2252
7.22k
   return (state & PNG_FP_SAW_DIGIT) != 0;
2253
7.22k
}
2254
2255
2256
/* The same but for a complete string. */
2257
int
2258
png_check_fp_string(png_const_charp string, size_t size)
2259
349
{
2260
349
   int        state=0;
2261
349
   size_t char_index=0;
2262
2263
349
   if (png_check_fp_number(string, size, &state, &char_index) != 0 &&
2264
333
      (char_index == size || string[char_index] == 0))
2265
313
      return state /* must be non-zero - see above */;
2266
2267
36
   return 0; /* i.e. fail */
2268
349
}
2269
#endif /* pCAL || sCAL */
2270
2271
#ifdef PNG_sCAL_SUPPORTED
2272
#  ifdef PNG_FLOATING_POINT_SUPPORTED
2273
/* Utility used below - a simple accurate power of ten from an integral
2274
 * exponent.
2275
 */
2276
static double
2277
png_pow10(int power)
2278
0
{
2279
0
   int recip = 0;
2280
0
   double d = 1;
2281
2282
   /* Handle negative exponent with a reciprocal at the end because
2283
    * 10 is exact whereas .1 is inexact in base 2
2284
    */
2285
0
   if (power < 0)
2286
0
   {
2287
0
      if (power < DBL_MIN_10_EXP) return 0;
2288
0
      recip = 1; power = -power;
2289
0
   }
2290
2291
0
   if (power > 0)
2292
0
   {
2293
      /* Decompose power bitwise. */
2294
0
      double mult = 10;
2295
0
      do
2296
0
      {
2297
0
         if (power & 1) d *= mult;
2298
0
         mult *= mult;
2299
0
         power >>= 1;
2300
0
      }
2301
0
      while (power > 0);
2302
2303
0
      if (recip != 0) d = 1/d;
2304
0
   }
2305
   /* else power is 0 and d is 1 */
2306
2307
0
   return d;
2308
0
}
2309
2310
/* Function to format a floating point value in ASCII with a given
2311
 * precision.
2312
 */
2313
void /* PRIVATE */
2314
png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size,
2315
    double fp, unsigned int precision)
2316
0
{
2317
   /* We use standard functions from math.h, but not printf because
2318
    * that would require stdio.  The caller must supply a buffer of
2319
    * sufficient size or we will png_error.  The tests on size and
2320
    * the space in ascii[] consumed are indicated below.
2321
    */
2322
0
   if (precision < 1)
2323
0
      precision = DBL_DIG;
2324
2325
   /* Enforce the limit of the implementation precision too. */
2326
0
   if (precision > DBL_DIG+1)
2327
0
      precision = DBL_DIG+1;
2328
2329
   /* Basic sanity checks */
2330
0
   if (size >= precision+5) /* See the requirements below. */
2331
0
   {
2332
0
      if (fp < 0)
2333
0
      {
2334
0
         fp = -fp;
2335
0
         *ascii++ = 45; /* '-'  PLUS 1 TOTAL 1 */
2336
0
         --size;
2337
0
      }
2338
2339
0
      if (fp >= DBL_MIN && fp <= DBL_MAX)
2340
0
      {
2341
0
         int exp_b10;   /* A base 10 exponent */
2342
0
         double base;   /* 10^exp_b10 */
2343
2344
         /* First extract a base 10 exponent of the number,
2345
          * the calculation below rounds down when converting
2346
          * from base 2 to base 10 (multiply by log10(2) -
2347
          * 0.3010, but 77/256 is 0.3008, so exp_b10 needs to
2348
          * be increased.  Note that the arithmetic shift
2349
          * performs a floor() unlike C arithmetic - using a
2350
          * C multiply would break the following for negative
2351
          * exponents.
2352
          */
2353
0
         (void)frexp(fp, &exp_b10); /* exponent to base 2 */
2354
2355
0
         exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
2356
2357
         /* Avoid underflow here. */
2358
0
         base = png_pow10(exp_b10); /* May underflow */
2359
2360
0
         while (base < DBL_MIN || base < fp)
2361
0
         {
2362
            /* And this may overflow. */
2363
0
            double test = png_pow10(exp_b10+1);
2364
2365
0
            if (test <= DBL_MAX)
2366
0
            {
2367
0
               ++exp_b10; base = test;
2368
0
            }
2369
2370
0
            else
2371
0
               break;
2372
0
         }
2373
2374
         /* Normalize fp and correct exp_b10, after this fp is in the
2375
          * range [.1,1) and exp_b10 is both the exponent and the digit
2376
          * *before* which the decimal point should be inserted
2377
          * (starting with 0 for the first digit).  Note that this
2378
          * works even if 10^exp_b10 is out of range because of the
2379
          * test on DBL_MAX above.
2380
          */
2381
0
         fp /= base;
2382
0
         while (fp >= 1)
2383
0
         {
2384
0
            fp /= 10; ++exp_b10;
2385
0
         }
2386
2387
         /* Because of the code above fp may, at this point, be
2388
          * less than .1, this is ok because the code below can
2389
          * handle the leading zeros this generates, so no attempt
2390
          * is made to correct that here.
2391
          */
2392
2393
0
         {
2394
0
            unsigned int czero, clead, cdigits;
2395
0
            char exponent[10];
2396
2397
            /* Allow up to two leading zeros - this will not lengthen
2398
             * the number compared to using E-n.
2399
             */
2400
0
            if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
2401
0
            {
2402
0
               czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */
2403
0
               exp_b10 = 0;      /* Dot added below before first output. */
2404
0
            }
2405
0
            else
2406
0
               czero = 0;    /* No zeros to add */
2407
2408
            /* Generate the digit list, stripping trailing zeros and
2409
             * inserting a '.' before a digit if the exponent is 0.
2410
             */
2411
0
            clead = czero; /* Count of leading zeros */
2412
0
            cdigits = 0;   /* Count of digits in list. */
2413
2414
0
            do
2415
0
            {
2416
0
               double d;
2417
2418
0
               fp *= 10;
2419
               /* Use modf here, not floor and subtract, so that
2420
                * the separation is done in one step.  At the end
2421
                * of the loop don't break the number into parts so
2422
                * that the final digit is rounded.
2423
                */
2424
0
               if (cdigits+czero+1 < precision+clead)
2425
0
                  fp = modf(fp, &d);
2426
2427
0
               else
2428
0
               {
2429
0
                  d = floor(fp + .5);
2430
2431
0
                  if (d > 9)
2432
0
                  {
2433
                     /* Rounding up to 10, handle that here. */
2434
0
                     if (czero > 0)
2435
0
                     {
2436
0
                        --czero; d = 1;
2437
0
                        if (cdigits == 0) --clead;
2438
0
                     }
2439
0
                     else
2440
0
                     {
2441
0
                        while (cdigits > 0 && d > 9)
2442
0
                        {
2443
0
                           int ch = *--ascii;
2444
2445
0
                           if (exp_b10 != (-1))
2446
0
                              ++exp_b10;
2447
2448
0
                           else if (ch == 46)
2449
0
                           {
2450
0
                              ch = *--ascii; ++size;
2451
                              /* Advance exp_b10 to '1', so that the
2452
                               * decimal point happens after the
2453
                               * previous digit.
2454
                               */
2455
0
                              exp_b10 = 1;
2456
0
                           }
2457
2458
0
                           --cdigits;
2459
0
                           d = ch - 47;  /* I.e. 1+(ch-48) */
2460
0
                        }
2461
2462
                        /* Did we reach the beginning? If so adjust the
2463
                         * exponent but take into account the leading
2464
                         * decimal point.
2465
                         */
2466
0
                        if (d > 9)  /* cdigits == 0 */
2467
0
                        {
2468
0
                           if (exp_b10 == (-1))
2469
0
                           {
2470
                              /* Leading decimal point (plus zeros?), if
2471
                               * we lose the decimal point here it must
2472
                               * be reentered below.
2473
                               */
2474
0
                              int ch = *--ascii;
2475
2476
0
                              if (ch == 46)
2477
0
                              {
2478
0
                                 ++size; exp_b10 = 1;
2479
0
                              }
2480
2481
                              /* Else lost a leading zero, so 'exp_b10' is
2482
                               * still ok at (-1)
2483
                               */
2484
0
                           }
2485
0
                           else
2486
0
                              ++exp_b10;
2487
2488
                           /* In all cases we output a '1' */
2489
0
                           d = 1;
2490
0
                        }
2491
0
                     }
2492
0
                  }
2493
0
                  fp = 0; /* Guarantees termination below. */
2494
0
               }
2495
2496
0
               if (d == 0)
2497
0
               {
2498
0
                  ++czero;
2499
0
                  if (cdigits == 0) ++clead;
2500
0
               }
2501
0
               else
2502
0
               {
2503
                  /* Included embedded zeros in the digit count. */
2504
0
                  cdigits += czero - clead;
2505
0
                  clead = 0;
2506
2507
0
                  while (czero > 0)
2508
0
                  {
2509
                     /* exp_b10 == (-1) means we just output the decimal
2510
                      * place - after the DP don't adjust 'exp_b10' any
2511
                      * more!
2512
                      */
2513
0
                     if (exp_b10 != (-1))
2514
0
                     {
2515
0
                        if (exp_b10 == 0)
2516
0
                        {
2517
0
                           *ascii++ = 46; --size;
2518
0
                        }
2519
                        /* PLUS 1: TOTAL 4 */
2520
0
                        --exp_b10;
2521
0
                     }
2522
0
                     *ascii++ = 48; --czero;
2523
0
                  }
2524
2525
0
                  if (exp_b10 != (-1))
2526
0
                  {
2527
0
                     if (exp_b10 == 0)
2528
0
                     {
2529
0
                        *ascii++ = 46; --size; /* counted above */
2530
0
                     }
2531
2532
0
                     --exp_b10;
2533
0
                  }
2534
0
                  *ascii++ = (char)(48 + (int)d); ++cdigits;
2535
0
               }
2536
0
            }
2537
0
            while (cdigits+czero < precision+clead && fp > DBL_MIN);
2538
2539
            /* The total output count (max) is now 4+precision */
2540
2541
            /* Check for an exponent, if we don't need one we are
2542
             * done and just need to terminate the string.  At this
2543
             * point, exp_b10==(-1) is effectively a flag: it got
2544
             * to '-1' because of the decrement, after outputting
2545
             * the decimal point above. (The exponent required is
2546
             * *not* -1.)
2547
             */
2548
0
            if (exp_b10 >= (-1) && exp_b10 <= 2)
2549
0
            {
2550
               /* The following only happens if we didn't output the
2551
                * leading zeros above for negative exponent, so this
2552
                * doesn't add to the digit requirement.  Note that the
2553
                * two zeros here can only be output if the two leading
2554
                * zeros were *not* output, so this doesn't increase
2555
                * the output count.
2556
                */
2557
0
               while (exp_b10-- > 0) *ascii++ = 48;
2558
2559
0
               *ascii = 0;
2560
2561
               /* Total buffer requirement (including the '\0') is
2562
                * 5+precision - see check at the start.
2563
                */
2564
0
               return;
2565
0
            }
2566
2567
            /* Here if an exponent is required, adjust size for
2568
             * the digits we output but did not count.  The total
2569
             * digit output here so far is at most 1+precision - no
2570
             * decimal point and no leading or trailing zeros have
2571
             * been output.
2572
             */
2573
0
            size -= cdigits;
2574
2575
0
            *ascii++ = 69; --size;    /* 'E': PLUS 1 TOTAL 2+precision */
2576
2577
            /* The following use of an unsigned temporary avoids ambiguities in
2578
             * the signed arithmetic on exp_b10 and permits GCC at least to do
2579
             * better optimization.
2580
             */
2581
0
            {
2582
0
               unsigned int uexp_b10;
2583
2584
0
               if (exp_b10 < 0)
2585
0
               {
2586
0
                  *ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */
2587
0
                  uexp_b10 = 0U-exp_b10;
2588
0
               }
2589
2590
0
               else
2591
0
                  uexp_b10 = 0U+exp_b10;
2592
2593
0
               cdigits = 0;
2594
2595
0
               while (uexp_b10 > 0)
2596
0
               {
2597
0
                  exponent[cdigits++] = (char)(48 + uexp_b10 % 10);
2598
0
                  uexp_b10 /= 10;
2599
0
               }
2600
0
            }
2601
2602
            /* Need another size check here for the exponent digits, so
2603
             * this need not be considered above.
2604
             */
2605
0
            if (size > cdigits)
2606
0
            {
2607
0
               while (cdigits > 0) *ascii++ = exponent[--cdigits];
2608
2609
0
               *ascii = 0;
2610
2611
0
               return;
2612
0
            }
2613
0
         }
2614
0
      }
2615
0
      else if (!(fp >= DBL_MIN))
2616
0
      {
2617
0
         *ascii++ = 48; /* '0' */
2618
0
         *ascii = 0;
2619
0
         return;
2620
0
      }
2621
0
      else
2622
0
      {
2623
0
         *ascii++ = 105; /* 'i' */
2624
0
         *ascii++ = 110; /* 'n' */
2625
0
         *ascii++ = 102; /* 'f' */
2626
0
         *ascii = 0;
2627
0
         return;
2628
0
      }
2629
0
   }
2630
2631
   /* Here on buffer too small. */
2632
0
   png_error(png_ptr, "ASCII conversion buffer too small");
2633
0
}
2634
#  endif /* FLOATING_POINT */
2635
2636
#  ifdef PNG_FIXED_POINT_SUPPORTED
2637
/* Function to format a fixed point value in ASCII.
2638
 */
2639
void /* PRIVATE */
2640
png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
2641
    size_t size, png_fixed_point fp)
2642
0
{
2643
   /* Require space for 10 decimal digits, a decimal point, a minus sign and a
2644
    * trailing \0, 13 characters:
2645
    */
2646
0
   if (size > 12)
2647
0
   {
2648
0
      png_uint_32 num;
2649
2650
      /* Avoid overflow here on the minimum integer. */
2651
0
      if (fp < 0)
2652
0
      {
2653
0
         *ascii++ = 45; num = (png_uint_32)(-fp);
2654
0
      }
2655
0
      else
2656
0
         num = (png_uint_32)fp;
2657
2658
0
      if (num <= 0x80000000) /* else overflowed */
2659
0
      {
2660
0
         unsigned int ndigits = 0, first = 16 /* flag value */;
2661
0
         char digits[10] = {0};
2662
2663
0
         while (num)
2664
0
         {
2665
            /* Split the low digit off num: */
2666
0
            unsigned int tmp = num/10;
2667
0
            num -= tmp*10;
2668
0
            digits[ndigits++] = (char)(48 + num);
2669
            /* Record the first non-zero digit, note that this is a number
2670
             * starting at 1, it's not actually the array index.
2671
             */
2672
0
            if (first == 16 && num > 0)
2673
0
               first = ndigits;
2674
0
            num = tmp;
2675
0
         }
2676
2677
0
         if (ndigits > 0)
2678
0
         {
2679
0
            while (ndigits > 5) *ascii++ = digits[--ndigits];
2680
            /* The remaining digits are fractional digits, ndigits is '5' or
2681
             * smaller at this point.  It is certainly not zero.  Check for a
2682
             * non-zero fractional digit:
2683
             */
2684
0
            if (first <= 5)
2685
0
            {
2686
0
               unsigned int i;
2687
0
               *ascii++ = 46; /* decimal point */
2688
               /* ndigits may be <5 for small numbers, output leading zeros
2689
                * then ndigits digits to first:
2690
                */
2691
0
               i = 5;
2692
0
               while (ndigits < i)
2693
0
               {
2694
0
                  *ascii++ = 48; --i;
2695
0
               }
2696
0
               while (ndigits >= first) *ascii++ = digits[--ndigits];
2697
               /* Don't output the trailing zeros! */
2698
0
            }
2699
0
         }
2700
0
         else
2701
0
            *ascii++ = 48;
2702
2703
         /* And null terminate the string: */
2704
0
         *ascii = 0;
2705
0
         return;
2706
0
      }
2707
0
   }
2708
2709
   /* Here on buffer too small. */
2710
0
   png_error(png_ptr, "ASCII conversion buffer too small");
2711
0
}
2712
#   endif /* FIXED_POINT */
2713
#endif /* SCAL */
2714
2715
#if defined(PNG_FLOATING_POINT_SUPPORTED) && \
2716
   !defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \
2717
   (defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \
2718
   defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \
2719
   defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \
2720
   (defined(PNG_sCAL_SUPPORTED) && \
2721
   defined(PNG_FLOATING_ARITHMETIC_SUPPORTED))
2722
png_fixed_point
2723
png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text)
2724
0
{
2725
0
   double r = floor(100000 * fp + .5);
2726
2727
0
   if (r > 2147483647. || r < -2147483648.)
2728
0
      png_fixed_error(png_ptr, text);
2729
2730
#  ifndef PNG_ERROR_TEXT_SUPPORTED
2731
   PNG_UNUSED(text)
2732
#  endif
2733
2734
0
   return (png_fixed_point)r;
2735
0
}
2736
#endif
2737
2738
#if defined(PNG_FLOATING_POINT_SUPPORTED) && \
2739
   !defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \
2740
   (defined(PNG_cLLI_SUPPORTED) || defined(PNG_mDCV_SUPPORTED))
2741
png_uint_32
2742
png_fixed_ITU(png_const_structrp png_ptr, double fp, png_const_charp text)
2743
0
{
2744
0
   double r = floor(10000 * fp + .5);
2745
2746
0
   if (r > 2147483647. || r < 0)
2747
0
      png_fixed_error(png_ptr, text);
2748
2749
#  ifndef PNG_ERROR_TEXT_SUPPORTED
2750
   PNG_UNUSED(text)
2751
#  endif
2752
2753
0
   return (png_uint_32)r;
2754
0
}
2755
#endif
2756
2757
2758
#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\
2759
    defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)
2760
/* muldiv functions */
2761
/* This API takes signed arguments and rounds the result to the nearest
2762
 * integer (or, for a fixed point number - the standard argument - to
2763
 * the nearest .00001).  Overflow and divide by zero are signalled in
2764
 * the result, a boolean - true on success, false on overflow.
2765
 */
2766
int /* PRIVATE */
2767
png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
2768
    png_int_32 divisor)
2769
741
{
2770
   /* Return a * times / divisor, rounded. */
2771
741
   if (divisor != 0)
2772
741
   {
2773
741
      if (a == 0 || times == 0)
2774
0
      {
2775
0
         *res = 0;
2776
0
         return 1;
2777
0
      }
2778
741
      else
2779
741
      {
2780
741
#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2781
741
         double r = a;
2782
741
         r *= times;
2783
741
         r /= divisor;
2784
741
         r = floor(r+.5);
2785
2786
         /* A png_fixed_point is a 32-bit integer. */
2787
741
         if (r <= 2147483647. && r >= -2147483648.)
2788
738
         {
2789
738
            *res = (png_fixed_point)r;
2790
738
            return 1;
2791
738
         }
2792
#else
2793
         int negative = 0;
2794
         png_uint_32 A, T, D;
2795
         png_uint_32 s16, s32, s00;
2796
2797
         if (a < 0)
2798
            negative = 1, A = -a;
2799
         else
2800
            A = a;
2801
2802
         if (times < 0)
2803
            negative = !negative, T = -times;
2804
         else
2805
            T = times;
2806
2807
         if (divisor < 0)
2808
            negative = !negative, D = -divisor;
2809
         else
2810
            D = divisor;
2811
2812
         /* Following can't overflow because the arguments only
2813
          * have 31 bits each, however the result may be 32 bits.
2814
          */
2815
         s16 = (A >> 16) * (T & 0xffff) +
2816
                           (A & 0xffff) * (T >> 16);
2817
         /* Can't overflow because the a*times bit is only 30
2818
          * bits at most.
2819
          */
2820
         s32 = (A >> 16) * (T >> 16) + (s16 >> 16);
2821
         s00 = (A & 0xffff) * (T & 0xffff);
2822
2823
         s16 = (s16 & 0xffff) << 16;
2824
         s00 += s16;
2825
2826
         if (s00 < s16)
2827
            ++s32; /* carry */
2828
2829
         if (s32 < D) /* else overflow */
2830
         {
2831
            /* s32.s00 is now the 64-bit product, do a standard
2832
             * division, we know that s32 < D, so the maximum
2833
             * required shift is 31.
2834
             */
2835
            int bitshift = 32;
2836
            png_fixed_point result = 0; /* NOTE: signed */
2837
2838
            while (--bitshift >= 0)
2839
            {
2840
               png_uint_32 d32, d00;
2841
2842
               if (bitshift > 0)
2843
                  d32 = D >> (32-bitshift), d00 = D << bitshift;
2844
2845
               else
2846
                  d32 = 0, d00 = D;
2847
2848
               if (s32 > d32)
2849
               {
2850
                  if (s00 < d00) --s32; /* carry */
2851
                  s32 -= d32, s00 -= d00, result += 1<<bitshift;
2852
               }
2853
2854
               else
2855
                  if (s32 == d32 && s00 >= d00)
2856
                     s32 = 0, s00 -= d00, result += 1<<bitshift;
2857
            }
2858
2859
            /* Handle the rounding. */
2860
            if (s00 >= (D >> 1))
2861
               ++result;
2862
2863
            if (negative != 0)
2864
               result = -result;
2865
2866
            /* Check for overflow. */
2867
            if ((negative != 0 && result <= 0) ||
2868
                (negative == 0 && result >= 0))
2869
            {
2870
               *res = result;
2871
               return 1;
2872
            }
2873
         }
2874
#endif
2875
741
      }
2876
741
   }
2877
2878
3
   return 0;
2879
741
}
2880
2881
/* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
2882
png_fixed_point
2883
png_reciprocal(png_fixed_point a)
2884
1.13k
{
2885
1.13k
#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2886
1.13k
   double r = floor(1E10/a+.5);
2887
2888
1.13k
   if (r <= 2147483647. && r >= -2147483648.)
2889
1.12k
      return (png_fixed_point)r;
2890
#else
2891
   png_fixed_point res;
2892
2893
   if (png_muldiv(&res, 100000, 100000, a) != 0)
2894
      return res;
2895
#endif
2896
2897
3
   return 0; /* error/overflow */
2898
1.13k
}
2899
#endif /* READ_GAMMA || COLORSPACE || INCH_CONVERSIONS || READ_pHYS */
2900
2901
#ifdef PNG_READ_GAMMA_SUPPORTED
2902
/* This is the shared test on whether a gamma value is 'significant' - whether
2903
 * it is worth doing gamma correction.
2904
 */
2905
int /* PRIVATE */
2906
png_gamma_significant(png_fixed_point gamma_val)
2907
3.61k
{
2908
   /* sRGB:       1/2.2 == 0.4545(45)
2909
    * AdobeRGB:   1/(2+51/256) ~= 0.45471 5dp
2910
    *
2911
    * So the correction from AdobeRGB to sRGB (output) is:
2912
    *
2913
    *    2.2/(2+51/256) == 1.00035524
2914
    *
2915
    * I.e. vanishly small (<4E-4) but still detectable in 16-bit linear (+/-
2916
    * 23).  Note that the Adobe choice seems to be something intended to give an
2917
    * exact number with 8 binary fractional digits - it is the closest to 2.2
2918
    * that is possible a base 2 .8p representation.
2919
    */
2920
3.61k
   return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
2921
3.53k
       gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
2922
3.61k
}
2923
2924
#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
2925
/* A local convenience routine. */
2926
static png_fixed_point
2927
png_product2(png_fixed_point a, png_fixed_point b)
2928
{
2929
   /* The required result is a * b; the following preserves accuracy. */
2930
#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* Should now be unused */
2931
   double r = a * 1E-5;
2932
   r *= b;
2933
   r = floor(r+.5);
2934
2935
   if (r <= 2147483647. && r >= -2147483648.)
2936
      return (png_fixed_point)r;
2937
#else
2938
   png_fixed_point res;
2939
2940
   if (png_muldiv(&res, a, b, 100000) != 0)
2941
      return res;
2942
#endif
2943
2944
   return 0; /* overflow */
2945
}
2946
#endif /* FLOATING_ARITHMETIC */
2947
2948
png_fixed_point
2949
png_reciprocal2(png_fixed_point a, png_fixed_point b)
2950
92
{
2951
   /* The required result is 1/a * 1/b; the following preserves accuracy. */
2952
92
#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2953
92
   if (a != 0 && b != 0)
2954
92
   {
2955
92
      double r = 1E15/a;
2956
92
      r /= b;
2957
92
      r = floor(r+.5);
2958
2959
92
      if (r <= 2147483647. && r >= -2147483648.)
2960
92
         return (png_fixed_point)r;
2961
92
   }
2962
#else
2963
   /* This may overflow because the range of png_fixed_point isn't symmetric,
2964
    * but this API is only used for the product of file and screen gamma so it
2965
    * doesn't matter that the smallest number it can produce is 1/21474, not
2966
    * 1/100000
2967
    */
2968
   png_fixed_point res = png_product2(a, b);
2969
2970
   if (res != 0)
2971
      return png_reciprocal(res);
2972
#endif
2973
2974
0
   return 0; /* overflow */
2975
92
}
2976
#endif /* READ_GAMMA */
2977
2978
#ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */
2979
#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
2980
/* Fixed point gamma.
2981
 *
2982
 * The code to calculate the tables used below can be found in the shell script
2983
 * contrib/tools/intgamma.sh
2984
 *
2985
 * To calculate gamma this code implements fast log() and exp() calls using only
2986
 * fixed point arithmetic.  This code has sufficient precision for either 8-bit
2987
 * or 16-bit sample values.
2988
 *
2989
 * The tables used here were calculated using simple 'bc' programs, but C double
2990
 * precision floating point arithmetic would work fine.
2991
 *
2992
 * 8-bit log table
2993
 *   This is a table of -log(value/255)/log(2) for 'value' in the range 128 to
2994
 *   255, so it's the base 2 logarithm of a normalized 8-bit floating point
2995
 *   mantissa.  The numbers are 32-bit fractions.
2996
 */
2997
static const png_uint_32
2998
png_8bit_l2[128] =
2999
{
3000
   4270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,
3001
   3986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,
3002
   3715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,
3003
   3455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,
3004
   3205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,
3005
   2965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,
3006
   2735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,
3007
   2512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,
3008
   2297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,
3009
   2089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,
3010
   1888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,
3011
   1694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,
3012
   1505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,
3013
   1322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,
3014
   1144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,
3015
   971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,
3016
   803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,
3017
   639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,
3018
   479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,
3019
   324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,
3020
   172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,
3021
   24347096U, 0U
3022
3023
#if 0
3024
   /* The following are the values for 16-bit tables - these work fine for the
3025
    * 8-bit conversions but produce very slightly larger errors in the 16-bit
3026
    * log (about 1.2 as opposed to 0.7 absolute error in the final value).  To
3027
    * use these all the shifts below must be adjusted appropriately.
3028
    */
3029
   65166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,
3030
   57371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,
3031
   50170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,
3032
   43479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,
3033
   37230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,
3034
   31369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,
3035
   25850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,
3036
   20636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,
3037
   15694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,
3038
   10997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,
3039
   6127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,
3040
   1119, 744, 372
3041
#endif
3042
};
3043
3044
static png_int_32
3045
png_log8bit(unsigned int x)
3046
{
3047
   unsigned int lg2 = 0;
3048
   /* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,
3049
    * because the log is actually negate that means adding 1.  The final
3050
    * returned value thus has the range 0 (for 255 input) to 7.994 (for 1
3051
    * input), return -1 for the overflow (log 0) case, - so the result is
3052
    * always at most 19 bits.
3053
    */
3054
   if ((x &= 0xff) == 0)
3055
      return -1;
3056
3057
   if ((x & 0xf0) == 0)
3058
      lg2  = 4, x <<= 4;
3059
3060
   if ((x & 0xc0) == 0)
3061
      lg2 += 2, x <<= 2;
3062
3063
   if ((x & 0x80) == 0)
3064
      lg2 += 1, x <<= 1;
3065
3066
   /* result is at most 19 bits, so this cast is safe: */
3067
   return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));
3068
}
3069
3070
/* The above gives exact (to 16 binary places) log2 values for 8-bit images,
3071
 * for 16-bit images we use the most significant 8 bits of the 16-bit value to
3072
 * get an approximation then multiply the approximation by a correction factor
3073
 * determined by the remaining up to 8 bits.  This requires an additional step
3074
 * in the 16-bit case.
3075
 *
3076
 * We want log2(value/65535), we have log2(v'/255), where:
3077
 *
3078
 *    value = v' * 256 + v''
3079
 *          = v' * f
3080
 *
3081
 * So f is value/v', which is equal to (256+v''/v') since v' is in the range 128
3082
 * to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less
3083
 * than 258.  The final factor also needs to correct for the fact that our 8-bit
3084
 * value is scaled by 255, whereas the 16-bit values must be scaled by 65535.
3085
 *
3086
 * This gives a final formula using a calculated value 'x' which is value/v' and
3087
 * scaling by 65536 to match the above table:
3088
 *
3089
 *   log2(x/257) * 65536
3090
 *
3091
 * Since these numbers are so close to '1' we can use simple linear
3092
 * interpolation between the two end values 256/257 (result -368.61) and 258/257
3093
 * (result 367.179).  The values used below are scaled by a further 64 to give
3094
 * 16-bit precision in the interpolation:
3095
 *
3096
 * Start (256): -23591
3097
 * Zero  (257):      0
3098
 * End   (258):  23499
3099
 */
3100
#ifdef PNG_16BIT_SUPPORTED
3101
static png_int_32
3102
png_log16bit(png_uint_32 x)
3103
{
3104
   unsigned int lg2 = 0;
3105
3106
   /* As above, but now the input has 16 bits. */
3107
   if ((x &= 0xffff) == 0)
3108
      return -1;
3109
3110
   if ((x & 0xff00) == 0)
3111
      lg2  = 8, x <<= 8;
3112
3113
   if ((x & 0xf000) == 0)
3114
      lg2 += 4, x <<= 4;
3115
3116
   if ((x & 0xc000) == 0)
3117
      lg2 += 2, x <<= 2;
3118
3119
   if ((x & 0x8000) == 0)
3120
      lg2 += 1, x <<= 1;
3121
3122
   /* Calculate the base logarithm from the top 8 bits as a 28-bit fractional
3123
    * value.
3124
    */
3125
   lg2 <<= 28;
3126
   lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;
3127
3128
   /* Now we need to interpolate the factor, this requires a division by the top
3129
    * 8 bits.  Do this with maximum precision.
3130
    */
3131
   x = ((x << 16) + (x >> 9)) / (x >> 8);
3132
3133
   /* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,
3134
    * the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly
3135
    * 16 bits to interpolate to get the low bits of the result.  Round the
3136
    * answer.  Note that the end point values are scaled by 64 to retain overall
3137
    * precision and that 'lg2' is current scaled by an extra 12 bits, so adjust
3138
    * the overall scaling by 6-12.  Round at every step.
3139
    */
3140
   x -= 1U << 24;
3141
3142
   if (x <= 65536U) /* <= '257' */
3143
      lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);
3144
3145
   else
3146
      lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
3147
3148
   /* Safe, because the result can't have more than 20 bits: */
3149
   return (png_int_32)((lg2 + 2048) >> 12);
3150
}
3151
#endif /* 16BIT */
3152
3153
/* The 'exp()' case must invert the above, taking a 20-bit fixed point
3154
 * logarithmic value and returning a 16 or 8-bit number as appropriate.  In
3155
 * each case only the low 16 bits are relevant - the fraction - since the
3156
 * integer bits (the top 4) simply determine a shift.
3157
 *
3158
 * The worst case is the 16-bit distinction between 65535 and 65534. This
3159
 * requires perhaps spurious accuracy in the decoding of the logarithm to
3160
 * distinguish log2(65535/65534.5) - 10^-5 or 17 bits.  There is little chance
3161
 * of getting this accuracy in practice.
3162
 *
3163
 * To deal with this the following exp() function works out the exponent of the
3164
 * fractional part of the logarithm by using an accurate 32-bit value from the
3165
 * top four fractional bits then multiplying in the remaining bits.
3166
 */
3167
static const png_uint_32
3168
png_32bit_exp[16] =
3169
{
3170
   /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
3171
   4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
3172
   3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
3173
   2553802834U, 2445529972U, 2341847524U, 2242560872U
3174
};
3175
3176
/* Adjustment table; provided to explain the numbers in the code below. */
3177
#if 0
3178
for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
3179
   11 44937.64284865548751208448
3180
   10 45180.98734845585101160448
3181
    9 45303.31936980687359311872
3182
    8 45364.65110595323018870784
3183
    7 45395.35850361789624614912
3184
    6 45410.72259715102037508096
3185
    5 45418.40724413220722311168
3186
    4 45422.25021786898173001728
3187
    3 45424.17186732298419044352
3188
    2 45425.13273269940811464704
3189
    1 45425.61317555035558641664
3190
    0 45425.85339951654943850496
3191
#endif
3192
3193
static png_uint_32
3194
png_exp(png_fixed_point x)
3195
{
3196
   if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
3197
   {
3198
      /* Obtain a 4-bit approximation */
3199
      png_uint_32 e = png_32bit_exp[(x >> 12) & 0x0f];
3200
3201
      /* Incorporate the low 12 bits - these decrease the returned value by
3202
       * multiplying by a number less than 1 if the bit is set.  The multiplier
3203
       * is determined by the above table and the shift. Notice that the values
3204
       * converge on 45426 and this is used to allow linear interpolation of the
3205
       * low bits.
3206
       */
3207
      if (x & 0x800)
3208
         e -= (((e >> 16) * 44938U) +  16U) >> 5;
3209
3210
      if (x & 0x400)
3211
         e -= (((e >> 16) * 45181U) +  32U) >> 6;
3212
3213
      if (x & 0x200)
3214
         e -= (((e >> 16) * 45303U) +  64U) >> 7;
3215
3216
      if (x & 0x100)
3217
         e -= (((e >> 16) * 45365U) + 128U) >> 8;
3218
3219
      if (x & 0x080)
3220
         e -= (((e >> 16) * 45395U) + 256U) >> 9;
3221
3222
      if (x & 0x040)
3223
         e -= (((e >> 16) * 45410U) + 512U) >> 10;
3224
3225
      /* And handle the low 6 bits in a single block. */
3226
      e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;
3227
3228
      /* Handle the upper bits of x. */
3229
      e >>= x >> 16;
3230
      return e;
3231
   }
3232
3233
   /* Check for overflow */
3234
   if (x <= 0)
3235
      return png_32bit_exp[0];
3236
3237
   /* Else underflow */
3238
   return 0;
3239
}
3240
3241
static png_byte
3242
png_exp8bit(png_fixed_point lg2)
3243
{
3244
   /* Get a 32-bit value: */
3245
   png_uint_32 x = png_exp(lg2);
3246
3247
   /* Convert the 32-bit value to 0..255 by multiplying by 256-1. Note that the
3248
    * second, rounding, step can't overflow because of the first, subtraction,
3249
    * step.
3250
    */
3251
   x -= x >> 8;
3252
   return (png_byte)(((x + 0x7fffffU) >> 24) & 0xff);
3253
}
3254
3255
#ifdef PNG_16BIT_SUPPORTED
3256
static png_uint_16
3257
png_exp16bit(png_fixed_point lg2)
3258
{
3259
   /* Get a 32-bit value: */
3260
   png_uint_32 x = png_exp(lg2);
3261
3262
   /* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */
3263
   x -= x >> 16;
3264
   return (png_uint_16)((x + 32767U) >> 16);
3265
}
3266
#endif /* 16BIT */
3267
#endif /* FLOATING_ARITHMETIC */
3268
3269
png_byte
3270
png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)
3271
7.68k
{
3272
7.68k
   if (value > 0 && value < 255)
3273
7.62k
   {
3274
7.62k
#     ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
3275
         /* 'value' is unsigned, ANSI-C90 requires the compiler to correctly
3276
          * convert this to a floating point value.  This includes values that
3277
          * would overflow if 'value' were to be converted to 'int'.
3278
          *
3279
          * Apparently GCC, however, does an intermediate conversion to (int)
3280
          * on some (ARM) but not all (x86) platforms, possibly because of
3281
          * hardware FP limitations.  (E.g. if the hardware conversion always
3282
          * assumes the integer register contains a signed value.)  This results
3283
          * in ANSI-C undefined behavior for large values.
3284
          *
3285
          * Other implementations on the same machine might actually be ANSI-C90
3286
          * conformant and therefore compile spurious extra code for the large
3287
          * values.
3288
          *
3289
          * We can be reasonably sure that an unsigned to float conversion
3290
          * won't be faster than an int to float one.  Therefore this code
3291
          * assumes responsibility for the undefined behavior, which it knows
3292
          * can't happen because of the check above.
3293
          *
3294
          * Note the argument to this routine is an (unsigned int) because, on
3295
          * 16-bit platforms, it is assigned a value which might be out of
3296
          * range for an (int); that would result in undefined behavior in the
3297
          * caller if the *argument* ('value') were to be declared (int).
3298
          */
3299
7.62k
         double r = floor(255*pow((int)/*SAFE*/value/255.,gamma_val*.00001)+.5);
3300
7.62k
         return (png_byte)r;
3301
#     else
3302
         png_int_32 lg2 = png_log8bit(value);
3303
         png_fixed_point res;
3304
3305
         if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)
3306
            return png_exp8bit(res);
3307
3308
         /* Overflow. */
3309
         value = 0;
3310
#     endif
3311
7.62k
   }
3312
3313
60
   return (png_byte)(value & 0xff);
3314
7.68k
}
3315
3316
#ifdef PNG_16BIT_SUPPORTED
3317
png_uint_16
3318
png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)
3319
15.8k
{
3320
15.8k
   if (value > 0 && value < 65535)
3321
15.8k
   {
3322
15.8k
# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
3323
      /* The same (unsigned int)->(double) constraints apply here as above,
3324
       * however in this case the (unsigned int) to (int) conversion can
3325
       * overflow on an ANSI-C90 compliant system so the cast needs to ensure
3326
       * that this is not possible.
3327
       */
3328
15.8k
      double r = floor(65535*pow((png_int_32)value/65535.,
3329
15.8k
          gamma_val*.00001)+.5);
3330
15.8k
      return (png_uint_16)r;
3331
# else
3332
      png_int_32 lg2 = png_log16bit(value);
3333
      png_fixed_point res;
3334
3335
      if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)
3336
         return png_exp16bit(res);
3337
3338
      /* Overflow. */
3339
      value = 0;
3340
# endif
3341
15.8k
   }
3342
3343
0
   return (png_uint_16)value;
3344
15.8k
}
3345
#endif /* 16BIT */
3346
3347
/* This does the right thing based on the bit_depth field of the
3348
 * png_struct, interpreting values as 8-bit or 16-bit.  While the result
3349
 * is nominally a 16-bit value if bit depth is 8 then the result is
3350
 * 8-bit (as are the arguments.)
3351
 */
3352
png_uint_16 /* PRIVATE */
3353
png_gamma_correct(png_structrp png_ptr, unsigned int value,
3354
    png_fixed_point gamma_val)
3355
0
{
3356
0
   if (png_ptr->bit_depth == 8)
3357
0
      return png_gamma_8bit_correct(value, gamma_val);
3358
3359
0
#ifdef PNG_16BIT_SUPPORTED
3360
0
   else
3361
0
      return png_gamma_16bit_correct(value, gamma_val);
3362
#else
3363
      /* should not reach this */
3364
      return 0;
3365
#endif /* 16BIT */
3366
0
}
3367
3368
#ifdef PNG_16BIT_SUPPORTED
3369
/* Internal function to build a single 16-bit table - the table consists of
3370
 * 'num' 256 entry subtables, where 'num' is determined by 'shift' - the amount
3371
 * to shift the input values right (or 16-number_of_signifiant_bits).
3372
 *
3373
 * The caller is responsible for ensuring that the table gets cleaned up on
3374
 * png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument
3375
 * should be somewhere that will be cleaned.
3376
 */
3377
static void
3378
png_build_16bit_table(png_structrp png_ptr, png_uint_16pp *ptable,
3379
    unsigned int shift, png_fixed_point gamma_val)
3380
0
{
3381
   /* Various values derived from 'shift': */
3382
0
   unsigned int num = 1U << (8U - shift);
3383
0
#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
3384
   /* CSE the division and work round wacky GCC warnings (see the comments
3385
    * in png_gamma_8bit_correct for where these come from.)
3386
    */
3387
0
   double fmax = 1.0 / (((png_int_32)1 << (16U - shift)) - 1);
3388
0
#endif
3389
0
   unsigned int max = (1U << (16U - shift)) - 1U;
3390
0
   unsigned int max_by_2 = 1U << (15U - shift);
3391
0
   unsigned int i;
3392
3393
0
   png_uint_16pp table = *ptable =
3394
0
       (png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
3395
3396
0
   for (i = 0; i < num; i++)
3397
0
   {
3398
0
      png_uint_16p sub_table = table[i] =
3399
0
          (png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));
3400
3401
      /* The 'threshold' test is repeated here because it can arise for one of
3402
       * the 16-bit tables even if the others don't hit it.
3403
       */
3404
0
      if (png_gamma_significant(gamma_val) != 0)
3405
0
      {
3406
         /* The old code would overflow at the end and this would cause the
3407
          * 'pow' function to return a result >1, resulting in an
3408
          * arithmetic error.  This code follows the spec exactly; ig is
3409
          * the recovered input sample, it always has 8-16 bits.
3410
          *
3411
          * We want input * 65535/max, rounded, the arithmetic fits in 32
3412
          * bits (unsigned) so long as max <= 32767.
3413
          */
3414
0
         unsigned int j;
3415
0
         for (j = 0; j < 256; j++)
3416
0
         {
3417
0
            png_uint_32 ig = (j << (8-shift)) + i;
3418
0
#           ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
3419
               /* Inline the 'max' scaling operation: */
3420
               /* See png_gamma_8bit_correct for why the cast to (int) is
3421
                * required here.
3422
                */
3423
0
               double d = floor(65535.*pow(ig*fmax, gamma_val*.00001)+.5);
3424
0
               sub_table[j] = (png_uint_16)d;
3425
#           else
3426
               if (shift != 0)
3427
                  ig = (ig * 65535U + max_by_2)/max;
3428
3429
               sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);
3430
#           endif
3431
0
         }
3432
0
      }
3433
0
      else
3434
0
      {
3435
         /* We must still build a table, but do it the fast way. */
3436
0
         unsigned int j;
3437
3438
0
         for (j = 0; j < 256; j++)
3439
0
         {
3440
0
            png_uint_32 ig = (j << (8-shift)) + i;
3441
3442
0
            if (shift != 0)
3443
0
               ig = (ig * 65535U + max_by_2)/max;
3444
3445
0
            sub_table[j] = (png_uint_16)ig;
3446
0
         }
3447
0
      }
3448
0
   }
3449
0
}
3450
3451
/* NOTE: this function expects the *inverse* of the overall gamma transformation
3452
 * required.
3453
 */
3454
static void
3455
png_build_16to8_table(png_structrp png_ptr, png_uint_16pp *ptable,
3456
    unsigned int shift, png_fixed_point gamma_val)
3457
62
{
3458
62
   unsigned int num = 1U << (8U - shift);
3459
62
   unsigned int max = (1U << (16U - shift))-1U;
3460
62
   unsigned int i;
3461
62
   png_uint_32 last;
3462
3463
62
   png_uint_16pp table = *ptable =
3464
62
       (png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
3465
3466
   /* 'num' is the number of tables and also the number of low bits of low
3467
    * bits of the input 16-bit value used to select a table.  Each table is
3468
    * itself indexed by the high 8 bits of the value.
3469
    */
3470
558
   for (i = 0; i < num; i++)
3471
496
      table[i] = (png_uint_16p)png_malloc(png_ptr,
3472
496
          256 * (sizeof (png_uint_16)));
3473
3474
   /* 'gamma_val' is set to the reciprocal of the value calculated above, so
3475
    * pow(out,g) is an *input* value.  'last' is the last input value set.
3476
    *
3477
    * In the loop 'i' is used to find output values.  Since the output is
3478
    * 8-bit there are only 256 possible values.  The tables are set up to
3479
    * select the closest possible output value for each input by finding
3480
    * the input value at the boundary between each pair of output values
3481
    * and filling the table up to that boundary with the lower output
3482
    * value.
3483
    *
3484
    * The boundary values are 0.5,1.5..253.5,254.5.  Since these are 9-bit
3485
    * values the code below uses a 16-bit value in i; the values start at
3486
    * 128.5 (for 0.5) and step by 257, for a total of 254 values (the last
3487
    * entries are filled with 255).  Start i at 128 and fill all 'last'
3488
    * table entries <= 'max'
3489
    */
3490
62
   last = 0;
3491
15.8k
   for (i = 0; i < 255; ++i) /* 8-bit output value */
3492
15.8k
   {
3493
      /* Find the corresponding maximum input value */
3494
15.8k
      png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */
3495
3496
      /* Find the boundary value in 16 bits: */
3497
15.8k
      png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);
3498
3499
      /* Adjust (round) to (16-shift) bits: */
3500
15.8k
      bound = (bound * max + 32768U)/65535U + 1U;
3501
3502
142k
      while (last < bound)
3503
126k
      {
3504
126k
         table[last & (0xffU >> shift)][last >> (8U - shift)] = out;
3505
126k
         last++;
3506
126k
      }
3507
15.8k
   }
3508
3509
   /* And fill in the final entries. */
3510
599
   while (last < (num << 8))
3511
537
   {
3512
537
      table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;
3513
537
      last++;
3514
537
   }
3515
62
}
3516
#endif /* 16BIT */
3517
3518
/* Build a single 8-bit table: same as the 16-bit case but much simpler (and
3519
 * typically much faster).  Note that libpng currently does no sBIT processing
3520
 * (apparently contrary to the spec) so a 256-entry table is always generated.
3521
 */
3522
static void
3523
png_build_8bit_table(png_structrp png_ptr, png_bytepp ptable,
3524
    png_fixed_point gamma_val)
3525
30
{
3526
30
   unsigned int i;
3527
30
   png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);
3528
3529
30
   if (png_gamma_significant(gamma_val) != 0)
3530
7.71k
      for (i=0; i<256; i++)
3531
7.68k
         table[i] = png_gamma_8bit_correct(i, gamma_val);
3532
3533
0
   else
3534
0
      for (i=0; i<256; ++i)
3535
0
         table[i] = (png_byte)(i & 0xff);
3536
30
}
3537
3538
/* Used from png_read_destroy and below to release the memory used by the gamma
3539
 * tables.
3540
 */
3541
void /* PRIVATE */
3542
png_destroy_gamma_table(png_structrp png_ptr)
3543
8.09k
{
3544
8.09k
   png_free(png_ptr, png_ptr->gamma_table);
3545
8.09k
   png_ptr->gamma_table = NULL;
3546
3547
8.09k
#ifdef PNG_16BIT_SUPPORTED
3548
8.09k
   if (png_ptr->gamma_16_table != NULL)
3549
62
   {
3550
62
      int i;
3551
62
      int istop = (1 << (8 - png_ptr->gamma_shift));
3552
558
      for (i = 0; i < istop; i++)
3553
496
      {
3554
496
         png_free(png_ptr, png_ptr->gamma_16_table[i]);
3555
496
      }
3556
62
   png_free(png_ptr, png_ptr->gamma_16_table);
3557
62
   png_ptr->gamma_16_table = NULL;
3558
62
   }
3559
8.09k
#endif /* 16BIT */
3560
3561
8.09k
#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
3562
8.09k
   defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
3563
8.09k
   defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
3564
8.09k
   png_free(png_ptr, png_ptr->gamma_from_1);
3565
8.09k
   png_ptr->gamma_from_1 = NULL;
3566
8.09k
   png_free(png_ptr, png_ptr->gamma_to_1);
3567
8.09k
   png_ptr->gamma_to_1 = NULL;
3568
3569
8.09k
#ifdef PNG_16BIT_SUPPORTED
3570
8.09k
   if (png_ptr->gamma_16_from_1 != NULL)
3571
0
   {
3572
0
      int i;
3573
0
      int istop = (1 << (8 - png_ptr->gamma_shift));
3574
0
      for (i = 0; i < istop; i++)
3575
0
      {
3576
0
         png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
3577
0
      }
3578
0
   png_free(png_ptr, png_ptr->gamma_16_from_1);
3579
0
   png_ptr->gamma_16_from_1 = NULL;
3580
0
   }
3581
8.09k
   if (png_ptr->gamma_16_to_1 != NULL)
3582
0
   {
3583
0
      int i;
3584
0
      int istop = (1 << (8 - png_ptr->gamma_shift));
3585
0
      for (i = 0; i < istop; i++)
3586
0
      {
3587
0
         png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
3588
0
      }
3589
0
   png_free(png_ptr, png_ptr->gamma_16_to_1);
3590
0
   png_ptr->gamma_16_to_1 = NULL;
3591
0
   }
3592
8.09k
#endif /* 16BIT */
3593
8.09k
#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
3594
8.09k
}
3595
3596
/* We build the 8- or 16-bit gamma tables here.  Note that for 16-bit
3597
 * tables, we don't make a full table if we are reducing to 8-bit in
3598
 * the future.  Note also how the gamma_16 tables are segmented so that
3599
 * we don't need to allocate > 64K chunks for a full 16-bit table.
3600
 *
3601
 * TODO: move this to pngrtran.c and make it static.  Better yet create
3602
 * pngcolor.c and put all the PNG_COLORSPACE stuff in there.
3603
 */
3604
#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
3605
   defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
3606
   defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
3607
#  define GAMMA_TRANSFORMS 1 /* #ifdef CSE */
3608
#else
3609
#  define GAMMA_TRANSFORMS 0
3610
#endif
3611
3612
void /* PRIVATE */
3613
png_build_gamma_table(png_structrp png_ptr, int bit_depth)
3614
92
{
3615
92
   png_fixed_point file_gamma, screen_gamma;
3616
92
   png_fixed_point correction;
3617
92
#  if GAMMA_TRANSFORMS
3618
92
      png_fixed_point file_to_linear, linear_to_screen;
3619
92
#  endif
3620
3621
92
   png_debug(1, "in png_build_gamma_table");
3622
3623
   /* Remove any existing table; this copes with multiple calls to
3624
    * png_read_update_info. The warning is because building the gamma tables
3625
    * multiple times is a performance hit - it's harmless but the ability to
3626
    * call png_read_update_info() multiple times is new in 1.5.6 so it seems
3627
    * sensible to warn if the app introduces such a hit.
3628
    */
3629
92
   if (png_ptr->gamma_table != NULL || png_ptr->gamma_16_table != NULL)
3630
0
   {
3631
0
      png_warning(png_ptr, "gamma table being rebuilt");
3632
0
      png_destroy_gamma_table(png_ptr);
3633
0
   }
3634
3635
   /* The following fields are set, finally, in png_init_read_transformations.
3636
    * If file_gamma is 0 (unset) nothing can be done otherwise if screen_gamma
3637
    * is 0 (unset) there is no gamma correction but to/from linear is possible.
3638
    */
3639
92
   file_gamma = png_ptr->file_gamma;
3640
92
   screen_gamma = png_ptr->screen_gamma;
3641
92
#  if GAMMA_TRANSFORMS
3642
92
      file_to_linear = png_reciprocal(file_gamma);
3643
92
#  endif
3644
3645
92
   if (screen_gamma > 0)
3646
92
   {
3647
92
#     if GAMMA_TRANSFORMS
3648
92
         linear_to_screen = png_reciprocal(screen_gamma);
3649
92
#     endif
3650
92
      correction = png_reciprocal2(screen_gamma, file_gamma);
3651
92
   }
3652
0
   else /* screen gamma unknown */
3653
0
   {
3654
0
#     if GAMMA_TRANSFORMS
3655
0
         linear_to_screen = file_gamma;
3656
0
#     endif
3657
0
      correction = PNG_FP_1;
3658
0
   }
3659
3660
92
   if (bit_depth <= 8)
3661
30
   {
3662
30
      png_build_8bit_table(png_ptr, &png_ptr->gamma_table, correction);
3663
3664
30
#if GAMMA_TRANSFORMS
3665
30
      if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)
3666
0
      {
3667
0
         png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1, file_to_linear);
3668
3669
0
         png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,
3670
0
            linear_to_screen);
3671
0
      }
3672
30
#endif /* GAMMA_TRANSFORMS */
3673
30
   }
3674
62
#ifdef PNG_16BIT_SUPPORTED
3675
62
   else
3676
62
   {
3677
62
      png_byte shift, sig_bit;
3678
3679
62
      if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
3680
25
      {
3681
25
         sig_bit = png_ptr->sig_bit.red;
3682
3683
25
         if (png_ptr->sig_bit.green > sig_bit)
3684
0
            sig_bit = png_ptr->sig_bit.green;
3685
3686
25
         if (png_ptr->sig_bit.blue > sig_bit)
3687
0
            sig_bit = png_ptr->sig_bit.blue;
3688
25
      }
3689
37
      else
3690
37
         sig_bit = png_ptr->sig_bit.gray;
3691
3692
      /* 16-bit gamma code uses this equation:
3693
       *
3694
       *   ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]
3695
       *
3696
       * Where 'iv' is the input color value and 'ov' is the output value -
3697
       * pow(iv, gamma).
3698
       *
3699
       * Thus the gamma table consists of up to 256 256-entry tables.  The table
3700
       * is selected by the (8-gamma_shift) most significant of the low 8 bits
3701
       * of the color value then indexed by the upper 8 bits:
3702
       *
3703
       *   table[low bits][high 8 bits]
3704
       *
3705
       * So the table 'n' corresponds to all those 'iv' of:
3706
       *
3707
       *   <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>
3708
       *
3709
       */
3710
62
      if (sig_bit > 0 && sig_bit < 16U)
3711
         /* shift == insignificant bits */
3712
0
         shift = (png_byte)((16U - sig_bit) & 0xff);
3713
3714
62
      else
3715
62
         shift = 0; /* keep all 16 bits */
3716
3717
62
      if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)
3718
62
      {
3719
         /* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively
3720
          * the significant bits in the *input* when the output will
3721
          * eventually be 8 bits.  By default it is 11.
3722
          */
3723
62
         if (shift < (16U - PNG_MAX_GAMMA_8))
3724
62
            shift = (16U - PNG_MAX_GAMMA_8);
3725
62
      }
3726
3727
62
      if (shift > 8U)
3728
0
         shift = 8U; /* Guarantees at least one table! */
3729
3730
62
      png_ptr->gamma_shift = shift;
3731
3732
      /* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now
3733
       * PNG_COMPOSE).  This effectively smashed the background calculation for
3734
       * 16-bit output because the 8-bit table assumes the result will be
3735
       * reduced to 8 bits.
3736
       */
3737
62
      if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)
3738
62
         png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,
3739
62
            png_reciprocal(correction));
3740
0
      else
3741
0
         png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,
3742
0
            correction);
3743
3744
62
#  if GAMMA_TRANSFORMS
3745
62
      if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)
3746
0
      {
3747
0
         png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,
3748
0
            file_to_linear);
3749
3750
         /* Notice that the '16 from 1' table should be full precision, however
3751
          * the lookup on this table still uses gamma_shift, so it can't be.
3752
          * TODO: fix this.
3753
          */
3754
0
         png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
3755
0
            linear_to_screen);
3756
0
      }
3757
62
#endif /* GAMMA_TRANSFORMS */
3758
62
   }
3759
92
#endif /* 16BIT */
3760
92
}
3761
#endif /* READ_GAMMA */
3762
3763
/* HARDWARE OR SOFTWARE OPTION SUPPORT */
3764
#ifdef PNG_SET_OPTION_SUPPORTED
3765
int PNGAPI
3766
png_set_option(png_structrp png_ptr, int option, int onoff)
3767
0
{
3768
0
   if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
3769
0
      (option & 1) == 0)
3770
0
   {
3771
0
      png_uint_32 mask = 3U << option;
3772
0
      png_uint_32 setting = (2U + (onoff != 0)) << option;
3773
0
      png_uint_32 current = png_ptr->options;
3774
3775
0
      png_ptr->options = (png_uint_32)((current & ~mask) | setting);
3776
3777
0
      return (int)(current & mask) >> option;
3778
0
   }
3779
3780
0
   return PNG_OPTION_INVALID;
3781
0
}
3782
#endif
3783
3784
/* sRGB support */
3785
#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
3786
   defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
3787
/* sRGB conversion tables; these are machine generated with the code in
3788
 * contrib/tools/makesRGB.c.  The actual sRGB transfer curve defined in the
3789
 * specification (see the article at https://en.wikipedia.org/wiki/SRGB)
3790
 * is used, not the gamma=1/2.2 approximation use elsewhere in libpng.
3791
 * The sRGB to linear table is exact (to the nearest 16-bit linear fraction).
3792
 * The inverse (linear to sRGB) table has accuracies as follows:
3793
 *
3794
 * For all possible (255*65535+1) input values:
3795
 *
3796
 *    error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact
3797
 *
3798
 * For the input values corresponding to the 65536 16-bit values:
3799
 *
3800
 *    error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact
3801
 *
3802
 * In all cases the inexact readings are only off by one.
3803
 */
3804
3805
#ifdef PNG_SIMPLIFIED_READ_SUPPORTED
3806
/* The convert-to-sRGB table is only currently required for read. */
3807
const png_uint_16 png_sRGB_table[256] =
3808
{
3809
   0,20,40,60,80,99,119,139,
3810
   159,179,199,219,241,264,288,313,
3811
   340,367,396,427,458,491,526,562,
3812
   599,637,677,718,761,805,851,898,
3813
   947,997,1048,1101,1156,1212,1270,1330,
3814
   1391,1453,1517,1583,1651,1720,1790,1863,
3815
   1937,2013,2090,2170,2250,2333,2418,2504,
3816
   2592,2681,2773,2866,2961,3058,3157,3258,
3817
   3360,3464,3570,3678,3788,3900,4014,4129,
3818
   4247,4366,4488,4611,4736,4864,4993,5124,
3819
   5257,5392,5530,5669,5810,5953,6099,6246,
3820
   6395,6547,6700,6856,7014,7174,7335,7500,
3821
   7666,7834,8004,8177,8352,8528,8708,8889,
3822
   9072,9258,9445,9635,9828,10022,10219,10417,
3823
   10619,10822,11028,11235,11446,11658,11873,12090,
3824
   12309,12530,12754,12980,13209,13440,13673,13909,
3825
   14146,14387,14629,14874,15122,15371,15623,15878,
3826
   16135,16394,16656,16920,17187,17456,17727,18001,
3827
   18277,18556,18837,19121,19407,19696,19987,20281,
3828
   20577,20876,21177,21481,21787,22096,22407,22721,
3829
   23038,23357,23678,24002,24329,24658,24990,25325,
3830
   25662,26001,26344,26688,27036,27386,27739,28094,
3831
   28452,28813,29176,29542,29911,30282,30656,31033,
3832
   31412,31794,32179,32567,32957,33350,33745,34143,
3833
   34544,34948,35355,35764,36176,36591,37008,37429,
3834
   37852,38278,38706,39138,39572,40009,40449,40891,
3835
   41337,41785,42236,42690,43147,43606,44069,44534,
3836
   45002,45473,45947,46423,46903,47385,47871,48359,
3837
   48850,49344,49841,50341,50844,51349,51858,52369,
3838
   52884,53401,53921,54445,54971,55500,56032,56567,
3839
   57105,57646,58190,58737,59287,59840,60396,60955,
3840
   61517,62082,62650,63221,63795,64372,64952,65535
3841
};
3842
#endif /* SIMPLIFIED_READ */
3843
3844
/* The base/delta tables are required for both read and write (but currently
3845
 * only the simplified versions.)
3846
 */
3847
const png_uint_16 png_sRGB_base[512] =
3848
{
3849
   128,1782,3383,4644,5675,6564,7357,8074,
3850
   8732,9346,9921,10463,10977,11466,11935,12384,
3851
   12816,13233,13634,14024,14402,14769,15125,15473,
3852
   15812,16142,16466,16781,17090,17393,17690,17981,
3853
   18266,18546,18822,19093,19359,19621,19879,20133,
3854
   20383,20630,20873,21113,21349,21583,21813,22041,
3855
   22265,22487,22707,22923,23138,23350,23559,23767,
3856
   23972,24175,24376,24575,24772,24967,25160,25352,
3857
   25542,25730,25916,26101,26284,26465,26645,26823,
3858
   27000,27176,27350,27523,27695,27865,28034,28201,
3859
   28368,28533,28697,28860,29021,29182,29341,29500,
3860
   29657,29813,29969,30123,30276,30429,30580,30730,
3861
   30880,31028,31176,31323,31469,31614,31758,31902,
3862
   32045,32186,32327,32468,32607,32746,32884,33021,
3863
   33158,33294,33429,33564,33697,33831,33963,34095,
3864
   34226,34357,34486,34616,34744,34873,35000,35127,
3865
   35253,35379,35504,35629,35753,35876,35999,36122,
3866
   36244,36365,36486,36606,36726,36845,36964,37083,
3867
   37201,37318,37435,37551,37668,37783,37898,38013,
3868
   38127,38241,38354,38467,38580,38692,38803,38915,
3869
   39026,39136,39246,39356,39465,39574,39682,39790,
3870
   39898,40005,40112,40219,40325,40431,40537,40642,
3871
   40747,40851,40955,41059,41163,41266,41369,41471,
3872
   41573,41675,41777,41878,41979,42079,42179,42279,
3873
   42379,42478,42577,42676,42775,42873,42971,43068,
3874
   43165,43262,43359,43456,43552,43648,43743,43839,
3875
   43934,44028,44123,44217,44311,44405,44499,44592,
3876
   44685,44778,44870,44962,45054,45146,45238,45329,
3877
   45420,45511,45601,45692,45782,45872,45961,46051,
3878
   46140,46229,46318,46406,46494,46583,46670,46758,
3879
   46846,46933,47020,47107,47193,47280,47366,47452,
3880
   47538,47623,47709,47794,47879,47964,48048,48133,
3881
   48217,48301,48385,48468,48552,48635,48718,48801,
3882
   48884,48966,49048,49131,49213,49294,49376,49458,
3883
   49539,49620,49701,49782,49862,49943,50023,50103,
3884
   50183,50263,50342,50422,50501,50580,50659,50738,
3885
   50816,50895,50973,51051,51129,51207,51285,51362,
3886
   51439,51517,51594,51671,51747,51824,51900,51977,
3887
   52053,52129,52205,52280,52356,52432,52507,52582,
3888
   52657,52732,52807,52881,52956,53030,53104,53178,
3889
   53252,53326,53400,53473,53546,53620,53693,53766,
3890
   53839,53911,53984,54056,54129,54201,54273,54345,
3891
   54417,54489,54560,54632,54703,54774,54845,54916,
3892
   54987,55058,55129,55199,55269,55340,55410,55480,
3893
   55550,55620,55689,55759,55828,55898,55967,56036,
3894
   56105,56174,56243,56311,56380,56448,56517,56585,
3895
   56653,56721,56789,56857,56924,56992,57059,57127,
3896
   57194,57261,57328,57395,57462,57529,57595,57662,
3897
   57728,57795,57861,57927,57993,58059,58125,58191,
3898
   58256,58322,58387,58453,58518,58583,58648,58713,
3899
   58778,58843,58908,58972,59037,59101,59165,59230,
3900
   59294,59358,59422,59486,59549,59613,59677,59740,
3901
   59804,59867,59930,59993,60056,60119,60182,60245,
3902
   60308,60370,60433,60495,60558,60620,60682,60744,
3903
   60806,60868,60930,60992,61054,61115,61177,61238,
3904
   61300,61361,61422,61483,61544,61605,61666,61727,
3905
   61788,61848,61909,61969,62030,62090,62150,62211,
3906
   62271,62331,62391,62450,62510,62570,62630,62689,
3907
   62749,62808,62867,62927,62986,63045,63104,63163,
3908
   63222,63281,63340,63398,63457,63515,63574,63632,
3909
   63691,63749,63807,63865,63923,63981,64039,64097,
3910
   64155,64212,64270,64328,64385,64443,64500,64557,
3911
   64614,64672,64729,64786,64843,64900,64956,65013,
3912
   65070,65126,65183,65239,65296,65352,65409,65465
3913
};
3914
3915
const png_byte png_sRGB_delta[512] =
3916
{
3917
   207,201,158,129,113,100,90,82,77,72,68,64,61,59,56,54,
3918
   52,50,49,47,46,45,43,42,41,40,39,39,38,37,36,36,
3919
   35,34,34,33,33,32,32,31,31,30,30,30,29,29,28,28,
3920
   28,27,27,27,27,26,26,26,25,25,25,25,24,24,24,24,
3921
   23,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,
3922
   21,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,
3923
   19,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,
3924
   17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
3925
   16,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,
3926
   15,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,
3927
   14,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,
3928
   13,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,
3929
   12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
3930
   12,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,
3931
   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
3932
   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
3933
   11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
3934
   10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
3935
   10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
3936
   10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
3937
   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
3938
   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
3939
   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
3940
   9,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
3941
   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
3942
   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
3943
   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
3944
   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
3945
   8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,
3946
   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
3947
   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
3948
   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
3949
};
3950
#endif /* SIMPLIFIED READ/WRITE sRGB support */
3951
3952
/* SIMPLIFIED READ/WRITE SUPPORT */
3953
#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
3954
   defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
3955
static int
3956
png_image_free_function(png_voidp argument)
3957
863
{
3958
863
   png_imagep image = png_voidcast(png_imagep, argument);
3959
863
   png_controlp cp = image->opaque;
3960
863
   png_control c;
3961
3962
   /* Double check that we have a png_ptr - it should be impossible to get here
3963
    * without one.
3964
    */
3965
863
   if (cp->png_ptr == NULL)
3966
0
      return 0;
3967
3968
   /* First free any data held in the control structure. */
3969
#  ifdef PNG_STDIO_SUPPORTED
3970
      if (cp->owned_file != 0)
3971
      {
3972
         FILE *fp = png_voidcast(FILE *, cp->png_ptr->io_ptr);
3973
         cp->owned_file = 0;
3974
3975
         /* Ignore errors here. */
3976
         if (fp != NULL)
3977
         {
3978
            cp->png_ptr->io_ptr = NULL;
3979
            (void)fclose(fp);
3980
         }
3981
      }
3982
#  endif
3983
3984
   /* Copy the control structure so that the original, allocated, version can be
3985
    * safely freed.  Notice that a png_error here stops the remainder of the
3986
    * cleanup, but this is probably fine because that would indicate bad memory
3987
    * problems anyway.
3988
    */
3989
863
   c = *cp;
3990
863
   image->opaque = &c;
3991
863
   png_free(c.png_ptr, cp);
3992
3993
   /* Then the structures, calling the correct API. */
3994
863
   if (c.for_write != 0)
3995
0
   {
3996
#     ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
3997
         png_destroy_write_struct(&c.png_ptr, &c.info_ptr);
3998
#     else
3999
0
         png_error(c.png_ptr, "simplified write not supported");
4000
0
#     endif
4001
0
   }
4002
863
   else
4003
863
   {
4004
863
#     ifdef PNG_SIMPLIFIED_READ_SUPPORTED
4005
863
         png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL);
4006
#     else
4007
         png_error(c.png_ptr, "simplified read not supported");
4008
#     endif
4009
863
   }
4010
4011
   /* Success. */
4012
863
   return 1;
4013
863
}
4014
4015
void PNGAPI
4016
png_image_free(png_imagep image)
4017
1.54k
{
4018
   /* Safely call the real function, but only if doing so is safe at this point
4019
    * (if not inside an error handling context).  Otherwise assume
4020
    * png_safe_execute will call this API after the return.
4021
    */
4022
1.54k
   if (image != NULL && image->opaque != NULL &&
4023
863
      image->opaque->error_buf == NULL)
4024
863
   {
4025
863
      png_image_free_function(image);
4026
863
      image->opaque = NULL;
4027
863
   }
4028
1.54k
}
4029
4030
int /* PRIVATE */
4031
png_image_error(png_imagep image, png_const_charp error_message)
4032
0
{
4033
   /* Utility to log an error. */
4034
0
   png_safecat(image->message, (sizeof image->message), 0, error_message);
4035
0
   image->warning_or_error |= PNG_IMAGE_ERROR;
4036
0
   png_image_free(image);
4037
0
   return 0;
4038
0
}
4039
4040
#endif /* SIMPLIFIED READ/WRITE */
4041
#endif /* READ || WRITE */