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