Coverage Report

Created: 2026-04-23 06:52

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