/
pngvalid.c
9835 lines (8344 loc) · 301 KB
/
pngvalid.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* pngvalid.c - validate libpng by constructing then reading png files.
*
* Last changed in libpng 1.5.8 [February 1, 2012]
* Copyright (c) 2012 Glenn Randers-Pehrson
* Written by John Cunningham Bowler
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
* NOTES:
* This is a C program that is intended to be linked against libpng. It
* generates bitmaps internally, stores them as PNG files (using the
* sequential write code) then reads them back (using the sequential
* read code) and validates that the result has the correct data.
*
* The program can be modified and extended to test the correctness of
* transformations performed by libpng.
*/
#define _POSIX_SOURCE 1
#define _ISOC99_SOURCE 1 /* For floating point */
#define _GNU_SOURCE 1 /* For the floating point exception extension */
#include <signal.h>
#ifdef HAVE_FEENABLEEXCEPT
# include <fenv.h>
#endif
/* Define the following to use this test against your installed libpng, rather
* than the one being built here:
*/
#ifdef PNG_FREESTANDING_TESTS
# include <png.h>
#else
# include "../../png.h"
#endif
#if PNG_LIBPNG_VER < 10500
/* This deliberately lacks the PNG_CONST. */
typedef png_byte *png_const_bytep;
/* This is copied from 1.5.1 png.h: */
#define PNG_INTERLACE_ADAM7_PASSES 7
#define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
#define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
#define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
-1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
#define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
-1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
(((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
#define PNG_COL_FROM_PASS_COL(xIn, pass) \
(((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
#define PNG_PASS_MASK(pass,off) ( \
((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
#define PNG_COL_IN_INTERLACE_PASS(x, pass) \
((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
/* These are needed too for the default build: */
#define PNG_WRITE_16BIT_SUPPORTED
#define PNG_READ_16BIT_SUPPORTED
/* This comes from pnglibconf.h afer 1.5: */
#define PNG_FP_1 100000
#define PNG_GAMMA_THRESHOLD_FIXED\
((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
#endif
#include "zlib.h" /* For crc32 */
#include <float.h> /* For floating point constants */
#include <stdlib.h> /* For malloc */
#include <string.h> /* For memcpy, memset */
#include <math.h> /* For floor */
/* Unused formal parameter errors are removed using the following macro which is
* expected to have no bad effects on performance.
*/
#ifndef UNUSED
# if defined(__GNUC__) || defined(_MSC_VER)
# define UNUSED(param) (void)param;
# else
# define UNUSED(param)
# endif
#endif
/***************************** EXCEPTION HANDLING *****************************/
#include "../visupng/cexcept.h"
#ifdef __cplusplus
# define this not_the_cpp_this
# define new not_the_cpp_new
# define voidcast(type, value) static_cast<type>(value)
#else
# define voidcast(type, value) (value)
#endif /* __cplusplus */
struct png_store;
define_exception_type(struct png_store*);
/* The following are macros to reduce typing everywhere where the well known
* name 'the_exception_context' must be defined.
*/
#define anon_context(ps) struct exception_context *the_exception_context = \
&(ps)->exception_context
#define context(ps,fault) anon_context(ps); png_store *fault
/******************************* UTILITIES ************************************/
/* Error handling is particularly problematic in production code - error
* handlers often themselves have bugs which lead to programs that detect
* minor errors crashing. The following functions deal with one very
* common class of errors in error handlers - attempting to format error or
* warning messages into buffers that are too small.
*/
static size_t safecat(char *buffer, size_t bufsize, size_t pos,
PNG_CONST char *cat)
{
while (pos < bufsize && cat != NULL && *cat != 0)
buffer[pos++] = *cat++;
if (pos >= bufsize)
pos = bufsize-1;
buffer[pos] = 0;
return pos;
}
static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
{
char number[64];
sprintf(number, "%d", n);
return safecat(buffer, bufsize, pos, number);
}
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
int precision)
{
char number[64];
sprintf(number, "%.*f", precision, d);
return safecat(buffer, bufsize, pos, number);
}
#endif
static PNG_CONST char invalid[] = "invalid";
static PNG_CONST char sep[] = ": ";
static PNG_CONST char *colour_types[8] =
{
"grayscale", invalid, "truecolour", "indexed-colour",
"grayscale with alpha", invalid, "truecolour with alpha", invalid
};
/* Convert a double precision value to fixed point. */
static png_fixed_point
fix(double d)
{
d = floor(d * PNG_FP_1 + .5);
return (png_fixed_point)d;
}
/* Generate random bytes. This uses a boring repeatable algorithm and it
* is implemented here so that it gives the same set of numbers on every
* architecture. It's a linear congruential generator (Knuth or Sedgewick
* "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
* Hill, "The Art of Electronics".
*/
static void
make_random_bytes(png_uint_32* seed, void* pv, size_t size)
{
png_uint_32 u0 = seed[0], u1 = seed[1];
png_bytep bytes = voidcast(png_bytep, pv);
/* There are thirty three bits, the next bit in the sequence is bit-33 XOR
* bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
*/
size_t i;
for (i=0; i<size; ++i)
{
/* First generate 8 new bits then shift them in at the end. */
png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
u1 <<= 8;
u1 |= u0 >> 24;
u0 <<= 8;
u0 |= u;
*bytes++ = (png_byte)u;
}
seed[0] = u0;
seed[1] = u1;
}
static void
make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
{
make_random_bytes(seed, bytes, 4);
}
static void
randomize(void *pv, size_t size)
{
static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
make_random_bytes(random_seed, pv, size);
}
#define RANDOMIZE(this) randomize(&(this), sizeof (this))
static unsigned int
random_mod(unsigned int max)
{
unsigned int x;
RANDOMIZE(x);
return x % max; /* 0 .. max-1 */
}
static int
random_choice(void)
{
unsigned char x;
RANDOMIZE(x);
return x & 1;
}
/* A numeric ID based on PNG file characteristics. The 'do_interlace' field
* simply records whether pngvalid did the interlace itself or whether it
* was done by libpng. Width and height must be less than 256. 'palette' is an
* index of the palette to use for formats with a palette (0 otherwise.)
*/
#define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
(((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
#define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
#define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
#define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
#define INTERLACE_FROM_ID(id) ((int)(((id) >> 13) & 0x3))
#define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
#define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
#define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
/* Utility to construct a standard name for a standard image. */
static size_t
standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
int bit_depth, unsigned int npalette, int interlace_type,
png_uint_32 w, png_uint_32 h, int do_interlace)
{
pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
if (npalette > 0)
{
pos = safecat(buffer, bufsize, pos, "[");
pos = safecatn(buffer, bufsize, pos, npalette);
pos = safecat(buffer, bufsize, pos, "]");
}
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, bit_depth);
pos = safecat(buffer, bufsize, pos, " bit");
if (interlace_type != PNG_INTERLACE_NONE)
{
pos = safecat(buffer, bufsize, pos, " interlaced");
if (do_interlace)
pos = safecat(buffer, bufsize, pos, "(pngvalid)");
else
pos = safecat(buffer, bufsize, pos, "(libpng)");
}
if (w > 0 || h > 0)
{
pos = safecat(buffer, bufsize, pos, " ");
pos = safecatn(buffer, bufsize, pos, w);
pos = safecat(buffer, bufsize, pos, "x");
pos = safecatn(buffer, bufsize, pos, h);
}
return pos;
}
static size_t
standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
{
return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
}
/* Convenience API and defines to list valid formats. Note that 16 bit read and
* write support is required to do 16 bit read tests (we must be able to make a
* 16 bit image to test!)
*/
#ifdef PNG_WRITE_16BIT_SUPPORTED
# define WRITE_BDHI 4
# ifdef PNG_READ_16BIT_SUPPORTED
# define READ_BDHI 4
# define DO_16BIT
# endif
#else
# define WRITE_BDHI 3
#endif
#ifndef DO_16BIT
# define READ_BDHI 3
#endif
/* The following defines the number of different palettes to generate for
* each log bit depth of a colour type 3 standard image.
*/
#define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
static int
next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number)
{
if (*bit_depth == 0)
{
*colour_type = 0, *bit_depth = 1, *palette_number = 0;
return 1;
}
if (*colour_type == 3)
{
/* Add multiple palettes for colour type 3. */
if (++*palette_number < PALETTE_COUNT(*bit_depth))
return 1;
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
# ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
# endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
static unsigned int
sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
png_uint_32 x, unsigned int sample_index)
{
png_uint_32 bit_index, result;
/* Find a sample index for the desired sample: */
x *= bit_depth;
bit_index = x;
if ((colour_type & 1) == 0) /* !palette */
{
if (colour_type & 2)
bit_index *= 3;
if (colour_type & 4)
bit_index += x; /* Alpha channel */
/* Multiple channels; select one: */
if (colour_type & (2+4))
bit_index += sample_index * bit_depth;
}
/* Return the sample from the row as an integer. */
row += bit_index >> 3;
result = *row;
if (bit_depth == 8)
return result;
else if (bit_depth > 8)
return (result << 8) + *++row;
/* Less than 8 bits per sample. */
bit_index &= 7;
return (result >> (8-bit_index-bit_depth)) & ((1U<<bit_depth)-1);
}
#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
/* Copy a single pixel, of a given size, from one buffer to another -
* while this is basically bit addressed there is an implicit assumption
* that pixels 8 or more bits in size are byte aligned and that pixels
* do not otherwise cross byte boundaries. (This is, so far as I know,
* universally true in bitmap computer graphics. [JCB 20101212])
*
* NOTE: The to and from buffers may be the same.
*/
static void
pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize)
{
/* Assume we can multiply by 'size' without overflow because we are
* just working in a single buffer.
*/
toIndex *= pixelSize;
fromIndex *= pixelSize;
if (pixelSize < 8) /* Sub-byte */
{
/* Mask to select the location of the copied pixel: */
unsigned int destMask = ((1U<<pixelSize)-1) << (8-pixelSize-(toIndex&7));
/* The following read the entire pixels and clears the extra: */
unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
unsigned int sourceByte = fromBuffer[fromIndex >> 3];
/* Don't rely on << or >> supporting '0' here, just in case: */
fromIndex &= 7;
if (fromIndex > 0) sourceByte <<= fromIndex;
if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
}
else /* One or more bytes */
memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
}
/* Copy a complete row of pixels, taking into account potential partial
* bytes at the end.
*/
static void
row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth)
{
memcpy(toBuffer, fromBuffer, bitWidth >> 3);
if ((bitWidth & 7) != 0)
{
unsigned int mask;
toBuffer += bitWidth >> 3;
fromBuffer += bitWidth >> 3;
/* The remaining bits are in the top of the byte, the mask is the bits to
* retain.
*/
mask = 0xff >> (bitWidth & 7);
*toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
}
}
/* Compare pixels - they are assumed to start at the first byte in the
* given buffers.
*/
static int
pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
{
#if PNG_LIBPNG_VER < 10506
if (memcmp(pa, pb, bit_width>>3) == 0)
{
png_uint_32 p;
if ((bit_width & 7) == 0) return 0;
/* Ok, any differences? */
p = pa[bit_width >> 3];
p ^= pb[bit_width >> 3];
if (p == 0) return 0;
/* There are, but they may not be significant, remove the bits
* after the end (the low order bits in PNG.)
*/
bit_width &= 7;
p >>= 8-bit_width;
if (p == 0) return 0;
}
#else
/* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
* bits too:
*/
if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
return 0;
#endif
/* Return the index of the changed byte. */
{
png_uint_32 where = 0;
while (pa[where] == pb[where]) ++where;
return 1+where;
}
}
/*************************** BASIC PNG FILE WRITING ***************************/
/* A png_store takes data from the sequential writer or provides data
* to the sequential reader. It can also store the result of a PNG
* write for later retrieval.
*/
#define STORE_BUFFER_SIZE 500 /* arbitrary */
typedef struct png_store_buffer
{
struct png_store_buffer* prev; /* NOTE: stored in reverse order */
png_byte buffer[STORE_BUFFER_SIZE];
} png_store_buffer;
#define FILE_NAME_SIZE 64
typedef struct store_palette_entry /* record of a single palette entry */
{
png_byte red;
png_byte green;
png_byte blue;
png_byte alpha;
} store_palette_entry, store_palette[256];
typedef struct png_store_file
{
struct png_store_file* next; /* as many as you like... */
char name[FILE_NAME_SIZE];
png_uint_32 id; /* must be correct (see FILEID) */
png_size_t datacount; /* In this (the last) buffer */
png_store_buffer data; /* Last buffer in file */
int npalette; /* Number of entries in palette */
store_palette_entry* palette; /* May be NULL */
} png_store_file;
/* The following is a pool of memory allocated by a single libpng read or write
* operation.
*/
typedef struct store_pool
{
struct png_store *store; /* Back pointer */
struct store_memory *list; /* List of allocated memory */
png_byte mark[4]; /* Before and after data */
/* Statistics for this run. */
png_alloc_size_t max; /* Maximum single allocation */
png_alloc_size_t current; /* Current allocation */
png_alloc_size_t limit; /* Highest current allocation */
png_alloc_size_t total; /* Total allocation */
/* Overall statistics (retained across successive runs). */
png_alloc_size_t max_max;
png_alloc_size_t max_limit;
png_alloc_size_t max_total;
} store_pool;
typedef struct png_store
{
/* For cexcept.h exception handling - simply store one of these;
* the context is a self pointer but it may point to a different
* png_store (in fact it never does in this program.)
*/
struct exception_context
exception_context;
unsigned int verbose :1;
unsigned int treat_warnings_as_errors :1;
unsigned int expect_error :1;
unsigned int expect_warning :1;
unsigned int saw_warning :1;
unsigned int speed :1;
unsigned int progressive :1; /* use progressive read */
unsigned int validated :1; /* used as a temporary flag */
int nerrors;
int nwarnings;
char test[128]; /* Name of test */
char error[256];
/* Read fields */
png_structp pread; /* Used to read a saved file */
png_infop piread;
png_store_file* current; /* Set when reading */
png_store_buffer* next; /* Set when reading */
png_size_t readpos; /* Position in *next */
png_byte* image; /* Buffer for reading interlaced images */
png_size_t cb_image; /* Size of this buffer */
png_size_t cb_row; /* Row size of the image(s) */
png_uint_32 image_h; /* Number of rows in a single image */
store_pool read_memory_pool;
/* Write fields */
png_store_file* saved;
png_structp pwrite; /* Used when writing a new file */
png_infop piwrite;
png_size_t writepos; /* Position in .new */
char wname[FILE_NAME_SIZE];
png_store_buffer new; /* The end of the new PNG file being written. */
store_pool write_memory_pool;
store_palette_entry* palette;
int npalette;
} png_store;
/* Initialization and cleanup */
static void
store_pool_mark(png_bytep mark)
{
static png_uint_32 store_seed[2] = { 0x12345678, 1};
make_four_random_bytes(store_seed, mark);
}
/* Use this for random 32 bit values; this function makes sure the result is
* non-zero.
*/
static png_uint_32
random_32(void)
{
for(;;)
{
png_byte mark[4];
png_uint_32 result;
store_pool_mark(mark);
result = png_get_uint_32(mark);
if (result != 0)
return result;
}
}
static void
store_pool_init(png_store *ps, store_pool *pool)
{
memset(pool, 0, sizeof *pool);
pool->store = ps;
pool->list = NULL;
pool->max = pool->current = pool->limit = pool->total = 0;
pool->max_max = pool->max_limit = pool->max_total = 0;
store_pool_mark(pool->mark);
}
static void
store_init(png_store* ps)
{
memset(ps, 0, sizeof *ps);
init_exception_context(&ps->exception_context);
store_pool_init(ps, &ps->read_memory_pool);
store_pool_init(ps, &ps->write_memory_pool);
ps->verbose = 0;
ps->treat_warnings_as_errors = 0;
ps->expect_error = 0;
ps->expect_warning = 0;
ps->saw_warning = 0;
ps->speed = 0;
ps->progressive = 0;
ps->validated = 0;
ps->nerrors = ps->nwarnings = 0;
ps->pread = NULL;
ps->piread = NULL;
ps->saved = ps->current = NULL;
ps->next = NULL;
ps->readpos = 0;
ps->image = NULL;
ps->cb_image = 0;
ps->cb_row = 0;
ps->image_h = 0;
ps->pwrite = NULL;
ps->piwrite = NULL;
ps->writepos = 0;
ps->new.prev = NULL;
ps->palette = NULL;
ps->npalette = 0;
}
static void
store_freebuffer(png_store_buffer* psb)
{
if (psb->prev)
{
store_freebuffer(psb->prev);
free(psb->prev);
psb->prev = NULL;
}
}
static void
store_freenew(png_store *ps)
{
store_freebuffer(&ps->new);
ps->writepos = 0;
if (ps->palette != NULL)
{
free(ps->palette);
ps->palette = NULL;
ps->npalette = 0;
}
}
static void
store_storenew(png_store *ps)
{
png_store_buffer *pb;
if (ps->writepos != STORE_BUFFER_SIZE)
png_error(ps->pwrite, "invalid store call");
pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
if (pb == NULL)
png_error(ps->pwrite, "store new: OOM");
*pb = ps->new;
ps->new.prev = pb;
ps->writepos = 0;
}
static void
store_freefile(png_store_file **ppf)
{
if (*ppf != NULL)
{
store_freefile(&(*ppf)->next);
store_freebuffer(&(*ppf)->data);
(*ppf)->datacount = 0;
if ((*ppf)->palette != NULL)
{
free((*ppf)->palette);
(*ppf)->palette = NULL;
(*ppf)->npalette = 0;
}
free(*ppf);
*ppf = NULL;
}
}
/* Main interface to file storeage, after writing a new PNG file (see the API
* below) call store_storefile to store the result with the given name and id.
*/
static void
store_storefile(png_store *ps, png_uint_32 id)
{
png_store_file *pf = voidcast(png_store_file*, malloc(sizeof *pf));
if (pf == NULL)
png_error(ps->pwrite, "storefile: OOM");
safecat(pf->name, sizeof pf->name, 0, ps->wname);
pf->id = id;
pf->data = ps->new;
pf->datacount = ps->writepos;
ps->new.prev = NULL;
ps->writepos = 0;
pf->palette = ps->palette;
pf->npalette = ps->npalette;
ps->palette = 0;
ps->npalette = 0;
/* And save it. */
pf->next = ps->saved;
ps->saved = pf;
}
/* Generate an error message (in the given buffer) */
static size_t
store_message(png_store *ps, png_structp pp, char *buffer, size_t bufsize,
size_t pos, PNG_CONST char *msg)
{
if (pp != NULL && pp == ps->pread)
{
/* Reading a file */
pos = safecat(buffer, bufsize, pos, "read: ");
if (ps->current != NULL)
{
pos = safecat(buffer, bufsize, pos, ps->current->name);
pos = safecat(buffer, bufsize, pos, sep);
}
}
else if (pp != NULL && pp == ps->pwrite)
{
/* Writing a file */
pos = safecat(buffer, bufsize, pos, "write: ");
pos = safecat(buffer, bufsize, pos, ps->wname);
pos = safecat(buffer, bufsize, pos, sep);
}
else
{
/* Neither reading nor writing (or a memory error in struct delete) */
pos = safecat(buffer, bufsize, pos, "pngvalid: ");
}
if (ps->test[0] != 0)
{
pos = safecat(buffer, bufsize, pos, ps->test);
pos = safecat(buffer, bufsize, pos, sep);
}
pos = safecat(buffer, bufsize, pos, msg);
return pos;
}
/* Verbose output to the error stream: */
static void
store_verbose(png_store *ps, png_structp pp, png_const_charp prefix,
png_const_charp message)
{
char buffer[512];
if (prefix)
fputs(prefix, stderr);
(void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
fputs(buffer, stderr);
fputc('\n', stderr);
}
/* Log an error or warning - the relevant count is always incremented. */
static void
store_log(png_store* ps, png_structp pp, png_const_charp message, int is_error)
{
/* The warning is copied to the error buffer if there are no errors and it is
* the first warning. The error is copied to the error buffer if it is the
* first error (overwriting any prior warnings).
*/
if (is_error ? (ps->nerrors)++ == 0 :
(ps->nwarnings)++ == 0 && ps->nerrors == 0)
store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
if (ps->verbose)
store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
}
/* Internal error function, called with a png_store but no libpng stuff. */
static void
internal_error(png_store *ps, png_const_charp message)
{
store_log(ps, NULL, message, 1 /* error */);
/* And finally throw an exception. */
{
struct exception_context *the_exception_context = &ps->exception_context;
Throw ps;
}
}
/* Functions to use as PNG callbacks. */
static void
store_error(png_structp pp, png_const_charp message) /* PNG_NORETURN */
{
png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
if (!ps->expect_error)
store_log(ps, pp, message, 1 /* error */);
/* And finally throw an exception. */
{
struct exception_context *the_exception_context = &ps->exception_context;
Throw ps;
}
}
static void
store_warning(png_structp pp, png_const_charp message)
{
png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
if (!ps->expect_warning)
store_log(ps, pp, message, 0 /* warning */);
else
ps->saw_warning = 1;
}
/* These somewhat odd functions are used when reading an image to ensure that
* the buffer is big enough, the png_structp is for errors.
*/
/* Return a single row from the correct image. */
static png_bytep
store_image_row(PNG_CONST png_store* ps, png_structp pp, int nImage,
png_uint_32 y)
{
png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
if (ps->image == NULL)
png_error(pp, "no allocated image");
if (coffset + ps->cb_row + 3 > ps->cb_image)
png_error(pp, "image too small");
return ps->image + coffset;
}
static void
store_image_free(png_store *ps, png_structp pp)
{
if (ps->image != NULL)
{
png_bytep image = ps->image;
if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
{
if (pp != NULL)
png_error(pp, "png_store image overwrite (1)");
else
store_log(ps, NULL, "png_store image overwrite (2)", 1);
}
ps->image = NULL;
ps->cb_image = 0;
--image;
free(image);
}
}
static void
store_ensure_image(png_store *ps, png_structp pp, int nImages, png_size_t cbRow,
png_uint_32 cRows)
{
png_size_t cb = nImages * cRows * (cbRow + 5);
if (ps->cb_image < cb)
{
png_bytep image;
store_image_free(ps, pp);
/* The buffer is deliberately mis-aligned. */
image = voidcast(png_bytep, malloc(cb+2));
if (image == NULL)
{
/* Called from the startup - ignore the error for the moment. */
if (pp == NULL)
return;
png_error(pp, "OOM allocating image buffer");
}
/* These magic tags are used to detect overwrites above. */
++image;
image[-1] = 0xed;
image[cb] = 0xfe;
ps->image = image;
ps->cb_image = cb;
}
/* We have an adequate sized image; lay out the rows. There are 2 bytes at
* the start and three at the end of each (this ensures that the row
* alignment starts out odd - 2+1 and changes for larger images on each row.)
*/
ps->cb_row = cbRow;
ps->image_h = cRows;
/* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
* This deliberately doesn't match the bits in the size test image which are
* outside the image; these are set to 0xff (all 1). To make the row
* comparison work in the 'size' test case the size rows are pre-initialized
* to the same value prior to calling 'standard_row'.
*/
memset(ps->image, 178, cb);
/* Then put in the marks. */
while (--nImages >= 0)
{
png_uint_32 y;
for (y=0; y<cRows; ++y)
{
png_bytep row = store_image_row(ps, pp, nImages, y);
/* The markers: */
row[-2] = 190;
row[-1] = 239;
row[cbRow] = 222;
row[cbRow+1] = 173;
row[cbRow+2] = 17;
}
}
}
static void
store_image_check(PNG_CONST png_store* ps, png_structp pp, int iImage)
{