This repository has been archived by the owner on Nov 20, 2020. It is now read-only.
/
pngvalid.c
4763 lines (4001 loc) · 139 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.0 [January 6, 2011]
* Copyright (c) 2011 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.
*/
#include "png.h"
#include "zlib.h" /* For crc32 */
#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
# define UNUSED(param) param = param;
#endif
/***************************** EXCEPTION HANDLING *****************************/
#include "contrib/visupng/cexcept.h"
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);
}
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);
}
static PNG_CONST char invalid[] = "invalid";
static PNG_CONST char sep[] = ": ";
/* NOTE: this is indexed by ln2(bit_depth)! */
static PNG_CONST char *bit_depths[8] =
{
"1", "2", "4", "8", "16", invalid, invalid, invalid
};
static PNG_CONST char *colour_types[8] =
{
"greyscale", invalid, "truecolour", "indexed-colour",
"greyscale with alpha", invalid, "truecolour with alpha", invalid
};
/* To get log-bit-depth from bit depth, returns 0 to 7 (7 on error). */
static unsigned int
log2depth(png_byte bit_depth)
{
switch (bit_depth)
{
case 1:
return 0;
case 2:
return 1;
case 4:
return 2;
case 8:
return 3;
case 16:
return 4;
default:
return 7;
}
}
/* 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.
*/
#define FILEID(col, depth, interlace, width, height, do_interlace) \
((png_uint_32)((col) + ((depth)<<3) + ((interlace)<<8) + \
(((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 INTERLACE_FROM_ID(id) ((int)(((id) >> 8) & 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 log_bit_depth, int interlace_type, png_uint_32 w, png_uint_32 h,
int do_interlace)
{
pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
pos = safecat(buffer, bufsize, pos, " ");
pos = safecat(buffer, bufsize, pos, bit_depths[log_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),
log2depth(DEPTH_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
static int
next_format(png_bytep colour_type, png_bytep bit_depth)
{
if (*bit_depth == 0)
{
*colour_type = 0, *bit_depth = 1;
return 1;
}
*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;
}
}
static unsigned int
sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
png_uint_32 x, unsigned int sample)
{
png_uint_32 index, result;
/* Find a sample index for the desired sample: */
x *= bit_depth;
index = x;
if ((colour_type & 1) == 0) /* !palette */
{
if (colour_type & 2)
index *= 3, index += sample; /* Colour channels; select one */
if (colour_type & 4)
index += x; /* Alpha channel */
}
/* Return the sample from the row as an integer. */
row += 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. */
index &= 7;
return (result >> (8-index-bit_depth)) & ((1U<<bit_depth)-1);
}
/* 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);
}
/* 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 (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;
}
return 1; /* Different */
}
/*************************** 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 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 */
} 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[64]; /* Name of test */
char error[128];
/* 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 */
size_t cb_image; /* Size of this buffer */
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;
} png_store;
/* Initialization and cleanup */
static void
store_pool_mark(png_byte *mark)
{
/* Generate a new mark. 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 png_uint_32 u0 = 0x12345678, u1 = 1;
/* 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.
*/
int i;
for (i=0; i<4; ++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;
*mark++ = (png_byte)u;
}
}
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->pwrite = NULL;
ps->piwrite = NULL;
ps->writepos = 0;
ps->new.prev = NULL;
}
/* This somewhat odd function is used when reading an image to ensure that the
* buffer is big enough - this is why a png_structp is available.
*/
static void
store_ensure_image(png_store *ps, png_structp pp, size_t cb)
{
if (ps->cb_image < cb)
{
if (ps->image != NULL)
{
free(ps->image-1);
ps->cb_image = 0;
}
/* The buffer is deliberately mis-aligned. */
ps->image = malloc(cb+1);
if (ps->image == NULL)
png_error(pp, "OOM allocating image buffer");
++(ps->image);
ps->cb_image = cb;
}
/* And, for error checking, the whole buffer is set to '1' - this
* matches what happens with the 'size' test images on write and also
* matches the unused bits in the test rows.
*/
memset(ps->image, 0xff, cb);
}
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;
}
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 = 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;
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 = 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;
/* 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;
}
/* 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)
{
char buffer[256];
size_t pos;
if (is_error)
pos = safecat(buffer, sizeof buffer, 0, "error: ");
else
pos = safecat(buffer, sizeof buffer, 0, "warning: ");
store_message(ps, pp, buffer, sizeof buffer, pos, message);
fputs(buffer, stderr);
fputc('\n', stderr);
}
}
/* Functions to use as PNG callbacks. */
static void
store_error(png_structp pp, png_const_charp message) /* PNG_NORETURN */
{
png_store *ps = 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 = png_get_error_ptr(pp);
if (!ps->expect_warning)
store_log(ps, pp, message, 0 /* warning */);
else
ps->saw_warning = 1;
}
static void
store_write(png_structp pp, png_bytep pb, png_size_t st)
{
png_store *ps = png_get_io_ptr(pp);
if (ps->pwrite != pp)
png_error(pp, "store state damaged");
while (st > 0)
{
size_t cb;
if (ps->writepos >= STORE_BUFFER_SIZE)
store_storenew(ps);
cb = st;
if (cb > STORE_BUFFER_SIZE - ps->writepos)
cb = STORE_BUFFER_SIZE - ps->writepos;
memcpy(ps->new.buffer + ps->writepos, pb, cb);
pb += cb;
st -= cb;
ps->writepos += cb;
}
}
static void
store_flush(png_structp pp)
{
UNUSED(pp) /*DOES NOTHING*/
}
static size_t
store_read_buffer_size(png_store *ps)
{
/* Return the bytes available for read in the current buffer. */
if (ps->next != &ps->current->data)
return STORE_BUFFER_SIZE;
return ps->current->datacount;
}
/* Return total bytes available for read. */
static size_t
store_read_buffer_avail(png_store *ps)
{
if (ps->current != NULL && ps->next != NULL)
{
png_store_buffer *next = &ps->current->data;
size_t cbAvail = ps->current->datacount;
while (next != ps->next && next != NULL)
{
next = next->prev;
cbAvail += STORE_BUFFER_SIZE;
}
if (next != ps->next)
png_error(ps->pread, "buffer read error");
if (cbAvail > ps->readpos)
return cbAvail - ps->readpos;
}
return 0;
}
static int
store_read_buffer_next(png_store *ps)
{
png_store_buffer *pbOld = ps->next;
png_store_buffer *pbNew = &ps->current->data;
if (pbOld != pbNew)
{
while (pbNew != NULL && pbNew->prev != pbOld)
pbNew = pbNew->prev;
if (pbNew != NULL)
{
ps->next = pbNew;
ps->readpos = 0;
return 1;
}
png_error(ps->pread, "buffer lost");
}
return 0; /* EOF or error */
}
/* Need separate implementation and callback to allow use of the same code
* during progressive read, where the io_ptr is set internally by libpng.
*/
static void
store_read_imp(png_store *ps, png_bytep pb, png_size_t st)
{
if (ps->current == NULL || ps->next == NULL)
png_error(ps->pread, "store state damaged");
while (st > 0)
{
size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
if (cbAvail > 0)
{
if (cbAvail > st) cbAvail = st;
memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
st -= cbAvail;
pb += cbAvail;
ps->readpos += cbAvail;
}
else if (!store_read_buffer_next(ps))
png_error(ps->pread, "read beyond end of file");
}
}
static void
store_read(png_structp pp, png_bytep pb, png_size_t st)
{
png_store *ps = png_get_io_ptr(pp);
if (ps == NULL || ps->pread != pp)
png_error(pp, "bad store read call");
store_read_imp(ps, pb, st);
}
static void
store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
{
/* Notice that a call to store_read will cause this function to fail because
* readpos will be set.
*/
if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
png_error(pp, "store state damaged (progressive)");
do
{
if (ps->readpos != 0)
png_error(pp, "store_read called during progressive read");
png_process_data(pp, pi, ps->next->buffer, store_read_buffer_size(ps));
}
while (store_read_buffer_next(ps));
}
/***************************** MEMORY MANAGEMENT*** ***************************/
/* A store_memory is simply the header for an allocated block of memory. The
* pointer returned to libpng is just after the end of the header block, the
* allocated memory is followed by a second copy of the 'mark'.
*/
typedef struct store_memory
{
store_pool *pool; /* Originating pool */
struct store_memory *next; /* Singly linked list */
png_alloc_size_t size; /* Size of memory allocated */
png_byte mark[4]; /* ID marker */
} store_memory;
/* Handle a fatal error in memory allocation. This calls png_error if the
* libpng struct is non-NULL, else it outputs a message and returns. This means
* that a memory problem while libpng is running will abort (png_error) the
* handling of particular file while one in cleanup (after the destroy of the
* struct has returned) will simply keep going and free (or attempt to free)
* all the memory.
*/
static void
store_pool_error(png_store *ps, png_structp pp, PNG_CONST char *msg)
{
if (pp != NULL)
png_error(pp, msg);
/* Else we have to do it ourselves. png_error eventually calls store_log,
* above. store_log accepts a NULL png_structp - it just changes what gets
* output by store_message.
*/
store_log(ps, pp, msg, 1 /* error */);
}
static void
store_memory_free(png_structp pp, store_pool *pool, store_memory *memory)
{
/* Note that pp may be NULL (see store_pool_delete below), the caller has
* found 'memory' in pool->list *and* unlinked this entry, so this is a valid
* pointer (for sure), but the contents may have been trashed.
*/
if (memory->pool != pool)
store_pool_error(pool->store, pp, "memory corrupted (pool)");
else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
store_pool_error(pool->store, pp, "memory corrupted (start)");
/* It should be safe to read the size field now. */
else
{
png_alloc_size_t cb = memory->size;
if (cb > pool->max)
store_pool_error(pool->store, pp, "memory corrupted (size)");
else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
!= 0)
store_pool_error(pool->store, pp, "memory corrupted (end)");
/* Finally give the library a chance to find problems too: */
else
{
pool->current -= cb;
free(memory);
}
}
}
static void
store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, next+1);
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
/* The memory callbacks: */
static png_voidp
store_malloc(png_structp pp, png_alloc_size_t cb)
{
store_pool *pool = png_get_mem_ptr(pp);
store_memory *new = malloc(cb + (sizeof *new) + (sizeof pool->mark));
if (new != NULL)
{
if (cb > pool->max)
pool->max = cb;
pool->current += cb;
if (pool->current > pool->limit)
pool->limit = pool->current;
pool->total += cb;
new->size = cb;
memcpy(new->mark, pool->mark, sizeof new->mark);
memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
new->pool = pool;
new->next = pool->list;
pool->list = new;
++new;
}
else
store_pool_error(pool->store, pp, "out of memory");
return new;
}
static void
store_free(png_structp pp, png_voidp memory)
{
store_pool *pool = png_get_mem_ptr(pp);
store_memory *this = memory, **test;
/* First check that this 'memory' really is valid memory - it must be in the
* pool list. If it is, use the shared memory_free function to free it.
*/
--this;
for (test = &pool->list; *test != this; test = &(*test)->next)