PageRenderTime 157ms CodeModel.GetById 65ms app.highlight 77ms RepoModel.GetById 2ms app.codeStats 0ms

/src/FreeImage/Source/LibTIFF/tif_dirread.c

https://bitbucket.org/cabalistic/ogredeps/
C | 2117 lines | 1537 code | 121 blank | 459 comment | 455 complexity | 59d28fb22a8c0615026dfdfaf9d54058 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file