~ubuntu-branches/ubuntu/quantal/tiff/quantal

« back to all changes in this revision

Viewing changes to libtiff/tif_dirread.c

  • Committer: Bazaar Package Importer
  • Author(s): Jay Berkenbilt
  • Date: 2009-08-28 15:44:23 UTC
  • mfrom: (1.1.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20090828154423-7oisj77n302jrroa
Tags: 3.9.1-1
New upstream release

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* $Id: tif_dirread.c,v 1.92.2.5 2009-01-01 00:10:43 bfriesen Exp $ */
 
2
 
 
3
/*
 
4
 * Copyright (c) 1988-1997 Sam Leffler
 
5
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
 
6
 *
 
7
 * Permission to use, copy, modify, distribute, and sell this software and 
 
8
 * its documentation for any purpose is hereby granted without fee, provided
 
9
 * that (i) the above copyright notices and this permission notice appear in
 
10
 * all copies of the software and related documentation, and (ii) the names of
 
11
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
 
12
 * publicity relating to the software without the specific, prior written
 
13
 * permission of Sam Leffler and Silicon Graphics.
 
14
 * 
 
15
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
 
16
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
 
17
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
 
18
 * 
 
19
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
 
20
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
 
21
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 
22
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
 
23
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
 
24
 * OF THIS SOFTWARE.
 
25
 */
 
26
 
 
27
/*
 
28
 * TIFF Library.
 
29
 *
 
30
 * Directory Read Support Routines.
 
31
 */
 
32
#include "tiffiop.h"
 
33
 
 
34
#define IGNORE  0               /* tag placeholder used below */
 
35
 
 
36
#ifdef HAVE_IEEEFP
 
37
# define        TIFFCvtIEEEFloatToNative(tif, n, fp)
 
38
# define        TIFFCvtIEEEDoubleToNative(tif, n, dp)
 
39
#else
 
40
extern  void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*);
 
41
extern  void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*);
 
42
#endif
 
43
 
 
44
static  TIFFDirEntry* TIFFReadDirectoryFind(TIFFDirEntry* dir,
 
45
                                            uint16 dircount, uint16 tagid);
 
46
static  int EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16);
 
47
static  void MissingRequired(TIFF*, const char*);
 
48
static  int TIFFCheckDirOffset(TIFF*, toff_t);
 
49
static  int CheckDirCount(TIFF*, TIFFDirEntry*, uint32);
 
50
static  uint16 TIFFFetchDirectory(TIFF*, toff_t, TIFFDirEntry**, toff_t *);
 
51
static  tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*);
 
52
static  tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*);
 
53
static  float TIFFFetchRational(TIFF*, TIFFDirEntry*);
 
54
static  int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*);
 
55
static  int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, uint16*);
 
56
static  int TIFFFetchPerSampleLongs(TIFF*, TIFFDirEntry*, uint32*);
 
57
static  int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*);
 
58
static  int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*);
 
59
static  int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**);
 
60
static  int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*);
 
61
static  int TIFFFetchSubjectDistance(TIFF*, TIFFDirEntry*);
 
62
static  float TIFFFetchFloat(TIFF*, TIFFDirEntry*);
 
63
static  int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*);
 
64
static  int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*);
 
65
static  int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*);
 
66
static  int TIFFFetchShortPair(TIFF*, TIFFDirEntry*);
 
67
static  void ChopUpSingleUncompressedStrip(TIFF*);
 
68
 
 
69
/*
 
70
 * Read the next TIFF directory from a file and convert it to the internal
 
71
 * format. We read directories sequentially.
 
72
 */
 
73
int
 
74
TIFFReadDirectory(TIFF* tif)
 
75
{
 
76
        static const char module[] = "TIFFReadDirectory";
 
77
 
 
78
        int n;
 
79
        TIFFDirectory* td;
 
80
        TIFFDirEntry *dp, *dir = NULL;
 
81
        uint16 iv;
 
82
        uint32 v;
 
83
        const TIFFFieldInfo* fip;
 
84
        size_t fix;
 
85
        uint16 dircount;
 
86
        int diroutoforderwarning = 0, compressionknown = 0;
 
87
 
 
88
        tif->tif_diroff = tif->tif_nextdiroff;
 
89
        /*
 
90
         * Check whether we have the last offset or bad offset (IFD looping).
 
91
         */
 
92
        if (!TIFFCheckDirOffset(tif, tif->tif_nextdiroff))
 
93
                return 0;
 
94
        /*
 
95
         * Cleanup any previous compression state.
 
96
         */
 
97
        (*tif->tif_cleanup)(tif);
 
98
        tif->tif_curdir++;
 
99
        dircount = TIFFFetchDirectory(tif, tif->tif_nextdiroff,
 
100
                                      &dir, &tif->tif_nextdiroff);
 
101
        if (!dircount) {
 
102
                TIFFErrorExt(tif->tif_clientdata, module,
 
103
                             "%s: Failed to read directory at offset %u",
 
104
                             tif->tif_name, tif->tif_nextdiroff);
 
105
                return 0;
 
106
        }
 
107
 
 
108
        tif->tif_flags &= ~TIFF_BEENWRITING;    /* reset before new dir */
 
109
        /*
 
110
         * Setup default value and then make a pass over
 
111
         * the fields to check type and tag information,
 
112
         * and to extract info required to size data
 
113
         * structures.  A second pass is made afterwards
 
114
         * to read in everthing not taken in the first pass.
 
115
         */
 
116
        td = &tif->tif_dir;
 
117
        /* free any old stuff and reinit */
 
118
        TIFFFreeDirectory(tif);
 
119
        TIFFDefaultDirectory(tif);
 
120
        /*
 
121
         * Electronic Arts writes gray-scale TIFF files
 
122
         * without a PlanarConfiguration directory entry.
 
123
         * Thus we setup a default value here, even though
 
124
         * the TIFF spec says there is no default value.
 
125
         */
 
126
        TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
 
127
 
 
128
        /*
 
129
         * Sigh, we must make a separate pass through the
 
130
         * directory for the following reason:
 
131
         *
 
132
         * We must process the Compression tag in the first pass
 
133
         * in order to merge in codec-private tag definitions (otherwise
 
134
         * we may get complaints about unknown tags).  However, the
 
135
         * Compression tag may be dependent on the SamplesPerPixel
 
136
         * tag value because older TIFF specs permited Compression
 
137
         * to be written as a SamplesPerPixel-count tag entry.
 
138
         * Thus if we don't first figure out the correct SamplesPerPixel
 
139
         * tag value then we may end up ignoring the Compression tag
 
140
         * value because it has an incorrect count value (if the
 
141
         * true value of SamplesPerPixel is not 1).
 
142
         *
 
143
         * It sure would have been nice if Aldus had really thought
 
144
         * this stuff through carefully.
 
145
         */
 
146
        for (dp = dir, n = dircount; n > 0; n--, dp++) {
 
147
                if (tif->tif_flags & TIFF_SWAB) {
 
148
                        TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
 
149
                        TIFFSwabArrayOfLong(&dp->tdir_count, 2);
 
150
                }
 
151
                if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) {
 
152
                        if (!TIFFFetchNormalTag(tif, dp))
 
153
                                goto bad;
 
154
                        dp->tdir_tag = IGNORE;
 
155
                }
 
156
        }
 
157
        /*
 
158
         * First real pass over the directory.
 
159
         */
 
160
        fix = 0;
 
161
        for (dp = dir, n = dircount; n > 0; n--, dp++) {
 
162
 
 
163
                if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE)
 
164
                        continue;
 
165
 
 
166
                /*
 
167
                 * Silicon Beach (at least) writes unordered
 
168
                 * directory tags (violating the spec).  Handle
 
169
                 * it here, but be obnoxious (maybe they'll fix it?).
 
170
                 */
 
171
                if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) {
 
172
                        if (!diroutoforderwarning) {
 
173
                                TIFFWarningExt(tif->tif_clientdata, module,
 
174
        "%s: invalid TIFF directory; tags are not sorted in ascending order",
 
175
                                            tif->tif_name);
 
176
                                diroutoforderwarning = 1;
 
177
                        }
 
178
                        fix = 0;                        /* O(n^2) */
 
179
                }
 
180
                while (fix < tif->tif_nfields &&
 
181
                    tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag)
 
182
                        fix++;
 
183
                if (fix >= tif->tif_nfields ||
 
184
                    tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) {
 
185
 
 
186
                                        TIFFWarningExt(tif->tif_clientdata,
 
187
                                                       module,
 
188
                        "%s: unknown field with tag %d (0x%x) encountered",
 
189
                                                       tif->tif_name,
 
190
                                                       dp->tdir_tag,
 
191
                                                       dp->tdir_tag);
 
192
 
 
193
                                        if (!_TIFFMergeFieldInfo(tif,
 
194
                                                _TIFFCreateAnonFieldInfo(tif,
 
195
                                                dp->tdir_tag,
 
196
                                                (TIFFDataType) dp->tdir_type),
 
197
                                                1))
 
198
                                        {
 
199
                                        TIFFWarningExt(tif->tif_clientdata,
 
200
                                                       module,
 
201
                        "Registering anonymous field with tag %d (0x%x) failed",
 
202
                                                       dp->tdir_tag,
 
203
                                                       dp->tdir_tag);
 
204
                                        goto ignore;
 
205
                                        }
 
206
                        fix = 0;
 
207
                        while (fix < tif->tif_nfields &&
 
208
                               tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag)
 
209
                                fix++;
 
210
                }
 
211
                /*
 
212
                 * Null out old tags that we ignore.
 
213
                 */
 
214
                if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) {
 
215
        ignore:
 
216
                        dp->tdir_tag = IGNORE;
 
217
                        continue;
 
218
                }
 
219
                /*
 
220
                 * Check data type.
 
221
                 */
 
222
                fip = tif->tif_fieldinfo[fix];
 
223
                while (dp->tdir_type != (unsigned short) fip->field_type
 
224
                    && fix < tif->tif_nfields) {
 
225
                        if (fip->field_type == TIFF_ANY)        /* wildcard */
 
226
                                break;
 
227
                        fip = tif->tif_fieldinfo[++fix];
 
228
                        if (fix >= tif->tif_nfields ||
 
229
                            fip->field_tag != dp->tdir_tag) {
 
230
                                TIFFWarningExt(tif->tif_clientdata, module,
 
231
                        "%s: wrong data type %d for \"%s\"; tag ignored",
 
232
                                            tif->tif_name, dp->tdir_type,
 
233
                                            tif->tif_fieldinfo[fix-1]->field_name);
 
234
                                goto ignore;
 
235
                        }
 
236
                }
 
237
                /*
 
238
                 * Check count if known in advance.
 
239
                 */
 
240
                if (fip->field_readcount != TIFF_VARIABLE
 
241
                    && fip->field_readcount != TIFF_VARIABLE2) {
 
242
                        uint32 expected = (fip->field_readcount == TIFF_SPP) ?
 
243
                            (uint32) td->td_samplesperpixel :
 
244
                            (uint32) fip->field_readcount;
 
245
                        if (!CheckDirCount(tif, dp, expected))
 
246
                                goto ignore;
 
247
                }
 
