Coverage Report

Created: 2025-09-29 06:50

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