1 /* $Header: /usr/people/sam/tiff/libtiff/RCS/tif_dirread.c,v 1.55 1994/09/28 00:54:41 sam Exp $ */
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994 Sam Leffler
5  * Copyright (c) 1991, 1992, 1993, 1994 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 #if HAVE_IEEEFP
37 #define	TIFFCvtIEEEFloatToNative(tif, n, fp)
38 #endif
39 
40 static	void EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16);
41 static	void MissingRequired(TIFF*, const char*);
42 static	int CheckDirCount(TIFF*, TIFFDirEntry*, uint32);
43 static	tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*);
44 static	tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*);
45 static	float TIFFFetchRational(TIFF*, TIFFDirEntry*);
46 static	int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*);
47 static	int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, int*);
48 static	int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*);
49 static	int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**);
50 static	int TIFFFetchExtraSamples(TIFF*, TIFFDirEntry*);
51 static	int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*);
52 static	int TIFFFetchJPEGQTables(TIFF*, TIFFDirEntry*);
53 static	int TIFFFetchJPEGCTables(TIFF*, TIFFDirEntry*, u_char***);
54 static	float TIFFFetchFloat(TIFF*, TIFFDirEntry*);
55 static	int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*);
56 static	int TIFFFetchShortPair(TIFF*, TIFFDirEntry*);
57 #if STRIPCHOP_SUPPORT
58 static	void ChopUpSingleUncompressedStrip(TIFF*);
59 #endif
60 
61 static char *
CheckMalloc(TIFF * tif,size_t n,const char * what)62 CheckMalloc(TIFF* tif, size_t n, const char* what)
63 {
64 	char *cp = (char*)_TIFFmalloc(n);
65 	if (cp == NULL)
66 		TIFFError(tif->tif_name, "No space %s", what);
67 	return (cp);
68 }
69 
70 /*
71  * Read the next TIFF directory from a file
72  * and convert it to the internal format.
73  * We read directories sequentially.
74  */
75 int
TIFFReadDirectory(TIFF * tif)76 TIFFReadDirectory(TIFF* tif)
77 {
78 	register TIFFDirEntry *dp;
79 	register int n;
80 	register TIFFDirectory *td;
81 	TIFFDirEntry *dir;
82 	int iv;
83 	long v;
84 	const TIFFFieldInfo *fip;
85 	uint16 dircount;
86 	uint32 nextdiroff;
87 	char *cp;
88 	int diroutoforderwarning = 0;
89 
90 	tif->tif_diroff = tif->tif_nextdiroff;
91 	if (tif->tif_diroff == 0)		/* no more directories */
92 		return (0);
93 	/*
94 	 * Cleanup any previous compression state.
95 	 */
96 	if (tif->tif_cleanup)
97 		(*tif->tif_cleanup)(tif);
98 	tif->tif_curdir++;
99 	nextdiroff = 0;
100 	if (!isMapped(tif)) {
101 		if (!SeekOK(tif, tif->tif_diroff)) {
102 			TIFFError(tif->tif_name,
103 			    "Seek error accessing TIFF directory");
104 			return (0);
105 		}
106 		if (!ReadOK(tif, &dircount, sizeof (uint16))) {
107 			TIFFError(tif->tif_name,
108 			    "Can not read TIFF directory count");
109 			return (0);
110 		}
111 		if (tif->tif_flags & TIFF_SWAB)
112 			TIFFSwabShort(&dircount);
113 		dir = (TIFFDirEntry *)CheckMalloc(tif,
114 		    dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
115 		if (dir == NULL)
116 			return (0);
117 		if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) {
118 			TIFFError(tif->tif_name, "Can not read TIFF directory");
119 			goto bad;
120 		}
121 		/*
122 		 * Read offset to next directory for sequential scans.
123 		 */
124 		(void) ReadOK(tif, &nextdiroff, sizeof (uint32));
125 	} else {
126 		toff_t off = tif->tif_diroff;
127 
128 		if (off + sizeof (short) > tif->tif_size) {
129 			TIFFError(tif->tif_name,
130 			    "Can not read TIFF directory count");
131 			return (0);
132 		} else
133 			_TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16));
134 		off += sizeof (uint16);
135 		if (tif->tif_flags & TIFF_SWAB)
136 			TIFFSwabShort(&dircount);
137 		dir = (TIFFDirEntry *)CheckMalloc(tif,
138 		    dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
139 		if (dir == NULL)
140 			return (0);
141 		if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) {
142 			TIFFError(tif->tif_name, "Can not read TIFF directory");
143 			goto bad;
144 		} else
145 			_TIFFmemcpy(dir, tif->tif_base + off,
146 			    dircount*sizeof (TIFFDirEntry));
147 		off += dircount* sizeof (TIFFDirEntry);
148 		if (off + sizeof (uint32) < tif->tif_size)
149 			_TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32));
150 	}
151 	if (tif->tif_flags & TIFF_SWAB)
152 		TIFFSwabLong(&nextdiroff);
153 	tif->tif_nextdiroff = nextdiroff;
154 
155 	tif->tif_flags &= ~TIFF_BEENWRITING;	/* reset before new dir */
156 	/*
157 	 * Setup default value and then make a pass over
158 	 * the fields to check type and tag information,
159 	 * and to extract info required to size data
160 	 * structures.  A second pass is made afterwards
161 	 * to read in everthing not taken in the first pass.
162 	 */
163 	td = &tif->tif_dir;
164 	/* free any old stuff and reinit */
165 	TIFFFreeDirectory(tif);
166 	TIFFDefaultDirectory(tif);
167 	tif->tif_postdecode = TIFFNoPostDecode;
168 	/*
169 	 * Electronic Arts writes gray-scale TIFF files
170 	 * without a PlanarConfiguration directory entry.
171 	 * Thus we setup a default value here, even though
172 	 * the TIFF spec says there is no default value.
173 	 */
174 	TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
175 	for (fip = tiffFieldInfo, dp = dir, n = dircount; n > 0; n--, dp++) {
176 		if (tif->tif_flags & TIFF_SWAB) {
177 			TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
178 			TIFFSwabArrayOfLong(&dp->tdir_count, 2);
179 		}
180 		/*
181 		 * Find the field information entry for this tag.
182 		 */
183 		/*
184 		 * Silicon Beach (at least) writes unordered
185 		 * directory tags (violating the spec).  Handle
186 		 * it here, but be obnoxious (maybe they'll fix it?).
187 		 */
188 		if (dp->tdir_tag < fip->field_tag) {
189 			if (!diroutoforderwarning) {
190 				TIFFWarning(tif->tif_name,
191 	"invalid TIFF directory; tags are not sorted in ascending order");
192 				diroutoforderwarning = 1;
193 			}
194 			fip = tiffFieldInfo;	/* O(n^2) */
195 		}
196 		while (fip->field_tag && fip->field_tag < dp->tdir_tag)
197 			fip++;
198 		if (!fip->field_tag || fip->field_tag != dp->tdir_tag) {
199 			TIFFWarning(tif->tif_name,
200 			    "unknown field with tag %d (0x%x) ignored",
201 			    dp->tdir_tag,  dp->tdir_tag);
202 			dp->tdir_tag = IGNORE;
203 			fip = tiffFieldInfo;	/* restart search */
204 			continue;
205 		}
206 		/*
207 		 * Null out old tags that we ignore.
208 		 */
209 		if (fip->field_bit == FIELD_IGNORE) {
210 	ignore:
211 			dp->tdir_tag = IGNORE;
212 			continue;
213 		}
214 		/*
215 		 * Check data type.
216 		 */
217 		while (dp->tdir_type != (u_short)fip->field_type) {
218 			if (fip->field_type == TIFF_ANY)	/* wildcard */
219 				break;
220 			fip++;
221 			if (!fip->field_tag || fip->field_tag != dp->tdir_tag) {
222 				TIFFWarning(tif->tif_name,
223 				   "wrong data type %d for \"%s\"; tag ignored",
224 				    dp->tdir_type, fip[-1].field_name);
225 				goto ignore;
226 			}
227 		}
228 		/*
229 		 * Check count if known in advance.
230 		 */
231 		if (fip->field_readcount != TIFF_VARIABLE) {
232 			uint32 expected = (fip->field_readcount == TIFF_SPP) ?
233 			    (uint32) td->td_samplesperpixel :
234 			    (uint32) fip->field_readcount;
235 			if (!CheckDirCount(tif, dp, expected))
236 				goto ignore;
237 		}
238 
239 		switch (dp->tdir_tag) {
240 		case TIFFTAG_STRIPOFFSETS:
241 		case TIFFTAG_STRIPBYTECOUNTS:
242 		case TIFFTAG_TILEOFFSETS:
243 		case TIFFTAG_TILEBYTECOUNTS:
244 			TIFFSetFieldBit(tif, fip->field_bit);
245 			break;
246 		case TIFFTAG_IMAGEWIDTH:
247 		case TIFFTAG_IMAGELENGTH:
248 		case TIFFTAG_IMAGEDEPTH:
249 		case TIFFTAG_TILELENGTH:
250 		case TIFFTAG_TILEWIDTH:
251 		case TIFFTAG_TILEDEPTH:
252 		case TIFFTAG_PLANARCONFIG:
253 		case TIFFTAG_SAMPLESPERPIXEL:
254 		case TIFFTAG_ROWSPERSTRIP:
255 			if (!TIFFFetchNormalTag(tif, dp))
256 				goto bad;
257 			dp->tdir_tag = IGNORE;
258 			break;
259 		case TIFFTAG_EXTRASAMPLES:
260 			(void) TIFFFetchExtraSamples(tif, dp);
261 			dp->tdir_tag = IGNORE;
262 			break;
263 		}
264 	}
265 
266 	/*
267 	 * Allocate directory structure and setup defaults.
268 	 */
269 	if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
270 		MissingRequired(tif, "ImageLength");
271 		goto bad;
272 	}
273 	if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
274 		MissingRequired(tif, "PlanarConfiguration");
275 		goto bad;
276 	}
277 	/*
278  	 * Setup appropriate structures (by strip or by tile)
279 	 */
280 	if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
281 		td->td_stripsperimage = (td->td_rowsperstrip == (uint32) -1 ?
282 		     (td->td_imagelength != 0 ? 1 : 0) :
283 		     howmany(td->td_imagelength, td->td_rowsperstrip));
284 		td->td_tilewidth = td->td_imagewidth;
285 		td->td_tilelength = td->td_rowsperstrip;
286 		td->td_tiledepth = td->td_imagedepth;
287 		tif->tif_flags &= ~TIFF_ISTILED;
288 	} else {
289 		td->td_stripsperimage = TIFFNumberOfTiles(tif);
290 		tif->tif_flags |= TIFF_ISTILED;
291 	}
292 	td->td_nstrips = td->td_stripsperimage;
293 	if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
294 		td->td_nstrips *= td->td_samplesperpixel;
295 	if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
296 		MissingRequired(tif,
297 		    isTiled(tif) ? "TileOffsets" : "StripOffsets");
298 		goto bad;
299 	}
300 
301 	/*
302 	 * Second pass: extract other information.
303 	 */
304 	for (dp = dir, n = dircount; n > 0; n--, dp++) {
305 		if (dp->tdir_tag == IGNORE)
306 			continue;
307 		switch (dp->tdir_tag) {
308 		case TIFFTAG_COMPRESSION:
309 		case TIFFTAG_MINSAMPLEVALUE:
310 		case TIFFTAG_MAXSAMPLEVALUE:
311 		case TIFFTAG_BITSPERSAMPLE:
312 			/*
313 			 * The 5.0 spec says the Compression tag has
314 			 * one value, while earlier specs say it has
315 			 * one value per sample.  Because of this, we
316 			 * accept the tag if one value is supplied.
317 			 *
318 			 * The MinSampleValue, MaxSampleValue and
319 			 * BitsPerSample tags are supposed to be written
320 			 * as one value/sample, but some vendors incorrectly
321 			 * write one value only -- so we accept that
322 			 * as well (yech).
323 			 */
324 			if (dp->tdir_count == 1) {
325 				v = TIFFExtractData(tif,
326 				    dp->tdir_type, dp->tdir_offset);
327 				if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
328 					goto bad;
329 				break;
330 			}
331 			/* fall thru... */
332 		case TIFFTAG_DATATYPE:
333 		case TIFFTAG_SAMPLEFORMAT:
334 			if (!TIFFFetchPerSampleShorts(tif, dp, &iv) ||
335 			    !TIFFSetField(tif, dp->tdir_tag, iv))
336 				goto bad;
337 			break;
338 		case TIFFTAG_STRIPOFFSETS:
339 		case TIFFTAG_TILEOFFSETS:
340 			if (!TIFFFetchStripThing(tif, dp,
341 			    td->td_nstrips, &td->td_stripoffset))
342 				goto bad;
343 			break;
344 		case TIFFTAG_STRIPBYTECOUNTS:
345 		case TIFFTAG_TILEBYTECOUNTS:
346 			if (!TIFFFetchStripThing(tif, dp,
347 			    td->td_nstrips, &td->td_stripbytecount))
348 				goto bad;
349 			break;
350 		case TIFFTAG_COLORMAP:
351 		case TIFFTAG_TRANSFERFUNCTION:
352 			/*
353 			 * TransferFunction can have either 1x or 3x data
354 			 * values; Colormap can have only 3x items.
355 			 */
356 			v = 1L<<td->td_bitspersample;
357 			if (dp->tdir_tag == TIFFTAG_COLORMAP ||
358 			    dp->tdir_count != (uint32) v) {
359 				if (!CheckDirCount(tif, dp, (uint32)(3*v)))
360 					break;
361 			}
362 			v *= sizeof (uint16);
363 			cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16),
364 			    "to read \"TransferFunction\" tag");
365 			if (cp != NULL) {
366 				if (TIFFFetchData(tif, dp, cp)) {
367 					/*
368 					 * This deals with there being only
369 					 * one array to apply to all samples.
370 					 */
371 					uint32 c =
372 					    (uint32)1 << td->td_bitspersample;
373 					if (dp->tdir_count == c)
374 						v = 0;
375 					TIFFSetField(tif, dp->tdir_tag,
376 					    cp, cp+v, cp+2*v);
377 				}
378 				_TIFFfree(cp);
379 			}
380 			break;
381 		case TIFFTAG_PAGENUMBER:
382 		case TIFFTAG_HALFTONEHINTS:
383 		case TIFFTAG_YCBCRSUBSAMPLING:
384 		case TIFFTAG_DOTRANGE:
385 			(void) TIFFFetchShortPair(tif, dp);
386 			break;
387 #ifdef COLORIMETRY_SUPPORT
388 		case TIFFTAG_REFERENCEBLACKWHITE:
389 			(void) TIFFFetchRefBlackWhite(tif, dp);
390 			break;
391 #endif
392 #ifdef JPEG_SUPPORT
393 		case TIFFTAG_JPEGQTABLES:
394 			if (TIFFFetchJPEGQTables(tif, dp))
395 				TIFFSetFieldBit(tif, FIELD_JPEGQTABLES);
396 			break;
397 		case TIFFTAG_JPEGDCTABLES:
398 			if (TIFFFetchJPEGCTables(tif, dp, &td->td_dctab))
399 				TIFFSetFieldBit(tif, FIELD_JPEGDCTABLES);
400 			break;
401 		case TIFFTAG_JPEGACTABLES:
402 			if (TIFFFetchJPEGCTables(tif, dp, &td->td_actab))
403 				TIFFSetFieldBit(tif, FIELD_JPEGACTABLES);
404 			break;
405 #endif
406 /* BEGIN REV 4.0 COMPATIBILITY */
407 		case TIFFTAG_OSUBFILETYPE:
408 			v = 0;
409 			switch (TIFFExtractData(tif, dp->tdir_type,
410 			    dp->tdir_offset)) {
411 			case OFILETYPE_REDUCEDIMAGE:
412 				v = FILETYPE_REDUCEDIMAGE;
413 				break;
414 			case OFILETYPE_PAGE:
415 				v = FILETYPE_PAGE;
416 				break;
417 			}
418 			if (v)
419 				(void) TIFFSetField(tif,
420 				    TIFFTAG_SUBFILETYPE, (int)v);
421 			break;
422 /* END REV 4.0 COMPATIBILITY */
423 		default:
424 			(void) TIFFFetchNormalTag(tif, dp);
425 			break;
426 		}
427 	}
428 	/*
429 	 * Verify Palette image has a Colormap.
430 	 */
431 	if (td->td_photometric == PHOTOMETRIC_PALETTE &&
432 	    !TIFFFieldSet(tif, FIELD_COLORMAP)) {
433 		MissingRequired(tif, "Colormap");
434 		goto bad;
435 	}
436 	/*
437 	 * Attempt to deal with a missing StripByteCounts tag.
438 	 */
439 	if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
440 		/*
441 		 * Some manufacturers violate the spec by not giving
442 		 * the size of the strips.  In this case, assume there
443 		 * is one uncompressed strip of data.
444 		 */
445 		if ((td->td_planarconfig == PLANARCONFIG_CONTIG &&
446 		    td->td_nstrips > 1) ||
447 		    (td->td_planarconfig != PLANARCONFIG_SEPARATE &&
448 		     td->td_nstrips != td->td_samplesperpixel)) {
449 		    MissingRequired(tif, "StripByteCounts");
450 		    goto bad;
451 		}
452 		TIFFWarning(tif->tif_name,
453 "TIFF directory is missing required \"%s\" field, calculating from imagelength",
454 		    TIFFFieldWithTag(TIFFTAG_STRIPBYTECOUNTS)->field_name);
455 		EstimateStripByteCounts(tif, dir, dircount);
456 #define	BYTECOUNTLOOKSBAD \
457     (td->td_stripbytecount[0] == 0 || \
458     (td->td_compression == COMPRESSION_NONE && \
459      td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]))
460 	} else if (td->td_nstrips == 1 && BYTECOUNTLOOKSBAD) {
461 		/*
462 		 * Plexus (and others) sometimes give a value
463 		 * of zero for a tag when they don't know what
464 		 * the correct value is!  Try and handle the
465 		 * simple case of estimating the size of a one
466 		 * strip image.
467 		 */
468 		TIFFWarning(tif->tif_name,
469 	    "Bogus \"%s\" field, ignoring and calculating from imagelength",
470 		    TIFFFieldWithTag(TIFFTAG_STRIPBYTECOUNTS)->field_name);
471 		EstimateStripByteCounts(tif, dir, dircount);
472 	}
473 	if (dir)
474 		_TIFFfree((char *)dir);
475 	if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
476 		td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1);
477 	/*
478 	 * Setup default compression scheme.
479 	 */
480 	if (!TIFFFieldSet(tif, FIELD_COMPRESSION))
481 		TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
482 #if STRIPCHOP_SUPPORT
483         /*
484          * Some manufacturers make life difficult by writing
485 	 * large amounts of uncompressed data as a single strip.
486 	 * This is contrary to the recommendations of the spec.
487          * The following makes an attempt at breaking such images
488 	 * into strips closer to the recommended 8k bytes.  A
489 	 * side effect, however, is that the RowsPerStrip tag
490 	 * value may be changed.
491          */
492         if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE &&
493 	    td->td_tilewidth == td->td_imagewidth)
494 		ChopUpSingleUncompressedStrip(tif);
495 #endif
496 	/*
497 	 * Reinitialize i/o since we are starting on a new directory.
498 	 */
499 	tif->tif_row = (uint32) -1;
500 	tif->tif_curstrip = (tstrip_t) -1;
501 	tif->tif_col = (uint32) -1;
502 	tif->tif_curtile = (ttile_t) -1;
503 	tif->tif_tilesize = TIFFTileSize(tif);
504 	tif->tif_scanlinesize = TIFFScanlineSize(tif);
505 	return (1);
506 bad:
507 	if (dir)
508 		_TIFFfree((char *)dir);
509 	return (0);
510 }
511 
512 static void
EstimateStripByteCounts(TIFF * tif,TIFFDirEntry * dir,uint16 dircount)513 EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount)
514 {
515 	register TIFFDirEntry *dp;
516 	register TIFFDirectory *td = &tif->tif_dir;
517 	int i;
518 
519 	td->td_stripbytecount = (uint32*)
520 	    CheckMalloc(tif, td->td_samplesperpixel * sizeof (uint32),
521 		"for \"StripByteCounts\" array");
522 	if (td->td_compression != COMPRESSION_NONE) {
523 		uint32 space = (uint32)(sizeof (TIFFHeader)
524 		    + sizeof (uint16)
525 		    + (dircount * sizeof (TIFFDirEntry))
526 		    + sizeof (uint32));
527 		toff_t filesize = TIFFGetFileSize(tif);
528 		uint16 n;
529 
530 		/* calculate amount of space used by indirect values */
531 		for (dp = dir, n = dircount; n > 0; n--, dp++) {
532 			uint32 cc = dp->tdir_count*tiffDataWidth[dp->tdir_type];
533 			if (cc > sizeof (uint32))
534 				space += cc;
535 		}
536 		space = (filesize - space) / td->td_samplesperpixel;
537 		for (i = 0; i < td->td_samplesperpixel; i++)
538 			td->td_stripbytecount[i] = space;
539 		/*
540 		 * This gross hack handles the case were the offset to
541 		 * the last strip is past the place where we think the strip
542 		 * should begin.  Since a strip of data must be contiguous,
543 		 * it's safe to assume that we've overestimated the amount
544 		 * of data in the strip and trim this number back accordingly.
545 		 */
546 		i--;
547 		if (td->td_stripoffset[i] + td->td_stripbytecount[i] > filesize)
548 			td->td_stripbytecount[i] =
549 			    filesize - td->td_stripoffset[i];
550 	} else {
551 		uint32 rowbytes = howmany(td->td_bitspersample *
552 		    td->td_samplesperpixel * td->td_imagewidth, 8);
553 		for (i = 0; i < td->td_samplesperpixel; i++)
554 			td->td_stripbytecount[i] =
555 			    td->td_imagelength*rowbytes/td->td_samplesperpixel;
556 	}
557 	TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
558 	if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
559 		td->td_rowsperstrip = td->td_imagelength;
560 }
561 
562 static void
MissingRequired(TIFF * tif,const char * tagname)563 MissingRequired(TIFF* tif, const char* tagname)
564 {
565 	TIFFError(tif->tif_name,
566 	    "TIFF directory is missing required \"%s\" field", tagname);
567 }
568 
569 /*
570  * Check the count field of a directory
571  * entry against a known value.  The caller
572  * is expected to skip/ignore the tag if
573  * there is a mismatch.
574  */
575 static int
CheckDirCount(TIFF * tif,TIFFDirEntry * dir,uint32 count)576 CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count)
577 {
578 	if (count != dir->tdir_count) {
579 		TIFFWarning(tif->tif_name,
580 	"incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored",
581 		    TIFFFieldWithTag(dir->tdir_tag)->field_name,
582 		    dir->tdir_count, count);
583 		return (0);
584 	}
585 	return (1);
586 }
587 
588 /*
589  * Fetch a contiguous directory item.
590  */
591 static tsize_t
TIFFFetchData(TIFF * tif,TIFFDirEntry * dir,char * cp)592 TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp)
593 {
594 	int w = tiffDataWidth[dir->tdir_type];
595 	tsize_t cc = dir->tdir_count * w;
596 
597 	if (!isMapped(tif)) {
598 		if (!SeekOK(tif, dir->tdir_offset))
599 			goto bad;
600 		if (!ReadOK(tif, cp, cc))
601 			goto bad;
602 	} else {
603 		if (dir->tdir_offset + cc > tif->tif_size)
604 			goto bad;
605 		_TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc);
606 	}
607 	if (tif->tif_flags & TIFF_SWAB) {
608 		switch (dir->tdir_type) {
609 		case TIFF_SHORT:
610 		case TIFF_SSHORT:
611 			TIFFSwabArrayOfShort((uint16*)cp, dir->tdir_count);
612 			break;
613 		case TIFF_LONG:
614 		case TIFF_SLONG:
615 		case TIFF_FLOAT:
616 			TIFFSwabArrayOfLong((uint32*)cp, dir->tdir_count);
617 			break;
618 		case TIFF_RATIONAL:
619 		case TIFF_SRATIONAL:
620 			TIFFSwabArrayOfLong((uint32*)cp, 2*dir->tdir_count);
621 			break;
622 		}
623 	}
624 	return (cc);
625 bad:
626 	TIFFError(tif->tif_name, "Error fetching data for field \"%s\"",
627 	    TIFFFieldWithTag(dir->tdir_tag)->field_name);
628 	return ((tsize_t) 0);
629 }
630 
631 /*
632  * Fetch an ASCII item from the file.
633  */
634 static tsize_t
TIFFFetchString(TIFF * tif,TIFFDirEntry * dir,char * cp)635 TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp)
636 {
637 	if (dir->tdir_count <= 4) {
638 		uint32 l = dir->tdir_offset;
639 		if (tif->tif_flags & TIFF_SWAB)
640 			TIFFSwabLong(&l);
641 		_TIFFmemcpy(cp, &l, dir->tdir_count);
642 		return (1);
643 	}
644 	return (TIFFFetchData(tif, dir, cp));
645 }
646 
647 /*
648  * Convert numerator+denominator to float.
649  */
650 static int
cvtRational(TIFF * tif,TIFFDirEntry * dir,uint32 num,uint32 denom,float * rv)651 cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv)
652 {
653 	if (denom == 0) {
654 		TIFFError(tif->tif_name,
655 		    "%s: Rational with zero denominator (num = %lu)",
656 		    TIFFFieldWithTag(dir->tdir_tag)->field_name, num);
657 		return (0);
658 	} else {
659 		if (dir->tdir_type == TIFF_RATIONAL)
660 			*rv = ((float)num / (float)denom);
661 		else
662 			*rv = ((float)(int32)num / (float)(int32)denom);
663 		return (1);
664 	}
665 }
666 
667 /*
668  * Fetch a rational item from the file
669  * at offset off and return the value
670  * as a floating point number.
671  */
672 static float
TIFFFetchRational(TIFF * tif,TIFFDirEntry * dir)673 TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir)
674 {
675 	uint32 l[2];
676 	float v;
677 
678 	return (!TIFFFetchData(tif, dir, (char *)l) ||
679 	    !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v);
680 }
681 
682 /*
683  * Fetch a single floating point value
684  * from the offset field and return it
685  * as a native float.
686  */
687 static float
TIFFFetchFloat(TIFF * tif,TIFFDirEntry * dir)688 TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir)
689 {
690 	float v = (float)
691 	    TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset);
692 	TIFFCvtIEEEFloatToNative(tif, 1, &v);
693 	return (v);
694 }
695 
696 /*
697  * Fetch an array of BYTE or SBYTE values.
698  */
699 static int
TIFFFetchByteArray(TIFF * tif,TIFFDirEntry * dir,uint16 * v)700 TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint16* v)
701 {
702 	if (dir->tdir_count <= 4) {
703 		/*
704 		 * Extract data from offset field.
705 		 */
706 		if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
707 			switch (dir->tdir_count) {
708 			case 4: v[3] = dir->tdir_offset & 0xff;
709 			case 3: v[2] = (dir->tdir_offset >> 8) & 0xff;
710 			case 2: v[1] = (dir->tdir_offset >> 16) & 0xff;
711 			case 1: v[0] = dir->tdir_offset >> 24;
712 			}
713 		} else {
714 			switch (dir->tdir_count) {
715 			case 4: v[3] = dir->tdir_offset >> 24;
716 			case 3: v[2] = (dir->tdir_offset >> 16) & 0xff;
717 			case 2: v[1] = (dir->tdir_offset >> 8) & 0xff;
718 			case 1: v[0] = dir->tdir_offset & 0xff;
719 			}
720 		}
721 		return (1);
722 	} else
723 		return (TIFFFetchData(tif, dir, (char *)v) != 0);	/* XXX */
724 }
725 
726 /*
727  * Fetch an array of SHORT or SSHORT values.
728  */
729 static int
TIFFFetchShortArray(TIFF * tif,TIFFDirEntry * dir,uint16 * v)730 TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v)
731 {
732 	if (dir->tdir_count <= 2) {
733 		if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
734 			switch (dir->tdir_count) {
735 			case 2: v[1] = dir->tdir_offset & 0xffff;
736 			case 1: v[0] = dir->tdir_offset >> 16;
737 			}
738 		} else {
739 			switch (dir->tdir_count) {
740 			case 2: v[1] = dir->tdir_offset >> 16;
741 			case 1: v[0] = dir->tdir_offset & 0xffff;
742 			}
743 		}
744 		return (1);
745 	} else
746 		return (TIFFFetchData(tif, dir, (char *)v) != 0);
747 }
748 
749 /*
750  * Fetch a pair of SHORT or BYTE values.
751  */
752 static int
TIFFFetchShortPair(TIFF * tif,TIFFDirEntry * dir)753 TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir)
754 {
755 	uint16 v[2];
756 	int ok = 0;
757 
758 	switch (dir->tdir_type) {
759 	case TIFF_SHORT:
760 	case TIFF_SSHORT:
761 		ok = TIFFFetchShortArray(tif, dir, v);
762 		break;
763 	case TIFF_BYTE:
764 	case TIFF_SBYTE:
765 		ok  = TIFFFetchByteArray(tif, dir, v);
766 		break;
767 	}
768 	if (ok)
769 		TIFFSetField(tif, dir->tdir_tag, v[0], v[1]);
770 	return (ok);
771 }
772 
773 /*
774  * Fetch an array of LONG or SLONG values.
775  */
776 static int
TIFFFetchLongArray(TIFF * tif,TIFFDirEntry * dir,uint32 * v)777 TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v)
778 {
779 	if (dir->tdir_count == 1) {
780 		v[0] = dir->tdir_offset;
781 		return (1);
782 	} else
783 		return (TIFFFetchData(tif, dir, (char *)v) != 0);
784 }
785 
786 /*
787  * Fetch an array of RATIONAL or SRATIONAL values.
788  */
789 static int
TIFFFetchRationalArray(TIFF * tif,TIFFDirEntry * dir,float * v)790 TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v)
791 {
792 	int ok = 0;
793 	uint32 *l;
794 
795 	l = (uint32*)CheckMalloc(tif,
796 	    dir->tdir_count*tiffDataWidth[dir->tdir_type],
797 	    "to fetch array of rationals");
798 	if (l) {
799 		if (TIFFFetchData(tif, dir, (char *)l)) {
800 			uint32 i;
801 			for (i = 0; i < dir->tdir_count; i++) {
802 				ok = cvtRational(tif, dir,
803 				    l[2*i+0], l[2*i+1], &v[i]);
804 				if (!ok)
805 					break;
806 			}
807 		}
808 		_TIFFfree((char *)l);
809 	}
810 	return (ok);
811 }
812 
813 /*
814  * Fetch an array of FLOAT values.
815  */
816 static int
TIFFFetchFloatArray(TIFF * tif,TIFFDirEntry * dir,float * v)817 TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v)
818 {
819 	if (TIFFFetchData(tif, dir, (char *)v)) {
820 		TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v);
821 		return (1);
822 	} else
823 		return (0);
824 }
825 
826 /*
827  * Fetch a tag that is not handled by special case code.
828  *
829  * NB: DOUBLE and UNDEFINED types are not handled.
830  */
831 static int
TIFFFetchNormalTag(TIFF * tif,TIFFDirEntry * dp)832 TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp)
833 {
834 	static char mesg[] = "to fetch tag value";
835 	int ok = 0;
836 	const TIFFFieldInfo* fip = TIFFFieldWithTag(dp->tdir_tag);
837 
838 	if (dp->tdir_count > 1) {		/* array of values */
839 		char* cp = NULL;
840 
841 		switch (dp->tdir_type) {
842 		case TIFF_BYTE:
843 		case TIFF_SBYTE:
844 			/* NB: always expand BYTE values to shorts */
845 			cp = CheckMalloc(tif,
846 			    dp->tdir_count * sizeof (uint16), mesg);
847 			ok = cp && TIFFFetchByteArray(tif, dp, (uint16*)cp);
848 			break;
849 		case TIFF_SHORT:
850 		case TIFF_SSHORT:
851 			cp = CheckMalloc(tif,
852 			    dp->tdir_count * sizeof (uint16), mesg);
853 			ok = cp && TIFFFetchShortArray(tif, dp, (uint16*)cp);
854 			break;
855 		case TIFF_LONG:
856 		case TIFF_SLONG:
857 			cp = CheckMalloc(tif,
858 			    dp->tdir_count * sizeof (uint32), mesg);
859 			ok = cp && TIFFFetchLongArray(tif, dp, (uint32*)cp);
860 			break;
861 		case TIFF_RATIONAL:
862 		case TIFF_SRATIONAL:
863 			cp = CheckMalloc(tif,
864 			    dp->tdir_count * sizeof (float), mesg);
865 			ok = cp && TIFFFetchRationalArray(tif, dp, (float *)cp);
866 			break;
867 		case TIFF_FLOAT:
868 			cp = CheckMalloc(tif,
869 			    dp->tdir_count * sizeof (float), mesg);
870 			ok = cp && TIFFFetchFloatArray(tif, dp, (float *)cp);
871 			break;
872 		case TIFF_ASCII:
873 			/*
874 			 * Some vendors write strings w/o the trailing
875 			 * NULL byte, so always append one just in case.
876 			 */
877 			cp = CheckMalloc(tif, dp->tdir_count+1, mesg);
878 			if (ok = (cp && TIFFFetchString(tif, dp, cp)))
879 				cp[dp->tdir_count] = '\0';	/* XXX */
880 			break;
881 		}
882 		if (ok) {
883 			ok = (fip->field_passcount ?
884 			    TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp)
885 			  : TIFFSetField(tif, dp->tdir_tag, cp));
886 		}
887 		if (cp != NULL)
888 			_TIFFfree(cp);
889 	} else if (CheckDirCount(tif, dp, 1)) {	/* singleton value */
890 		switch (dp->tdir_type) {
891 		case TIFF_BYTE:
892 		case TIFF_SBYTE:
893 		case TIFF_SHORT:
894 		case TIFF_SSHORT:
895 			/*
896 			 * If the tag is also acceptable as a LONG or SLONG
897 			 * then TIFFSetField will expect an uint32 parameter
898 			 * passed to it (through varargs).  Thus, for machines
899 			 * where sizeof (int) != sizeof (uint32) we must do
900 			 * a careful check here.  It's hard to say if this
901 			 * is worth optimizing.
902 			 *
903 			 * NB: We use TIFFFieldWithTag here knowing that
904 			 *     it returns us the first entry in the table
905 			 *     for the tag and that that entry is for the
906 			 *     widest potential data type the tag may have.
907 			 */
908 			{ TIFFDataType type = fip->field_type;
909 			  if (type != TIFF_LONG && type != TIFF_SLONG) {
910 				uint16 v = (uint16)
911 			   TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
912 				ok = (fip->field_passcount ?
913 				    TIFFSetField(tif, dp->tdir_tag, 1, &v)
914 				  : TIFFSetField(tif, dp->tdir_tag, v));
915 				break;
916 			  }
917 			}
918 			/* fall thru... */
919 		case TIFF_LONG:
920 		case TIFF_SLONG:
921 			{ uint32 v32 =
922 		    TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
923 			  ok = (fip->field_passcount ?
924 			      TIFFSetField(tif, dp->tdir_tag, 1, &v32)
925 			    : TIFFSetField(tif, dp->tdir_tag, v32));
926 			}
927 			break;
928 		case TIFF_RATIONAL:
929 		case TIFF_SRATIONAL:
930 		case TIFF_FLOAT:
931 			{ float v = (dp->tdir_type == TIFF_FLOAT ?
932 			      TIFFFetchFloat(tif, dp)
933 			    : TIFFFetchRational(tif, dp));
934 			  ok = (fip->field_passcount ?
935 			      TIFFSetField(tif, dp->tdir_tag, 1, &v)
936 			    : TIFFSetField(tif, dp->tdir_tag, v));
937 			}
938 			break;
939 		case TIFF_ASCII:
940 			{ char c[2];
941 			  if (ok = (TIFFFetchString(tif, dp, c) != 0)) {
942 				c[1] = '\0';		/* XXX paranoid */
943 				ok = TIFFSetField(tif, dp->tdir_tag, c);
944 			  }
945 			}
946 			break;
947 		}
948 	}
949 	return (ok);
950 }
951 
952 #define	NITEMS(x)	(sizeof (x) / sizeof (x[0]))
953 /*
954  * Fetch samples/pixel short values for
955  * the specified tag and verify that
956  * all values are the same.
957  */
958 static int
TIFFFetchPerSampleShorts(TIFF * tif,TIFFDirEntry * dir,int * pl)959 TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, int* pl)
960 {
961 	int samples = tif->tif_dir.td_samplesperpixel;
962 	int status = 0;
963 
964 	if (CheckDirCount(tif, dir, (uint32) samples)) {
965 		uint16 buf[10];
966 		uint16* v = buf;
967 
968 		if (samples > NITEMS(buf))
969 			v = (uint16*)_TIFFmalloc(samples * sizeof (uint16));
970 		if (TIFFFetchShortArray(tif, dir, v)) {
971 			int i;
972 			for (i = 1; i < samples; i++)
973 				if (v[i] != v[0]) {
974 					TIFFError(tif->tif_name,
975 		"Cannot handle different per-sample values for field \"%s\"",
976 				   TIFFFieldWithTag(dir->tdir_tag)->field_name);
977 					goto bad;
978 				}
979 			*pl = v[0];
980 			status = 1;
981 		}
982 	bad:
983 		if (v != buf)
984 			_TIFFfree((char *)v);
985 	}
986 	return (status);
987 }
988 #undef NITEMS
989 
990 /*
991  * Fetch a set of offsets or lengths.
992  * While this routine says "strips",
993  * in fact it's also used for tiles.
994  */
995 static int
TIFFFetchStripThing(TIFF * tif,TIFFDirEntry * dir,long nstrips,uint32 ** lpp)996 TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp)
997 {
998 	register uint32 *lp;
999 	int status;
1000 
1001 	if (!CheckDirCount(tif, dir, (uint32) nstrips))
1002 		return (0);
1003 	/*
1004 	 * Allocate space for strip information.
1005 	 */
1006 	if (*lpp == NULL &&
1007 	    (*lpp = (uint32 *)CheckMalloc(tif,
1008 	      nstrips * sizeof (uint32), "for strip array")) == NULL)
1009 		return (0);
1010 	lp = *lpp;
1011 	if (dir->tdir_type == (int)TIFF_SHORT) {
1012 		/*
1013 		 * Handle uint16->uint32 expansion.
1014 		 */
1015 		uint16 *dp = (uint16 *)CheckMalloc(tif,
1016 		    dir->tdir_count* sizeof (uint16), "to fetch strip tag");
1017 		if (dp == NULL)
1018 			return (0);
1019 		if (status = TIFFFetchShortArray(tif, dir, dp)) {
1020 			register uint16 *wp = dp;
1021 			while (nstrips-- > 0)
1022 				*lp++ = *wp++;
1023 		}
1024 		_TIFFfree((char *)dp);
1025 	} else
1026 		status = TIFFFetchLongArray(tif, dir, lp);
1027 	return (status);
1028 }
1029 
1030 #define	NITEMS(x)	(sizeof (x) / sizeof (x[0]))
1031 /*
1032  * Fetch and set the ExtraSamples tag.
1033  */
1034 static int
TIFFFetchExtraSamples(TIFF * tif,TIFFDirEntry * dir)1035 TIFFFetchExtraSamples(TIFF* tif, TIFFDirEntry* dir)
1036 {
1037 	uint16 buf[10], *v = buf;
1038 	int status;
1039 
1040 	if (dir->tdir_count > NITEMS(buf))
1041 		v = (uint16*)_TIFFmalloc(dir->tdir_count * sizeof (uint16));
1042 	if (dir->tdir_type == TIFF_BYTE)
1043 		status = TIFFFetchByteArray(tif, dir, v);
1044 	else
1045 		status = TIFFFetchShortArray(tif, dir, v);
1046 	if (status)
1047 		status = TIFFSetField(tif, dir->tdir_tag, dir->tdir_count, v);
1048 	if (v != buf)
1049 		_TIFFfree((char *)v);
1050 	return (status);
1051 }
1052 #undef NITEMS
1053 
1054 #ifdef COLORIMETRY_SUPPORT
1055 /*
1056  * Fetch and set the RefBlackWhite tag.
1057  */
1058 static int
TIFFFetchRefBlackWhite(TIFF * tif,TIFFDirEntry * dir)1059 TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir)
1060 {
1061 	static char mesg[] = "for \"ReferenceBlackWhite\" array";
1062 	char* cp;
1063 	int ok;
1064 
1065 	if (dir->tdir_type == TIFF_RATIONAL)
1066 		return (TIFFFetchNormalTag(tif, dir));
1067 	/*
1068 	 * Handle LONG's for backward compatibility.
1069 	 */
1070 	cp = CheckMalloc(tif, dir->tdir_count * sizeof (uint32), mesg);
1071 	if (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*)cp))) {
1072 		float *fp = (float *)
1073 		    CheckMalloc(tif, dir->tdir_count * sizeof (float), mesg);
1074 		if (ok = (fp != NULL)) {
1075 			uint32 i;
1076 			for (i = 0; i < dir->tdir_count; i++)
1077 				fp[i] = (float)((uint32*)cp)[i];
1078 			ok = TIFFSetField(tif, dir->tdir_tag, fp);
1079 			_TIFFfree((char *)fp);
1080 		}
1081 	}
1082 	if (cp)
1083 		_TIFFfree(cp);
1084 	return (ok);
1085 }
1086 #endif
1087 
1088 #ifdef JPEG_SUPPORT
1089 /*
1090  * Fetch the JPEG Quantization tables
1091  * for the specified directory entry.
1092  * Storage for the td_qtab array is
1093  * allocated as a side effect.
1094  */
1095 static int
TIFFFetchJPEGQTables(TIFF * tif,TIFFDirEntry * dir)1096 TIFFFetchJPEGQTables(TIFF* tif, TIFFDirEntry* dir)
1097 {
1098 	TIFFDirectory *td = &tif->tif_dir;
1099 	uint32 off[4], i;
1100 	TIFFDirEntry tdir;
1101 	char *qmat;
1102 
1103 	if (dir->tdir_count > 1) {
1104 		/* XXX verify count <= 4 */
1105 		if (!TIFFFetchData(tif, dir, (char *)off))
1106 			return (0);
1107 	} else
1108 		off[0] = dir->tdir_offset;
1109 	/*
1110 	 * We don't share per-component q matrices because
1111 	 * (besides complicating this logic even more), it
1112 	 * would make it very painful if the user does a ``set''.
1113 	 */
1114 	td->td_qtab = (u_char **)CheckMalloc(tif,
1115 	    dir->tdir_count*(sizeof (u_char *) + 64*sizeof (u_char)),
1116 	    "for JPEG Q table");
1117 	if (td->td_qtab == NULL)
1118 		return (0);
1119 	tdir.tdir_type = TIFF_BYTE;
1120 	tdir.tdir_count = 64;
1121 	qmat = (((char *)td->td_qtab) + dir->tdir_count*sizeof (u_char *));
1122 	for (i = 0; i < dir->tdir_count; i++) {
1123 		td->td_qtab[i] = (u_char *)qmat;
1124 		tdir.tdir_offset = off[i];
1125 		if (!TIFFFetchData(tif, &tdir, qmat))
1126 			return (0);
1127 		qmat += 64*sizeof (u_char);
1128 	}
1129 	return (1);
1130 }
1131 
1132 /*
1133  * Fetch JPEG Huffman code tables for the
1134  * specified directory entry.  Storage for
1135  * the tables are allocated as a side effect.
1136  */
1137 static int
TIFFFetchJPEGCTables(TIFF * tif,TIFFDirEntry * dir,u_char *** ptab)1138 TIFFFetchJPEGCTables(TIFF* tif, TIFFDirEntry* dir, u_char*** ptab)
1139 {
1140 	uint32 off[4], i;
1141 	int j, ncodes;
1142 	TIFFDirEntry tdir;
1143 	char *tab;
1144 
1145 	if (dir->tdir_count > 1) {
1146 		/* XXX verify count <= 4 */
1147 		if (!TIFFFetchData(tif, dir, (char *)off))
1148 			return (0);
1149 	} else
1150 		off[0] = dir->tdir_offset;
1151 	/*
1152 	 * We don't share per-component tables because
1153 	 * (besides complicating this logic even more), it
1154 	 * would make it very painful if the user does a
1155 	 * ``set''.  Note also that we don't try to optimize
1156 	 * storage of the tables -- we just allocate enough
1157 	 * space to hold the largest possible.  All this
1158 	 * stuff is so complicated 'cuz the tag is defined
1159 	 * to be compatible with the JPEG table format,
1160 	 * rather than something that fits well into the
1161 	 * structure of TIFF -- argh!
1162 	 */
1163 	*ptab = (u_char **)CheckMalloc(tif, dir->tdir_count*
1164 	    (sizeof (u_char *) + (16+256)*sizeof (u_char)),
1165 	    "for JPEG Huffman table");
1166 	if (*ptab == NULL)
1167 		return (0);
1168 	tdir.tdir_type = TIFF_BYTE;
1169 	tab = (((char *)*ptab) + dir->tdir_count*sizeof (u_char *));
1170 	for (i = 0; i < dir->tdir_count; i++) {
1171 		(*ptab)[i] = (u_char *)tab;
1172 		tdir.tdir_offset = off[i];
1173 		tdir.tdir_count = 16;
1174 		/*
1175 		 * We must fetch the array that holds the
1176 		 * count of codes for each bit length first
1177 		 * and the count up the number of codes that
1178 		 * are in the variable length table.  This
1179 		 * information is implicit in the JPEG format
1180 		 * 'cuz it's preceded by a length field.
1181 		 */
1182 		if (!TIFFFetchData(tif, &tdir, tab))	/* count array */
1183 			return (0);
1184 		for (ncodes = 0, j = 0; j < 16; j++)
1185 			ncodes += tab[j];
1186 		/*
1187 		 * Adjust offsets and fetch codes separately.
1188 		 */
1189 		tdir.tdir_offset += 16;
1190 		tdir.tdir_count = ncodes;
1191 		tab += 16;
1192 		if (!TIFFFetchData(tif, &tdir, tab))
1193 			return (0);
1194 		tab += ncodes;
1195 	}
1196 	return (1);
1197 }
1198 #endif
1199 
1200 #if STRIPCHOP_SUPPORT
1201 /*
1202  * Replace a single strip (tile) of uncompressed data by
1203  * multiple strips (tiles), each approximately 8Kbytes.
1204  * This is useful for dealing with large images or
1205  * for dealing with machines with a limited amount
1206  * memory.
1207  */
1208 static void
ChopUpSingleUncompressedStrip(TIFF * tif)1209 ChopUpSingleUncompressedStrip(TIFF* tif)
1210 {
1211 	register TIFFDirectory *td = &tif->tif_dir;
1212 	uint32 bytecount = td->td_stripbytecount[0];
1213 	uint32 offset = td->td_stripoffset[0];
1214 	tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes;
1215 	tstrip_t strip, nstrips, rowsperstrip;
1216 	uint32* newcounts;
1217 	uint32* newoffsets;
1218 
1219 	/*
1220 	 * Make the rows hold at least one
1221 	 * scanline, but fill 8k if possible.
1222 	 */
1223 	if (rowbytes > 8192) {
1224 		stripbytes = rowbytes;
1225 		rowsperstrip = 1;
1226 	} else {
1227 		rowsperstrip = 8192 / rowbytes;
1228 		stripbytes = rowbytes * rowsperstrip;
1229 	}
1230 	/* never increase the number of strips in an image */
1231 	if (rowsperstrip >= td->td_rowsperstrip)
1232 		return;
1233 	nstrips = (tstrip_t) howmany(bytecount, stripbytes);
1234 	newcounts = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32),
1235 				"for chopped \"StripByteCounts\" array");
1236 	newoffsets = (uint32*) CheckMalloc(tif, nstrips * sizeof (uint32),
1237 				"for chopped \"StripOffsets\" array");
1238 	if (newcounts == NULL || newoffsets == NULL) {
1239 	        /*
1240 		 * Unable to allocate new strip information, give
1241 		 * up and use the original one strip information.
1242 		 */
1243 		if (newcounts != NULL)
1244 			_TIFFfree(newcounts);
1245 		if (newoffsets != NULL)
1246 			_TIFFfree(newoffsets);
1247 		return;
1248 	}
1249 	/*
1250 	 * Fill the strip information arrays with
1251 	 * new bytecounts and offsets that reflect
1252 	 * the broken-up format.
1253 	 */
1254 	for (strip = 0; strip < nstrips; strip++) {
1255 		if (stripbytes > bytecount)
1256 			stripbytes = bytecount;
1257 		newcounts[strip] = stripbytes;
1258 		newoffsets[strip] = offset;
1259 		offset += stripbytes;
1260 		bytecount -= stripbytes;
1261 	}
1262 	/*
1263 	 * Replace old single strip info with multi-strip info.
1264 	 */
1265 	td->td_stripsperimage = td->td_nstrips = nstrips;
1266 	TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
1267 
1268 	_TIFFfree(td->td_stripbytecount);
1269 	_TIFFfree(td->td_stripoffset);
1270 	td->td_stripbytecount = newcounts;
1271 	td->td_stripoffset = newoffsets;
1272 }
1273 #endif /* STRIPCHOP_SUPPORT */
1274