248
 
 
249
                switch (dp->tdir_tag) {
 
250
                case TIFFTAG_COMPRESSION:
 
251
                        /*
 
252
                         * The 5.0 spec says the Compression tag has
 
253
                         * one value, while earlier specs say it has
 
254
                         * one value per sample.  Because of this, we
 
255
                         * accept the tag if one value is supplied.
 
256
                         */
 
257
                        if (dp->tdir_count == 1) {
 
258
                                v = TIFFExtractData(tif,
 
259
                                    dp->tdir_type, dp->tdir_offset);
 
260
                                if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v))
 
261
                                        goto bad;
 
262
                                else
 
263
                                        compressionknown = 1;
 
264
                                break;
 
265
                        /* XXX: workaround for broken TIFFs */
 
266
                        } else if (dp->tdir_type == TIFF_LONG) {
 
267
                                if (!TIFFFetchPerSampleLongs(tif, dp, &v) ||
 
268
                                    !TIFFSetField(tif, dp->tdir_tag, (uint16)v))
 
269
                                        goto bad;
 
270
                        } else {
 
271
                                if (!TIFFFetchPerSampleShorts(tif, dp, &iv)
 
272
                                    || !TIFFSetField(tif, dp->tdir_tag, iv))
 
273
                                        goto bad;
 
274
                        }
 
275
                        dp->tdir_tag = IGNORE;
 
276
                        break;
 
277
                case TIFFTAG_STRIPOFFSETS:
 
278
                case TIFFTAG_STRIPBYTECOUNTS:
 
279
                case TIFFTAG_TILEOFFSETS:
 
280
                case TIFFTAG_TILEBYTECOUNTS:
 
281
                        TIFFSetFieldBit(tif, fip->field_bit);
 
282
                        break;
 
283
                case TIFFTAG_IMAGEWIDTH:
 
284
                case TIFFTAG_IMAGELENGTH:
 
285
                case TIFFTAG_IMAGEDEPTH:
 
286
                case TIFFTAG_TILELENGTH:
 
287
                case TIFFTAG_TILEWIDTH:
 
288
                case TIFFTAG_TILEDEPTH:
 
289
                case TIFFTAG_PLANARCONFIG:
 
290
                case TIFFTAG_ROWSPERSTRIP:
 
291
                case TIFFTAG_EXTRASAMPLES:
 
292
                        if (!TIFFFetchNormalTag(tif, dp))
 
293
                                goto bad;
 
294
                        dp->tdir_tag = IGNORE;
 
295
                        break;
 
296
                }
 
297
        }
 
298
 
 
299
        /*
 
300
         * XXX: OJPEG hack.
 
301
         * If a) compression is OJPEG, b) planarconfig tag says it's separate,
 
302
         * c) strip offsets/bytecounts tag are both present and
 
303
         * d) both contain exactly one value, then we consistently find
 
304
         * that the buggy implementation of the buggy compression scheme
 
305
         * matches contig planarconfig best. So we 'fix-up' the tag here
 
306
         */
 
307
        if ((td->td_compression==COMPRESSION_OJPEG) &&
 
308
            (td->td_planarconfig==PLANARCONFIG_SEPARATE)) {
 
309
                dp = TIFFReadDirectoryFind(dir,dircount,TIFFTAG_STRIPOFFSETS);
 
310
                if ((dp!=0) && (dp->tdir_count==1)) {
 
311
                        dp = TIFFReadDirectoryFind(dir, dircount,
 
312
                                                   TIFFTAG_STRIPBYTECOUNTS);
 
313
                        if ((dp!=0) && (dp->tdir_count==1)) {
 
314
                                td->td_planarconfig=PLANARCONFIG_CONTIG;
 
315
                                TIFFWarningExt(tif->tif_clientdata,
 
316
                                               "TIFFReadDirectory",
 
317
                                "Planarconfig tag value assumed incorrect, "
 
318
                                "assuming data is contig instead of chunky");
 
319
                        }
 
320
                }
 
321
        }
 
322
 
 
323
        /*
 
324
         * Allocate directory structure and setup defaults.
 
325
         */
 
326
        if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
 
327
                MissingRequired(tif, "ImageLength");
 
328
                goto bad;
 
329
        }
 
330
        /* 
 
331
         * Setup appropriate structures (by strip or by tile)
 
332
         */
 
333
        if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
 
334
                td->td_nstrips = TIFFNumberOfStrips(tif);
 
335
                td->td_tilewidth = td->td_imagewidth;
 
336
                td->td_tilelength = td->td_rowsperstrip;
 
337
                td->td_tiledepth = td->td_imagedepth;
 
338
                tif->tif_flags &= ~TIFF_ISTILED;
 
339
        } else {
 
340
                td->td_nstrips = TIFFNumberOfTiles(tif);
 
341
                tif->tif_flags |= TIFF_ISTILED;
 
342
        }
 
343
        if (!td->td_nstrips) {
 
344
                TIFFErrorExt(tif->tif_clientdata, module,
 
345
                             "%s: cannot handle zero number of %s",
 
346
                             tif->tif_name, isTiled(tif) ? "tiles" : "strips");
 
347
                goto bad;
 
348
        }
 
349
        td->td_stripsperimage = td->td_nstrips;
 
350
        if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
 
351
                td->td_stripsperimage /= td->td_samplesperpixel;
 
352
        if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
 
353
                if ((td->td_compression==COMPRESSION_OJPEG) &&
 
354
                    (isTiled(tif)==0) &&
 
355
                    (td->td_nstrips==1)) {
 
356
                        /*
 
357
                         * XXX: OJPEG hack.
 
358
                         * If a) compression is OJPEG, b) it's not a tiled TIFF,
 
359
                         * and c) the number of strips is 1,
 
360
                         * then we tolerate the absence of stripoffsets tag,
 
361
                         * because, presumably, all required data is in the
 
362
                         * JpegInterchangeFormat stream.
 
363
                         */
 
364
                        TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
 
365
                } else {
 
366
                        MissingRequired(tif,
 
367
                                isTiled(tif) ? "TileOffsets" : "StripOffsets");
 
368
                        goto bad;
 
369
                }
 
370
        }
 
371
 
 
372
        /*
 
373
         * Second pass: extract other information.
 
374
         */
 
375
        for (dp = dir, n = dircount; n > 0; n--, dp++) {
 
376
                if (dp->tdir_tag == IGNORE)
 
377
                        continue;
 
378
                switch (dp->tdir_tag) {
 
379
                case TIFFTAG_MINSAMPLEVALUE:
 
380
                case TIFFTAG_MAXSAMPLEVALUE:
 
381
                case TIFFTAG_BITSPERSAMPLE:
 
382
                case TIFFTAG_DATATYPE:
 
383
                case TIFFTAG_SAMPLEFORMAT:
 
384
                        /*
 
385
                         * The 5.0 spec says the Compression tag has
 
386
                         * one value, while earlier specs say it has
 
387
                         * one value per sample.  Because of this, we
 
388
                         * accept the tag if one value is supplied.
 
389
                         *
 
390
                         * The MinSampleValue, MaxSampleValue, BitsPerSample
 
391
                         * DataType and SampleFormat tags are supposed to be
 
392
                         * written as one value/sample, but some vendors
 
393
                         * incorrectly write one value only -- so we accept
 
394
                         * that as well (yech). Other vendors write correct
 
395
                         * value for NumberOfSamples, but incorrect one for
 
396
                         * BitsPerSample and friends, and we will read this
 
397
                         * too.
 
398
                         */
 
399
                        if (dp->tdir_count == 1) {
 
400
                                v = TIFFExtractData(tif,
 
401
                                    dp->tdir_type, dp->tdir_offset);
 
402
                                if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v))
 
403
                                        goto bad;
 
404
                        /* XXX: workaround for broken TIFFs */
 
405
                        } else if (dp->tdir_tag == TIFFTAG_BITSPERSAMPLE
 
406
                                   && dp->tdir_type == TIFF_LONG) {
 
407
                                if (!TIFFFetchPerSampleLongs(tif, dp, &v) ||
 
408
                                    !TIFFSetField(tif, dp->tdir_tag, (uint16)v))
 
409
                                        goto bad;
 
410
                        } else {
 
411
                                if (!TIFFFetchPerSampleShorts(tif, dp, &iv) ||
 
412
                                    !TIFFSetField(tif, dp->tdir_tag, iv))
 
413
                                        goto bad;
 
414
                        }
 
415
                        break;
 
416
                case TIFFTAG_SMINSAMPLEVALUE:
 
417
                case TIFFTAG_SMAXSAMPLEVALUE:
 
418
                        {
 
419
                                double dv = 0.0;
 
420
                                if (!TIFFFetchPerSampleAnys(tif, dp, &dv) ||
 
421
                                    !TIFFSetField(tif, dp->tdir_tag, dv))
 
422
                                        goto bad;
 
423
                        }
 
424
                        break;
 
425
                case TIFFTAG_STRIPOFFSETS:
 
426
                case TIFFTAG_TILEOFFSETS:
 
427
                        if (!TIFFFetchStripThing(tif, dp,
 
428
                            td->td_nstrips, &td->td_stripoffset))
 
429
                                goto bad;
 
430
                        break;
 
431
                case TIFFTAG_STRIPBYTECOUNTS:
 
432
                case TIFFTAG_TILEBYTECOUNTS:
 
433
                        if (!TIFFFetchStripThing(tif, dp,
 
434
                            td->td_nstrips, &td->td_stripbytecount))
 
435
                                goto bad;
 
436
                        break;
 
437
                case TIFFTAG_COLORMAP:
 
438
                case TIFFTAG_TRANSFERFUNCTION:
 
439
                        {
 
440
                                char* cp;
 
441
                                /*
 
442
                                 * TransferFunction can have either 1x or 3x
 
443
                                 * data values; Colormap can have only 3x
 
444
                                 * items.
 
445
                                 */
 
446
                                v = 1L<<td->td_bitspersample;
 
447
                                if (dp->tdir_tag == TIFFTAG_COLORMAP ||
 
448
                                    dp->tdir_count != v) {
 
449
                                        if (!CheckDirCount(tif, dp, 3 * v))
 
450
                                                break;
 
451
                                }
 
452
                                v *= sizeof(uint16);
 
453
                                cp = (char *)_TIFFCheckMalloc(tif,
 
454
                                                              dp->tdir_count,
 
455
                                                              sizeof (uint16),
 
456
                                        "to read \"TransferFunction\" tag");
 
457
                                if (cp != NULL) {
 
458
                                        if (TIFFFetchData(tif, dp, cp)) {
 
459
                                                /*
 
460
                                                 * This deals with there being
 
461
                                                 * only one array to apply to
 
462
                                                 * all samples.
 
463
                                                 */
 
464
                                                uint32 c = 1L << td->td_bitspersample;
 
465
                                                if (dp->tdir_count == c)
 
466
                                                        v = 0L;
 
467
                                                TIFFSetField(tif, dp->tdir_tag,
 
468
                                                    cp, cp+v, cp+2*v);
 
469
                                        }
 
470
                                        _TIFFfree(cp);
 
471
                                }
 
472
                                break;
 
473
                        }
 
