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