474
                case TIFFTAG_PAGENUMBER:
 
475
                case TIFFTAG_HALFTONEHINTS:
 
476
                case TIFFTAG_YCBCRSUBSAMPLING:
 
477
                case TIFFTAG_DOTRANGE:
 
478
                        (void) TIFFFetchShortPair(tif, dp);
 
479
                        break;
 
480
                case TIFFTAG_REFERENCEBLACKWHITE:
 
481
                        (void) TIFFFetchRefBlackWhite(tif, dp);
 
482
                        break;
 
483
/* BEGIN REV 4.0 COMPATIBILITY */
 
484
                case TIFFTAG_OSUBFILETYPE:
 
485
                        v = 0L;
 
486
                        switch (TIFFExtractData(tif, dp->tdir_type,
 
487
                            dp->tdir_offset)) {
 
488
                        case OFILETYPE_REDUCEDIMAGE:
 
489
                                v = FILETYPE_REDUCEDIMAGE;
 
490
                                break;
 
491
                        case OFILETYPE_PAGE:
 
492
                                v = FILETYPE_PAGE;
 
493
                                break;
 
494
                        }
 
495
                        if (v)
 
496
                                TIFFSetField(tif, TIFFTAG_SUBFILETYPE, v);
 
497
                        break;
 
498
/* END REV 4.0 COMPATIBILITY */
 
499
                default:
 
500
                        (void) TIFFFetchNormalTag(tif, dp);
 
501
                        break;
 
502
                }
 
503
        }
 
504
        /*
 
505
         * OJPEG hack:
 
506
         * - If a) compression is OJPEG, and b) photometric tag is missing,
 
507
         * then we consistently find that photometric should be YCbCr
 
508
         * - If a) compression is OJPEG, and b) photometric tag says it's RGB,
 
509
         * then we consistently find that the buggy implementation of the
 
510
         * buggy compression scheme matches photometric YCbCr instead.
 
511
         * - If a) compression is OJPEG, and b) bitspersample tag is missing,
 
512
         * then we consistently find bitspersample should be 8.
 
513
         * - If a) compression is OJPEG, b) samplesperpixel tag is missing,
 
514
         * and c) photometric is RGB or YCbCr, then we consistently find
 
515
         * samplesperpixel should be 3
 
516
         * - If a) compression is OJPEG, b) samplesperpixel tag is missing,
 
517
         * and c) photometric is MINISWHITE or MINISBLACK, then we consistently
 
518
         * find samplesperpixel should be 3
 
519
         */
 
520
        if (td->td_compression==COMPRESSION_OJPEG)
 
521
        {
 
522
                if (!TIFFFieldSet(tif,FIELD_PHOTOMETRIC))
 
523
                {
 
524
                        TIFFWarningExt(tif->tif_clientdata, "TIFFReadDirectory",
 
525
                        "Photometric tag is missing, assuming data is YCbCr");
 
526
                        if (!TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,PHOTOMETRIC_YCBCR))
 
527
                                goto bad;
 
528
                }
 
529
                else if (td->td_photometric==PHOTOMETRIC_RGB)
 
530
                {
 
531
                        td->td_photometric=PHOTOMETRIC_YCBCR;
 
532
                        TIFFWarningExt(tif->tif_clientdata, "TIFFReadDirectory",
 
533
                        "Photometric tag value assumed incorrect, "
 
534
                        "assuming data is YCbCr instead of RGB");
 
535
                }
 
536
                if (!TIFFFieldSet(tif,FIELD_BITSPERSAMPLE))
 
537
                {
 
538
                        TIFFWarningExt(tif->tif_clientdata,"TIFFReadDirectory",
 
539
                "BitsPerSample tag is missing, assuming 8 bits per sample");
 
540
                        if (!TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,8))
 
541
                                goto bad;
 
542
                }
 
543
                if (!TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL))
 
544
                {
 
545
                        if ((td->td_photometric==PHOTOMETRIC_RGB)
 
546
                            || (td->td_photometric==PHOTOMETRIC_YCBCR))
 
547
                        {
 
548
                                TIFFWarningExt(tif->tif_clientdata,
 
549
                                               "TIFFReadDirectory",
 
550
                                "SamplesPerPixel tag is missing, "
 
551
                                "assuming correct SamplesPerPixel value is 3");
 
552
                                if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3))
 
553
                                        goto bad;
 
554
                        }
 
555
                        else if ((td->td_photometric==PHOTOMETRIC_MINISWHITE)
 
556
                                 || (td->td_photometric==PHOTOMETRIC_MINISBLACK))
 
557
                        {
 
558
                                TIFFWarningExt(tif->tif_clientdata,
 
559
                                               "TIFFReadDirectory",
 
560
                                "SamplesPerPixel tag is missing, "
 
561
                                "assuming correct SamplesPerPixel value is 1");
 
562
                                if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,1))
 
563
                                        goto bad;
 
564
                        }
 
565
                }
 
566
        }
 
567
        /*
 
568
         * Verify Palette image has a Colormap.
 
569
         */
 
570
        if (td->td_photometric == PHOTOMETRIC_PALETTE &&
 
571
            !TIFFFieldSet(tif, FIELD_COLORMAP)) {
 
572
                MissingRequired(tif, "Colormap");
 
573
                goto bad;
 
574
        }
 
575
        /*
 
576
         * OJPEG hack:
 
577
         * We do no further messing with strip/tile offsets/bytecounts in OJPEG
 
578
         * TIFFs
 
579
         */
 
580
        if (td->td_compression!=COMPRESSION_OJPEG)
 
581
        {
 
582
                /*
 
583
                 * Attempt to deal with a missing StripByteCounts tag.
 
584
                 */
 
585
                if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
 
586
                        /*
 
587
                         * Some manufacturers violate the spec by not giving
 
588
                         * the size of the strips.  In this case, assume there
 
589
                         * is one uncompressed strip of data.
 
590
                         */
 
591
                        if ((td->td_planarconfig == PLANARCONFIG_CONTIG &&
 
592
                            td->td_nstrips > 1) ||
 
593
                            (td->td_planarconfig == PLANARCONFIG_SEPARATE &&
 
594
                             td->td_nstrips != td->td_samplesperpixel)) {
 
595
                            MissingRequired(tif, "StripByteCounts");
 
596
                            goto bad;
 
597
                        }
 
598
                        TIFFWarningExt(tif->tif_clientdata, module,
 
599
                                "%s: TIFF directory is missing required "
 
600
                                "\"%s\" field, calculating from imagelength",
 
601
                                tif->tif_name,
 
602
                                _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name);
 
603
                        if (EstimateStripByteCounts(tif, dir, dircount) < 0)
 
604
                            goto bad;
 
605
                /*
 
606
                 * Assume we have wrong StripByteCount value (in case
 
607
                 * of single strip) in following cases:
 
608
                 *   - it is equal to zero along with StripOffset;
 
609
                 *   - it is larger than file itself (in case of uncompressed
 
610
                 *     image);
 
611
                 *   - it is smaller than the size of the bytes per row
 
612
                 *     multiplied on the number of rows.  The last case should
 
613
                 *     not be checked in the case of writing new image,
 
614
                 *     because we may do not know the exact strip size
 
615
                 *     until the whole image will be written and directory
 
616
                 *     dumped out.
 
617
                 */
 
618
                #define BYTECOUNTLOOKSBAD \
 
619
                    ( (td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \
 
620
                      (td->td_compression == COMPRESSION_NONE && \
 
621
                       td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]) || \
 
622
                      (tif->tif_mode == O_RDONLY && \
 
623
                       td->td_compression == COMPRESSION_NONE && \
 
624
                       td->td_stripbytecount[0] < TIFFScanlineSize(tif) * td->td_imagelength) )
 
625
 
 
626
                } else if (td->td_nstrips == 1
 
627
                           && td->td_stripoffset[0] != 0
 
628
                           && BYTECOUNTLOOKSBAD) {
 
629
                        /*
 
630
                         * XXX: Plexus (and others) sometimes give a value of
 
631
                         * zero for a tag when they don't know what the
 
632
                         * correct value is!  Try and handle the simple case
 
633
                         * of estimating the size of a one strip image.
 
634
                         */
 
635
                        TIFFWarningExt(tif->tif_clientdata, module,
 
636
        "%s: Bogus \"%s\" field, ignoring and calculating from imagelength",
 
637
                                    tif->tif_name,
 
638
                                    _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name);
 
639
                        if(EstimateStripByteCounts(tif, dir, dircount) < 0)
 
640
                            goto bad;
 
641
                } else if (td->td_planarconfig == PLANARCONFIG_CONTIG
 
642
                           && td->td_nstrips > 2
 
643
                           && td->td_compression == COMPRESSION_NONE
 
644
                           && td->td_stripbytecount[0] != td->td_stripbytecount[1]
 
645
                           && td->td_stripbytecount[0] != 0 
 
646
                           && td->td_stripbytecount[1] != 0 ) {
 
647
                        /*
 
648
                         * XXX: Some vendors fill StripByteCount array with 
 
649
                         * absolutely wrong values (it can be equal to 
 
650
                         * StripOffset array, for example). Catch this case 
 
651
                         * here.
 
652
                         */
 
653
                        TIFFWarningExt(tif->tif_clientdata, module,
 
654
        "%s: Wrong \"%s\" field, ignoring and calculating from imagelength",
 
655
                                    tif->tif_name,
 
656
                                    _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name);
 
657
                        if (EstimateStripByteCounts(tif, dir, dircount) < 0)
 
658
                            goto bad;
 
659
                }
 
660
        }
 
661
        if (dir) {
 
662
                _TIFFfree((char *)dir);
 
663
                dir = NULL;
 
664
        }
 
665
        if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
 
666
                td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1);
 
667
        /*
 
668
         * Setup default compression scheme.
 
669
         */
 
670
 
 
671
        /*
 
672
         * XXX: We can optimize checking for the strip bounds using the sorted
 
673
         * bytecounts array. See also comments for TIFFAppendToStrip()
 
674
         * function in tif_write.c.
 
675
         */
 
676
        if (td->td_nstrips > 1) {
 
677
                tstrip_t strip;
 
678
 
 
679
                td->td_stripbytecountsorted = 1;
 
680
                for (strip = 1; strip < td->td_nstrips; strip++) {
 
681
                        if (td->td_stripoffset[strip - 1] >
 
682
                            td->td_stripoffset[strip]) {
 
683
                                td->td_stripbytecountsorted = 0;
 
684
                                break;
 
685
                        }
 
686
                }
 
687
        }
 
688
 
 
689
        if (!TIFFFieldSet(tif, FIELD_COMPRESSION))
 
690
                TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
 
691
        /*
 
692
         * Some manufacturers make life difficult by writing
 
693
         * large amounts of uncompressed data as a single strip.
 
694
         * This is contrary to the recommendations of the spec.
 
695
         * The following makes an attempt at breaking such images
 
696
         * into strips closer to the recommended 8k bytes.  A
 
697
         * side effect, however, is that the RowsPerStrip tag
 
698
         * value may be changed.
 
699
         */
 
700
        if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE &&
 
701
            (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP)
 
702
                ChopUpSingleUncompressedStrip(tif);
 
703
 
 
704
        /*
 
705
         * Reinitialize i/o since we are starting on a new directory.
 
706
         */
 
707
        tif->tif_row = (uint32) -1;
 
708
        tif->tif_curstrip = (tstrip_t) -1;
 
709
        tif->tif_col = (uint32) -1;
 
710
        tif->tif_curtile = (ttile_t) -1;
 
711
        tif->tif_tilesize = (tsize_t) -1;
 
712
 
 
713
        tif->tif_scanlinesize = TIFFScanlineSize(tif);
 
714
        if (!tif->tif_scanlinesize) {
 
715
                TIFFErrorExt(tif->tif_clientdata, module,
 
716
                             "%s: cannot handle zero scanline size",
 
717
                             tif->tif_name);
 
718
                return (0);
 
719
        }
 
720
 
 
721
        if (isTiled(tif)) {
 
722
                tif->tif_tilesize = TIFFTileSize(tif);
 
723
                if (!tif->tif_tilesize) {
 
724
                        TIFFErrorExt(tif->tif_clientdata, module,
 
725
                                     "%s: cannot handle zero tile size",
 
726
                                     tif->tif_name);
 
727
                        return (0);
 
728
                }
 
729
        } else {
 
730
                if (!TIFFStripSize(tif)) {
 
731
                        TIFFErrorExt(tif->tif_clientdata, module,
 
732
                                     "%s: cannot handle zero strip size",
 
733
                                     tif->tif_name);
 
734
                        return (0);
 
735
                }
 
736
        }
 
737
        return (1);
 
738
bad:
 
739
        if (dir)
 
740
                _TIFFfree(dir);
 
741
        return (0);
 
742
}
 
743
 
 
744
static TIFFDirEntry*
 
745
TIFFReadDirectoryFind(TIFFDirEntry* dir, uint16 dircount, uint16 tagid)
 
746
{
 
747
        TIFFDirEntry* m;
 
748
        uint16 n;
 
749
        for (m=dir, n=0; n<dircount; m++, n++)
 
750
        {
 
751
                if (m->tdir_tag==tagid)
 
752
                        return(m);
 
753
        }
 
754
        return(0);
 
755
}
 
756
 
 
757
/*
 
758
 * Read custom directory from the arbitarry offset.
 
759
 * The code is very similar to TIFFReadDirectory().
 
760
 */
 
761
int
 
762
TIFFReadCustomDirectory(TIFF* tif, toff_t diroff,
 
763
                        const TIFFFieldInfo info[], size_t n)
 
764
{
 
765
        static const char module[] = "TIFFReadCustomDirectory";
 
766
 
 
767
        TIFFDirectory* td = &tif->tif_dir;
 
768
        TIFFDirEntry *dp, *dir = NULL;
 
769
        const TIFFFieldInfo* fip;
 
770
        size_t fix;
 
771
        uint16 i, dircount;
 
772
 
 
773
        _TIFFSetupFieldInfo(tif, info, n);
 
774
 
 
775
        dircount = TIFFFetchDirectory(tif, diroff, &dir, NULL);
 
776
        if (!dircount) {
 
777
                TIFFErrorExt(tif->tif_clientdata, module,
 
778
                        "%s: Failed to read custom directory at offset %u",
 
779
                             tif->tif_name, diroff);
 
780
                return 0;
 
781
        }
 
782
 
 
783
        TIFFFreeDirectory(tif);
 
784
        _TIFFmemset(&tif->tif_dir, 0, sizeof(TIFFDirectory));
 
785
 
 
786
        fix = 0;
 
787
        for (dp = dir, i = dircount; i > 0; i--, dp++) {
 
788
                if (tif->tif_flags & TIFF_SWAB) {
 
789
                        TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
 
790
                        TIFFSwabArrayOfLong(&dp->tdir_count, 2);
 
791
                }
 
792
 
 
793
                if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE)
 
794
                        continue;
 
795
 
 
796
                while (fix < tif->tif_nfields &&
 
797
                       tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag)
 
798
                        fix++;
 
799
 
 
800
                if (fix >= tif->tif_nfields ||
 
801
                    tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) {
 
802
 
 
803
                        TIFFWarningExt(tif->tif_clientdata, module,
 
804
                        "%s: unknown field with tag %d (0x%x) encountered",
 
805
                                    tif->tif_name, dp->tdir_tag, dp->tdir_tag);
 
806
                        if (!_TIFFMergeFieldInfo(tif,
 
807
                                                 _TIFFCreateAnonFieldInfo(tif,
 
808
                                                 dp->tdir_tag,
 
809
                                                 (TIFFDataType) dp->tdir_type),
 
810
                                                 1))
 
811
                        {
 
812
                                TIFFWarningExt(tif->tif_clientdata, module,
 
813
                        "Registering anonymous field with tag %d (0x%x) failed",
 
814
                                                dp->tdir_tag, dp->tdir_tag);
 
815
                                goto ignore;
 
816
                        }
 
817
 
 
818
                        fix = 0;
 
819
                        while (fix < tif->tif_nfields &&
 
820
                               tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag)
 
821
                                fix++;
 
822
                }
 
823
                /*
 
824
                 * Null out old tags that we ignore.
 
825
                 */
 
826
                if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) {
 
827
        ignore:
 
828
                        dp->tdir_tag = IGNORE;
 
829
                        continue;
 
830
                }
 
831
                /*
 
832
                 * Check data type.
 
833
                 */
 
834
                fip = tif->tif_fieldinfo[fix];
 
835
                while (dp->tdir_type != (unsigned short) fip->field_type
 
836
                       && fix < tif->tif_nfields) {
 
837
                        if (fip->field_type == TIFF_ANY)        /* wildcard */
 
838
                                break;
 
839
                        fip = tif->tif_fieldinfo[++fix];
 
840
                        if (fix >= tif->tif_nfields ||
 
841
                            fip->field_tag != dp->tdir_tag) {
 
842
                                TIFFWarningExt(tif->tif_clientdata, module,
 
843
                        "%s: wrong data type %d for \"%s\"; tag ignored",
 
844
                                            tif->tif_name, dp->tdir_type,
 
845
                                            tif->tif_fieldinfo[fix-1]->field_name);
 
846
                                goto ignore;
 
847
                        }
 
848
                }
 
849
                /*
 
850
                 * Check count if known in advance.
 
851
                 */
 
852
                if (fip->field_readcount != TIFF_VARIABLE
 
853
                    && fip->field_readcount != TIFF_VARIABLE2) {
 
854
                        uint32 expected = (fip->field_readcount == TIFF_SPP) ?
 
855
                            (uint32) td->td_samplesperpixel :
 
856
                            (uint32) fip->field_readcount;
 
857
                        if (!CheckDirCount(tif, dp, expected))
 
858
                                goto ignore;
 
859
                }
 
860
 
 
861
                /*
 
862
                 * EXIF tags which need to be specifically processed.
 
863
                 */
 
864
                switch (dp->tdir_tag) {
 
865
                        case EXIFTAG_SUBJECTDISTANCE:
 
866
                                (void) TIFFFetchSubjectDistance(tif, dp);
 
867
                                break;
 
868
                        default:
 
869
                                (void) TIFFFetchNormalTag(tif, dp);
 
870
                                break;
 
871
                }
 
872
        }
 
873
        
 
874
        if (dir)
 
875
                _TIFFfree(dir);
 
876
        return 1;
 
877
}
 
878
 
 
879
/*
 
880
 * EXIF is important special case of custom IFD, so we have a special
 
881
 * function to read it.
 
882
 */
 
883
int
 
884
TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff)
 
885
{
 
886
        size_t exifFieldInfoCount;
 
887
        const TIFFFieldInfo *exifFieldInfo =
 
888
                _TIFFGetExifFieldInfo(&exifFieldInfoCount);
 
889
        return TIFFReadCustomDirectory(tif, diroff, exifFieldInfo,
 
890
                                       exifFieldInfoCount);
 
891
}
 
892
 
 
893
static int
 
894
EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount)
 
895
{
 
896
        static const char module[] = "EstimateStripByteCounts";
 
897
 
 
898
        TIFFDirEntry *dp;
 
899
        TIFFDirectory *td = &tif->tif_dir;
 
900
        uint32 strip;
 
901
 
 
902
        if (td->td_stripbytecount)
 
903
                _TIFFfree(td->td_stripbytecount);
 
904
        td->td_stripbytecount = (uint32*)
 
905
            _TIFFCheckMalloc(tif, td->td_nstrips, sizeof (uint32),
 
906
                "for \"StripByteCounts\" array");
 
907
        if( td->td_stripbytecount == NULL )
 
908
            return -1;
 
909
 
 
910
        if (td->td_compression != COMPRESSION_NONE) {
 
911
                uint32 space = (uint32)(sizeof (TIFFHeader)
 
912
                    + sizeof (uint16)
 
913
                    + (dircount * sizeof (TIFFDirEntry))
 
914
                    + sizeof (uint32));
 
915
                toff_t filesize = TIFFGetFileSize(tif);
 
916
                uint16 n;
 
917
 
 
918
                /* calculate amount of space used by indirect values */
 
919
                for (dp = dir, n = dircount; n > 0; n--, dp++)
 
920
                {
 
921
                        uint32 cc = TIFFDataWidth((TIFFDataType) dp->tdir_type);
 
922
                        if (cc == 0) {
 
923
                                TIFFErrorExt(tif->tif_clientdata, module,
 
924
                        "%s: Cannot determine size of unknown tag type %d",
 
925
                                          tif->tif_name, dp->tdir_type);
 
926
                                return -1;
 
927
                        }
 
928
                        cc = cc * dp->tdir_count;
 
929
                        if (cc > sizeof (uint32))
 
930
                                space += cc;
 
931
                }
 
932
                space = filesize - space;
 
933
                if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
 
934
                        space /= td->td_samplesperpixel;
 
935
                for (strip = 0; strip < td->td_nstrips; strip++)
 
936
                        td->td_stripbytecount[strip] = space;
 
937
                /*
 
938
                 * This gross hack handles the case were the offset to
 
939
                 * the last strip is past the place where we think the strip
 
940
                 * should begin.  Since a strip of data must be contiguous,
 
941
                 * it's safe to assume that we've overestimated the amount
 
942
                 * of data in the strip and trim this number back accordingly.
 
943
                 */ 
 
944
                strip--;
 
945
                if (((toff_t)(td->td_stripoffset[strip]+
 
946
                              td->td_stripbytecount[strip])) > filesize)
 
947
                        td->td_stripbytecount[strip] =
 
948
                            filesize - td->td_stripoffset[strip];
 
949
        } else if (isTiled(tif)) {
 
950
                uint32 bytespertile = TIFFTileSize(tif);
 
951
 
 
952
                for (strip = 0; strip < td->td_nstrips; strip++)
 
953
                    td->td_stripbytecount[strip] = bytespertile;
 
954
        } else {
 
955
                uint32 rowbytes = TIFFScanlineSize(tif);
 
956
                uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage;
 
957
                for (strip = 0; strip < td->td_nstrips; strip++)
 
958
                        td->td_stripbytecount[strip] = rowbytes * rowsperstrip;
 
959
        }
 
960
        TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
 
961
        if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
 
962
                td->td_rowsperstrip = td->td_imagelength;
 
963
        return 1;
 
964
}
 
965
 
 
966
static void
 
967
MissingRequired(TIFF* tif, const char* tagname)
 
968
{
 
969
        static const char module[] = "MissingRequired";
 
970
 
 
971
        TIFFErrorExt(tif->tif_clientdata, module,
 
972
                  "%s: TIFF directory is missing required \"%s\" field",
 
973
                  tif->tif_name, tagname);
 
974
}
 
975
 
 
976
/*
 
977
 * Check the directory offset against the list of already seen directory
 
978
 * offsets. This is a trick to prevent IFD looping. The one can create TIFF
 
979
 * file with looped directory pointers. We will maintain a list of already
 
980
 * seen directories and check every IFD offset against that list.
 
981
 */
 
982
static int
 
983
TIFFCheckDirOffset(TIFF* tif, toff_t diroff)
 
984
{
 
985
        uint16 n;
 
986
 
 
987
        if (diroff == 0)                        /* no more directories */
 
988
                return 0;
 
989
 
 
990
        for (n = 0; n < tif->tif_dirnumber && tif->tif_dirlist; n++) {
 
991
                if (tif->tif_dirlist[n] == diroff)
 
992
                        return 0;
 
993
        }
 
994
 
 
995
        tif->tif_dirnumber++;
 
996
 
 
997
        if (tif->tif_dirnumber > tif->tif_dirlistsize) {
 
998
                toff_t* new_dirlist;
 
999
 
 
1000
                /*
 
1001
                 * XXX: Reduce memory allocation granularity of the dirlist
 
1002
                 * array.
 
1003
                 */
 
1004
                new_dirlist = (toff_t *)_TIFFCheckRealloc(tif,
 
1005
                                                          tif->tif_dirlist,
 
1006
                                                          tif->tif_dirnumber,
 
1007
                                                          2 * sizeof(toff_t),
 
1008
                                                          "for IFD list");
 
1009
                if (!new_dirlist)
 
1010
                        return 0;
 
1011
                tif->tif_dirlistsize = 2 * tif->tif_dirnumber;
 
1012
                tif->tif_dirlist = new_dirlist;
 
1013
        }
 
1014
 
 
1015
        tif->tif_dirlist[tif->tif_dirnumber - 1] = diroff;
 
1016
 
 
1017
        return 1;
 
1018
}
 
1019
 
 
1020
/*
 
1021
 * Check the count field of a directory entry against a known value.  The
 
1022
 * caller is expected to skip/ignore the tag if there is a mismatch.
 
1023
 */
 
1024
static int
 
1025
CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count)
 
1026
{
 
1027
        if (count > dir->tdir_count) {
 
1028
                TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
 
1029
        "incorrect count for field \"%s\" (%u, expecting %u); tag ignored",
 
1030
                    _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name,
 
1031
                    dir->tdir_count, count);
 
1032
                return (0);
 
1033
        } else if (count < dir->tdir_count) {
 
1034
                TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
 
1035
        "incorrect count for field \"%s\" (%u, expecting %u); tag trimmed",
 
1036
                    _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name,
 
1037
                    dir->tdir_count, count);
 
1038
                return (1);
 
1039
        }
 
1040
        return (1);
 
1041
}
 
1042
 
 
1043
/*
 
1044
 * Read IFD structure from the specified offset. If the pointer to
 
1045
 * nextdiroff variable has been specified, read it too. Function returns a
 
1046
 * number of fields in the directory or 0 if failed.
 
1047
 */
 
1048
static uint16
 
1049
TIFFFetchDirectory(TIFF* tif, toff_t diroff, TIFFDirEntry **pdir,
 
1050
                   toff_t *nextdiroff)
 
1051
{
 
1052
        static const char module[] = "TIFFFetchDirectory";
 
1053
 
 
1054
        TIFFDirEntry *dir;
 
1055
        uint16 dircount;
 
1056
 
 
1057
        assert(pdir);
 
1058
 
 
1059
        tif->tif_diroff = diroff;
 
1060
        if (nextdiroff)
 
1061
                *nextdiroff = 0;
 
1062
        if (!isMapped(tif)) {
 
1063
                if (!SeekOK(tif, tif->tif_diroff)) {
 
1064
                        TIFFErrorExt(tif->tif_clientdata, module,
 
1065
                                "%s: Seek error accessing TIFF directory",
 
1066
                                tif->tif_name);
 
1067
                        return 0;
 
1068
                }
 
1069
                if (!ReadOK(tif, &dircount, sizeof (uint16))) {
 
1070
                        TIFFErrorExt(tif->tif_clientdata, module,
 
1071
                                "%s: Can not read TIFF directory count",
 
1072
                                tif->tif_name);
 
1073
                        return 0;
 
1074
                }
 
1075
                if (tif->tif_flags & TIFF_SWAB)
 
1076
                        TIFFSwabShort(&dircount);
 
1077
                dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount,
 
1078
                                                sizeof (TIFFDirEntry),
 
1079
                                                "to read TIFF directory");
 
1080
                if (dir == NULL)
 
1081
                        return 0;
 
1082
                if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) {
 
1083
                        TIFFErrorExt(tif->tif_clientdata, module,
 
1084
                                "%.100s: Can not read TIFF directory",
 
1085
                                tif->tif_name);
 
1086
                        _TIFFfree(dir);
 
1087
                        return 0;
 
1088
                }
 
1089
                /*
 
1090
                 * Read offset to next directory for sequential scans if
 
1091
                 * needed.
 
1092
                 */
 
1093
                if (nextdiroff)
 
1094
                        (void) ReadOK(tif, nextdiroff, sizeof(uint32));
 
1095
        } else {
 
1096
                toff_t off = tif->tif_diroff;
 
1097
 
 
1098
                /*
 
1099
                 * Check for integer overflow when validating the dir_off,
 
1100
                 * otherwise a very high offset may cause an OOB read and
 
1101
                 * crash the client. Make two comparisons instead of
 
1102
                 *
 
1103
                 *  off + sizeof(uint16) > tif->tif_size
 
1104
                 *
 
1105
                 * to avoid overflow.
 
1106
                 */
 
1107
                if (tif->tif_size < sizeof (uint16) ||
 
1108
                    off > tif->tif_size - sizeof(uint16)) {
 
1109
                        TIFFErrorExt(tif->tif_clientdata, module,
 
1110
                                "%s: Can not read TIFF directory count",
 
1111
                                tif->tif_name);
 
1112
                        return 0;
 
1113
                } else {
 
1114
                        _TIFFmemcpy(&dircount, tif->tif_base + off,
 
1115
                                    sizeof(uint16));
 
1116
                }
 
1117
                off += sizeof (uint16);
 
1118
                if (tif->tif_flags & TIFF_SWAB)
 
1119
                        TIFFSwabShort(&dircount);
 
1120
                dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount,
 
1121
                                                sizeof(TIFFDirEntry),
 
1122
                                                "to read TIFF directory");
 
1123
                if (dir == NULL)
 
1124
                        return 0;
 
1125
                if (off + dircount * sizeof (TIFFDirEntry) > tif->tif_size) {
 
1126
                        TIFFErrorExt(tif->tif_clientdata, module,
 
1127
                                     "%s: Can not read TIFF directory",
 
1128
                                     tif->tif_name);
 
1129
                        _TIFFfree(dir);
 
1130
                        return 0;
 
1131
                } else {
 
1132
                        _TIFFmemcpy(dir, tif->tif_base + off,
 
1133
                                    dircount * sizeof(TIFFDirEntry));
 
1134
                }
 
1135
                if (nextdiroff) {
 
1136
                        off += dircount * sizeof (TIFFDirEntry);
 
1137
                        if (off + sizeof (uint32) <= tif->tif_size) {
 
1138
                                _TIFFmemcpy(nextdiroff, tif->tif_base + off,
 
1139
                                            sizeof (uint32));
 
1140
                        }
 
1141
                }
 
1142
        }
 
1143
        if (nextdiroff && tif->tif_flags & TIFF_SWAB)
 
1144
                TIFFSwabLong(nextdiroff);
 
1145
        *pdir = dir;
 
1146
        return dircount;
 
1147
}
 
1148
 
 
1149
/*
 
1150
 * Fetch a contiguous directory item.
 
1151
 */
 
1152
static tsize_t
 
1153
TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp)
 
1154
{
 
1155
        uint32 w = TIFFDataWidth((TIFFDataType) dir->tdir_type);
 
1156
        /* 
 
1157
         * FIXME: butecount should have tsize_t type, but for now libtiff
 
1158
         * defines tsize_t as a signed 32-bit integer and we are losing
 
1159
         * ability to read arrays larger than 2^31 bytes. So we are using
 
1160
         * uint32 instead of tsize_t here.
 
1161
         */
 
1162
        uint32 cc = dir->tdir_count * w;
 
1163
 
 
1164
        /* Check for overflow. */
 
1165
        if (!dir->tdir_count || !w || cc / w != dir->tdir_count)
 
1166
                goto bad;
 
1167
 
 
1168
        if (!isMapped(tif)) {
 
1169
                if (!SeekOK(tif, dir->tdir_offset))
 
1170
                        goto bad;
 
1171
                if (!ReadOK(tif, cp, cc))
 
1172
                        goto bad;
 
1173
        } else {
 
1174
                /* Check for overflow. */
 
1175
                if (dir->tdir_offset + cc < dir->tdir_offset
 
1176
                    || dir->tdir_offset + cc < cc
 
1177
                    || dir->tdir_offset + cc > tif->tif_size)
 
1178
                        goto bad;
 
1179
                _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc);
 
1180
        }
 
1181
        if (tif->tif_flags & TIFF_SWAB) {
 
1182
                switch (dir->tdir_type) {
 
1183
                case TIFF_SHORT:
 
1184
                case TIFF_SSHORT:
 
1185
                        TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count);
 
1186
                        break;
 
1187
                case TIFF_LONG:
 
1188
                case TIFF_SLONG:
 
1189
                case TIFF_FLOAT:
 
1190
                        TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count);
 
1191
                        break;
 
1192
                case TIFF_RATIONAL:
 
1193
                case TIFF_SRATIONAL:
 
1194
                        TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count);
 
1195
                        break;
 
1196
                case TIFF_DOUBLE:
 
1197
                        TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count);
 
1198
                        break;
 
1199
                }
 
1200
        }
 
1201
        return (cc);
 
1202
bad:
 
1203
        TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 
1204
                     "Error fetching data for field \"%s\"",
 
1205
                     _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
 
1206
        return (tsize_t) 0;
 
1207
}
 
1208
 
 
1209
/*
 
1210
 * Fetch an ASCII item from the file.
 
1211
 */
 
1212
static tsize_t
 
1213
TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp)
 
1214
{
 
1215
        if (dir->tdir_count <= 4) {
 
1216
                uint32 l = dir->tdir_offset;
 
1217
                if (tif->tif_flags & TIFF_SWAB)
 
1218
                        TIFFSwabLong(&l);
 
1219
                _TIFFmemcpy(cp, &l, dir->tdir_count);
 
1220
                return (1);
 
1221
        }
 
1222
        return (TIFFFetchData(tif, dir, cp));
 
1223
}
 
1224
 
 
1225
/*
 
1226
 * Convert numerator+denominator to float.
 
1227
 */
 
1228
static int
 
1229
cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv)
 
1230
{
 
1231
        if (denom == 0) {
 
1232
                TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 
1233
                    "%s: Rational with zero denominator (num = %u)",
 
1234
                    _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num);
 
1235
                return (0);
 
1236
        } else {
 
1237
                if (dir->tdir_type == TIFF_RATIONAL)
 
1238
                        *rv = ((float)num / (float)denom);
 
1239
                else
 
1240
                        *rv = ((float)(int32)num / (float)(int32)denom);
 
1241
                return (1);
 
1242
        }
 
1243
}
 
1244
 
 
1245
/*
 
1246
 * Fetch a rational item from the file at offset off and return the value as a
 
1247
 * floating point number.
 
1248
 */
 
1249
static float
 
1250
TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir)
 
1251
{
 
1252
        uint32 l[2];
 
1253
        float v;
 
1254
 
 
1255
        return (!TIFFFetchData(tif, dir, (char *)l) ||
 
1256
            !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v);
 
1257
}
 
1258
 
 
1259
/*
 
1260
 * Fetch a single floating point value from the offset field and return it as
 
1261
 * a native float.
 
1262
 */
 
1263
static float
 
1264
TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir)
 
1265
{
 
1266
        float v;
 
1267
        int32 l = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset);
 
1268
        _TIFFmemcpy(&v, &l, sizeof(float));
 
1269
        TIFFCvtIEEEFloatToNative(tif, 1, &v);
 
1270
        return (v);
 
1271
}
 
1272
 
 
1273
/*
 
1274
 * Fetch an array of BYTE or SBYTE values.
 
1275
 */
 
1276
static int
 
1277
TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint8* v)
 
1278
{
 
1279
    if (dir->tdir_count <= 4) {
 
1280
        /*
 
1281
         * Extract data from offset field.
 
1282
         */
 
1283
        if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
 
1284
            if (dir->tdir_type == TIFF_SBYTE)
 
1285
                switch (dir->tdir_count) {
 
1286
                    case 4: v[3] = dir->tdir_offset & 0xff;
 
1287
                    case 3: v[2] = (dir->tdir_offset >> 8) & 0xff;
 
1288
                    case 2: v[1] = (dir->tdir_offset >> 16) & 0xff;
 
1289
                    case 1: v[0] = dir->tdir_offset >> 24;
 
1290
                }
 
1291
            else
 
1292
                switch (dir->tdir_count) {
 
1293
                    case 4: v[3] = dir->tdir_offset & 0xff;
 
1294
                    case 3: v[2] = (dir->tdir_offset >> 8) & 0xff;
 
1295
                    case 2: v[1] = (dir->tdir_offset >> 16) & 0xff;
 
1296
                    case 1: v[0] = dir->tdir_offset >> 24;
 
1297
                }
 
1298
        } else {
 
1299
            if (dir->tdir_type == TIFF_SBYTE)
 
1300
                switch (dir->tdir_count) {
 
1301
                    case 4: v[3] = dir->tdir_offset >> 24;
 
1302
                    case 3: v[2] = (dir->tdir_offset >> 16) & 0xff;
 
1303
                    case 2: v[1] = (dir->tdir_offset >> 8) & 0xff;
 
1304
                    case 1: v[0] = dir->tdir_offset & 0xff;
 
1305
                }
 
1306
            else
 
1307
                switch (dir->tdir_count) {
 
1308
                    case 4: v[3] = dir->tdir_offset >> 24;
 
1309
                    case 3: v[2] = (dir->tdir_offset >> 16) & 0xff;
 
1310
                    case 2: v[1] = (dir->tdir_offset >> 8) & 0xff;
 
1311
                    case 1: v[0] = dir->tdir_offset & 0xff;
 
1312
                }
 
1313
        }
 
1314
        return (1);
 
1315
    } else
 
1316
        return (TIFFFetchData(tif, dir, (char*) v) != 0);       /* XXX */
 
1317
}
 
1318
 
 
1319
/*
 
1320
 * Fetch an array of SHORT or SSHORT values.
 
1321
 */
 
1322
static int
 
1323
TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v)
 
1324
{
 
1325
        if (dir->tdir_count <= 2) {
 
1326
                if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
 
1327
                        switch (dir->tdir_count) {
 
1328
                        case 2: v[1] = (uint16) (dir->tdir_offset & 0xffff);
 
1329
                        case 1: v[0] = (uint16) (dir->tdir_offset >> 16);
 
1330
                        }
 
1331
                } else {
 
1332
                        switch (dir->tdir_count) {
 
1333
                        case 2: v[1] = (uint16) (dir->tdir_offset >> 16);
 
1334
                        case 1: v[0] = (uint16) (dir->tdir_offset & 0xffff);
 
1335
                        }
 
1336
                }
 
1337
                return (1);
 
1338
        } else
 
1339
                return (TIFFFetchData(tif, dir, (char *)v) != 0);
 
1340
}
 
1341
 
 
1342
/*
 
1343
 * Fetch a pair of SHORT or BYTE values. Some tags may have either BYTE
 
1344
 * or SHORT type and this function works with both ones.
 
1345
 */
 
1346
static int
 
1347
TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir)
 
1348
{
 
1349
        /*
 
1350
         * Prevent overflowing the v stack arrays below by performing a sanity
 
1351
         * check on tdir_count, this should never be greater than two.
 
1352
         */
 
1353
        if (dir->tdir_count > 2) {
 
1354
                TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
 
1355
                "unexpected count for field \"%s\", %u, expected 2; ignored",
 
1356
                        _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name,
 
1357
                        dir->tdir_count);
 
1358
                return 0;
 
1359
        }
 
1360
 
 
1361
        switch (dir->tdir_type) {
 
1362
                case TIFF_BYTE:
 
1363
                case TIFF_SBYTE:
 
1364
                        {
 
1365
                        uint8 v[4];
 
1366
                        return TIFFFetchByteArray(tif, dir, v)
 
1367
                                && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]);
 
1368
                        }
 
1369
                case TIFF_SHORT:
 
1370
                case TIFF_SSHORT:
 
1371
                        {
 
1372
                        uint16 v[2];
 
1373
                        return TIFFFetchShortArray(tif, dir, v)
 
1374
                                && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]);
 
1375
                        }
 
1376
                default:
 
1377
                        return 0;
 
1378
        }
 
1379
}
 
1380
 
 
1381
/*
 
1382
 * Fetch an array of LONG or SLONG values.
 
1383
 */
 
1384
static int
 
1385
TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v)
 
1386
{
 
1387
        if (dir->tdir_count == 1) {
 
1388
                v[0] = dir->tdir_offset;
 
1389
                return (1);
 
1390
        } else
 
1391
                return (TIFFFetchData(tif, dir, (char*) v) != 0);
 
1392
}
 
1393
 
 
1394
/*
 
1395
 * Fetch an array of RATIONAL or SRATIONAL values.
 
1396
 */
 
1397
static int
 
1398
TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v)
 
1399
{
 
1400
        int ok = 0;
 
1401
        uint32* l;
 
1402
 
 
1403
        l = (uint32*)_TIFFCheckMalloc(tif,
 
1404
            dir->tdir_count, TIFFDataWidth((TIFFDataType) dir->tdir_type),
 
1405
            "to fetch array of rationals");
 
1406
        if (l) {
 
1407
                if (TIFFFetchData(tif, dir, (char *)l)) {
 
1408
                        uint32 i;
 
1409
                        for (i = 0; i < dir->tdir_count; i++) {
 
1410
                                ok = cvtRational(tif, dir,
 
1411
                                    l[2*i+0], l[2*i+1], &v[i]);
 
1412
                                if (!ok)
 
1413
                                        break;
 
1414
                        }
 
1415
                }
 
1416
                _TIFFfree((char *)l);
 
1417
        }
 
1418
        return (ok);
 
1419
}
 
1420
 
 
1421
/*
 
1422
 * Fetch an array of FLOAT values.
 
1423
 */
 
1424
static int
 
1425
TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v)
 
1426
{
 
1427
 
 
1428
        if (dir->tdir_count == 1) {
 
1429
                v[0] = *(float*) &dir->tdir_offset;
 
1430
                TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v);
 
1431
                return (1);
 
1432
        } else  if (TIFFFetchData(tif, dir, (char*) v)) {
 
1433
                TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v);
 
1434
                return (1);
 
1435
        } else
 
1436
                return (0);
 
1437
}
 
1438
 
 
1439
/*
 
1440
 * Fetch an array of DOUBLE values.
 
1441
 */
 
1442
static int
 
1443
TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v)
 
1444
{
 
1445
        if (TIFFFetchData(tif, dir, (char*) v)) {
 
1446
                TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v);
 
1447
                return (1);
 
1448
        } else
 
1449
                return (0);
 
1450
}
 
1451
 
 
1452
/*
 
1453
 * Fetch an array of ANY values.  The actual values are returned as doubles
 
1454
 * which should be able hold all the types.  Yes, there really should be an
 
1455
 * tany_t to avoid this potential non-portability ...  Note in particular that
 
1456
 * we assume that the double return value vector is large enough to read in
 
1457
 * any fundamental type.  We use that vector as a buffer to read in the base
 
1458
 * type vector and then convert it in place to double (from end to front of
 
1459
 * course).
 
1460
 */
 
1461
static int
 
1462
TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v)
 
1463
{
 
1464
        int i;
 
1465
 
 
1466
        switch (dir->tdir_type) {
 
1467
        case TIFF_BYTE:
 
1468
        case TIFF_SBYTE:
 
1469
                if (!TIFFFetchByteArray(tif, dir, (uint8*) v))
 
1470
                        return (0);
 
1471
                if (dir->tdir_type == TIFF_BYTE) {
 
1472
                        uint8* vp = (uint8*) v;
 
1473
                        for (i = dir->tdir_count-1; i >= 0; i--)
 
1474
                                v[i] = vp[i];
 
1475
                } else {
 
1476
                        int8* vp = (int8*) v;
 
1477
                        for (i = dir->tdir_count-1; i >= 0; i--)
 
1478
                                v[i] = vp[i];
 
1479
                }
 
1480
                break;
 
1481
        case TIFF_SHORT:
 
1482
        case TIFF_SSHORT:
 
1483
                if (!TIFFFetchShortArray(tif, dir, (uint16*) v))
 
1484
                        return (0);
 
1485
                if (dir->tdir_type == TIFF_SHORT) {
 
1486
                        uint16* vp = (uint16*) v;
 
1487
                        for (i = dir->tdir_count-1; i >= 0; i--)
 
1488
                                v[i] = vp[i];
 
1489
                } else {
 
1490
                        int16* vp = (int16*) v;
 
1491
                        for (i = dir->tdir_count-1; i >= 0; i--)
 
1492
                                v[i] = vp[i];
 
1493
                }
 
1494
                break;
 
1495
        case TIFF_LONG:
 
1496
        case TIFF_SLONG:
 
1497
                if (!TIFFFetchLongArray(tif, dir, (uint32*) v))
 
1498
                        return (0);
 
1499
                if (dir->tdir_type == TIFF_LONG) {
 
1500
                        uint32* vp = (uint32*) v;
 
1501
                        for (i = dir->tdir_count-1; i >= 0; i--)
 
1502
                                v[i] = vp[i];
 
1503
                } else {
 
1504
                        int32* vp = (int32*) v;
 
1505
                        for (i = dir->tdir_count-1; i >= 0; i--)
 
1506
                                v[i] = vp[i];
 
1507
                }
 
1508
                break;
 
1509
        case TIFF_RATIONAL:
 
1510
        case TIFF_SRATIONAL:
 
1511
                if (!TIFFFetchRationalArray(tif, dir, (float*) v))
 
1512
                        return (0);
 
1513
                { float* vp = (float*) v;
 
1514
                  for (i = dir->tdir_count-1; i >= 0; i--)
 
1515
                        v[i] = vp[i];
 
1516
                }
 
1517
                break;
 
1518
        case TIFF_FLOAT:
 
1519
                if (!TIFFFetchFloatArray(tif, dir, (float*) v))
 
1520
                        return (0);
 
1521
                { float* vp = (float*) v;
 
1522
                  for (i = dir->tdir_count-1; i >= 0; i--)
 
1523
                        v[i] = vp[i];
 
1524
                }
 
1525
                break;
 
1526
        case TIFF_DOUBLE:
 
1527
                return (TIFFFetchDoubleArray(tif, dir, (double*) v));
 
1528
        default:
 
1529
                /* TIFF_NOTYPE */
 
1530
                /* TIFF_ASCII */
 
1531
                /* TIFF_UNDEFINED */
 
1532
                TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 
1533
                             "cannot read TIFF_ANY type %d for field \"%s\"",
 
1534
                             dir->tdir_type,
 
1535
                             _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
 
1536
                return (0);
 
1537
        }
 
1538
        return (1);
 
1539
}
 
1540
 
 
1541
/*
 
1542
 * Fetch a tag that is not handled by special case code.
 
1543
 */
 
1544
static int
 
1545
TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp)
 
1546
{
 
1547
        static const char mesg[] = "to fetch tag value";
 
1548
        int ok = 0;
 
1549
        const TIFFFieldInfo* fip = _TIFFFieldWithTag(tif, dp->tdir_tag);
 
1550
 
 
1551
        if (dp->tdir_count > 1) {               /* array of values */
 
1552
                char* cp = NULL;
 
1553
 
 
1554
                switch (dp->tdir_type) {
 
1555
                case TIFF_BYTE:
 
1556
                case TIFF_SBYTE:
 
1557
                        cp = (char *)_TIFFCheckMalloc(tif,
 
1558
                            dp->tdir_count, sizeof (uint8), mesg);
 
1559
                        ok = cp && TIFFFetchByteArray(tif, dp, (uint8*) cp);
 
1560
                        break;
 
1561
                case TIFF_SHORT:
 
1562
                case TIFF_SSHORT:
 
1563
                        cp = (char *)_TIFFCheckMalloc(tif,
 
1564
                            dp->tdir_count, sizeof (uint16), mesg);
 
1565
                        ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp);
 
1566
                        break;
 
1567
                case TIFF_LONG:
 
1568
                case TIFF_SLONG:
 
1569
                        cp = (char *)_TIFFCheckMalloc(tif,
 
1570
                            dp->tdir_count, sizeof (uint32), mesg);
 
1571
                        ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp);
 
1572
                        break;
 
1573
                case TIFF_RATIONAL:
 
1574
                case TIFF_SRATIONAL:
 
1575
                        cp = (char *)_TIFFCheckMalloc(tif,
 
1576
                            dp->tdir_count, sizeof (float), mesg);
 
1577
                        ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp);
 
1578
                        break;
 
1579
                case TIFF_FLOAT:
 
1580
                        cp = (char *)_TIFFCheckMalloc(tif,
 
1581
                            dp->tdir_count, sizeof (float), mesg);
 
1582
                        ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp);
 
1583
                        break;
 
1584
                case TIFF_DOUBLE:
 
1585
                        cp = (char *)_TIFFCheckMalloc(tif,
 
1586
                            dp->tdir_count, sizeof (double), mesg);
 
1587
                        ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp);
 
1588
                        break;
 
1589
                case TIFF_ASCII:
 
1590
                case TIFF_UNDEFINED:            /* bit of a cheat... */
 
1591
                        /*
 
1592
                         * Some vendors write strings w/o the trailing
 
1593
                         * NULL byte, so always append one just in case.
 
1594
                         */
 
1595
                        cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count + 1,
 
1596
                                                      1, mesg);
 
1597
                        if( (ok = (cp && TIFFFetchString(tif, dp, cp))) != 0 )
 
1598
                                cp[dp->tdir_count] = '\0';      /* XXX */
 
1599
                        break;
 
1600
                }
 
1601
                if (ok) {
 
1602
                        ok = (fip->field_passcount ?
 
1603
                            TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp)
 
1604
                          : TIFFSetField(tif, dp->tdir_tag, cp));
 
1605
                }
 
1606
                if (cp != NULL)
 
1607
                        _TIFFfree(cp);
 
1608
        } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */
 
1609
                switch (dp->tdir_type) {
 
1610
                case TIFF_BYTE:
 
1611
                case TIFF_SBYTE:
 
1612
                case TIFF_SHORT:
 
1613
                case TIFF_SSHORT:
 
1614
                        /*
 
1615
                         * If the tag is also acceptable as a LONG or SLONG
 
1616
                         * then TIFFSetField will expect an uint32 parameter
 
1617
                         * passed to it (through varargs).  Thus, for machines
 
1618
                         * where sizeof (int) != sizeof (uint32) we must do
 
1619
                         * a careful check here.  It's hard to say if this
 
1620
                         * is worth optimizing.
 
1621
                         *
 
1622
                         * NB: We use TIFFFieldWithTag here knowing that
 
1623
                         *     it returns us the first entry in the table
 
1624
                         *     for the tag and that that entry is for the
 
1625
                         *     widest potential data type the tag may have.
 
1626
                         */
 
1627
                        { TIFFDataType type = fip->field_type;
 
1628
                          if (type != TIFF_LONG && type != TIFF_SLONG) {
 
1629
                                uint16 v = (uint16)
 
1630
                           TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
 
1631
                                ok = (fip->field_passcount ?
 
1632
                                    TIFFSetField(tif, dp->tdir_tag, 1, &v)
 
1633
                                  : TIFFSetField(tif, dp->tdir_tag, v));
 
1634
                                break;
 
1635
                          }
 
1636
                        }
 
1637
                        /* fall thru... */
 
1638
                case TIFF_LONG:
 
1639
                case TIFF_SLONG:
 
1640
                        { uint32 v32 =
 
1641
                    TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
 
1642
                          ok = (fip->field_passcount ? 
 
1643
                              TIFFSetField(tif, dp->tdir_tag, 1, &v32)
 
1644
                            : TIFFSetField(tif, dp->tdir_tag, v32));
 
1645
                        }
 
1646
                        break;
 
1647
                case TIFF_RATIONAL:
 
1648
                case TIFF_SRATIONAL:
 
1649
                case TIFF_FLOAT:
 
1650
                        { float v = (dp->tdir_type == TIFF_FLOAT ? 
 
1651
                              TIFFFetchFloat(tif, dp)
 
1652
                            : TIFFFetchRational(tif, dp));
 
1653
                          ok = (fip->field_passcount ?
 
1654
                              TIFFSetField(tif, dp->tdir_tag, 1, &v)
 
1655
                            : TIFFSetField(tif, dp->tdir_tag, v));
 
1656
                        }
 
1657
                        break;
 
1658
                case TIFF_DOUBLE:
 
1659
                        { double v;
 
1660
                          ok = (TIFFFetchDoubleArray(tif, dp, &v) &&
 
1661
                            (fip->field_passcount ?
 
1662
                              TIFFSetField(tif, dp->tdir_tag, 1, &v)
 
1663
                            : TIFFSetField(tif, dp->tdir_tag, v))
 
1664
                          );
 
1665
                        }
 
1666
                        break;
 
1667
                case TIFF_ASCII:
 
1668
                case TIFF_UNDEFINED:            /* bit of a cheat... */
 
1669
                        { char c[2];
 
1670
                          if( (ok = (TIFFFetchString(tif, dp, c) != 0)) != 0 ) {
 
1671
                                c[1] = '\0';            /* XXX paranoid */
 
1672
                                ok = (fip->field_passcount ?
 
1673
                                        TIFFSetField(tif, dp->tdir_tag, 1, c)
 
1674
                                      : TIFFSetField(tif, dp->tdir_tag, c));
 
1675
                          }
 
1676
                        }
 
1677
                        break;
 
1678
                }
 
1679
        }
 
1680
        return (ok);
 
1681
}
 
1682
 
 
1683
#define NITEMS(x)       (sizeof (x) / sizeof (x[0]))
 
1684
/*
 
1685
 * Fetch samples/pixel short values for 
 
1686
 * the specified tag and verify that
 
1687
 * all values are the same.
 
1688
 */
 
1689
static int
 
1690
TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, uint16* pl)
 
1691
{
 
1692
    uint16 samples = tif->tif_dir.td_samplesperpixel;
 
1693
    int status = 0;
 
1694
 
 
1695
    if (CheckDirCount(tif, dir, (uint32) samples)) {
 
1696
        uint16 buf[10];
 
1697
        uint16* v = buf;
 
1698
 
 
1699
        if (dir->tdir_count > NITEMS(buf))
 
1700
            v = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint16),
 
1701
                                      "to fetch per-sample values");
 
1702
        if (v && TIFFFetchShortArray(tif, dir, v)) {
 
1703
            uint16 i;
 
1704
            int check_count = dir->tdir_count;
 
1705
            if( samples < check_count )
 
1706
                check_count = samples;
 
1707
 
 
1708
            for (i = 1; i < check_count; i++)
 
1709
                if (v[i] != v[0]) {
 
1710
                        TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 
1711
                "Cannot handle different per-sample values for field \"%s\"",
 
1712
                        _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
 
1713
                        goto bad;
 
1714
                }
 
1715
            *pl = v[0];
 
1716
            status = 1;
 
1717
        }
 
1718
      bad:
 
1719
        if (v && v != buf)
 
1720
            _TIFFfree(v);
 
1721
    }
 
1722
    return (status);
 
1723
}
 
1724
 
 
1725
/*
 
1726
 * Fetch samples/pixel long values for 
 
1727
 * the specified tag and verify that
 
1728
 * all values are the same.
 
1729
 */
 
1730
static int
 
1731
TIFFFetchPerSampleLongs(TIFF* tif, TIFFDirEntry* dir, uint32* pl)
 
1732
{
 
1733
    uint16 samples = tif->tif_dir.td_samplesperpixel;
 
1734
    int status = 0;
 
1735
 
 
1736
    if (CheckDirCount(tif, dir, (uint32) samples)) {
 
1737
        uint32 buf[10];
 
1738
        uint32* v = buf;
 
1739
 
 
1740
        if (dir->tdir_count > NITEMS(buf))
 
1741
            v = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint32),
 
1742
                                      "to fetch per-sample values");
 
1743
        if (v && TIFFFetchLongArray(tif, dir, v)) {
 
1744
            uint16 i;
 
1745
            int check_count = dir->tdir_count;
 
1746
 
 
1747
            if( samples < check_count )
 
1748
                check_count = samples;
 
1749
            for (i = 1; i < check_count; i++)
 
1750
                if (v[i] != v[0]) {
 
1751
                        TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 
1752
                "Cannot handle different per-sample values for field \"%s\"",
 
1753
                        _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
 
1754
                        goto bad;
 
1755
                }
 
1756
            *pl = v[0];
 
1757
            status = 1;
 
1758
        }
 
1759
      bad:
 
1760
        if (v && v != buf)
 
1761
            _TIFFfree(v);
 
1762
    }
 
1763
    return (status);
 
1764
}
 
1765
 
 
1766
/*
 
1767
 * Fetch samples/pixel ANY values for the specified tag and verify that all
 
1768
 * values are the same.
 
1769
 */
 
1770
static int
 
1771
TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl)
 
1772
{
 
1773
    uint16 samples = tif->tif_dir.td_samplesperpixel;
 
1774
    int status = 0;
 
1775
 
 
1776
    if (CheckDirCount(tif, dir, (uint32) samples)) {
 
1777
        double buf[10];
 
1778
        double* v = buf;
 
1779
 
 
1780
        if (dir->tdir_count > NITEMS(buf))
 
1781
            v = (double*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (double),
 
1782
                                      "to fetch per-sample values");
 
1783
        if (v && TIFFFetchAnyArray(tif, dir, v)) {
 
1784
            uint16 i;
 
1785
            int check_count = dir->tdir_count;
 
1786
            if( samples < check_count )
 
1787
                check_count = samples;
 
1788
 
 
1789
            for (i = 1; i < check_count; i++)
 
1790
                if (v[i] != v[0]) {
 
1791
                        TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 
1792
                "Cannot handle different per-sample values for field \"%s\"",
 
1793
                        _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name);
 
1794
                        goto bad;
 
1795
                }
 
1796
            *pl = v[0];
 
1797
            status = 1;
 
1798
        }
 
1799
      bad:
 
1800
        if (v && v != buf)
 
1801
            _TIFFfree(v);
 
1802
    }
 
1803
    return (status);
 
1804
}
 
1805
#undef NITEMS
 
1806
 
 
1807
/*
 
1808
 * Fetch a set of offsets or lengths.
 
1809
 * While this routine says "strips", in fact it's also used for tiles.
 
1810
 */
 
1811
static int
 
1812
TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp)
 
1813
{
 
1814
        register uint32* lp;
 
1815
        int status;
 
1816
 
 
1817
        CheckDirCount(tif, dir, (uint32) nstrips);
 
1818
 
 
1819
        /*
 
1820
         * Allocate space for strip information.
 
1821
         */
 
1822
        if (*lpp == NULL &&
 
1823
            (*lpp = (uint32 *)_TIFFCheckMalloc(tif,
 
1824
              nstrips, sizeof (uint32), "for strip array")) == NULL)
 
1825
                return (0);
 
1826
        lp = *lpp;
 
1827
        _TIFFmemset( lp, 0, sizeof(uint32) * nstrips );
 
1828
 
 
1829
        if (dir->tdir_type == (int)TIFF_SHORT) {
 
1830
                /*
 
1831
                 * Handle uint16->uint32 expansion.
 
1832
                 */
 
1833
                uint16* dp = (uint16*) _TIFFCheckMalloc(tif,
 
1834
                    dir->tdir_count, sizeof (uint16), "to fetch strip tag");
 
1835
                if (dp == NULL)
 
1836
                        return (0);
 
1837
                if( (status = TIFFFetchShortArray(tif, dir, dp)) != 0 ) {
 
1838
                    int i;
 
1839
                    
 
1840
                    for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ )
 
1841
                    {
 
1842
                        lp[i] = dp[i];
 
1843
                    }
 
1844
                }
 
1845
                _TIFFfree((char*) dp);
 
1846
 
 
1847
        } else if( nstrips != (int) dir->tdir_count ) {
 
1848
            /* Special case to correct length */
 
1849
 
 
1850
            uint32* dp = (uint32*) _TIFFCheckMalloc(tif,
 
1851
                    dir->tdir_count, sizeof (uint32), "to fetch strip tag");
 
1852
            if (dp == NULL)
 
1853
                return (0);
 
1854
 
 
1855
            status = TIFFFetchLongArray(tif, dir, dp);
 
1856
            if( status != 0 ) {
 
1857
                int i;
 
1858
 
 
1859
                for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ )
 
1860
                {
 
1861
                    lp[i] = dp[i];
 
1862
                }
 
1863
            }
 
1864
 
 
1865
            _TIFFfree( (char *) dp );
 
1866
        } else
 
1867
            status = TIFFFetchLongArray(tif, dir, lp);
 
1868
        
 
1869
        return (status);
 
1870
}
 
1871
 
 
1872
/*
 
1873
 * Fetch and set the RefBlackWhite tag.
 
1874
 */
 
1875
static int
 
1876
TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir)
 
1877
{
 
1878
        static const char mesg[] = "for \"ReferenceBlackWhite\" array";
 
1879
        char* cp;
 
1880
        int ok;
 
1881
 
 
1882
        if (dir->tdir_type == TIFF_RATIONAL)
 
1883
                return (TIFFFetchNormalTag(tif, dir));
 
1884
        /*
 
1885
         * Handle LONG's for backward compatibility.
 
1886
         */
 
1887
        cp = (char *)_TIFFCheckMalloc(tif, dir->tdir_count,
 
1888
                                      sizeof (uint32), mesg);
 
1889
        if( (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) != 0) {
 
1890
                float* fp = (float*)
 
1891
                    _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (float), mesg);
 
1892
                if( (ok = (fp != NULL)) != 0 ) {
 
1893
                        uint32 i;
 
1894
                        for (i = 0; i < dir->tdir_count; i++)
 
1895
                                fp[i] = (float)((uint32*) cp)[i];
 
1896
                        ok = TIFFSetField(tif, dir->tdir_tag, fp);
 
1897
                        _TIFFfree((char*) fp);
 
1898
                }
 
1899
        }
 
1900
        if (cp)
 
1901
                _TIFFfree(cp);
 
1902
        return (ok);
 
1903
}
 
1904
 
 
1905
/*
 
1906
 * Fetch and set the SubjectDistance EXIF tag.
 
1907
 */
 
1908
static int
 
1909
TIFFFetchSubjectDistance(TIFF* tif, TIFFDirEntry* dir)
 
1910
{
 
1911
        uint32 l[2];
 
1912
        float v;
 
1913
        int ok = 0;
 
1914
 
 
1915
        if (TIFFFetchData(tif, dir, (char *)l)
 
1916
            && cvtRational(tif, dir, l[0], l[1], &v)) {
 
1917
                /*
 
1918
                 * XXX: Numerator 0xFFFFFFFF means that we have infinite
 
1919
                 * distance. Indicate that with a negative floating point
 
1920
                 * SubjectDistance value.
 
1921
                 */
 
1922
                ok = TIFFSetField(tif, dir->tdir_tag,
 
1923
                                  (l[0] != 0xFFFFFFFF) ? v : -v);
 
1924
        }
 
1925
 
 
1926
        return ok;
 
1927
}
 
1928
 
 
1929
/*
 
1930
 * Replace a single strip (tile) of uncompressed data by multiple strips
 
1931
 * (tiles), each approximately STRIP_SIZE_DEFAULT bytes. This is useful for
 
1932
 * dealing with large images or for dealing with machines with a limited
 
1933
 * amount memory.
 
1934
 */
 
1935
static void
 
1936
ChopUpSingleUncompressedStrip(TIFF* tif)
 
1937
{
 
1938
        register TIFFDirectory *td = &tif->tif_dir;
 
1939
        uint32 bytecount = td->td_stripbytecount[0];
 
1940
        uint32 offset = td->td_stripoffset[0];
 
1941
        tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes;
 
1942
        tstrip_t strip, nstrips, rowsperstrip;
 
1943
        uint32* newcounts;
 
1944
        uint32* newoffsets;
 
1945
 
 
1946
        /*
 
1947
         * Make the rows hold at least one scanline, but fill specified amount
 
1948
         * of data if possible.
 
1949
         */
 
1950
        if (rowbytes > STRIP_SIZE_DEFAULT) {
 
1951
                stripbytes = rowbytes;
 
1952
                rowsperstrip = 1;
 
1953
        } else if (rowbytes > 0 ) {
 
1954
                rowsperstrip = STRIP_SIZE_DEFAULT / rowbytes;
 
1955
                stripbytes = rowbytes * rowsperstrip;
 
1956
        }
 
1957
        else
 
1958
            return;
 
1959
 
 
1960
        /* 
 
1961
         * never increase the number of strips in an image
 
1962
         */
 
1963
        if (rowsperstrip >= td->td_rowsperstrip)
 
1964
                return;
 
1965
        nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes);
 
1966
        if( nstrips == 0 ) /* something is wonky, do nothing. */
 
1967
            return;
 
1968
 
 
1969
        newcounts = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32),
 
1970
                                "for chopped \"StripByteCounts\" array");
 
1971
        newoffsets = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32),
 
1972
                                "for chopped \"StripOffsets\" array");
 
1973
        if (newcounts == NULL || newoffsets == NULL) {
 
1974
                /*
 
1975
                 * Unable to allocate new strip information, give up and use
 
1976
                 * the original one strip information.
 
1977
                 */
 
1978
                if (newcounts != NULL)
 
1979
                        _TIFFfree(newcounts);
 
1980
                if (newoffsets != NULL)
 
1981
                        _TIFFfree(newoffsets);
 
1982
                return;
 
1983
        }
 
1984
        /*
 
1985
         * Fill the strip information arrays with new bytecounts and offsets
 
1986
         * that reflect the broken-up format.
 
1987
         */
 
1988
        for (strip = 0; strip < nstrips; strip++) {
 
1989
                if ((uint32)stripbytes > bytecount)
 
1990
                        stripbytes = bytecount;
 
1991
                newcounts[strip] = stripbytes;
 
1992
                newoffsets[strip] = offset;
 
1993
                offset += stripbytes;
 
1994
                bytecount -= stripbytes;
 
1995
        }
 
1996
        /*
 
1997
         * Replace old single strip info with multi-strip info.
 
1998
         */
 
1999
        td->td_stripsperimage = td->td_nstrips = nstrips;
 
2000
        TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
 
2001
 
 
2002
        _TIFFfree(td->td_stripbytecount);
 
2003
        _TIFFfree(td->td_stripoffset);
 
2004
        td->td_stripbytecount = newcounts;
 
2005
        td->td_stripoffset = newoffsets;
 
2006
        td->td_stripbytecountsorted = 1;
 
2007
}
 
2008
 
 
2009
/* vim: set ts=8 sts=8 sw=8 noet: */