1 /*
2  * Copyright (c) 1988-1997 Sam Leffler
3  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and
6  * its documentation for any purpose is hereby granted without fee, provided
7  * that (i) the above copyright notices and this permission notice appear in
8  * all copies of the software and related documentation, and (ii) the names of
9  * Sam Leffler and Silicon Graphics may not be used in any advertising or
10  * publicity relating to the software without the specific, prior written
11  * permission of Sam Leffler and Silicon Graphics.
12  *
13  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16  *
17  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22  * OF THIS SOFTWARE.
23  */
24 
25 /*
26  * TIFF Library.
27  *
28  * Directory Read Support Routines.
29  */
30 
31 /* Suggested pending improvements:
32  * - add a field 'field_info' to the TIFFDirEntry structure, and set that with
33  *   the pointer to the appropriate TIFFField structure early on in
34  *   TIFFReadDirectory, so as to eliminate current possibly repetitive lookup.
35  */
36 
37 #include "tiffiop.h"
38 #include <float.h>
39 #include <stdlib.h>
40 
41 #define FAILED_FII    ((uint32) -1)
42 
43 /*
44  * Largest 64-bit signed integer value.
45  */
46 #define TIFF_INT64_MAX ((int64)(TIFF_UINT64_MAX >> 1))
47 
48 #ifdef HAVE_IEEEFP
49 # define TIFFCvtIEEEFloatToNative(tif, n, fp)
50 # define TIFFCvtIEEEDoubleToNative(tif, n, dp)
51 #else
52 extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*);
53 extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*);
54 #endif
55 
56 enum TIFFReadDirEntryErr {
57 	TIFFReadDirEntryErrOk = 0,
58 	TIFFReadDirEntryErrCount = 1,
59 	TIFFReadDirEntryErrType = 2,
60 	TIFFReadDirEntryErrIo = 3,
61 	TIFFReadDirEntryErrRange = 4,
62 	TIFFReadDirEntryErrPsdif = 5,
63 	TIFFReadDirEntryErrSizesan = 6,
64 	TIFFReadDirEntryErrAlloc = 7,
65 };
66 
67 static enum TIFFReadDirEntryErr TIFFReadDirEntryByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value);
68 static enum TIFFReadDirEntryErr TIFFReadDirEntryShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value);
69 static enum TIFFReadDirEntryErr TIFFReadDirEntryLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value);
70 static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value);
71 static enum TIFFReadDirEntryErr TIFFReadDirEntryFloat(TIFF* tif, TIFFDirEntry* direntry, float* value);
72 static enum TIFFReadDirEntryErr TIFFReadDirEntryDouble(TIFF* tif, TIFFDirEntry* direntry, double* value);
73 static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8(TIFF* tif, TIFFDirEntry* direntry, uint64* value);
74 
75 static enum TIFFReadDirEntryErr TIFFReadDirEntryArray(TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize, void** value);
76 static enum TIFFReadDirEntryErr TIFFReadDirEntryByteArray(TIFF* tif, TIFFDirEntry* direntry, uint8** value);
77 static enum TIFFReadDirEntryErr TIFFReadDirEntrySbyteArray(TIFF* tif, TIFFDirEntry* direntry, int8** value);
78 static enum TIFFReadDirEntryErr TIFFReadDirEntryShortArray(TIFF* tif, TIFFDirEntry* direntry, uint16** value);
79 static enum TIFFReadDirEntryErr TIFFReadDirEntrySshortArray(TIFF* tif, TIFFDirEntry* direntry, int16** value);
80 static enum TIFFReadDirEntryErr TIFFReadDirEntryLongArray(TIFF* tif, TIFFDirEntry* direntry, uint32** value);
81 static enum TIFFReadDirEntryErr TIFFReadDirEntrySlongArray(TIFF* tif, TIFFDirEntry* direntry, int32** value);
82 static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value);
83 static enum TIFFReadDirEntryErr TIFFReadDirEntrySlong8Array(TIFF* tif, TIFFDirEntry* direntry, int64** value);
84 static enum TIFFReadDirEntryErr TIFFReadDirEntryFloatArray(TIFF* tif, TIFFDirEntry* direntry, float** value);
85 static enum TIFFReadDirEntryErr TIFFReadDirEntryDoubleArray(TIFF* tif, TIFFDirEntry* direntry, double** value);
86 static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value);
87 
88 static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value);
89 #if 0
90 static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleDouble(TIFF* tif, TIFFDirEntry* direntry, double* value);
91 #endif
92 
93 static void TIFFReadDirEntryCheckedByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value);
94 static void TIFFReadDirEntryCheckedSbyte(TIFF* tif, TIFFDirEntry* direntry, int8* value);
95 static void TIFFReadDirEntryCheckedShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value);
96 static void TIFFReadDirEntryCheckedSshort(TIFF* tif, TIFFDirEntry* direntry, int16* value);
97 static void TIFFReadDirEntryCheckedLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value);
98 static void TIFFReadDirEntryCheckedSlong(TIFF* tif, TIFFDirEntry* direntry, int32* value);
99 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value);
100 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSlong8(TIFF* tif, TIFFDirEntry* direntry, int64* value);
101 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedRational(TIFF* tif, TIFFDirEntry* direntry, double* value);
102 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSrational(TIFF* tif, TIFFDirEntry* direntry, double* value);
103 static void TIFFReadDirEntryCheckedFloat(TIFF* tif, TIFFDirEntry* direntry, float* value);
104 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedDouble(TIFF* tif, TIFFDirEntry* direntry, double* value);
105 
106 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSbyte(int8 value);
107 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteShort(uint16 value);
108 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSshort(int16 value);
109 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong(uint32 value);
110 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong(int32 value);
111 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong8(uint64 value);
112 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong8(int64 value);
113 
114 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteByte(uint8 value);
115 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteShort(uint16 value);
116 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSshort(int16 value);
117 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong(uint32 value);
118 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong(int32 value);
119 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong8(uint64 value);
120 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong8(int64 value);
121 
122 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSbyte(int8 value);
123 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSshort(int16 value);
124 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong(uint32 value);
125 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong(int32 value);
126 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong8(uint64 value);
127 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong8(int64 value);
128 
129 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortShort(uint16 value);
130 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong(uint32 value);
131 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong(int32 value);
132 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong8(uint64 value);
133 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong8(int64 value);
134 
135 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSbyte(int8 value);
136 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSshort(int16 value);
137 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong(int32 value);
138 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongLong8(uint64 value);
139 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong8(int64 value);
140 
141 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongLong(uint32 value);
142 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongLong8(uint64 value);
143 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongSlong8(int64 value);
144 
145 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Sbyte(int8 value);
146 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Sshort(int16 value);
147 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Slong(int32 value);
148 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Slong8(int64 value);
149 
150 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlong8Long8(uint64 value);
151 
152 static enum TIFFReadDirEntryErr TIFFReadDirEntryData(TIFF* tif, uint64 offset, tmsize_t size, void* dest);
153 static void TIFFReadDirEntryOutputErr(TIFF* tif, enum TIFFReadDirEntryErr err, const char* module, const char* tagname, int recover);
154 
155 static void TIFFReadDirectoryCheckOrder(TIFF* tif, TIFFDirEntry* dir, uint16 dircount);
156 static TIFFDirEntry* TIFFReadDirectoryFindEntry(TIFF* tif, TIFFDirEntry* dir, uint16 dircount, uint16 tagid);
157 static void TIFFReadDirectoryFindFieldInfo(TIFF* tif, uint16 tagid, uint32* fii);
158 
159 static int EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount);
160 static void MissingRequired(TIFF*, const char*);
161 static int TIFFCheckDirOffset(TIFF* tif, uint64 diroff);
162 static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32);
163 static uint16 TIFFFetchDirectory(TIFF* tif, uint64 diroff, TIFFDirEntry** pdir, uint64* nextdiroff);
164 static int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*, int recover);
165 static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, uint32 nstrips, uint64** lpp);
166 static int TIFFFetchSubjectDistance(TIFF*, TIFFDirEntry*);
167 static void ChopUpSingleUncompressedStrip(TIFF*);
168 static void TryChopUpUncompressedBigTiff(TIFF*);
169 static uint64 TIFFReadUInt64(const uint8 *value);
170 static int _TIFFGetMaxColorChannels(uint16 photometric);
171 
172 static int _TIFFFillStrilesInternal( TIFF *tif, int loadStripByteCount );
173 
174 typedef union _UInt64Aligned_t
175 {
176         double d;
177 	uint64 l;
178 	uint32 i[2];
179 	uint16 s[4];
180 	uint8  c[8];
181 } UInt64Aligned_t;
182 
183 /*
184   Unaligned safe copy of a uint64 value from an octet array.
185 */
TIFFReadUInt64(const uint8 * value)186 static uint64 TIFFReadUInt64(const uint8 *value)
187 {
188 	UInt64Aligned_t result;
189 
190 	result.c[0]=value[0];
191 	result.c[1]=value[1];
192 	result.c[2]=value[2];
193 	result.c[3]=value[3];
194 	result.c[4]=value[4];
195 	result.c[5]=value[5];
196 	result.c[6]=value[6];
197 	result.c[7]=value[7];
198 
199 	return result.l;
200 }
201 
TIFFReadDirEntryByte(TIFF * tif,TIFFDirEntry * direntry,uint8 * value)202 static enum TIFFReadDirEntryErr TIFFReadDirEntryByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value)
203 {
204 	enum TIFFReadDirEntryErr err;
205 	if (direntry->tdir_count!=1)
206 		return(TIFFReadDirEntryErrCount);
207 	switch (direntry->tdir_type)
208 	{
209 		case TIFF_BYTE:
210 		case TIFF_UNDEFINED:	/* Support to read TIFF_UNDEFINED with field_readcount==1 */
211 			TIFFReadDirEntryCheckedByte(tif,direntry,value);
212 			return(TIFFReadDirEntryErrOk);
213 		case TIFF_SBYTE:
214 			{
215 				int8 m;
216 				TIFFReadDirEntryCheckedSbyte(tif,direntry,&m);
217 				err=TIFFReadDirEntryCheckRangeByteSbyte(m);
218 				if (err!=TIFFReadDirEntryErrOk)
219 					return(err);
220 				*value=(uint8)m;
221 				return(TIFFReadDirEntryErrOk);
222 			}
223 		case TIFF_SHORT:
224 			{
225 				uint16 m;
226 				TIFFReadDirEntryCheckedShort(tif,direntry,&m);
227 				err=TIFFReadDirEntryCheckRangeByteShort(m);
228 				if (err!=TIFFReadDirEntryErrOk)
229 					return(err);
230 				*value=(uint8)m;
231 				return(TIFFReadDirEntryErrOk);
232 			}
233 		case TIFF_SSHORT:
234 			{
235 				int16 m;
236 				TIFFReadDirEntryCheckedSshort(tif,direntry,&m);
237 				err=TIFFReadDirEntryCheckRangeByteSshort(m);
238 				if (err!=TIFFReadDirEntryErrOk)
239 					return(err);
240 				*value=(uint8)m;
241 				return(TIFFReadDirEntryErrOk);
242 			}
243 		case TIFF_LONG:
244 			{
245 				uint32 m;
246 				TIFFReadDirEntryCheckedLong(tif,direntry,&m);
247 				err=TIFFReadDirEntryCheckRangeByteLong(m);
248 				if (err!=TIFFReadDirEntryErrOk)
249 					return(err);
250 				*value=(uint8)m;
251 				return(TIFFReadDirEntryErrOk);
252 			}
253 		case TIFF_SLONG:
254 			{
255 				int32 m;
256 				TIFFReadDirEntryCheckedSlong(tif,direntry,&m);
257 				err=TIFFReadDirEntryCheckRangeByteSlong(m);
258 				if (err!=TIFFReadDirEntryErrOk)
259 					return(err);
260 				*value=(uint8)m;
261 				return(TIFFReadDirEntryErrOk);
262 			}
263 		case TIFF_LONG8:
264 			{
265 				uint64 m;
266 				err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m);
267 				if (err!=TIFFReadDirEntryErrOk)
268 					return(err);
269 				err=TIFFReadDirEntryCheckRangeByteLong8(m);
270 				if (err!=TIFFReadDirEntryErrOk)
271 					return(err);
272 				*value=(uint8)m;
273 				return(TIFFReadDirEntryErrOk);
274 			}
275 		case TIFF_SLONG8:
276 			{
277 				int64 m;
278 				err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m);
279 				if (err!=TIFFReadDirEntryErrOk)
280 					return(err);
281 				err=TIFFReadDirEntryCheckRangeByteSlong8(m);
282 				if (err!=TIFFReadDirEntryErrOk)
283 					return(err);
284 				*value=(uint8)m;
285 				return(TIFFReadDirEntryErrOk);
286 			}
287 		default:
288 			return(TIFFReadDirEntryErrType);
289 	}
290 }
291 
TIFFReadDirEntryShort(TIFF * tif,TIFFDirEntry * direntry,uint16 * value)292 static enum TIFFReadDirEntryErr TIFFReadDirEntryShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value)
293 {
294 	enum TIFFReadDirEntryErr err;
295 	if (direntry->tdir_count!=1)
296 		return(TIFFReadDirEntryErrCount);
297 	switch (direntry->tdir_type)
298 	{
299 		case TIFF_BYTE:
300 			{
301 				uint8 m;
302 				TIFFReadDirEntryCheckedByte(tif,direntry,&m);
303 				*value=(uint16)m;
304 				return(TIFFReadDirEntryErrOk);
305 			}
306 		case TIFF_SBYTE:
307 			{
308 				int8 m;
309 				TIFFReadDirEntryCheckedSbyte(tif,direntry,&m);
310 				err=TIFFReadDirEntryCheckRangeShortSbyte(m);
311 				if (err!=TIFFReadDirEntryErrOk)
312 					return(err);
313 				*value=(uint16)m;
314 				return(TIFFReadDirEntryErrOk);
315 			}
316 		case TIFF_SHORT:
317 			TIFFReadDirEntryCheckedShort(tif,direntry,value);
318 			return(TIFFReadDirEntryErrOk);
319 		case TIFF_SSHORT:
320 			{
321 				int16 m;
322 				TIFFReadDirEntryCheckedSshort(tif,direntry,&m);
323 				err=TIFFReadDirEntryCheckRangeShortSshort(m);
324 				if (err!=TIFFReadDirEntryErrOk)
325 					return(err);
326 				*value=(uint16)m;
327 				return(TIFFReadDirEntryErrOk);
328 			}
329 		case TIFF_LONG:
330 			{
331 				uint32 m;
332 				TIFFReadDirEntryCheckedLong(tif,direntry,&m);
333 				err=TIFFReadDirEntryCheckRangeShortLong(m);
334 				if (err!=TIFFReadDirEntryErrOk)
335 					return(err);
336 				*value=(uint16)m;
337 				return(TIFFReadDirEntryErrOk);
338 			}
339 		case TIFF_SLONG:
340 			{
341 				int32 m;
342 				TIFFReadDirEntryCheckedSlong(tif,direntry,&m);
343 				err=TIFFReadDirEntryCheckRangeShortSlong(m);
344 				if (err!=TIFFReadDirEntryErrOk)
345 					return(err);
346 				*value=(uint16)m;
347 				return(TIFFReadDirEntryErrOk);
348 			}
349 		case TIFF_LONG8:
350 			{
351 				uint64 m;
352 				err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m);
353 				if (err!=TIFFReadDirEntryErrOk)
354 					return(err);
355 				err=TIFFReadDirEntryCheckRangeShortLong8(m);
356 				if (err!=TIFFReadDirEntryErrOk)
357 					return(err);
358 				*value=(uint16)m;
359 				return(TIFFReadDirEntryErrOk);
360 			}
361 		case TIFF_SLONG8:
362 			{
363 				int64 m;
364 				err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m);
365 				if (err!=TIFFReadDirEntryErrOk)
366 					return(err);
367 				err=TIFFReadDirEntryCheckRangeShortSlong8(m);
368 				if (err!=TIFFReadDirEntryErrOk)
369 					return(err);
370 				*value=(uint16)m;
371 				return(TIFFReadDirEntryErrOk);
372 			}
373 		default:
374 			return(TIFFReadDirEntryErrType);
375 	}
376 }
377 
TIFFReadDirEntryLong(TIFF * tif,TIFFDirEntry * direntry,uint32 * value)378 static enum TIFFReadDirEntryErr TIFFReadDirEntryLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value)
379 {
380 	enum TIFFReadDirEntryErr err;
381 	if (direntry->tdir_count!=1)
382 		return(TIFFReadDirEntryErrCount);
383 	switch (direntry->tdir_type)
384 	{
385 		case TIFF_BYTE:
386 			{
387 				uint8 m;
388 				TIFFReadDirEntryCheckedByte(tif,direntry,&m);
389 				*value=(uint32)m;
390 				return(TIFFReadDirEntryErrOk);
391 			}
392 		case TIFF_SBYTE:
393 			{
394 				int8 m;
395 				TIFFReadDirEntryCheckedSbyte(tif,direntry,&m);
396 				err=TIFFReadDirEntryCheckRangeLongSbyte(m);
397 				if (err!=TIFFReadDirEntryErrOk)
398 					return(err);
399 				*value=(uint32)m;
400 				return(TIFFReadDirEntryErrOk);
401 			}
402 		case TIFF_SHORT:
403 			{
404 				uint16 m;
405 				TIFFReadDirEntryCheckedShort(tif,direntry,&m);
406 				*value=(uint32)m;
407 				return(TIFFReadDirEntryErrOk);
408 			}
409 		case TIFF_SSHORT:
410 			{
411 				int16 m;
412 				TIFFReadDirEntryCheckedSshort(tif,direntry,&m);
413 				err=TIFFReadDirEntryCheckRangeLongSshort(m);
414 				if (err!=TIFFReadDirEntryErrOk)
415 					return(err);
416 				*value=(uint32)m;
417 				return(TIFFReadDirEntryErrOk);
418 			}
419 		case TIFF_LONG:
420 			TIFFReadDirEntryCheckedLong(tif,direntry,value);
421 			return(TIFFReadDirEntryErrOk);
422 		case TIFF_SLONG:
423 			{
424 				int32 m;
425 				TIFFReadDirEntryCheckedSlong(tif,direntry,&m);
426 				err=TIFFReadDirEntryCheckRangeLongSlong(m);
427 				if (err!=TIFFReadDirEntryErrOk)
428 					return(err);
429 				*value=(uint32)m;
430 				return(TIFFReadDirEntryErrOk);
431 			}
432 		case TIFF_LONG8:
433 			{
434 				uint64 m;
435 				err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m);
436 				if (err!=TIFFReadDirEntryErrOk)
437 					return(err);
438 				err=TIFFReadDirEntryCheckRangeLongLong8(m);
439 				if (err!=TIFFReadDirEntryErrOk)
440 					return(err);
441 				*value=(uint32)m;
442 				return(TIFFReadDirEntryErrOk);
443 			}
444 		case TIFF_SLONG8:
445 			{
446 				int64 m;
447 				err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m);
448 				if (err!=TIFFReadDirEntryErrOk)
449 					return(err);
450 				err=TIFFReadDirEntryCheckRangeLongSlong8(m);
451 				if (err!=TIFFReadDirEntryErrOk)
452 					return(err);
453 				*value=(uint32)m;
454 				return(TIFFReadDirEntryErrOk);
455 			}
456 		default:
457 			return(TIFFReadDirEntryErrType);
458 	}
459 }
460 
TIFFReadDirEntryLong8(TIFF * tif,TIFFDirEntry * direntry,uint64 * value)461 static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value)
462 {
463 	enum TIFFReadDirEntryErr err;
464 	if (direntry->tdir_count!=1)
465 		return(TIFFReadDirEntryErrCount);
466 	switch (direntry->tdir_type)
467 	{
468 		case TIFF_BYTE:
469 			{
470 				uint8 m;
471 				TIFFReadDirEntryCheckedByte(tif,direntry,&m);
472 				*value=(uint64)m;
473 				return(TIFFReadDirEntryErrOk);
474 			}
475 		case TIFF_SBYTE:
476 			{
477 				int8 m;
478 				TIFFReadDirEntryCheckedSbyte(tif,direntry,&m);
479 				err=TIFFReadDirEntryCheckRangeLong8Sbyte(m);
480 				if (err!=TIFFReadDirEntryErrOk)
481 					return(err);
482 				*value=(uint64)m;
483 				return(TIFFReadDirEntryErrOk);
484 			}
485 		case TIFF_SHORT:
486 			{
487 				uint16 m;
488 				TIFFReadDirEntryCheckedShort(tif,direntry,&m);
489 				*value=(uint64)m;
490 				return(TIFFReadDirEntryErrOk);
491 			}
492 		case TIFF_SSHORT:
493 			{
494 				int16 m;
495 				TIFFReadDirEntryCheckedSshort(tif,direntry,&m);
496 				err=TIFFReadDirEntryCheckRangeLong8Sshort(m);
497 				if (err!=TIFFReadDirEntryErrOk)
498 					return(err);
499 				*value=(uint64)m;
500 				return(TIFFReadDirEntryErrOk);
501 			}
502 		case TIFF_LONG:
503 			{
504 				uint32 m;
505 				TIFFReadDirEntryCheckedLong(tif,direntry,&m);
506 				*value=(uint64)m;
507 				return(TIFFReadDirEntryErrOk);
508 			}
509 		case TIFF_SLONG:
510 			{
511 				int32 m;
512 				TIFFReadDirEntryCheckedSlong(tif,direntry,&m);
513 				err=TIFFReadDirEntryCheckRangeLong8Slong(m);
514 				if (err!=TIFFReadDirEntryErrOk)
515 					return(err);
516 				*value=(uint64)m;
517 				return(TIFFReadDirEntryErrOk);
518 			}
519 		case TIFF_LONG8:
520 			err=TIFFReadDirEntryCheckedLong8(tif,direntry,value);
521 			return(err);
522 		case TIFF_SLONG8:
523 			{
524 				int64 m;
525 				err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m);
526 				if (err!=TIFFReadDirEntryErrOk)
527 					return(err);
528 				err=TIFFReadDirEntryCheckRangeLong8Slong8(m);
529 				if (err!=TIFFReadDirEntryErrOk)
530 					return(err);
531 				*value=(uint64)m;
532 				return(TIFFReadDirEntryErrOk);
533 			}
534 		default:
535 			return(TIFFReadDirEntryErrType);
536 	}
537 }
538 
TIFFReadDirEntryFloat(TIFF * tif,TIFFDirEntry * direntry,float * value)539 static enum TIFFReadDirEntryErr TIFFReadDirEntryFloat(TIFF* tif, TIFFDirEntry* direntry, float* value)
540 {
541 	enum TIFFReadDirEntryErr err;
542 	if (direntry->tdir_count!=1)
543 		return(TIFFReadDirEntryErrCount);
544 	switch (direntry->tdir_type)
545 	{
546 		case TIFF_BYTE:
547 			{
548 				uint8 m;
549 				TIFFReadDirEntryCheckedByte(tif,direntry,&m);
550 				*value=(float)m;
551 				return(TIFFReadDirEntryErrOk);
552 			}
553 		case TIFF_SBYTE:
554 			{
555 				int8 m;
556 				TIFFReadDirEntryCheckedSbyte(tif,direntry,&m);
557 				*value=(float)m;
558 				return(TIFFReadDirEntryErrOk);
559 			}
560 		case TIFF_SHORT:
561 			{
562 				uint16 m;
563 				TIFFReadDirEntryCheckedShort(tif,direntry,&m);
564 				*value=(float)m;
565 				return(TIFFReadDirEntryErrOk);
566 			}
567 		case TIFF_SSHORT:
568 			{
569 				int16 m;
570 				TIFFReadDirEntryCheckedSshort(tif,direntry,&m);
571 				*value=(float)m;
572 				return(TIFFReadDirEntryErrOk);
573 			}
574 		case TIFF_LONG:
575 			{
576 				uint32 m;
577 				TIFFReadDirEntryCheckedLong(tif,direntry,&m);
578 				*value=(float)m;
579 				return(TIFFReadDirEntryErrOk);
580 			}
581 		case TIFF_SLONG:
582 			{
583 				int32 m;
584 				TIFFReadDirEntryCheckedSlong(tif,direntry,&m);
585 				*value=(float)m;
586 				return(TIFFReadDirEntryErrOk);
587 			}
588 		case TIFF_LONG8:
589 			{
590 				uint64 m;
591 				err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m);
592 				if (err!=TIFFReadDirEntryErrOk)
593 					return(err);
594 #if defined(__WIN32__) && (_MSC_VER < 1500)
595 				/*
596 				 * XXX: MSVC 6.0 does not support conversion
597 				 * of 64-bit integers into floating point
598 				 * values.
599 				 */
600 				*value = _TIFFUInt64ToFloat(m);
601 #else
602 				*value=(float)m;
603 #endif
604 				return(TIFFReadDirEntryErrOk);
605 			}
606 		case TIFF_SLONG8:
607 			{
608 				int64 m;
609 				err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m);
610 				if (err!=TIFFReadDirEntryErrOk)
611 					return(err);
612 				*value=(float)m;
613 				return(TIFFReadDirEntryErrOk);
614 			}
615 		case TIFF_RATIONAL:
616 			{
617 				double m;
618 				err=TIFFReadDirEntryCheckedRational(tif,direntry,&m);
619 				if (err!=TIFFReadDirEntryErrOk)
620 					return(err);
621 				*value=(float)m;
622 				return(TIFFReadDirEntryErrOk);
623 			}
624 		case TIFF_SRATIONAL:
625 			{
626 				double m;
627 				err=TIFFReadDirEntryCheckedSrational(tif,direntry,&m);
628 				if (err!=TIFFReadDirEntryErrOk)
629 					return(err);
630 				*value=(float)m;
631 				return(TIFFReadDirEntryErrOk);
632 			}
633 		case TIFF_FLOAT:
634 			TIFFReadDirEntryCheckedFloat(tif,direntry,value);
635 			return(TIFFReadDirEntryErrOk);
636 		case TIFF_DOUBLE:
637 			{
638 				double m;
639 				err=TIFFReadDirEntryCheckedDouble(tif,direntry,&m);
640 				if (err!=TIFFReadDirEntryErrOk)
641 					return(err);
642 				if ((m > FLT_MAX) || (m < FLT_MIN))
643 					return(TIFFReadDirEntryErrRange);
644 				*value=(float)m;
645 				return(TIFFReadDirEntryErrOk);
646 			}
647 		default:
648 			return(TIFFReadDirEntryErrType);
649 	}
650 }
651 
TIFFReadDirEntryDouble(TIFF * tif,TIFFDirEntry * direntry,double * value)652 static enum TIFFReadDirEntryErr TIFFReadDirEntryDouble(TIFF* tif, TIFFDirEntry* direntry, double* value)
653 {
654 	enum TIFFReadDirEntryErr err;
655 	if (direntry->tdir_count!=1)
656 		return(TIFFReadDirEntryErrCount);
657 	switch (direntry->tdir_type)
658 	{
659 		case TIFF_BYTE:
660 			{
661 				uint8 m;
662 				TIFFReadDirEntryCheckedByte(tif,direntry,&m);
663 				*value=(double)m;
664 				return(TIFFReadDirEntryErrOk);
665 			}
666 		case TIFF_SBYTE:
667 			{
668 				int8 m;
669 				TIFFReadDirEntryCheckedSbyte(tif,direntry,&m);
670 				*value=(double)m;
671 				return(TIFFReadDirEntryErrOk);
672 			}
673 		case TIFF_SHORT:
674 			{
675 				uint16 m;
676 				TIFFReadDirEntryCheckedShort(tif,direntry,&m);
677 				*value=(double)m;
678 				return(TIFFReadDirEntryErrOk);
679 			}
680 		case TIFF_SSHORT:
681 			{
682 				int16 m;
683 				TIFFReadDirEntryCheckedSshort(tif,direntry,&m);
684 				*value=(double)m;
685 				return(TIFFReadDirEntryErrOk);
686 			}
687 		case TIFF_LONG:
688 			{
689 				uint32 m;
690 				TIFFReadDirEntryCheckedLong(tif,direntry,&m);
691 				*value=(double)m;
692 				return(TIFFReadDirEntryErrOk);
693 			}
694 		case TIFF_SLONG:
695 			{
696 				int32 m;
697 				TIFFReadDirEntryCheckedSlong(tif,direntry,&m);
698 				*value=(double)m;
699 				return(TIFFReadDirEntryErrOk);
700 			}
701 		case TIFF_LONG8:
702 			{
703 				uint64 m;
704 				err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m);
705 				if (err!=TIFFReadDirEntryErrOk)
706 					return(err);
707 #if defined(__WIN32__) && (_MSC_VER < 1500)
708 				/*
709 				 * XXX: MSVC 6.0 does not support conversion
710 				 * of 64-bit integers into floating point
711 				 * values.
712 				 */
713 				*value = _TIFFUInt64ToDouble(m);
714 #else
715 				*value = (double)m;
716 #endif
717 				return(TIFFReadDirEntryErrOk);
718 			}
719 		case TIFF_SLONG8:
720 			{
721 				int64 m;
722 				err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m);
723 				if (err!=TIFFReadDirEntryErrOk)
724 					return(err);
725 				*value=(double)m;
726 				return(TIFFReadDirEntryErrOk);
727 			}
728 		case TIFF_RATIONAL:
729 			err=TIFFReadDirEntryCheckedRational(tif,direntry,value);
730 			return(err);
731 		case TIFF_SRATIONAL:
732 			err=TIFFReadDirEntryCheckedSrational(tif,direntry,value);
733 			return(err);
734 		case TIFF_FLOAT:
735 			{
736 				float m;
737 				TIFFReadDirEntryCheckedFloat(tif,direntry,&m);
738 				*value=(double)m;
739 				return(TIFFReadDirEntryErrOk);
740 			}
741 		case TIFF_DOUBLE:
742 			err=TIFFReadDirEntryCheckedDouble(tif,direntry,value);
743 			return(err);
744 		default:
745 			return(TIFFReadDirEntryErrType);
746 	}
747 }
748 
TIFFReadDirEntryIfd8(TIFF * tif,TIFFDirEntry * direntry,uint64 * value)749 static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8(TIFF* tif, TIFFDirEntry* direntry, uint64* value)
750 {
751 	enum TIFFReadDirEntryErr err;
752 	if (direntry->tdir_count!=1)
753 		return(TIFFReadDirEntryErrCount);
754 	switch (direntry->tdir_type)
755 	{
756 		case TIFF_LONG:
757 		case TIFF_IFD:
758 			{
759 				uint32 m;
760 				TIFFReadDirEntryCheckedLong(tif,direntry,&m);
761 				*value=(uint64)m;
762 				return(TIFFReadDirEntryErrOk);
763 			}
764 		case TIFF_LONG8:
765 		case TIFF_IFD8:
766 			err=TIFFReadDirEntryCheckedLong8(tif,direntry,value);
767 			return(err);
768 		default:
769 			return(TIFFReadDirEntryErrType);
770 	}
771 }
772 
773 
774 #define INITIAL_THRESHOLD (1024 * 1024)
775 #define THRESHOLD_MULTIPLIER 10
776 #define MAX_THRESHOLD (THRESHOLD_MULTIPLIER * THRESHOLD_MULTIPLIER * THRESHOLD_MULTIPLIER * INITIAL_THRESHOLD)
777 
TIFFReadDirEntryDataAndRealloc(TIFF * tif,uint64 offset,tmsize_t size,void ** pdest)778 static enum TIFFReadDirEntryErr TIFFReadDirEntryDataAndRealloc(
779                     TIFF* tif, uint64 offset, tmsize_t size, void** pdest)
780 {
781 #if SIZEOF_SIZE_T == 8
782         tmsize_t threshold = INITIAL_THRESHOLD;
783 #endif
784         tmsize_t already_read = 0;
785 
786         assert( !isMapped(tif) );
787 
788         if (!SeekOK(tif,offset))
789                 return(TIFFReadDirEntryErrIo);
790 
791         /* On 64 bit processes, read first a maximum of 1 MB, then 10 MB, etc */
792         /* so as to avoid allocating too much memory in case the file is too */
793         /* short. We could ask for the file size, but this might be */
794         /* expensive with some I/O layers (think of reading a gzipped file) */
795         /* Restrict to 64 bit processes, so as to avoid reallocs() */
796         /* on 32 bit processes where virtual memory is scarce.  */
797         while( already_read < size )
798         {
799             void* new_dest;
800             tmsize_t bytes_read;
801             tmsize_t to_read = size - already_read;
802 #if SIZEOF_SIZE_T == 8
803             if( to_read >= threshold && threshold < MAX_THRESHOLD )
804             {
805                 to_read = threshold;
806                 threshold *= THRESHOLD_MULTIPLIER;
807             }
808 #endif
809 
810             new_dest = (uint8*) _TIFFrealloc(
811                             *pdest, already_read + to_read);
812             if( new_dest == NULL )
813             {
814                 TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
815                             "Failed to allocate memory for %s "
816                             "(%ld elements of %ld bytes each)",
817                             "TIFFReadDirEntryArray",
818                              (long) 1, (long) (already_read + to_read));
819                 return TIFFReadDirEntryErrAlloc;
820             }
821             *pdest = new_dest;
822 
823             bytes_read = TIFFReadFile(tif,
824                 (char*)*pdest + already_read, to_read);
825             already_read += bytes_read;
826             if (bytes_read != to_read) {
827                 return TIFFReadDirEntryErrIo;
828             }
829         }
830         return TIFFReadDirEntryErrOk;
831 }
832 
TIFFReadDirEntryArrayWithLimit(TIFF * tif,TIFFDirEntry * direntry,uint32 * count,uint32 desttypesize,void ** value,uint64 maxcount)833 static enum TIFFReadDirEntryErr TIFFReadDirEntryArrayWithLimit(
834     TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize,
835     void** value, uint64 maxcount)
836 {
837 	int typesize;
838 	uint32 datasize;
839 	void* data;
840         uint64 target_count64;
841 	typesize=TIFFDataWidth(direntry->tdir_type);
842 
843         target_count64 = (direntry->tdir_count > maxcount) ?
844                 maxcount : direntry->tdir_count;
845 
846 	if ((target_count64==0)||(typesize==0))
847 	{
848 		*value=0;
849 		return(TIFFReadDirEntryErrOk);
850 	}
851         (void) desttypesize;
852 
853         /*
854          * As a sanity check, make sure we have no more than a 2GB tag array
855          * in either the current data type or the dest data type.  This also
856          * avoids problems with overflow of tmsize_t on 32bit systems.
857          */
858 	if ((uint64)(2147483647/typesize)<target_count64)
859 		return(TIFFReadDirEntryErrSizesan);
860 	if ((uint64)(2147483647/desttypesize)<target_count64)
861 		return(TIFFReadDirEntryErrSizesan);
862 
863 	*count=(uint32)target_count64;
864 	datasize=(*count)*typesize;
865 	assert((tmsize_t)datasize>0);
866 
867 	if( isMapped(tif) && datasize > (uint32)tif->tif_size )
868 		return TIFFReadDirEntryErrIo;
869 
870 	if( !isMapped(tif) &&
871 		(((tif->tif_flags&TIFF_BIGTIFF) && datasize > 8) ||
872 		(!(tif->tif_flags&TIFF_BIGTIFF) && datasize > 4)) )
873 	{
874 		data = NULL;
875 	}
876 	else
877 	{
878 		data=_TIFFCheckMalloc(tif, *count, typesize, "ReadDirEntryArray");
879 		if (data==0)
880 			return(TIFFReadDirEntryErrAlloc);
881 	}
882 	if (!(tif->tif_flags&TIFF_BIGTIFF))
883 	{
884 		if (datasize<=4)
885 			_TIFFmemcpy(data,&direntry->tdir_offset,datasize);
886 		else
887 		{
888 			enum TIFFReadDirEntryErr err;
889 			uint32 offset = direntry->tdir_offset.toff_long;
890 			if (tif->tif_flags&TIFF_SWAB)
891 				TIFFSwabLong(&offset);
892 			if( isMapped(tif) )
893 				err=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data);
894 			else
895 				err=TIFFReadDirEntryDataAndRealloc(tif,(uint64)offset,(tmsize_t)datasize,&data);
896 			if (err!=TIFFReadDirEntryErrOk)
897 			{
898 				_TIFFfree(data);
899 				return(err);
900 			}
901 		}
902 	}
903 	else
904 	{
905 		if (datasize<=8)
906 			_TIFFmemcpy(data,&direntry->tdir_offset,datasize);
907 		else
908 		{
909 			enum TIFFReadDirEntryErr err;
910 			uint64 offset = direntry->tdir_offset.toff_long8;
911 			if (tif->tif_flags&TIFF_SWAB)
912 				TIFFSwabLong8(&offset);
913 			if( isMapped(tif) )
914 				err=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data);
915 			else
916 				err=TIFFReadDirEntryDataAndRealloc(tif,(uint64)offset,(tmsize_t)datasize,&data);
917 			if (err!=TIFFReadDirEntryErrOk)
918 			{
919 				_TIFFfree(data);
920 				return(err);
921 			}
922 		}
923 	}
924 	*value=data;
925 	return(TIFFReadDirEntryErrOk);
926 }
927 
TIFFReadDirEntryArray(TIFF * tif,TIFFDirEntry * direntry,uint32 * count,uint32 desttypesize,void ** value)928 static enum TIFFReadDirEntryErr TIFFReadDirEntryArray(TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize, void** value)
929 {
930     return TIFFReadDirEntryArrayWithLimit(tif, direntry, count,
931                                           desttypesize, value, ~((uint64)0));
932 }
933 
TIFFReadDirEntryByteArray(TIFF * tif,TIFFDirEntry * direntry,uint8 ** value)934 static enum TIFFReadDirEntryErr TIFFReadDirEntryByteArray(TIFF* tif, TIFFDirEntry* direntry, uint8** value)
935 {
936 	enum TIFFReadDirEntryErr err;
937 	uint32 count;
938 	void* origdata;
939 	uint8* data;
940 	switch (direntry->tdir_type)
941 	{
942 		case TIFF_ASCII:
943 		case TIFF_UNDEFINED:
944 		case TIFF_BYTE:
945 		case TIFF_SBYTE:
946 		case TIFF_SHORT:
947 		case TIFF_SSHORT:
948 		case TIFF_LONG:
949 		case TIFF_SLONG:
950 		case TIFF_LONG8:
951 		case TIFF_SLONG8:
952 			break;
953 		default:
954 			return(TIFFReadDirEntryErrType);
955 	}
956 	err=TIFFReadDirEntryArray(tif,direntry,&count,1,&origdata);
957 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
958 	{
959 		*value=0;
960 		return(err);
961 	}
962 	switch (direntry->tdir_type)
963 	{
964 		case TIFF_ASCII:
965 		case TIFF_UNDEFINED:
966 		case TIFF_BYTE:
967 			*value=(uint8*)origdata;
968 			return(TIFFReadDirEntryErrOk);
969 		case TIFF_SBYTE:
970 			{
971 				int8* m;
972 				uint32 n;
973 				m=(int8*)origdata;
974 				for (n=0; n<count; n++)
975 				{
976 					err=TIFFReadDirEntryCheckRangeByteSbyte(*m);
977 					if (err!=TIFFReadDirEntryErrOk)
978 					{
979 						_TIFFfree(origdata);
980 						return(err);
981 					}
982 					m++;
983 				}
984 				*value=(uint8*)origdata;
985 				return(TIFFReadDirEntryErrOk);
986 			}
987 	}
988 	data=(uint8*)_TIFFmalloc(count);
989 	if (data==0)
990 	{
991 		_TIFFfree(origdata);
992 		return(TIFFReadDirEntryErrAlloc);
993 	}
994 	switch (direntry->tdir_type)
995 	{
996 		case TIFF_SHORT:
997 			{
998 				uint16* ma;
999 				uint8* mb;
1000 				uint32 n;
1001 				ma=(uint16*)origdata;
1002 				mb=data;
1003 				for (n=0; n<count; n++)
1004 				{
1005 					if (tif->tif_flags&TIFF_SWAB)
1006 						TIFFSwabShort(ma);
1007 					err=TIFFReadDirEntryCheckRangeByteShort(*ma);
1008 					if (err!=TIFFReadDirEntryErrOk)
1009 						break;
1010 					*mb++=(uint8)(*ma++);
1011 				}
1012 			}
1013 			break;
1014 		case TIFF_SSHORT:
1015 			{
1016 				int16* ma;
1017 				uint8* mb;
1018 				uint32 n;
1019 				ma=(int16*)origdata;
1020 				mb=data;
1021 				for (n=0; n<count; n++)
1022 				{
1023 					if (tif->tif_flags&TIFF_SWAB)
1024 						TIFFSwabShort((uint16*)ma);
1025 					err=TIFFReadDirEntryCheckRangeByteSshort(*ma);
1026 					if (err!=TIFFReadDirEntryErrOk)
1027 						break;
1028 					*mb++=(uint8)(*ma++);
1029 				}
1030 			}
1031 			break;
1032 		case TIFF_LONG:
1033 			{
1034 				uint32* ma;
1035 				uint8* mb;
1036 				uint32 n;
1037 				ma=(uint32*)origdata;
1038 				mb=data;
1039 				for (n=0; n<count; n++)
1040 				{
1041 					if (tif->tif_flags&TIFF_SWAB)
1042 						TIFFSwabLong(ma);
1043 					err=TIFFReadDirEntryCheckRangeByteLong(*ma);
1044 					if (err!=TIFFReadDirEntryErrOk)
1045 						break;
1046 					*mb++=(uint8)(*ma++);
1047 				}
1048 			}
1049 			break;
1050 		case TIFF_SLONG:
1051 			{
1052 				int32* ma;
1053 				uint8* mb;
1054 				uint32 n;
1055 				ma=(int32*)origdata;
1056 				mb=data;
1057 				for (n=0; n<count; n++)
1058 				{
1059 					if (tif->tif_flags&TIFF_SWAB)
1060 						TIFFSwabLong((uint32*)ma);
1061 					err=TIFFReadDirEntryCheckRangeByteSlong(*ma);
1062 					if (err!=TIFFReadDirEntryErrOk)
1063 						break;
1064 					*mb++=(uint8)(*ma++);
1065 				}
1066 			}
1067 			break;
1068 		case TIFF_LONG8:
1069 			{
1070 				uint64* ma;
1071 				uint8* mb;
1072 				uint32 n;
1073 				ma=(uint64*)origdata;
1074 				mb=data;
1075 				for (n=0; n<count; n++)
1076 				{
1077 					if (tif->tif_flags&TIFF_SWAB)
1078 						TIFFSwabLong8(ma);
1079 					err=TIFFReadDirEntryCheckRangeByteLong8(*ma);
1080 					if (err!=TIFFReadDirEntryErrOk)
1081 						break;
1082 					*mb++=(uint8)(*ma++);
1083 				}
1084 			}
1085 			break;
1086 		case TIFF_SLONG8:
1087 			{
1088 				int64* ma;
1089 				uint8* mb;
1090 				uint32 n;
1091 				ma=(int64*)origdata;
1092 				mb=data;
1093 				for (n=0; n<count; n++)
1094 				{
1095 					if (tif->tif_flags&TIFF_SWAB)
1096 						TIFFSwabLong8((uint64*)ma);
1097 					err=TIFFReadDirEntryCheckRangeByteSlong8(*ma);
1098 					if (err!=TIFFReadDirEntryErrOk)
1099 						break;
1100 					*mb++=(uint8)(*ma++);
1101 				}
1102 			}
1103 			break;
1104 	}
1105 	_TIFFfree(origdata);
1106 	if (err!=TIFFReadDirEntryErrOk)
1107 	{
1108 		_TIFFfree(data);
1109 		return(err);
1110 	}
1111 	*value=data;
1112 	return(TIFFReadDirEntryErrOk);
1113 }
1114 
TIFFReadDirEntrySbyteArray(TIFF * tif,TIFFDirEntry * direntry,int8 ** value)1115 static enum TIFFReadDirEntryErr TIFFReadDirEntrySbyteArray(TIFF* tif, TIFFDirEntry* direntry, int8** value)
1116 {
1117 	enum TIFFReadDirEntryErr err;
1118 	uint32 count;
1119 	void* origdata;
1120 	int8* data;
1121 	switch (direntry->tdir_type)
1122 	{
1123 		case TIFF_UNDEFINED:
1124 		case TIFF_BYTE:
1125 		case TIFF_SBYTE:
1126 		case TIFF_SHORT:
1127 		case TIFF_SSHORT:
1128 		case TIFF_LONG:
1129 		case TIFF_SLONG:
1130 		case TIFF_LONG8:
1131 		case TIFF_SLONG8:
1132 			break;
1133 		default:
1134 			return(TIFFReadDirEntryErrType);
1135 	}
1136 	err=TIFFReadDirEntryArray(tif,direntry,&count,1,&origdata);
1137 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
1138 	{
1139 		*value=0;
1140 		return(err);
1141 	}
1142 	switch (direntry->tdir_type)
1143 	{
1144 		case TIFF_UNDEFINED:
1145 		case TIFF_BYTE:
1146 			{
1147 				uint8* m;
1148 				uint32 n;
1149 				m=(uint8*)origdata;
1150 				for (n=0; n<count; n++)
1151 				{
1152 					err=TIFFReadDirEntryCheckRangeSbyteByte(*m);
1153 					if (err!=TIFFReadDirEntryErrOk)
1154 					{
1155 						_TIFFfree(origdata);
1156 						return(err);
1157 					}
1158 					m++;
1159 				}
1160 				*value=(int8*)origdata;
1161 				return(TIFFReadDirEntryErrOk);
1162 			}
1163 		case TIFF_SBYTE:
1164 			*value=(int8*)origdata;
1165 			return(TIFFReadDirEntryErrOk);
1166 	}
1167 	data=(int8*)_TIFFmalloc(count);
1168 	if (data==0)
1169 	{
1170 		_TIFFfree(origdata);
1171 		return(TIFFReadDirEntryErrAlloc);
1172 	}
1173 	switch (direntry->tdir_type)
1174 	{
1175 		case TIFF_SHORT:
1176 			{
1177 				uint16* ma;
1178 				int8* mb;
1179 				uint32 n;
1180 				ma=(uint16*)origdata;
1181 				mb=data;
1182 				for (n=0; n<count; n++)
1183 				{
1184 					if (tif->tif_flags&TIFF_SWAB)
1185 						TIFFSwabShort(ma);
1186 					err=TIFFReadDirEntryCheckRangeSbyteShort(*ma);
1187 					if (err!=TIFFReadDirEntryErrOk)
1188 						break;
1189 					*mb++=(int8)(*ma++);
1190 				}
1191 			}
1192 			break;
1193 		case TIFF_SSHORT:
1194 			{
1195 				int16* ma;
1196 				int8* mb;
1197 				uint32 n;
1198 				ma=(int16*)origdata;
1199 				mb=data;
1200 				for (n=0; n<count; n++)
1201 				{
1202 					if (tif->tif_flags&TIFF_SWAB)
1203 						TIFFSwabShort((uint16*)ma);
1204 					err=TIFFReadDirEntryCheckRangeSbyteSshort(*ma);
1205 					if (err!=TIFFReadDirEntryErrOk)
1206 						break;
1207 					*mb++=(int8)(*ma++);
1208 				}
1209 			}
1210 			break;
1211 		case TIFF_LONG:
1212 			{
1213 				uint32* ma;
1214 				int8* mb;
1215 				uint32 n;
1216 				ma=(uint32*)origdata;
1217 				mb=data;
1218 				for (n=0; n<count; n++)
1219 				{
1220 					if (tif->tif_flags&TIFF_SWAB)
1221 						TIFFSwabLong(ma);
1222 					err=TIFFReadDirEntryCheckRangeSbyteLong(*ma);
1223 					if (err!=TIFFReadDirEntryErrOk)
1224 						break;
1225 					*mb++=(int8)(*ma++);
1226 				}
1227 			}
1228 			break;
1229 		case TIFF_SLONG:
1230 			{
1231 				int32* ma;
1232 				int8* mb;
1233 				uint32 n;
1234 				ma=(int32*)origdata;
1235 				mb=data;
1236 				for (n=0; n<count; n++)
1237 				{
1238 					if (tif->tif_flags&TIFF_SWAB)
1239 						TIFFSwabLong((uint32*)ma);
1240 					err=TIFFReadDirEntryCheckRangeSbyteSlong(*ma);
1241 					if (err!=TIFFReadDirEntryErrOk)
1242 						break;
1243 					*mb++=(int8)(*ma++);
1244 				}
1245 			}
1246 			break;
1247 		case TIFF_LONG8:
1248 			{
1249 				uint64* ma;
1250 				int8* mb;
1251 				uint32 n;
1252 				ma=(uint64*)origdata;
1253 				mb=data;
1254 				for (n=0; n<count; n++)
1255 				{
1256 					if (tif->tif_flags&TIFF_SWAB)
1257 						TIFFSwabLong8(ma);
1258 					err=TIFFReadDirEntryCheckRangeSbyteLong8(*ma);
1259 					if (err!=TIFFReadDirEntryErrOk)
1260 						break;
1261 					*mb++=(int8)(*ma++);
1262 				}
1263 			}
1264 			break;
1265 		case TIFF_SLONG8:
1266 			{
1267 				int64* ma;
1268 				int8* mb;
1269 				uint32 n;
1270 				ma=(int64*)origdata;
1271 				mb=data;
1272 				for (n=0; n<count; n++)
1273 				{
1274 					if (tif->tif_flags&TIFF_SWAB)
1275 						TIFFSwabLong8((uint64*)ma);
1276 					err=TIFFReadDirEntryCheckRangeSbyteSlong8(*ma);
1277 					if (err!=TIFFReadDirEntryErrOk)
1278 						break;
1279 					*mb++=(int8)(*ma++);
1280 				}
1281 			}
1282 			break;
1283 	}
1284 	_TIFFfree(origdata);
1285 	if (err!=TIFFReadDirEntryErrOk)
1286 	{
1287 		_TIFFfree(data);
1288 		return(err);
1289 	}
1290 	*value=data;
1291 	return(TIFFReadDirEntryErrOk);
1292 }
1293 
TIFFReadDirEntryShortArray(TIFF * tif,TIFFDirEntry * direntry,uint16 ** value)1294 static enum TIFFReadDirEntryErr TIFFReadDirEntryShortArray(TIFF* tif, TIFFDirEntry* direntry, uint16** value)
1295 {
1296 	enum TIFFReadDirEntryErr err;
1297 	uint32 count;
1298 	void* origdata;
1299 	uint16* data;
1300 	switch (direntry->tdir_type)
1301 	{
1302 		case TIFF_BYTE:
1303 		case TIFF_SBYTE:
1304 		case TIFF_SHORT:
1305 		case TIFF_SSHORT:
1306 		case TIFF_LONG:
1307 		case TIFF_SLONG:
1308 		case TIFF_LONG8:
1309 		case TIFF_SLONG8:
1310 			break;
1311 		default:
1312 			return(TIFFReadDirEntryErrType);
1313 	}
1314 	err=TIFFReadDirEntryArray(tif,direntry,&count,2,&origdata);
1315 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
1316 	{
1317 		*value=0;
1318 		return(err);
1319 	}
1320 	switch (direntry->tdir_type)
1321 	{
1322 		case TIFF_SHORT:
1323 			*value=(uint16*)origdata;
1324 			if (tif->tif_flags&TIFF_SWAB)
1325 				TIFFSwabArrayOfShort(*value,count);
1326 			return(TIFFReadDirEntryErrOk);
1327 		case TIFF_SSHORT:
1328 			{
1329 				int16* m;
1330 				uint32 n;
1331 				m=(int16*)origdata;
1332 				for (n=0; n<count; n++)
1333 				{
1334 					if (tif->tif_flags&TIFF_SWAB)
1335 						TIFFSwabShort((uint16*)m);
1336 					err=TIFFReadDirEntryCheckRangeShortSshort(*m);
1337 					if (err!=TIFFReadDirEntryErrOk)
1338 					{
1339 						_TIFFfree(origdata);
1340 						return(err);
1341 					}
1342 					m++;
1343 				}
1344 				*value=(uint16*)origdata;
1345 				return(TIFFReadDirEntryErrOk);
1346 			}
1347 	}
1348 	data=(uint16*)_TIFFmalloc(count*2);
1349 	if (data==0)
1350 	{
1351 		_TIFFfree(origdata);
1352 		return(TIFFReadDirEntryErrAlloc);
1353 	}
1354 	switch (direntry->tdir_type)
1355 	{
1356 		case TIFF_BYTE:
1357 			{
1358 				uint8* ma;
1359 				uint16* mb;
1360 				uint32 n;
1361 				ma=(uint8*)origdata;
1362 				mb=data;
1363 				for (n=0; n<count; n++)
1364 					*mb++=(uint16)(*ma++);
1365 			}
1366 			break;
1367 		case TIFF_SBYTE:
1368 			{
1369 				int8* ma;
1370 				uint16* mb;
1371 				uint32 n;
1372 				ma=(int8*)origdata;
1373 				mb=data;
1374 				for (n=0; n<count; n++)
1375 				{
1376 					err=TIFFReadDirEntryCheckRangeShortSbyte(*ma);
1377 					if (err!=TIFFReadDirEntryErrOk)
1378 						break;
1379 					*mb++=(uint16)(*ma++);
1380 				}
1381 			}
1382 			break;
1383 		case TIFF_LONG:
1384 			{
1385 				uint32* ma;
1386 				uint16* mb;
1387 				uint32 n;
1388 				ma=(uint32*)origdata;
1389 				mb=data;
1390 				for (n=0; n<count; n++)
1391 				{
1392 					if (tif->tif_flags&TIFF_SWAB)
1393 						TIFFSwabLong(ma);
1394 					err=TIFFReadDirEntryCheckRangeShortLong(*ma);
1395 					if (err!=TIFFReadDirEntryErrOk)
1396 						break;
1397 					*mb++=(uint16)(*ma++);
1398 				}
1399 			}
1400 			break;
1401 		case TIFF_SLONG:
1402 			{
1403 				int32* ma;
1404 				uint16* mb;
1405 				uint32 n;
1406 				ma=(int32*)origdata;
1407 				mb=data;
1408 				for (n=0; n<count; n++)
1409 				{
1410 					if (tif->tif_flags&TIFF_SWAB)
1411 						TIFFSwabLong((uint32*)ma);
1412 					err=TIFFReadDirEntryCheckRangeShortSlong(*ma);
1413 					if (err!=TIFFReadDirEntryErrOk)
1414 						break;
1415 					*mb++=(uint16)(*ma++);
1416 				}
1417 			}
1418 			break;
1419 		case TIFF_LONG8:
1420 			{
1421 				uint64* ma;
1422 				uint16* mb;
1423 				uint32 n;
1424 				ma=(uint64*)origdata;
1425 				mb=data;
1426 				for (n=0; n<count; n++)
1427 				{
1428 					if (tif->tif_flags&TIFF_SWAB)
1429 						TIFFSwabLong8(ma);
1430 					err=TIFFReadDirEntryCheckRangeShortLong8(*ma);
1431 					if (err!=TIFFReadDirEntryErrOk)
1432 						break;
1433 					*mb++=(uint16)(*ma++);
1434 				}
1435 			}
1436 			break;
1437 		case TIFF_SLONG8:
1438 			{
1439 				int64* ma;
1440 				uint16* mb;
1441 				uint32 n;
1442 				ma=(int64*)origdata;
1443 				mb=data;
1444 				for (n=0; n<count; n++)
1445 				{
1446 					if (tif->tif_flags&TIFF_SWAB)
1447 						TIFFSwabLong8((uint64*)ma);
1448 					err=TIFFReadDirEntryCheckRangeShortSlong8(*ma);
1449 					if (err!=TIFFReadDirEntryErrOk)
1450 						break;
1451 					*mb++=(uint16)(*ma++);
1452 				}
1453 			}
1454 			break;
1455 	}
1456 	_TIFFfree(origdata);
1457 	if (err!=TIFFReadDirEntryErrOk)
1458 	{
1459 		_TIFFfree(data);
1460 		return(err);
1461 	}
1462 	*value=data;
1463 	return(TIFFReadDirEntryErrOk);
1464 }
1465 
TIFFReadDirEntrySshortArray(TIFF * tif,TIFFDirEntry * direntry,int16 ** value)1466 static enum TIFFReadDirEntryErr TIFFReadDirEntrySshortArray(TIFF* tif, TIFFDirEntry* direntry, int16** value)
1467 {
1468 	enum TIFFReadDirEntryErr err;
1469 	uint32 count;
1470 	void* origdata;
1471 	int16* data;
1472 	switch (direntry->tdir_type)
1473 	{
1474 		case TIFF_BYTE:
1475 		case TIFF_SBYTE:
1476 		case TIFF_SHORT:
1477 		case TIFF_SSHORT:
1478 		case TIFF_LONG:
1479 		case TIFF_SLONG:
1480 		case TIFF_LONG8:
1481 		case TIFF_SLONG8:
1482 			break;
1483 		default:
1484 			return(TIFFReadDirEntryErrType);
1485 	}
1486 	err=TIFFReadDirEntryArray(tif,direntry,&count,2,&origdata);
1487 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
1488 	{
1489 		*value=0;
1490 		return(err);
1491 	}
1492 	switch (direntry->tdir_type)
1493 	{
1494 		case TIFF_SHORT:
1495 			{
1496 				uint16* m;
1497 				uint32 n;
1498 				m=(uint16*)origdata;
1499 				for (n=0; n<count; n++)
1500 				{
1501 					if (tif->tif_flags&TIFF_SWAB)
1502 						TIFFSwabShort(m);
1503 					err=TIFFReadDirEntryCheckRangeSshortShort(*m);
1504 					if (err!=TIFFReadDirEntryErrOk)
1505 					{
1506 						_TIFFfree(origdata);
1507 						return(err);
1508 					}
1509 					m++;
1510 				}
1511 				*value=(int16*)origdata;
1512 				return(TIFFReadDirEntryErrOk);
1513 			}
1514 		case TIFF_SSHORT:
1515 			*value=(int16*)origdata;
1516 			if (tif->tif_flags&TIFF_SWAB)
1517 				TIFFSwabArrayOfShort((uint16*)(*value),count);
1518 			return(TIFFReadDirEntryErrOk);
1519 	}
1520 	data=(int16*)_TIFFmalloc(count*2);
1521 	if (data==0)
1522 	{
1523 		_TIFFfree(origdata);
1524 		return(TIFFReadDirEntryErrAlloc);
1525 	}
1526 	switch (direntry->tdir_type)
1527 	{
1528 		case TIFF_BYTE:
1529 			{
1530 				uint8* ma;
1531 				int16* mb;
1532 				uint32 n;
1533 				ma=(uint8*)origdata;
1534 				mb=data;
1535 				for (n=0; n<count; n++)
1536 					*mb++=(int16)(*ma++);
1537 			}
1538 			break;
1539 		case TIFF_SBYTE:
1540 			{
1541 				int8* ma;
1542 				int16* mb;
1543 				uint32 n;
1544 				ma=(int8*)origdata;
1545 				mb=data;
1546 				for (n=0; n<count; n++)
1547 					*mb++=(int16)(*ma++);
1548 			}
1549 			break;
1550 		case TIFF_LONG:
1551 			{
1552 				uint32* ma;
1553 				int16* mb;
1554 				uint32 n;
1555 				ma=(uint32*)origdata;
1556 				mb=data;
1557 				for (n=0; n<count; n++)
1558 				{
1559 					if (tif->tif_flags&TIFF_SWAB)
1560 						TIFFSwabLong(ma);
1561 					err=TIFFReadDirEntryCheckRangeSshortLong(*ma);
1562 					if (err!=TIFFReadDirEntryErrOk)
1563 						break;
1564 					*mb++=(int16)(*ma++);
1565 				}
1566 			}
1567 			break;
1568 		case TIFF_SLONG:
1569 			{
1570 				int32* ma;
1571 				int16* mb;
1572 				uint32 n;
1573 				ma=(int32*)origdata;
1574 				mb=data;
1575 				for (n=0; n<count; n++)
1576 				{
1577 					if (tif->tif_flags&TIFF_SWAB)
1578 						TIFFSwabLong((uint32*)ma);
1579 					err=TIFFReadDirEntryCheckRangeSshortSlong(*ma);
1580 					if (err!=TIFFReadDirEntryErrOk)
1581 						break;
1582 					*mb++=(int16)(*ma++);
1583 				}
1584 			}
1585 			break;
1586 		case TIFF_LONG8:
1587 			{
1588 				uint64* ma;
1589 				int16* mb;
1590 				uint32 n;
1591 				ma=(uint64*)origdata;
1592 				mb=data;
1593 				for (n=0; n<count; n++)
1594 				{
1595 					if (tif->tif_flags&TIFF_SWAB)
1596 						TIFFSwabLong8(ma);
1597 					err=TIFFReadDirEntryCheckRangeSshortLong8(*ma);
1598 					if (err!=TIFFReadDirEntryErrOk)
1599 						break;
1600 					*mb++=(int16)(*ma++);
1601 				}
1602 			}
1603 			break;
1604 		case TIFF_SLONG8:
1605 			{
1606 				int64* ma;
1607 				int16* mb;
1608 				uint32 n;
1609 				ma=(int64*)origdata;
1610 				mb=data;
1611 				for (n=0; n<count; n++)
1612 				{
1613 					if (tif->tif_flags&TIFF_SWAB)
1614 						TIFFSwabLong8((uint64*)ma);
1615 					err=TIFFReadDirEntryCheckRangeSshortSlong8(*ma);
1616 					if (err!=TIFFReadDirEntryErrOk)
1617 						break;
1618 					*mb++=(int16)(*ma++);
1619 				}
1620 			}
1621 			break;
1622 	}
1623 	_TIFFfree(origdata);
1624 	if (err!=TIFFReadDirEntryErrOk)
1625 	{
1626 		_TIFFfree(data);
1627 		return(err);
1628 	}
1629 	*value=data;
1630 	return(TIFFReadDirEntryErrOk);
1631 }
1632 
TIFFReadDirEntryLongArray(TIFF * tif,TIFFDirEntry * direntry,uint32 ** value)1633 static enum TIFFReadDirEntryErr TIFFReadDirEntryLongArray(TIFF* tif, TIFFDirEntry* direntry, uint32** value)
1634 {
1635 	enum TIFFReadDirEntryErr err;
1636 	uint32 count;
1637 	void* origdata;
1638 	uint32* data;
1639 	switch (direntry->tdir_type)
1640 	{
1641 		case TIFF_BYTE:
1642 		case TIFF_SBYTE:
1643 		case TIFF_SHORT:
1644 		case TIFF_SSHORT:
1645 		case TIFF_LONG:
1646 		case TIFF_SLONG:
1647 		case TIFF_LONG8:
1648 		case TIFF_SLONG8:
1649 			break;
1650 		default:
1651 			return(TIFFReadDirEntryErrType);
1652 	}
1653 	err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata);
1654 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
1655 	{
1656 		*value=0;
1657 		return(err);
1658 	}
1659 	switch (direntry->tdir_type)
1660 	{
1661 		case TIFF_LONG:
1662 			*value=(uint32*)origdata;
1663 			if (tif->tif_flags&TIFF_SWAB)
1664 				TIFFSwabArrayOfLong(*value,count);
1665 			return(TIFFReadDirEntryErrOk);
1666 		case TIFF_SLONG:
1667 			{
1668 				int32* m;
1669 				uint32 n;
1670 				m=(int32*)origdata;
1671 				for (n=0; n<count; n++)
1672 				{
1673 					if (tif->tif_flags&TIFF_SWAB)
1674 						TIFFSwabLong((uint32*)m);
1675 					err=TIFFReadDirEntryCheckRangeLongSlong(*m);
1676 					if (err!=TIFFReadDirEntryErrOk)
1677 					{
1678 						_TIFFfree(origdata);
1679 						return(err);
1680 					}
1681 					m++;
1682 				}
1683 				*value=(uint32*)origdata;
1684 				return(TIFFReadDirEntryErrOk);
1685 			}
1686 	}
1687 	data=(uint32*)_TIFFmalloc(count*4);
1688 	if (data==0)
1689 	{
1690 		_TIFFfree(origdata);
1691 		return(TIFFReadDirEntryErrAlloc);
1692 	}
1693 	switch (direntry->tdir_type)
1694 	{
1695 		case TIFF_BYTE:
1696 			{
1697 				uint8* ma;
1698 				uint32* mb;
1699 				uint32 n;
1700 				ma=(uint8*)origdata;
1701 				mb=data;
1702 				for (n=0; n<count; n++)
1703 					*mb++=(uint32)(*ma++);
1704 			}
1705 			break;
1706 		case TIFF_SBYTE:
1707 			{
1708 				int8* ma;
1709 				uint32* mb;
1710 				uint32 n;
1711 				ma=(int8*)origdata;
1712 				mb=data;
1713 				for (n=0; n<count; n++)
1714 				{
1715 					err=TIFFReadDirEntryCheckRangeLongSbyte(*ma);
1716 					if (err!=TIFFReadDirEntryErrOk)
1717 						break;
1718 					*mb++=(uint32)(*ma++);
1719 				}
1720 			}
1721 			break;
1722 		case TIFF_SHORT:
1723 			{
1724 				uint16* ma;
1725 				uint32* mb;
1726 				uint32 n;
1727 				ma=(uint16*)origdata;
1728 				mb=data;
1729 				for (n=0; n<count; n++)
1730 				{
1731 					if (tif->tif_flags&TIFF_SWAB)
1732 						TIFFSwabShort(ma);
1733 					*mb++=(uint32)(*ma++);
1734 				}
1735 			}
1736 			break;
1737 		case TIFF_SSHORT:
1738 			{
1739 				int16* ma;
1740 				uint32* mb;
1741 				uint32 n;
1742 				ma=(int16*)origdata;
1743 				mb=data;
1744 				for (n=0; n<count; n++)
1745 				{
1746 					if (tif->tif_flags&TIFF_SWAB)
1747 						TIFFSwabShort((uint16*)ma);
1748 					err=TIFFReadDirEntryCheckRangeLongSshort(*ma);
1749 					if (err!=TIFFReadDirEntryErrOk)
1750 						break;
1751 					*mb++=(uint32)(*ma++);
1752 				}
1753 			}
1754 			break;
1755 		case TIFF_LONG8:
1756 			{
1757 				uint64* ma;
1758 				uint32* mb;
1759 				uint32 n;
1760 				ma=(uint64*)origdata;
1761 				mb=data;
1762 				for (n=0; n<count; n++)
1763 				{
1764 					if (tif->tif_flags&TIFF_SWAB)
1765 						TIFFSwabLong8(ma);
1766 					err=TIFFReadDirEntryCheckRangeLongLong8(*ma);
1767 					if (err!=TIFFReadDirEntryErrOk)
1768 						break;
1769 					*mb++=(uint32)(*ma++);
1770 				}
1771 			}
1772 			break;
1773 		case TIFF_SLONG8:
1774 			{
1775 				int64* ma;
1776 				uint32* mb;
1777 				uint32 n;
1778 				ma=(int64*)origdata;
1779 				mb=data;
1780 				for (n=0; n<count; n++)
1781 				{
1782 					if (tif->tif_flags&TIFF_SWAB)
1783 						TIFFSwabLong8((uint64*)ma);
1784 					err=TIFFReadDirEntryCheckRangeLongSlong8(*ma);
1785 					if (err!=TIFFReadDirEntryErrOk)
1786 						break;
1787 					*mb++=(uint32)(*ma++);
1788 				}
1789 			}
1790 			break;
1791 	}
1792 	_TIFFfree(origdata);
1793 	if (err!=TIFFReadDirEntryErrOk)
1794 	{
1795 		_TIFFfree(data);
1796 		return(err);
1797 	}
1798 	*value=data;
1799 	return(TIFFReadDirEntryErrOk);
1800 }
1801 
TIFFReadDirEntrySlongArray(TIFF * tif,TIFFDirEntry * direntry,int32 ** value)1802 static enum TIFFReadDirEntryErr TIFFReadDirEntrySlongArray(TIFF* tif, TIFFDirEntry* direntry, int32** value)
1803 {
1804 	enum TIFFReadDirEntryErr err;
1805 	uint32 count;
1806 	void* origdata;
1807 	int32* data;
1808 	switch (direntry->tdir_type)
1809 	{
1810 		case TIFF_BYTE:
1811 		case TIFF_SBYTE:
1812 		case TIFF_SHORT:
1813 		case TIFF_SSHORT:
1814 		case TIFF_LONG:
1815 		case TIFF_SLONG:
1816 		case TIFF_LONG8:
1817 		case TIFF_SLONG8:
1818 			break;
1819 		default:
1820 			return(TIFFReadDirEntryErrType);
1821 	}
1822 	err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata);
1823 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
1824 	{
1825 		*value=0;
1826 		return(err);
1827 	}
1828 	switch (direntry->tdir_type)
1829 	{
1830 		case TIFF_LONG:
1831 			{
1832 				uint32* m;
1833 				uint32 n;
1834 				m=(uint32*)origdata;
1835 				for (n=0; n<count; n++)
1836 				{
1837 					if (tif->tif_flags&TIFF_SWAB)
1838 						TIFFSwabLong((uint32*)m);
1839 					err=TIFFReadDirEntryCheckRangeSlongLong(*m);
1840 					if (err!=TIFFReadDirEntryErrOk)
1841 					{
1842 						_TIFFfree(origdata);
1843 						return(err);
1844 					}
1845 					m++;
1846 				}
1847 				*value=(int32*)origdata;
1848 				return(TIFFReadDirEntryErrOk);
1849 			}
1850 		case TIFF_SLONG:
1851 			*value=(int32*)origdata;
1852 			if (tif->tif_flags&TIFF_SWAB)
1853 				TIFFSwabArrayOfLong((uint32*)(*value),count);
1854 			return(TIFFReadDirEntryErrOk);
1855 	}
1856 	data=(int32*)_TIFFmalloc(count*4);
1857 	if (data==0)
1858 	{
1859 		_TIFFfree(origdata);
1860 		return(TIFFReadDirEntryErrAlloc);
1861 	}
1862 	switch (direntry->tdir_type)
1863 	{
1864 		case TIFF_BYTE:
1865 			{
1866 				uint8* ma;
1867 				int32* mb;
1868 				uint32 n;
1869 				ma=(uint8*)origdata;
1870 				mb=data;
1871 				for (n=0; n<count; n++)
1872 					*mb++=(int32)(*ma++);
1873 			}
1874 			break;
1875 		case TIFF_SBYTE:
1876 			{
1877 				int8* ma;
1878 				int32* mb;
1879 				uint32 n;
1880 				ma=(int8*)origdata;
1881 				mb=data;
1882 				for (n=0; n<count; n++)
1883 					*mb++=(int32)(*ma++);
1884 			}
1885 			break;
1886 		case TIFF_SHORT:
1887 			{
1888 				uint16* ma;
1889 				int32* mb;
1890 				uint32 n;
1891 				ma=(uint16*)origdata;
1892 				mb=data;
1893 				for (n=0; n<count; n++)
1894 				{
1895 					if (tif->tif_flags&TIFF_SWAB)
1896 						TIFFSwabShort(ma);
1897 					*mb++=(int32)(*ma++);
1898 				}
1899 			}
1900 			break;
1901 		case TIFF_SSHORT:
1902 			{
1903 				int16* ma;
1904 				int32* mb;
1905 				uint32 n;
1906 				ma=(int16*)origdata;
1907 				mb=data;
1908 				for (n=0; n<count; n++)
1909 				{
1910 					if (tif->tif_flags&TIFF_SWAB)
1911 						TIFFSwabShort((uint16*)ma);
1912 					*mb++=(int32)(*ma++);
1913 				}
1914 			}
1915 			break;
1916 		case TIFF_LONG8:
1917 			{
1918 				uint64* ma;
1919 				int32* mb;
1920 				uint32 n;
1921 				ma=(uint64*)origdata;
1922 				mb=data;
1923 				for (n=0; n<count; n++)
1924 				{
1925 					if (tif->tif_flags&TIFF_SWAB)
1926 						TIFFSwabLong8(ma);
1927 					err=TIFFReadDirEntryCheckRangeSlongLong8(*ma);
1928 					if (err!=TIFFReadDirEntryErrOk)
1929 						break;
1930 					*mb++=(int32)(*ma++);
1931 				}
1932 			}
1933 			break;
1934 		case TIFF_SLONG8:
1935 			{
1936 				int64* ma;
1937 				int32* mb;
1938 				uint32 n;
1939 				ma=(int64*)origdata;
1940 				mb=data;
1941 				for (n=0; n<count; n++)
1942 				{
1943 					if (tif->tif_flags&TIFF_SWAB)
1944 						TIFFSwabLong8((uint64*)ma);
1945 					err=TIFFReadDirEntryCheckRangeSlongSlong8(*ma);
1946 					if (err!=TIFFReadDirEntryErrOk)
1947 						break;
1948 					*mb++=(int32)(*ma++);
1949 				}
1950 			}
1951 			break;
1952 	}
1953 	_TIFFfree(origdata);
1954 	if (err!=TIFFReadDirEntryErrOk)
1955 	{
1956 		_TIFFfree(data);
1957 		return(err);
1958 	}
1959 	*value=data;
1960 	return(TIFFReadDirEntryErrOk);
1961 }
1962 
TIFFReadDirEntryLong8ArrayWithLimit(TIFF * tif,TIFFDirEntry * direntry,uint64 ** value,uint64 maxcount)1963 static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8ArrayWithLimit(
1964         TIFF* tif, TIFFDirEntry* direntry, uint64** value, uint64 maxcount)
1965 {
1966 	enum TIFFReadDirEntryErr err;
1967 	uint32 count;
1968 	void* origdata;
1969 	uint64* data;
1970 	switch (direntry->tdir_type)
1971 	{
1972 		case TIFF_BYTE:
1973 		case TIFF_SBYTE:
1974 		case TIFF_SHORT:
1975 		case TIFF_SSHORT:
1976 		case TIFF_LONG:
1977 		case TIFF_SLONG:
1978 		case TIFF_LONG8:
1979 		case TIFF_SLONG8:
1980 			break;
1981 		default:
1982 			return(TIFFReadDirEntryErrType);
1983 	}
1984 	err=TIFFReadDirEntryArrayWithLimit(tif,direntry,&count,8,&origdata,maxcount);
1985 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
1986 	{
1987 		*value=0;
1988 		return(err);
1989 	}
1990 	switch (direntry->tdir_type)
1991 	{
1992 		case TIFF_LONG8:
1993 			*value=(uint64*)origdata;
1994 			if (tif->tif_flags&TIFF_SWAB)
1995 				TIFFSwabArrayOfLong8(*value,count);
1996 			return(TIFFReadDirEntryErrOk);
1997 		case TIFF_SLONG8:
1998 			{
1999 				int64* m;
2000 				uint32 n;
2001 				m=(int64*)origdata;
2002 				for (n=0; n<count; n++)
2003 				{
2004 					if (tif->tif_flags&TIFF_SWAB)
2005 						TIFFSwabLong8((uint64*)m);
2006 					err=TIFFReadDirEntryCheckRangeLong8Slong8(*m);
2007 					if (err!=TIFFReadDirEntryErrOk)
2008 					{
2009 						_TIFFfree(origdata);
2010 						return(err);
2011 					}
2012 					m++;
2013 				}
2014 				*value=(uint64*)origdata;
2015 				return(TIFFReadDirEntryErrOk);
2016 			}
2017 	}
2018 	data=(uint64*)_TIFFmalloc(count*8);
2019 	if (data==0)
2020 	{
2021 		_TIFFfree(origdata);
2022 		return(TIFFReadDirEntryErrAlloc);
2023 	}
2024 	switch (direntry->tdir_type)
2025 	{
2026 		case TIFF_BYTE:
2027 			{
2028 				uint8* ma;
2029 				uint64* mb;
2030 				uint32 n;
2031 				ma=(uint8*)origdata;
2032 				mb=data;
2033 				for (n=0; n<count; n++)
2034 					*mb++=(uint64)(*ma++);
2035 			}
2036 			break;
2037 		case TIFF_SBYTE:
2038 			{
2039 				int8* ma;
2040 				uint64* mb;
2041 				uint32 n;
2042 				ma=(int8*)origdata;
2043 				mb=data;
2044 				for (n=0; n<count; n++)
2045 				{
2046 					err=TIFFReadDirEntryCheckRangeLong8Sbyte(*ma);
2047 					if (err!=TIFFReadDirEntryErrOk)
2048 						break;
2049 					*mb++=(uint64)(*ma++);
2050 				}
2051 			}
2052 			break;
2053 		case TIFF_SHORT:
2054 			{
2055 				uint16* ma;
2056 				uint64* mb;
2057 				uint32 n;
2058 				ma=(uint16*)origdata;
2059 				mb=data;
2060 				for (n=0; n<count; n++)
2061 				{
2062 					if (tif->tif_flags&TIFF_SWAB)
2063 						TIFFSwabShort(ma);
2064 					*mb++=(uint64)(*ma++);
2065 				}
2066 			}
2067 			break;
2068 		case TIFF_SSHORT:
2069 			{
2070 				int16* ma;
2071 				uint64* mb;
2072 				uint32 n;
2073 				ma=(int16*)origdata;
2074 				mb=data;
2075 				for (n=0; n<count; n++)
2076 				{
2077 					if (tif->tif_flags&TIFF_SWAB)
2078 						TIFFSwabShort((uint16*)ma);
2079 					err=TIFFReadDirEntryCheckRangeLong8Sshort(*ma);
2080 					if (err!=TIFFReadDirEntryErrOk)
2081 						break;
2082 					*mb++=(uint64)(*ma++);
2083 				}
2084 			}
2085 			break;
2086 		case TIFF_LONG:
2087 			{
2088 				uint32* ma;
2089 				uint64* mb;
2090 				uint32 n;
2091 				ma=(uint32*)origdata;
2092 				mb=data;
2093 				for (n=0; n<count; n++)
2094 				{
2095 					if (tif->tif_flags&TIFF_SWAB)
2096 						TIFFSwabLong(ma);
2097 					*mb++=(uint64)(*ma++);
2098 				}
2099 			}
2100 			break;
2101 		case TIFF_SLONG:
2102 			{
2103 				int32* ma;
2104 				uint64* mb;
2105 				uint32 n;
2106 				ma=(int32*)origdata;
2107 				mb=data;
2108 				for (n=0; n<count; n++)
2109 				{
2110 					if (tif->tif_flags&TIFF_SWAB)
2111 						TIFFSwabLong((uint32*)ma);
2112 					err=TIFFReadDirEntryCheckRangeLong8Slong(*ma);
2113 					if (err!=TIFFReadDirEntryErrOk)
2114 						break;
2115 					*mb++=(uint64)(*ma++);
2116 				}
2117 			}
2118 			break;
2119 	}
2120 	_TIFFfree(origdata);
2121 	if (err!=TIFFReadDirEntryErrOk)
2122 	{
2123 		_TIFFfree(data);
2124 		return(err);
2125 	}
2126 	*value=data;
2127 	return(TIFFReadDirEntryErrOk);
2128 }
2129 
TIFFReadDirEntryLong8Array(TIFF * tif,TIFFDirEntry * direntry,uint64 ** value)2130 static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value)
2131 {
2132     return TIFFReadDirEntryLong8ArrayWithLimit(tif, direntry, value, ~((uint64)0));
2133 }
2134 
TIFFReadDirEntrySlong8Array(TIFF * tif,TIFFDirEntry * direntry,int64 ** value)2135 static enum TIFFReadDirEntryErr TIFFReadDirEntrySlong8Array(TIFF* tif, TIFFDirEntry* direntry, int64** value)
2136 {
2137 	enum TIFFReadDirEntryErr err;
2138 	uint32 count;
2139 	void* origdata;
2140 	int64* data;
2141 	switch (direntry->tdir_type)
2142 	{
2143 		case TIFF_BYTE:
2144 		case TIFF_SBYTE:
2145 		case TIFF_SHORT:
2146 		case TIFF_SSHORT:
2147 		case TIFF_LONG:
2148 		case TIFF_SLONG:
2149 		case TIFF_LONG8:
2150 		case TIFF_SLONG8:
2151 			break;
2152 		default:
2153 			return(TIFFReadDirEntryErrType);
2154 	}
2155 	err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata);
2156 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
2157 	{
2158 		*value=0;
2159 		return(err);
2160 	}
2161 	switch (direntry->tdir_type)
2162 	{
2163 		case TIFF_LONG8:
2164 			{
2165 				uint64* m;
2166 				uint32 n;
2167 				m=(uint64*)origdata;
2168 				for (n=0; n<count; n++)
2169 				{
2170 					if (tif->tif_flags&TIFF_SWAB)
2171 						TIFFSwabLong8(m);
2172 					err=TIFFReadDirEntryCheckRangeSlong8Long8(*m);
2173 					if (err!=TIFFReadDirEntryErrOk)
2174 					{
2175 						_TIFFfree(origdata);
2176 						return(err);
2177 					}
2178 					m++;
2179 				}
2180 				*value=(int64*)origdata;
2181 				return(TIFFReadDirEntryErrOk);
2182 			}
2183 		case TIFF_SLONG8:
2184 			*value=(int64*)origdata;
2185 			if (tif->tif_flags&TIFF_SWAB)
2186 				TIFFSwabArrayOfLong8((uint64*)(*value),count);
2187 			return(TIFFReadDirEntryErrOk);
2188 	}
2189 	data=(int64*)_TIFFmalloc(count*8);
2190 	if (data==0)
2191 	{
2192 		_TIFFfree(origdata);
2193 		return(TIFFReadDirEntryErrAlloc);
2194 	}
2195 	switch (direntry->tdir_type)
2196 	{
2197 		case TIFF_BYTE:
2198 			{
2199 				uint8* ma;
2200 				int64* mb;
2201 				uint32 n;
2202 				ma=(uint8*)origdata;
2203 				mb=data;
2204 				for (n=0; n<count; n++)
2205 					*mb++=(int64)(*ma++);
2206 			}
2207 			break;
2208 		case TIFF_SBYTE:
2209 			{
2210 				int8* ma;
2211 				int64* mb;
2212 				uint32 n;
2213 				ma=(int8*)origdata;
2214 				mb=data;
2215 				for (n=0; n<count; n++)
2216 					*mb++=(int64)(*ma++);
2217 			}
2218 			break;
2219 		case TIFF_SHORT:
2220 			{
2221 				uint16* ma;
2222 				int64* mb;
2223 				uint32 n;
2224 				ma=(uint16*)origdata;
2225 				mb=data;
2226 				for (n=0; n<count; n++)
2227 				{
2228 					if (tif->tif_flags&TIFF_SWAB)
2229 						TIFFSwabShort(ma);
2230 					*mb++=(int64)(*ma++);
2231 				}
2232 			}
2233 			break;
2234 		case TIFF_SSHORT:
2235 			{
2236 				int16* ma;
2237 				int64* mb;
2238 				uint32 n;
2239 				ma=(int16*)origdata;
2240 				mb=data;
2241 				for (n=0; n<count; n++)
2242 				{
2243 					if (tif->tif_flags&TIFF_SWAB)
2244 						TIFFSwabShort((uint16*)ma);
2245 					*mb++=(int64)(*ma++);
2246 				}
2247 			}
2248 			break;
2249 		case TIFF_LONG:
2250 			{
2251 				uint32* ma;
2252 				int64* mb;
2253 				uint32 n;
2254 				ma=(uint32*)origdata;
2255 				mb=data;
2256 				for (n=0; n<count; n++)
2257 				{
2258 					if (tif->tif_flags&TIFF_SWAB)
2259 						TIFFSwabLong(ma);
2260 					*mb++=(int64)(*ma++);
2261 				}
2262 			}
2263 			break;
2264 		case TIFF_SLONG:
2265 			{
2266 				int32* ma;
2267 				int64* mb;
2268 				uint32 n;
2269 				ma=(int32*)origdata;
2270 				mb=data;
2271 				for (n=0; n<count; n++)
2272 				{
2273 					if (tif->tif_flags&TIFF_SWAB)
2274 						TIFFSwabLong((uint32*)ma);
2275 					*mb++=(int64)(*ma++);
2276 				}
2277 			}
2278 			break;
2279 	}
2280 	_TIFFfree(origdata);
2281 	*value=data;
2282 	return(TIFFReadDirEntryErrOk);
2283 }
2284 
TIFFReadDirEntryFloatArray(TIFF * tif,TIFFDirEntry * direntry,float ** value)2285 static enum TIFFReadDirEntryErr TIFFReadDirEntryFloatArray(TIFF* tif, TIFFDirEntry* direntry, float** value)
2286 {
2287 	enum TIFFReadDirEntryErr err;
2288 	uint32 count;
2289 	void* origdata;
2290 	float* data;
2291 	switch (direntry->tdir_type)
2292 	{
2293 		case TIFF_BYTE:
2294 		case TIFF_SBYTE:
2295 		case TIFF_SHORT:
2296 		case TIFF_SSHORT:
2297 		case TIFF_LONG:
2298 		case TIFF_SLONG:
2299 		case TIFF_LONG8:
2300 		case TIFF_SLONG8:
2301 		case TIFF_RATIONAL:
2302 		case TIFF_SRATIONAL:
2303 		case TIFF_FLOAT:
2304 		case TIFF_DOUBLE:
2305 			break;
2306 		default:
2307 			return(TIFFReadDirEntryErrType);
2308 	}
2309 	err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata);
2310 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
2311 	{
2312 		*value=0;
2313 		return(err);
2314 	}
2315 	switch (direntry->tdir_type)
2316 	{
2317 		case TIFF_FLOAT:
2318 			if (tif->tif_flags&TIFF_SWAB)
2319 				TIFFSwabArrayOfLong((uint32*)origdata,count);
2320 			TIFFCvtIEEEDoubleToNative(tif,count,(float*)origdata);
2321 			*value=(float*)origdata;
2322 			return(TIFFReadDirEntryErrOk);
2323 	}
2324 	data=(float*)_TIFFmalloc(count*sizeof(float));
2325 	if (data==0)
2326 	{
2327 		_TIFFfree(origdata);
2328 		return(TIFFReadDirEntryErrAlloc);
2329 	}
2330 	switch (direntry->tdir_type)
2331 	{
2332 		case TIFF_BYTE:
2333 			{
2334 				uint8* ma;
2335 				float* mb;
2336 				uint32 n;
2337 				ma=(uint8*)origdata;
2338 				mb=data;
2339 				for (n=0; n<count; n++)
2340 					*mb++=(float)(*ma++);
2341 			}
2342 			break;
2343 		case TIFF_SBYTE:
2344 			{
2345 				int8* ma;
2346 				float* mb;
2347 				uint32 n;
2348 				ma=(int8*)origdata;
2349 				mb=data;
2350 				for (n=0; n<count; n++)
2351 					*mb++=(float)(*ma++);
2352 			}
2353 			break;
2354 		case TIFF_SHORT:
2355 			{
2356 				uint16* ma;
2357 				float* mb;
2358 				uint32 n;
2359 				ma=(uint16*)origdata;
2360 				mb=data;
2361 				for (n=0; n<count; n++)
2362 				{
2363 					if (tif->tif_flags&TIFF_SWAB)
2364 						TIFFSwabShort(ma);
2365 					*mb++=(float)(*ma++);
2366 				}
2367 			}
2368 			break;
2369 		case TIFF_SSHORT:
2370 			{
2371 				int16* ma;
2372 				float* mb;
2373 				uint32 n;
2374 				ma=(int16*)origdata;
2375 				mb=data;
2376 				for (n=0; n<count; n++)
2377 				{
2378 					if (tif->tif_flags&TIFF_SWAB)
2379 						TIFFSwabShort((uint16*)ma);
2380 					*mb++=(float)(*ma++);
2381 				}
2382 			}
2383 			break;
2384 		case TIFF_LONG:
2385 			{
2386 				uint32* ma;
2387 				float* mb;
2388 				uint32 n;
2389 				ma=(uint32*)origdata;
2390 				mb=data;
2391 				for (n=0; n<count; n++)
2392 				{
2393 					if (tif->tif_flags&TIFF_SWAB)
2394 						TIFFSwabLong(ma);
2395 					*mb++=(float)(*ma++);
2396 				}
2397 			}
2398 			break;
2399 		case TIFF_SLONG:
2400 			{
2401 				int32* ma;
2402 				float* mb;
2403 				uint32 n;
2404 				ma=(int32*)origdata;
2405 				mb=data;
2406 				for (n=0; n<count; n++)
2407 				{
2408 					if (tif->tif_flags&TIFF_SWAB)
2409 						TIFFSwabLong((uint32*)ma);
2410 					*mb++=(float)(*ma++);
2411 				}
2412 			}
2413 			break;
2414 		case TIFF_LONG8:
2415 			{
2416 				uint64* ma;
2417 				float* mb;
2418 				uint32 n;
2419 				ma=(uint64*)origdata;
2420 				mb=data;
2421 				for (n=0; n<count; n++)
2422 				{
2423 					if (tif->tif_flags&TIFF_SWAB)
2424 						TIFFSwabLong8(ma);
2425 #if defined(__WIN32__) && (_MSC_VER < 1500)
2426 					/*
2427 					 * XXX: MSVC 6.0 does not support
2428 					 * conversion of 64-bit integers into
2429 					 * floating point values.
2430 					 */
2431 					*mb++ = _TIFFUInt64ToFloat(*ma++);
2432 #else
2433 					*mb++ = (float)(*ma++);
2434 #endif
2435 				}
2436 			}
2437 			break;
2438 		case TIFF_SLONG8:
2439 			{
2440 				int64* ma;
2441 				float* mb;
2442 				uint32 n;
2443 				ma=(int64*)origdata;
2444 				mb=data;
2445 				for (n=0; n<count; n++)
2446 				{
2447 					if (tif->tif_flags&TIFF_SWAB)
2448 						TIFFSwabLong8((uint64*)ma);
2449 					*mb++=(float)(*ma++);
2450 				}
2451 			}
2452 			break;
2453 		case TIFF_RATIONAL:
2454 			{
2455 				uint32* ma;
2456 				uint32 maa;
2457 				uint32 mab;
2458 				float* mb;
2459 				uint32 n;
2460 				ma=(uint32*)origdata;
2461 				mb=data;
2462 				for (n=0; n<count; n++)
2463 				{
2464 					if (tif->tif_flags&TIFF_SWAB)
2465 						TIFFSwabLong(ma);
2466 					maa=*ma++;
2467 					if (tif->tif_flags&TIFF_SWAB)
2468 						TIFFSwabLong(ma);
2469 					mab=*ma++;
2470 					if (mab==0)
2471 						*mb++=0.0;
2472 					else
2473 						*mb++=(float)maa/(float)mab;
2474 				}
2475 			}
2476 			break;
2477 		case TIFF_SRATIONAL:
2478 			{
2479 				uint32* ma;
2480 				int32 maa;
2481 				uint32 mab;
2482 				float* mb;
2483 				uint32 n;
2484 				ma=(uint32*)origdata;
2485 				mb=data;
2486 				for (n=0; n<count; n++)
2487 				{
2488 					if (tif->tif_flags&TIFF_SWAB)
2489 						TIFFSwabLong(ma);
2490 					maa=*(int32*)ma;
2491 					ma++;
2492 					if (tif->tif_flags&TIFF_SWAB)
2493 						TIFFSwabLong(ma);
2494 					mab=*ma++;
2495 					if (mab==0)
2496 						*mb++=0.0;
2497 					else
2498 						*mb++=(float)maa/(float)mab;
2499 				}
2500 			}
2501 			break;
2502 		case TIFF_DOUBLE:
2503 			{
2504 				double* ma;
2505 				float* mb;
2506 				uint32 n;
2507 				if (tif->tif_flags&TIFF_SWAB)
2508 					TIFFSwabArrayOfLong8((uint64*)origdata,count);
2509 				TIFFCvtIEEEDoubleToNative(tif,count,(double*)origdata);
2510 				ma=(double*)origdata;
2511 				mb=data;
2512 				for (n=0; n<count; n++)
2513                                 {
2514                                     double val = *ma++;
2515                                     if( val > FLT_MAX )
2516                                         val = FLT_MAX;
2517                                     else if( val < -FLT_MAX )
2518                                         val = -FLT_MAX;
2519                                     *mb++=(float)val;
2520                                 }
2521 			}
2522 			break;
2523 	}
2524 	_TIFFfree(origdata);
2525 	*value=data;
2526 	return(TIFFReadDirEntryErrOk);
2527 }
2528 
2529 static enum TIFFReadDirEntryErr
TIFFReadDirEntryDoubleArray(TIFF * tif,TIFFDirEntry * direntry,double ** value)2530 TIFFReadDirEntryDoubleArray(TIFF* tif, TIFFDirEntry* direntry, double** value)
2531 {
2532 	enum TIFFReadDirEntryErr err;
2533 	uint32 count;
2534 	void* origdata;
2535 	double* data;
2536 	switch (direntry->tdir_type)
2537 	{
2538 		case TIFF_BYTE:
2539 		case TIFF_SBYTE:
2540 		case TIFF_SHORT:
2541 		case TIFF_SSHORT:
2542 		case TIFF_LONG:
2543 		case TIFF_SLONG:
2544 		case TIFF_LONG8:
2545 		case TIFF_SLONG8:
2546 		case TIFF_RATIONAL:
2547 		case TIFF_SRATIONAL:
2548 		case TIFF_FLOAT:
2549 		case TIFF_DOUBLE:
2550 			break;
2551 		default:
2552 			return(TIFFReadDirEntryErrType);
2553 	}
2554 	err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata);
2555 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
2556 	{
2557 		*value=0;
2558 		return(err);
2559 	}
2560 	switch (direntry->tdir_type)
2561 	{
2562 		case TIFF_DOUBLE:
2563 			if (tif->tif_flags&TIFF_SWAB)
2564 				TIFFSwabArrayOfLong8((uint64*)origdata,count);
2565 			TIFFCvtIEEEDoubleToNative(tif,count,(double*)origdata);
2566 			*value=(double*)origdata;
2567 			return(TIFFReadDirEntryErrOk);
2568 	}
2569 	data=(double*)_TIFFmalloc(count*sizeof(double));
2570 	if (data==0)
2571 	{
2572 		_TIFFfree(origdata);
2573 		return(TIFFReadDirEntryErrAlloc);
2574 	}
2575 	switch (direntry->tdir_type)
2576 	{
2577 		case TIFF_BYTE:
2578 			{
2579 				uint8* ma;
2580 				double* mb;
2581 				uint32 n;
2582 				ma=(uint8*)origdata;
2583 				mb=data;
2584 				for (n=0; n<count; n++)
2585 					*mb++=(double)(*ma++);
2586 			}
2587 			break;
2588 		case TIFF_SBYTE:
2589 			{
2590 				int8* ma;
2591 				double* mb;
2592 				uint32 n;
2593 				ma=(int8*)origdata;
2594 				mb=data;
2595 				for (n=0; n<count; n++)
2596 					*mb++=(double)(*ma++);
2597 			}
2598 			break;
2599 		case TIFF_SHORT:
2600 			{
2601 				uint16* ma;
2602 				double* mb;
2603 				uint32 n;
2604 				ma=(uint16*)origdata;
2605 				mb=data;
2606 				for (n=0; n<count; n++)
2607 				{
2608 					if (tif->tif_flags&TIFF_SWAB)
2609 						TIFFSwabShort(ma);
2610 					*mb++=(double)(*ma++);
2611 				}
2612 			}
2613 			break;
2614 		case TIFF_SSHORT:
2615 			{
2616 				int16* ma;
2617 				double* mb;
2618 				uint32 n;
2619 				ma=(int16*)origdata;
2620 				mb=data;
2621 				for (n=0; n<count; n++)
2622 				{
2623 					if (tif->tif_flags&TIFF_SWAB)
2624 						TIFFSwabShort((uint16*)ma);
2625 					*mb++=(double)(*ma++);
2626 				}
2627 			}
2628 			break;
2629 		case TIFF_LONG:
2630 			{
2631 				uint32* ma;
2632 				double* mb;
2633 				uint32 n;
2634 				ma=(uint32*)origdata;
2635 				mb=data;
2636 				for (n=0; n<count; n++)
2637 				{
2638 					if (tif->tif_flags&TIFF_SWAB)
2639 						TIFFSwabLong(ma);
2640 					*mb++=(double)(*ma++);
2641 				}
2642 			}
2643 			break;
2644 		case TIFF_SLONG:
2645 			{
2646 				int32* ma;
2647 				double* mb;
2648 				uint32 n;
2649 				ma=(int32*)origdata;
2650 				mb=data;
2651 				for (n=0; n<count; n++)
2652 				{
2653 					if (tif->tif_flags&TIFF_SWAB)
2654 						TIFFSwabLong((uint32*)ma);
2655 					*mb++=(double)(*ma++);
2656 				}
2657 			}
2658 			break;
2659 		case TIFF_LONG8:
2660 			{
2661 				uint64* ma;
2662 				double* mb;
2663 				uint32 n;
2664 				ma=(uint64*)origdata;
2665 				mb=data;
2666 				for (n=0; n<count; n++)
2667 				{
2668 					if (tif->tif_flags&TIFF_SWAB)
2669 						TIFFSwabLong8(ma);
2670 #if defined(__WIN32__) && (_MSC_VER < 1500)
2671 					/*
2672 					 * XXX: MSVC 6.0 does not support
2673 					 * conversion of 64-bit integers into
2674 					 * floating point values.
2675 					 */
2676 					*mb++ = _TIFFUInt64ToDouble(*ma++);
2677 #else
2678 					*mb++ = (double)(*ma++);
2679 #endif
2680 				}
2681 			}
2682 			break;
2683 		case TIFF_SLONG8:
2684 			{
2685 				int64* ma;
2686 				double* mb;
2687 				uint32 n;
2688 				ma=(int64*)origdata;
2689 				mb=data;
2690 				for (n=0; n<count; n++)
2691 				{
2692 					if (tif->tif_flags&TIFF_SWAB)
2693 						TIFFSwabLong8((uint64*)ma);
2694 					*mb++=(double)(*ma++);
2695 				}
2696 			}
2697 			break;
2698 		case TIFF_RATIONAL:
2699 			{
2700 				uint32* ma;
2701 				uint32 maa;
2702 				uint32 mab;
2703 				double* mb;
2704 				uint32 n;
2705 				ma=(uint32*)origdata;
2706 				mb=data;
2707 				for (n=0; n<count; n++)
2708 				{
2709 					if (tif->tif_flags&TIFF_SWAB)
2710 						TIFFSwabLong(ma);
2711 					maa=*ma++;
2712 					if (tif->tif_flags&TIFF_SWAB)
2713 						TIFFSwabLong(ma);
2714 					mab=*ma++;
2715 					if (mab==0)
2716 						*mb++=0.0;
2717 					else
2718 						*mb++=(double)maa/(double)mab;
2719 				}
2720 			}
2721 			break;
2722 		case TIFF_SRATIONAL:
2723 			{
2724 				uint32* ma;
2725 				int32 maa;
2726 				uint32 mab;
2727 				double* mb;
2728 				uint32 n;
2729 				ma=(uint32*)origdata;
2730 				mb=data;
2731 				for (n=0; n<count; n++)
2732 				{
2733 					if (tif->tif_flags&TIFF_SWAB)
2734 						TIFFSwabLong(ma);
2735 					maa=*(int32*)ma;
2736 					ma++;
2737 					if (tif->tif_flags&TIFF_SWAB)
2738 						TIFFSwabLong(ma);
2739 					mab=*ma++;
2740 					if (mab==0)
2741 						*mb++=0.0;
2742 					else
2743 						*mb++=(double)maa/(double)mab;
2744 				}
2745 			}
2746 			break;
2747 		case TIFF_FLOAT:
2748 			{
2749 				float* ma;
2750 				double* mb;
2751 				uint32 n;
2752 				if (tif->tif_flags&TIFF_SWAB)
2753 					TIFFSwabArrayOfLong((uint32*)origdata,count);
2754 				TIFFCvtIEEEFloatToNative(tif,count,(float*)origdata);
2755 				ma=(float*)origdata;
2756 				mb=data;
2757 				for (n=0; n<count; n++)
2758 					*mb++=(double)(*ma++);
2759 			}
2760 			break;
2761 	}
2762 	_TIFFfree(origdata);
2763 	*value=data;
2764 	return(TIFFReadDirEntryErrOk);
2765 }
2766 
TIFFReadDirEntryIfd8Array(TIFF * tif,TIFFDirEntry * direntry,uint64 ** value)2767 static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value)
2768 {
2769 	enum TIFFReadDirEntryErr err;
2770 	uint32 count;
2771 	void* origdata;
2772 	uint64* data;
2773 	switch (direntry->tdir_type)
2774 	{
2775 		case TIFF_LONG:
2776 		case TIFF_LONG8:
2777 		case TIFF_IFD:
2778 		case TIFF_IFD8:
2779 			break;
2780 		default:
2781 			return(TIFFReadDirEntryErrType);
2782 	}
2783 	err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata);
2784 	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
2785 	{
2786 		*value=0;
2787 		return(err);
2788 	}
2789 	switch (direntry->tdir_type)
2790 	{
2791 		case TIFF_LONG8:
2792 		case TIFF_IFD8:
2793 			*value=(uint64*)origdata;
2794 			if (tif->tif_flags&TIFF_SWAB)
2795 				TIFFSwabArrayOfLong8(*value,count);
2796 			return(TIFFReadDirEntryErrOk);
2797 	}
2798 	data=(uint64*)_TIFFmalloc(count*8);
2799 	if (data==0)
2800 	{
2801 		_TIFFfree(origdata);
2802 		return(TIFFReadDirEntryErrAlloc);
2803 	}
2804 	switch (direntry->tdir_type)
2805 	{
2806 		case TIFF_LONG:
2807 		case TIFF_IFD:
2808 			{
2809 				uint32* ma;
2810 				uint64* mb;
2811 				uint32 n;
2812 				ma=(uint32*)origdata;
2813 				mb=data;
2814 				for (n=0; n<count; n++)
2815 				{
2816 					if (tif->tif_flags&TIFF_SWAB)
2817 						TIFFSwabLong(ma);
2818 					*mb++=(uint64)(*ma++);
2819 				}
2820 			}
2821 			break;
2822 	}
2823 	_TIFFfree(origdata);
2824 	*value=data;
2825 	return(TIFFReadDirEntryErrOk);
2826 }
2827 
TIFFReadDirEntryPersampleShort(TIFF * tif,TIFFDirEntry * direntry,uint16 * value)2828 static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value)
2829 {
2830 	enum TIFFReadDirEntryErr err;
2831 	uint16* m;
2832 	uint16* na;
2833 	uint16 nb;
2834 	if (direntry->tdir_count<(uint64)tif->tif_dir.td_samplesperpixel)
2835 		return(TIFFReadDirEntryErrCount);
2836 	err=TIFFReadDirEntryShortArray(tif,direntry,&m);
2837 	if (err!=TIFFReadDirEntryErrOk || m == NULL)
2838 		return(err);
2839 	na=m;
2840 	nb=tif->tif_dir.td_samplesperpixel;
2841 	*value=*na++;
2842 	nb--;
2843 	while (nb>0)
2844 	{
2845 		if (*na++!=*value)
2846 		{
2847 			err=TIFFReadDirEntryErrPsdif;
2848 			break;
2849 		}
2850 		nb--;
2851 	}
2852 	_TIFFfree(m);
2853 	return(err);
2854 }
2855 
2856 #if 0
2857 static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleDouble(TIFF* tif, TIFFDirEntry* direntry, double* value)
2858 {
2859 	enum TIFFReadDirEntryErr err;
2860 	double* m;
2861 	double* na;
2862 	uint16 nb;
2863 	if (direntry->tdir_count<(uint64)tif->tif_dir.td_samplesperpixel)
2864 		return(TIFFReadDirEntryErrCount);
2865 	err=TIFFReadDirEntryDoubleArray(tif,direntry,&m);
2866 	if (err!=TIFFReadDirEntryErrOk)
2867 		return(err);
2868 	na=m;
2869 	nb=tif->tif_dir.td_samplesperpixel;
2870 	*value=*na++;
2871 	nb--;
2872 	while (nb>0)
2873 	{
2874 		if (*na++!=*value)
2875 		{
2876 			err=TIFFReadDirEntryErrPsdif;
2877 			break;
2878 		}
2879 		nb--;
2880 	}
2881 	_TIFFfree(m);
2882 	return(err);
2883 }
2884 #endif
2885 
TIFFReadDirEntryCheckedByte(TIFF * tif,TIFFDirEntry * direntry,uint8 * value)2886 static void TIFFReadDirEntryCheckedByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value)
2887 {
2888 	(void) tif;
2889 	*value=*(uint8*)(&direntry->tdir_offset);
2890 }
2891 
TIFFReadDirEntryCheckedSbyte(TIFF * tif,TIFFDirEntry * direntry,int8 * value)2892 static void TIFFReadDirEntryCheckedSbyte(TIFF* tif, TIFFDirEntry* direntry, int8* value)
2893 {
2894 	(void) tif;
2895 	*value=*(int8*)(&direntry->tdir_offset);
2896 }
2897 
TIFFReadDirEntryCheckedShort(TIFF * tif,TIFFDirEntry * direntry,uint16 * value)2898 static void TIFFReadDirEntryCheckedShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value)
2899 {
2900 	*value = direntry->tdir_offset.toff_short;
2901 	/* *value=*(uint16*)(&direntry->tdir_offset); */
2902 	if (tif->tif_flags&TIFF_SWAB)
2903 		TIFFSwabShort(value);
2904 }
2905 
TIFFReadDirEntryCheckedSshort(TIFF * tif,TIFFDirEntry * direntry,int16 * value)2906 static void TIFFReadDirEntryCheckedSshort(TIFF* tif, TIFFDirEntry* direntry, int16* value)
2907 {
2908 	*value=*(int16*)(&direntry->tdir_offset);
2909 	if (tif->tif_flags&TIFF_SWAB)
2910 		TIFFSwabShort((uint16*)value);
2911 }
2912 
TIFFReadDirEntryCheckedLong(TIFF * tif,TIFFDirEntry * direntry,uint32 * value)2913 static void TIFFReadDirEntryCheckedLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value)
2914 {
2915 	*value=*(uint32*)(&direntry->tdir_offset);
2916 	if (tif->tif_flags&TIFF_SWAB)
2917 		TIFFSwabLong(value);
2918 }
2919 
TIFFReadDirEntryCheckedSlong(TIFF * tif,TIFFDirEntry * direntry,int32 * value)2920 static void TIFFReadDirEntryCheckedSlong(TIFF* tif, TIFFDirEntry* direntry, int32* value)
2921 {
2922 	*value=*(int32*)(&direntry->tdir_offset);
2923 	if (tif->tif_flags&TIFF_SWAB)
2924 		TIFFSwabLong((uint32*)value);
2925 }
2926 
TIFFReadDirEntryCheckedLong8(TIFF * tif,TIFFDirEntry * direntry,uint64 * value)2927 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value)
2928 {
2929 	if (!(tif->tif_flags&TIFF_BIGTIFF))
2930 	{
2931 		enum TIFFReadDirEntryErr err;
2932 		uint32 offset = direntry->tdir_offset.toff_long;
2933 		if (tif->tif_flags&TIFF_SWAB)
2934 			TIFFSwabLong(&offset);
2935 		err=TIFFReadDirEntryData(tif,offset,8,value);
2936 		if (err!=TIFFReadDirEntryErrOk)
2937 			return(err);
2938 	}
2939 	else
2940 		*value = direntry->tdir_offset.toff_long8;
2941 	if (tif->tif_flags&TIFF_SWAB)
2942 		TIFFSwabLong8(value);
2943 	return(TIFFReadDirEntryErrOk);
2944 }
2945 
TIFFReadDirEntryCheckedSlong8(TIFF * tif,TIFFDirEntry * direntry,int64 * value)2946 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSlong8(TIFF* tif, TIFFDirEntry* direntry, int64* value)
2947 {
2948 	if (!(tif->tif_flags&TIFF_BIGTIFF))
2949 	{
2950 		enum TIFFReadDirEntryErr err;
2951 		uint32 offset = direntry->tdir_offset.toff_long;
2952 		if (tif->tif_flags&TIFF_SWAB)
2953 			TIFFSwabLong(&offset);
2954 		err=TIFFReadDirEntryData(tif,offset,8,value);
2955 		if (err!=TIFFReadDirEntryErrOk)
2956 			return(err);
2957 	}
2958 	else
2959 		*value=*(int64*)(&direntry->tdir_offset);
2960 	if (tif->tif_flags&TIFF_SWAB)
2961 		TIFFSwabLong8((uint64*)value);
2962 	return(TIFFReadDirEntryErrOk);
2963 }
2964 
TIFFReadDirEntryCheckedRational(TIFF * tif,TIFFDirEntry * direntry,double * value)2965 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedRational(TIFF* tif, TIFFDirEntry* direntry, double* value)
2966 {
2967 	UInt64Aligned_t m;
2968 
2969 	assert(sizeof(double)==8);
2970 	assert(sizeof(uint64)==8);
2971 	assert(sizeof(uint32)==4);
2972 	if (!(tif->tif_flags&TIFF_BIGTIFF))
2973 	{
2974 		enum TIFFReadDirEntryErr err;
2975 		uint32 offset = direntry->tdir_offset.toff_long;
2976 		if (tif->tif_flags&TIFF_SWAB)
2977 			TIFFSwabLong(&offset);
2978 		err=TIFFReadDirEntryData(tif,offset,8,m.i);
2979 		if (err!=TIFFReadDirEntryErrOk)
2980 			return(err);
2981 	}
2982 	else
2983 		m.l = direntry->tdir_offset.toff_long8;
2984 	if (tif->tif_flags&TIFF_SWAB)
2985 		TIFFSwabArrayOfLong(m.i,2);
2986         /* Not completely sure what we should do when m.i[1]==0, but some */
2987         /* sanitizers do not like division by 0.0: */
2988         /* http://bugzilla.maptools.org/show_bug.cgi?id=2644 */
2989 	if (m.i[0]==0 || m.i[1]==0)
2990 		*value=0.0;
2991 	else
2992 		*value=(double)m.i[0]/(double)m.i[1];
2993 	return(TIFFReadDirEntryErrOk);
2994 }
2995 
TIFFReadDirEntryCheckedSrational(TIFF * tif,TIFFDirEntry * direntry,double * value)2996 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSrational(TIFF* tif, TIFFDirEntry* direntry, double* value)
2997 {
2998 	UInt64Aligned_t m;
2999 	assert(sizeof(double)==8);
3000 	assert(sizeof(uint64)==8);
3001 	assert(sizeof(int32)==4);
3002 	assert(sizeof(uint32)==4);
3003 	if (!(tif->tif_flags&TIFF_BIGTIFF))
3004 	{
3005 		enum TIFFReadDirEntryErr err;
3006 		uint32 offset = direntry->tdir_offset.toff_long;
3007 		if (tif->tif_flags&TIFF_SWAB)
3008 			TIFFSwabLong(&offset);
3009 		err=TIFFReadDirEntryData(tif,offset,8,m.i);
3010 		if (err!=TIFFReadDirEntryErrOk)
3011 			return(err);
3012 	}
3013 	else
3014 		m.l=direntry->tdir_offset.toff_long8;
3015 	if (tif->tif_flags&TIFF_SWAB)
3016 		TIFFSwabArrayOfLong(m.i,2);
3017         /* Not completely sure what we should do when m.i[1]==0, but some */
3018         /* sanitizers do not like division by 0.0: */
3019         /* http://bugzilla.maptools.org/show_bug.cgi?id=2644 */
3020 	if ((int32)m.i[0]==0 || m.i[1]==0)
3021 		*value=0.0;
3022 	else
3023 		*value=(double)((int32)m.i[0])/(double)m.i[1];
3024 	return(TIFFReadDirEntryErrOk);
3025 }
3026 
TIFFReadDirEntryCheckedFloat(TIFF * tif,TIFFDirEntry * direntry,float * value)3027 static void TIFFReadDirEntryCheckedFloat(TIFF* tif, TIFFDirEntry* direntry, float* value)
3028 {
3029          union
3030 	 {
3031 	   float  f;
3032 	   uint32 i;
3033 	 } float_union;
3034 	assert(sizeof(float)==4);
3035 	assert(sizeof(uint32)==4);
3036 	assert(sizeof(float_union)==4);
3037 	float_union.i=*(uint32*)(&direntry->tdir_offset);
3038 	*value=float_union.f;
3039 	if (tif->tif_flags&TIFF_SWAB)
3040 		TIFFSwabLong((uint32*)value);
3041 }
3042 
TIFFReadDirEntryCheckedDouble(TIFF * tif,TIFFDirEntry * direntry,double * value)3043 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedDouble(TIFF* tif, TIFFDirEntry* direntry, double* value)
3044 {
3045 	assert(sizeof(double)==8);
3046 	assert(sizeof(uint64)==8);
3047 	assert(sizeof(UInt64Aligned_t)==8);
3048 	if (!(tif->tif_flags&TIFF_BIGTIFF))
3049 	{
3050 		enum TIFFReadDirEntryErr err;
3051 		uint32 offset = direntry->tdir_offset.toff_long;
3052 		if (tif->tif_flags&TIFF_SWAB)
3053 			TIFFSwabLong(&offset);
3054 		err=TIFFReadDirEntryData(tif,offset,8,value);
3055 		if (err!=TIFFReadDirEntryErrOk)
3056 			return(err);
3057 	}
3058 	else
3059 	{
3060 	       UInt64Aligned_t uint64_union;
3061 	       uint64_union.l=direntry->tdir_offset.toff_long8;
3062 	       *value=uint64_union.d;
3063 	}
3064 	if (tif->tif_flags&TIFF_SWAB)
3065 		TIFFSwabLong8((uint64*)value);
3066 	return(TIFFReadDirEntryErrOk);
3067 }
3068 
TIFFReadDirEntryCheckRangeByteSbyte(int8 value)3069 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSbyte(int8 value)
3070 {
3071 	if (value<0)
3072 		return(TIFFReadDirEntryErrRange);
3073 	else
3074 		return(TIFFReadDirEntryErrOk);
3075 }
3076 
TIFFReadDirEntryCheckRangeByteShort(uint16 value)3077 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteShort(uint16 value)
3078 {
3079 	if (value>0xFF)
3080 		return(TIFFReadDirEntryErrRange);
3081 	else
3082 		return(TIFFReadDirEntryErrOk);
3083 }
3084 
TIFFReadDirEntryCheckRangeByteSshort(int16 value)3085 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSshort(int16 value)
3086 {
3087 	if ((value<0)||(value>0xFF))
3088 		return(TIFFReadDirEntryErrRange);
3089 	else
3090 		return(TIFFReadDirEntryErrOk);
3091 }
3092 
TIFFReadDirEntryCheckRangeByteLong(uint32 value)3093 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong(uint32 value)
3094 {
3095 	if (value>0xFF)
3096 		return(TIFFReadDirEntryErrRange);
3097 	else
3098 		return(TIFFReadDirEntryErrOk);
3099 }
3100 
TIFFReadDirEntryCheckRangeByteSlong(int32 value)3101 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong(int32 value)
3102 {
3103 	if ((value<0)||(value>0xFF))
3104 		return(TIFFReadDirEntryErrRange);
3105 	else
3106 		return(TIFFReadDirEntryErrOk);
3107 }
3108 
TIFFReadDirEntryCheckRangeByteLong8(uint64 value)3109 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong8(uint64 value)
3110 {
3111 	if (value>0xFF)
3112 		return(TIFFReadDirEntryErrRange);
3113 	else
3114 		return(TIFFReadDirEntryErrOk);
3115 }
3116 
TIFFReadDirEntryCheckRangeByteSlong8(int64 value)3117 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong8(int64 value)
3118 {
3119 	if ((value<0)||(value>0xFF))
3120 		return(TIFFReadDirEntryErrRange);
3121 	else
3122 		return(TIFFReadDirEntryErrOk);
3123 }
3124 
TIFFReadDirEntryCheckRangeSbyteByte(uint8 value)3125 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteByte(uint8 value)
3126 {
3127 	if (value>0x7F)
3128 		return(TIFFReadDirEntryErrRange);
3129 	else
3130 		return(TIFFReadDirEntryErrOk);
3131 }
3132 
TIFFReadDirEntryCheckRangeSbyteShort(uint16 value)3133 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteShort(uint16 value)
3134 {
3135 	if (value>0x7F)
3136 		return(TIFFReadDirEntryErrRange);
3137 	else
3138 		return(TIFFReadDirEntryErrOk);
3139 }
3140 
TIFFReadDirEntryCheckRangeSbyteSshort(int16 value)3141 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSshort(int16 value)
3142 {
3143 	if ((value<-0x80)||(value>0x7F))
3144 		return(TIFFReadDirEntryErrRange);
3145 	else
3146 		return(TIFFReadDirEntryErrOk);
3147 }
3148 
TIFFReadDirEntryCheckRangeSbyteLong(uint32 value)3149 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong(uint32 value)
3150 {
3151 	if (value>0x7F)
3152 		return(TIFFReadDirEntryErrRange);
3153 	else
3154 		return(TIFFReadDirEntryErrOk);
3155 }
3156 
TIFFReadDirEntryCheckRangeSbyteSlong(int32 value)3157 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong(int32 value)
3158 {
3159 	if ((value<-0x80)||(value>0x7F))
3160 		return(TIFFReadDirEntryErrRange);
3161 	else
3162 		return(TIFFReadDirEntryErrOk);
3163 }
3164 
TIFFReadDirEntryCheckRangeSbyteLong8(uint64 value)3165 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong8(uint64 value)
3166 {
3167 	if (value>0x7F)
3168 		return(TIFFReadDirEntryErrRange);
3169 	else
3170 		return(TIFFReadDirEntryErrOk);
3171 }
3172 
TIFFReadDirEntryCheckRangeSbyteSlong8(int64 value)3173 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong8(int64 value)
3174 {
3175 	if ((value<-0x80)||(value>0x7F))
3176 		return(TIFFReadDirEntryErrRange);
3177 	else
3178 		return(TIFFReadDirEntryErrOk);
3179 }
3180 
TIFFReadDirEntryCheckRangeShortSbyte(int8 value)3181 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSbyte(int8 value)
3182 {
3183 	if (value<0)
3184 		return(TIFFReadDirEntryErrRange);
3185 	else
3186 		return(TIFFReadDirEntryErrOk);
3187 }
3188 
TIFFReadDirEntryCheckRangeShortSshort(int16 value)3189 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSshort(int16 value)
3190 {
3191 	if (value<0)
3192 		return(TIFFReadDirEntryErrRange);
3193 	else
3194 		return(TIFFReadDirEntryErrOk);
3195 }
3196 
TIFFReadDirEntryCheckRangeShortLong(uint32 value)3197 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong(uint32 value)
3198 {
3199 	if (value>0xFFFF)
3200 		return(TIFFReadDirEntryErrRange);
3201 	else
3202 		return(TIFFReadDirEntryErrOk);
3203 }
3204 
TIFFReadDirEntryCheckRangeShortSlong(int32 value)3205 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong(int32 value)
3206 {
3207 	if ((value<0)||(value>0xFFFF))
3208 		return(TIFFReadDirEntryErrRange);
3209 	else
3210 		return(TIFFReadDirEntryErrOk);
3211 }
3212 
TIFFReadDirEntryCheckRangeShortLong8(uint64 value)3213 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong8(uint64 value)
3214 {
3215 	if (value>0xFFFF)
3216 		return(TIFFReadDirEntryErrRange);
3217 	else
3218 		return(TIFFReadDirEntryErrOk);
3219 }
3220 
TIFFReadDirEntryCheckRangeShortSlong8(int64 value)3221 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong8(int64 value)
3222 {
3223 	if ((value<0)||(value>0xFFFF))
3224 		return(TIFFReadDirEntryErrRange);
3225 	else
3226 		return(TIFFReadDirEntryErrOk);
3227 }
3228 
TIFFReadDirEntryCheckRangeSshortShort(uint16 value)3229 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortShort(uint16 value)
3230 {
3231 	if (value>0x7FFF)
3232 		return(TIFFReadDirEntryErrRange);
3233 	else
3234 		return(TIFFReadDirEntryErrOk);
3235 }
3236 
TIFFReadDirEntryCheckRangeSshortLong(uint32 value)3237 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong(uint32 value)
3238 {
3239 	if (value>0x7FFF)
3240 		return(TIFFReadDirEntryErrRange);
3241 	else
3242 		return(TIFFReadDirEntryErrOk);
3243 }
3244 
TIFFReadDirEntryCheckRangeSshortSlong(int32 value)3245 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong(int32 value)
3246 {
3247 	if ((value<-0x8000)||(value>0x7FFF))
3248 		return(TIFFReadDirEntryErrRange);
3249 	else
3250 		return(TIFFReadDirEntryErrOk);
3251 }
3252 
TIFFReadDirEntryCheckRangeSshortLong8(uint64 value)3253 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong8(uint64 value)
3254 {
3255 	if (value>0x7FFF)
3256 		return(TIFFReadDirEntryErrRange);
3257 	else
3258 		return(TIFFReadDirEntryErrOk);
3259 }
3260 
TIFFReadDirEntryCheckRangeSshortSlong8(int64 value)3261 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong8(int64 value)
3262 {
3263 	if ((value<-0x8000)||(value>0x7FFF))
3264 		return(TIFFReadDirEntryErrRange);
3265 	else
3266 		return(TIFFReadDirEntryErrOk);
3267 }
3268 
TIFFReadDirEntryCheckRangeLongSbyte(int8 value)3269 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSbyte(int8 value)
3270 {
3271 	if (value<0)
3272 		return(TIFFReadDirEntryErrRange);
3273 	else
3274 		return(TIFFReadDirEntryErrOk);
3275 }
3276 
TIFFReadDirEntryCheckRangeLongSshort(int16 value)3277 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSshort(int16 value)
3278 {
3279 	if (value<0)
3280 		return(TIFFReadDirEntryErrRange);
3281 	else
3282 		return(TIFFReadDirEntryErrOk);
3283 }
3284 
TIFFReadDirEntryCheckRangeLongSlong(int32 value)3285 static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong(int32 value)
3286 {
3287 	if (value<0)
3288 		return(TIFFReadDirEntryErrRange);
3289 	else
3290 		return(TIFFReadDirEntryErrOk);
3291 }
3292 
3293 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeLongLong8(uint64 value)3294 TIFFReadDirEntryCheckRangeLongLong8(uint64 value)
3295 {
3296 	if (value > TIFF_UINT32_MAX)
3297 		return(TIFFReadDirEntryErrRange);
3298 	else
3299 		return(TIFFReadDirEntryErrOk);
3300 }
3301 
3302 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeLongSlong8(int64 value)3303 TIFFReadDirEntryCheckRangeLongSlong8(int64 value)
3304 {
3305 	if ((value < 0) || (value > (int64) TIFF_UINT32_MAX))
3306 		return(TIFFReadDirEntryErrRange);
3307 	else
3308 		return(TIFFReadDirEntryErrOk);
3309 }
3310 
3311 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeSlongLong(uint32 value)3312 TIFFReadDirEntryCheckRangeSlongLong(uint32 value)
3313 {
3314 	if (value > 0x7FFFFFFFUL)
3315 		return(TIFFReadDirEntryErrRange);
3316 	else
3317 		return(TIFFReadDirEntryErrOk);
3318 }
3319 
3320 /* Check that the 8-byte unsigned value can fit in a 4-byte unsigned range */
3321 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeSlongLong8(uint64 value)3322 TIFFReadDirEntryCheckRangeSlongLong8(uint64 value)
3323 {
3324 	if (value > 0x7FFFFFFF)
3325 		return(TIFFReadDirEntryErrRange);
3326 	else
3327 		return(TIFFReadDirEntryErrOk);
3328 }
3329 
3330 /* Check that the 8-byte signed value can fit in a 4-byte signed range */
3331 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeSlongSlong8(int64 value)3332 TIFFReadDirEntryCheckRangeSlongSlong8(int64 value)
3333 {
3334         if ((value < 0-((int64) 0x7FFFFFFF+1)) || (value > 0x7FFFFFFF))
3335 		return(TIFFReadDirEntryErrRange);
3336 	else
3337 		return(TIFFReadDirEntryErrOk);
3338 }
3339 
3340 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeLong8Sbyte(int8 value)3341 TIFFReadDirEntryCheckRangeLong8Sbyte(int8 value)
3342 {
3343 	if (value < 0)
3344 		return(TIFFReadDirEntryErrRange);
3345 	else
3346 		return(TIFFReadDirEntryErrOk);
3347 }
3348 
3349 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeLong8Sshort(int16 value)3350 TIFFReadDirEntryCheckRangeLong8Sshort(int16 value)
3351 {
3352 	if (value < 0)
3353 		return(TIFFReadDirEntryErrRange);
3354 	else
3355 		return(TIFFReadDirEntryErrOk);
3356 }
3357 
3358 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeLong8Slong(int32 value)3359 TIFFReadDirEntryCheckRangeLong8Slong(int32 value)
3360 {
3361 	if (value < 0)
3362 		return(TIFFReadDirEntryErrRange);
3363 	else
3364 		return(TIFFReadDirEntryErrOk);
3365 }
3366 
3367 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeLong8Slong8(int64 value)3368 TIFFReadDirEntryCheckRangeLong8Slong8(int64 value)
3369 {
3370 	if (value < 0)
3371 		return(TIFFReadDirEntryErrRange);
3372 	else
3373 		return(TIFFReadDirEntryErrOk);
3374 }
3375 
3376 static enum TIFFReadDirEntryErr
TIFFReadDirEntryCheckRangeSlong8Long8(uint64 value)3377 TIFFReadDirEntryCheckRangeSlong8Long8(uint64 value)
3378 {
3379 	if (value > TIFF_INT64_MAX)
3380 		return(TIFFReadDirEntryErrRange);
3381 	else
3382 		return(TIFFReadDirEntryErrOk);
3383 }
3384 
3385 static enum TIFFReadDirEntryErr
TIFFReadDirEntryData(TIFF * tif,uint64 offset,tmsize_t size,void * dest)3386 TIFFReadDirEntryData(TIFF* tif, uint64 offset, tmsize_t size, void* dest)
3387 {
3388 	assert(size>0);
3389 	if (!isMapped(tif)) {
3390 		if (!SeekOK(tif,offset))
3391 			return(TIFFReadDirEntryErrIo);
3392 		if (!ReadOK(tif,dest,size))
3393 			return(TIFFReadDirEntryErrIo);
3394 	} else {
3395 		size_t ma,mb;
3396 		ma=(size_t)offset;
3397                 if( (uint64)ma!=offset ||
3398                     ma > (~(size_t)0) - (size_t)size )
3399                 {
3400                     return TIFFReadDirEntryErrIo;
3401                 }
3402 		mb=ma+size;
3403 		if (mb > (size_t)tif->tif_size)
3404 			return(TIFFReadDirEntryErrIo);
3405 		_TIFFmemcpy(dest,tif->tif_base+ma,size);
3406 	}
3407 	return(TIFFReadDirEntryErrOk);
3408 }
3409 
TIFFReadDirEntryOutputErr(TIFF * tif,enum TIFFReadDirEntryErr err,const char * module,const char * tagname,int recover)3410 static void TIFFReadDirEntryOutputErr(TIFF* tif, enum TIFFReadDirEntryErr err, const char* module, const char* tagname, int recover)
3411 {
3412 	if (!recover) {
3413 		switch (err) {
3414 			case TIFFReadDirEntryErrCount:
3415 				TIFFErrorExt(tif->tif_clientdata, module,
3416 					     "Incorrect count for \"%s\"",
3417 					     tagname);
3418 				break;
3419 			case TIFFReadDirEntryErrType:
3420 				TIFFErrorExt(tif->tif_clientdata, module,
3421 					     "Incompatible type for \"%s\"",
3422 					     tagname);
3423 				break;
3424 			case TIFFReadDirEntryErrIo:
3425 				TIFFErrorExt(tif->tif_clientdata, module,
3426 					     "IO error during reading of \"%s\"",
3427 					     tagname);
3428 				break;
3429 			case TIFFReadDirEntryErrRange:
3430 				TIFFErrorExt(tif->tif_clientdata, module,
3431 					     "Incorrect value for \"%s\"",
3432 					     tagname);
3433 				break;
3434 			case TIFFReadDirEntryErrPsdif:
3435 				TIFFErrorExt(tif->tif_clientdata, module,
3436 			"Cannot handle different values per sample for \"%s\"",
3437 					     tagname);
3438 				break;
3439 			case TIFFReadDirEntryErrSizesan:
3440 				TIFFErrorExt(tif->tif_clientdata, module,
3441 				"Sanity check on size of \"%s\" value failed",
3442 					     tagname);
3443 				break;
3444 			case TIFFReadDirEntryErrAlloc:
3445 				TIFFErrorExt(tif->tif_clientdata, module,
3446 					     "Out of memory reading of \"%s\"",
3447 					     tagname);
3448 				break;
3449 			default:
3450 				assert(0);   /* we should never get here */
3451 				break;
3452 		}
3453 	} else {
3454 		switch (err) {
3455 			case TIFFReadDirEntryErrCount:
3456 				TIFFWarningExt(tif->tif_clientdata, module,
3457 				"Incorrect count for \"%s\"; tag ignored",
3458 					     tagname);
3459 				break;
3460 			case TIFFReadDirEntryErrType:
3461 				TIFFWarningExt(tif->tif_clientdata, module,
3462 				"Incompatible type for \"%s\"; tag ignored",
3463 					       tagname);
3464 				break;
3465 			case TIFFReadDirEntryErrIo:
3466 				TIFFWarningExt(tif->tif_clientdata, module,
3467 			"IO error during reading of \"%s\"; tag ignored",
3468 					       tagname);
3469 				break;
3470 			case TIFFReadDirEntryErrRange:
3471 				TIFFWarningExt(tif->tif_clientdata, module,
3472 				"Incorrect value for \"%s\"; tag ignored",
3473 					       tagname);
3474 				break;
3475 			case TIFFReadDirEntryErrPsdif:
3476 				TIFFWarningExt(tif->tif_clientdata, module,
3477 	"Cannot handle different values per sample for \"%s\"; tag ignored",
3478 					       tagname);
3479 				break;
3480 			case TIFFReadDirEntryErrSizesan:
3481 				TIFFWarningExt(tif->tif_clientdata, module,
3482 		"Sanity check on size of \"%s\" value failed; tag ignored",
3483 					       tagname);
3484 				break;
3485 			case TIFFReadDirEntryErrAlloc:
3486 				TIFFWarningExt(tif->tif_clientdata, module,
3487 				"Out of memory reading of \"%s\"; tag ignored",
3488 					       tagname);
3489 				break;
3490 			default:
3491 				assert(0);   /* we should never get here */
3492 				break;
3493 		}
3494 	}
3495 }
3496 
3497 /*
3498  * Return the maximum number of color channels specified for a given photometric
3499  * type. 0 is returned if photometric type isn't supported or no default value
3500  * is defined by the specification.
3501  */
_TIFFGetMaxColorChannels(uint16 photometric)3502 static int _TIFFGetMaxColorChannels( uint16 photometric )
3503 {
3504     switch (photometric) {
3505 	case PHOTOMETRIC_PALETTE:
3506 	case PHOTOMETRIC_MINISWHITE:
3507 	case PHOTOMETRIC_MINISBLACK:
3508             return 1;
3509 	case PHOTOMETRIC_YCBCR:
3510 	case PHOTOMETRIC_RGB:
3511 	case PHOTOMETRIC_CIELAB:
3512 	case PHOTOMETRIC_LOGLUV:
3513 	case PHOTOMETRIC_ITULAB:
3514 	case PHOTOMETRIC_ICCLAB:
3515             return 3;
3516 	case PHOTOMETRIC_SEPARATED:
3517 	case PHOTOMETRIC_MASK:
3518             return 4;
3519 	case PHOTOMETRIC_LOGL:
3520 	case PHOTOMETRIC_CFA:
3521 	default:
3522             return 0;
3523     }
3524 }
3525 
ByteCountLooksBad(TIFF * tif)3526 static int ByteCountLooksBad(TIFF* tif)
3527 {
3528     /*
3529         * Assume we have wrong StripByteCount value (in case
3530         * of single strip) in following cases:
3531         *   - it is equal to zero along with StripOffset;
3532         *   - it is larger than file itself (in case of uncompressed
3533         *     image);
3534         *   - it is smaller than the size of the bytes per row
3535         *     multiplied on the number of rows.  The last case should
3536         *     not be checked in the case of writing new image,
3537         *     because we may do not know the exact strip size
3538         *     until the whole image will be written and directory
3539         *     dumped out.
3540         */
3541     uint64 bytecount = TIFFGetStrileByteCount(tif, 0);
3542     uint64 offset = TIFFGetStrileOffset(tif, 0);
3543     uint64 filesize;
3544 
3545     if( offset == 0 )
3546         return 0;
3547     if (bytecount == 0)
3548         return 1;
3549     if ( tif->tif_dir.td_compression != COMPRESSION_NONE )
3550         return 0;
3551     filesize = TIFFGetFileSize(tif);
3552     if( offset <= filesize && bytecount > filesize - offset )
3553         return 1;
3554     if( tif->tif_mode == O_RDONLY )
3555     {
3556         uint64 scanlinesize = TIFFScanlineSize64(tif);
3557         if( tif->tif_dir.td_imagelength > 0 &&
3558             scanlinesize > TIFF_UINT64_MAX / tif->tif_dir.td_imagelength )
3559         {
3560             return 1;
3561         }
3562         if( bytecount < scanlinesize * tif->tif_dir.td_imagelength)
3563             return 1;
3564     }
3565     return 0;
3566 }
3567 
3568 
3569 /*
3570  * Read the next TIFF directory from a file and convert it to the internal
3571  * format. We read directories sequentially.
3572  */
3573 int
TIFFReadDirectory(TIFF * tif)3574 TIFFReadDirectory(TIFF* tif)
3575 {
3576 	static const char module[] = "TIFFReadDirectory";
3577 	TIFFDirEntry* dir;
3578 	uint16 dircount;
3579 	TIFFDirEntry* dp;
3580 	uint16 di;
3581 	const TIFFField* fip;
3582 	uint32 fii=FAILED_FII;
3583         toff_t nextdiroff;
3584     int bitspersample_read = FALSE;
3585         int color_channels;
3586 
3587 	tif->tif_diroff=tif->tif_nextdiroff;
3588 	if (!TIFFCheckDirOffset(tif,tif->tif_nextdiroff))
3589 		return 0;           /* last offset or bad offset (IFD looping) */
3590 	(*tif->tif_cleanup)(tif);   /* cleanup any previous compression state */
3591 	tif->tif_curdir++;
3592         nextdiroff = tif->tif_nextdiroff;
3593 	dircount=TIFFFetchDirectory(tif,nextdiroff,&dir,&tif->tif_nextdiroff);
3594 	if (!dircount)
3595 	{
3596 		TIFFErrorExt(tif->tif_clientdata,module,
3597 		    "Failed to read directory at offset " TIFF_UINT64_FORMAT,nextdiroff);
3598 		return 0;
3599 	}
3600 	TIFFReadDirectoryCheckOrder(tif,dir,dircount);
3601 
3602         /*
3603          * Mark duplicates of any tag to be ignored (bugzilla 1994)
3604          * to avoid certain pathological problems.
3605          */
3606 	{
3607 		TIFFDirEntry* ma;
3608 		uint16 mb;
3609 		for (ma=dir, mb=0; mb<dircount; ma++, mb++)
3610 		{
3611 			TIFFDirEntry* na;
3612 			uint16 nb;
3613 			for (na=ma+1, nb=mb+1; nb<dircount; na++, nb++)
3614 			{
3615 				if (ma->tdir_tag == na->tdir_tag) {
3616 					na->tdir_ignore = TRUE;
3617 				}
3618 			}
3619 		}
3620 	}
3621 
3622 	tif->tif_flags &= ~TIFF_BEENWRITING;    /* reset before new dir */
3623 	tif->tif_flags &= ~TIFF_BUF4WRITE;      /* reset before new dir */
3624 	tif->tif_flags &= ~TIFF_CHOPPEDUPARRAYS;
3625 
3626 	/* free any old stuff and reinit */
3627 	TIFFFreeDirectory(tif);
3628 	TIFFDefaultDirectory(tif);
3629 	/*
3630 	 * Electronic Arts writes gray-scale TIFF files
3631 	 * without a PlanarConfiguration directory entry.
3632 	 * Thus we setup a default value here, even though
3633 	 * the TIFF spec says there is no default value.
3634 	 */
3635 	TIFFSetField(tif,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
3636 	/*
3637 	 * Setup default value and then make a pass over
3638 	 * the fields to check type and tag information,
3639 	 * and to extract info required to size data
3640 	 * structures.  A second pass is made afterwards
3641 	 * to read in everything not taken in the first pass.
3642 	 * But we must process the Compression tag first
3643 	 * in order to merge in codec-private tag definitions (otherwise
3644 	 * we may get complaints about unknown tags).  However, the
3645 	 * Compression tag may be dependent on the SamplesPerPixel
3646 	 * tag value because older TIFF specs permitted Compression
3647 	 * to be written as a SamplesPerPixel-count tag entry.
3648 	 * Thus if we don't first figure out the correct SamplesPerPixel
3649 	 * tag value then we may end up ignoring the Compression tag
3650 	 * value because it has an incorrect count value (if the
3651 	 * true value of SamplesPerPixel is not 1).
3652 	 */
3653 	dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_SAMPLESPERPIXEL);
3654 	if (dp)
3655 	{
3656 		if (!TIFFFetchNormalTag(tif,dp,0))
3657 			goto bad;
3658 		dp->tdir_ignore = TRUE;
3659 	}
3660 	dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_COMPRESSION);
3661 	if (dp)
3662 	{
3663 		/*
3664 		 * The 5.0 spec says the Compression tag has one value, while
3665 		 * earlier specs say it has one value per sample.  Because of
3666 		 * this, we accept the tag if one value is supplied with either
3667 		 * count.
3668 		 */
3669 		uint16 value;
3670 		enum TIFFReadDirEntryErr err;
3671 		err=TIFFReadDirEntryShort(tif,dp,&value);
3672 		if (err==TIFFReadDirEntryErrCount)
3673 			err=TIFFReadDirEntryPersampleShort(tif,dp,&value);
3674 		if (err!=TIFFReadDirEntryErrOk)
3675 		{
3676 			TIFFReadDirEntryOutputErr(tif,err,module,"Compression",0);
3677 			goto bad;
3678 		}
3679 		if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,value))
3680 			goto bad;
3681 		dp->tdir_ignore = TRUE;
3682 	}
3683 	else
3684 	{
3685 		if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,COMPRESSION_NONE))
3686 			goto bad;
3687 	}
3688 	/*
3689 	 * First real pass over the directory.
3690 	 */
3691 	for (di=0, dp=dir; di<dircount; di++, dp++)
3692 	{
3693 		if (!dp->tdir_ignore)
3694 		{
3695 			TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii);
3696 			if (fii == FAILED_FII)
3697 			{
3698 				TIFFWarningExt(tif->tif_clientdata, module,
3699 				    "Unknown field with tag %d (0x%x) encountered",
3700 				    dp->tdir_tag,dp->tdir_tag);
3701 				/* the following knowingly leaks the
3702 				   anonymous field structure */
3703 				if (!_TIFFMergeFields(tif,
3704 					_TIFFCreateAnonField(tif,
3705 						dp->tdir_tag,
3706 						(TIFFDataType) dp->tdir_type),
3707 					1)) {
3708 					TIFFWarningExt(tif->tif_clientdata,
3709 					    module,
3710 					    "Registering anonymous field with tag %d (0x%x) failed",
3711 					    dp->tdir_tag,
3712 					    dp->tdir_tag);
3713 					dp->tdir_ignore = TRUE;
3714 				} else {
3715 					TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii);
3716 					assert(fii != FAILED_FII);
3717 				}
3718 			}
3719 		}
3720 		if (!dp->tdir_ignore)
3721 		{
3722 			fip=tif->tif_fields[fii];
3723 			if (fip->field_bit==FIELD_IGNORE)
3724 				dp->tdir_ignore = TRUE;
3725 			else
3726 			{
3727 				switch (dp->tdir_tag)
3728 				{
3729 					case TIFFTAG_STRIPOFFSETS:
3730 					case TIFFTAG_STRIPBYTECOUNTS:
3731 					case TIFFTAG_TILEOFFSETS:
3732 					case TIFFTAG_TILEBYTECOUNTS:
3733 						TIFFSetFieldBit(tif,fip->field_bit);
3734 						break;
3735 					case TIFFTAG_IMAGEWIDTH:
3736 					case TIFFTAG_IMAGELENGTH:
3737 					case TIFFTAG_IMAGEDEPTH:
3738 					case TIFFTAG_TILELENGTH:
3739 					case TIFFTAG_TILEWIDTH:
3740 					case TIFFTAG_TILEDEPTH:
3741 					case TIFFTAG_PLANARCONFIG:
3742 					case TIFFTAG_ROWSPERSTRIP:
3743 					case TIFFTAG_EXTRASAMPLES:
3744 						if (!TIFFFetchNormalTag(tif,dp,0))
3745 							goto bad;
3746 						dp->tdir_ignore = TRUE;
3747 						break;
3748 					default:
3749 						if( !_TIFFCheckFieldIsValidForCodec(tif, dp->tdir_tag) )
3750 							dp->tdir_ignore = TRUE;
3751 						break;
3752 				}
3753 			}
3754 		}
3755 	}
3756 	/*
3757 	 * XXX: OJPEG hack.
3758 	 * If a) compression is OJPEG, b) planarconfig tag says it's separate,
3759 	 * c) strip offsets/bytecounts tag are both present and
3760 	 * d) both contain exactly one value, then we consistently find
3761 	 * that the buggy implementation of the buggy compression scheme
3762 	 * matches contig planarconfig best. So we 'fix-up' the tag here
3763 	 */
3764 	if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG)&&
3765 	    (tif->tif_dir.td_planarconfig==PLANARCONFIG_SEPARATE))
3766 	{
3767 		if (!_TIFFFillStriles(tif))
3768 		    goto bad;
3769 		dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_STRIPOFFSETS);
3770 		if ((dp!=0)&&(dp->tdir_count==1))
3771 		{
3772 			dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,
3773 			    TIFFTAG_STRIPBYTECOUNTS);
3774 			if ((dp!=0)&&(dp->tdir_count==1))
3775 			{
3776 				tif->tif_dir.td_planarconfig=PLANARCONFIG_CONTIG;
3777 				TIFFWarningExt(tif->tif_clientdata,module,
3778 				    "Planarconfig tag value assumed incorrect, "
3779 				    "assuming data is contig instead of chunky");
3780 			}
3781 		}
3782 	}
3783 	/*
3784 	 * Allocate directory structure and setup defaults.
3785 	 */
3786 	if (!TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS))
3787 	{
3788 		MissingRequired(tif,"ImageLength");
3789 		goto bad;
3790 	}
3791 	/*
3792 	 * Setup appropriate structures (by strip or by tile)
3793 	 */
3794 	if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
3795 		tif->tif_dir.td_nstrips = TIFFNumberOfStrips(tif);
3796 		tif->tif_dir.td_tilewidth = tif->tif_dir.td_imagewidth;
3797 		tif->tif_dir.td_tilelength = tif->tif_dir.td_rowsperstrip;
3798 		tif->tif_dir.td_tiledepth = tif->tif_dir.td_imagedepth;
3799 		tif->tif_flags &= ~TIFF_ISTILED;
3800 	} else {
3801 		tif->tif_dir.td_nstrips = TIFFNumberOfTiles(tif);
3802 		tif->tif_flags |= TIFF_ISTILED;
3803 	}
3804 	if (!tif->tif_dir.td_nstrips) {
3805 		TIFFErrorExt(tif->tif_clientdata, module,
3806 		    "Cannot handle zero number of %s",
3807 		    isTiled(tif) ? "tiles" : "strips");
3808 		goto bad;
3809 	}
3810 	tif->tif_dir.td_stripsperimage = tif->tif_dir.td_nstrips;
3811 	if (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE)
3812 		tif->tif_dir.td_stripsperimage /= tif->tif_dir.td_samplesperpixel;
3813 	if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
3814 #ifdef OJPEG_SUPPORT
3815 		if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG) &&
3816 		    (isTiled(tif)==0) &&
3817 		    (tif->tif_dir.td_nstrips==1)) {
3818 			/*
3819 			 * XXX: OJPEG hack.
3820 			 * If a) compression is OJPEG, b) it's not a tiled TIFF,
3821 			 * and c) the number of strips is 1,
3822 			 * then we tolerate the absence of stripoffsets tag,
3823 			 * because, presumably, all required data is in the
3824 			 * JpegInterchangeFormat stream.
3825 			 */
3826 			TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
3827 		} else
3828 #endif
3829         {
3830 			MissingRequired(tif,
3831 				isTiled(tif) ? "TileOffsets" : "StripOffsets");
3832 			goto bad;
3833 		}
3834 	}
3835 	/*
3836 	 * Second pass: extract other information.
3837 	 */
3838 	for (di=0, dp=dir; di<dircount; di++, dp++)
3839 	{
3840 		if (!dp->tdir_ignore) {
3841 			switch (dp->tdir_tag)
3842 			{
3843 				case TIFFTAG_MINSAMPLEVALUE:
3844 				case TIFFTAG_MAXSAMPLEVALUE:
3845 				case TIFFTAG_BITSPERSAMPLE:
3846 				case TIFFTAG_DATATYPE:
3847 				case TIFFTAG_SAMPLEFORMAT:
3848 					/*
3849 					 * The MinSampleValue, MaxSampleValue, BitsPerSample
3850 					 * DataType and SampleFormat tags are supposed to be
3851 					 * written as one value/sample, but some vendors
3852 					 * incorrectly write one value only -- so we accept
3853 					 * that as well (yuck). Other vendors write correct
3854 					 * value for NumberOfSamples, but incorrect one for
3855 					 * BitsPerSample and friends, and we will read this
3856 					 * too.
3857 					 */
3858 					{
3859 						uint16 value;
3860 						enum TIFFReadDirEntryErr err;
3861 						err=TIFFReadDirEntryShort(tif,dp,&value);
3862 						if (err==TIFFReadDirEntryErrCount)
3863 							err=TIFFReadDirEntryPersampleShort(tif,dp,&value);
3864 						if (err!=TIFFReadDirEntryErrOk)
3865 						{
3866 							fip = TIFFFieldWithTag(tif,dp->tdir_tag);
3867 							TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",0);
3868 							goto bad;
3869 						}
3870 						if (!TIFFSetField(tif,dp->tdir_tag,value))
3871 							goto bad;
3872 						if( dp->tdir_tag == TIFFTAG_BITSPERSAMPLE )
3873 						    bitspersample_read = TRUE;
3874 					}
3875 					break;
3876 				case TIFFTAG_SMINSAMPLEVALUE:
3877 				case TIFFTAG_SMAXSAMPLEVALUE:
3878 					{
3879 
3880 						double *data = NULL;
3881 						enum TIFFReadDirEntryErr err;
3882 						uint32 saved_flags;
3883 						int m;
3884 						if (dp->tdir_count != (uint64)tif->tif_dir.td_samplesperpixel)
3885 							err = TIFFReadDirEntryErrCount;
3886 						else
3887 							err = TIFFReadDirEntryDoubleArray(tif, dp, &data);
3888 						if (err!=TIFFReadDirEntryErrOk)
3889 						{
3890 							fip = TIFFFieldWithTag(tif,dp->tdir_tag);
3891 							TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",0);
3892 							goto bad;
3893 						}
3894 						saved_flags = tif->tif_flags;
3895 						tif->tif_flags |= TIFF_PERSAMPLE;
3896 						m = TIFFSetField(tif,dp->tdir_tag,data);
3897 						tif->tif_flags = saved_flags;
3898 						_TIFFfree(data);
3899 						if (!m)
3900 							goto bad;
3901 					}
3902 					break;
3903 				case TIFFTAG_STRIPOFFSETS:
3904 				case TIFFTAG_TILEOFFSETS:
3905 					_TIFFmemcpy( &(tif->tif_dir.td_stripoffset_entry),
3906 					   dp, sizeof(TIFFDirEntry) );
3907 					break;
3908 				case TIFFTAG_STRIPBYTECOUNTS:
3909 				case TIFFTAG_TILEBYTECOUNTS:
3910 					_TIFFmemcpy( &(tif->tif_dir.td_stripbytecount_entry),
3911 					   dp, sizeof(TIFFDirEntry) );
3912 					break;
3913 				case TIFFTAG_COLORMAP:
3914 				case TIFFTAG_TRANSFERFUNCTION:
3915 					{
3916 						enum TIFFReadDirEntryErr err;
3917 						uint32 countpersample;
3918 						uint32 countrequired;
3919 						uint32 incrementpersample;
3920 						uint16* value=NULL;
3921 						/* It would be dangerous to instantiate those tag values */
3922 						/* since if td_bitspersample has not yet been read (due to */
3923 						/* unordered tags), it could be read afterwards with a */
3924 						/* values greater than the default one (1), which may cause */
3925 						/* crashes in user code */
3926 						if( !bitspersample_read )
3927 						{
3928 							fip = TIFFFieldWithTag(tif,dp->tdir_tag);
3929 							TIFFWarningExt(tif->tif_clientdata,module,
3930 								"Ignoring %s since BitsPerSample tag not found",
3931 								fip ? fip->field_name : "unknown tagname");
3932 							continue;
3933 						}
3934 						/* ColorMap or TransferFunction for high bit */
3935 						/* depths do not make much sense and could be */
3936 						/* used as a denial of service vector */
3937 						if (tif->tif_dir.td_bitspersample > 24)
3938 						{
3939 							fip = TIFFFieldWithTag(tif,dp->tdir_tag);
3940 							TIFFWarningExt(tif->tif_clientdata,module,
3941 								"Ignoring %s because BitsPerSample=%d>24",
3942 								fip ? fip->field_name : "unknown tagname",
3943 								tif->tif_dir.td_bitspersample);
3944 							continue;
3945 						}
3946 						countpersample=(1U<<tif->tif_dir.td_bitspersample);
3947 						if ((dp->tdir_tag==TIFFTAG_TRANSFERFUNCTION)&&(dp->tdir_count==(uint64)countpersample))
3948 						{
3949 							countrequired=countpersample;
3950 							incrementpersample=0;
3951 						}
3952 						else
3953 						{
3954 							countrequired=3*countpersample;
3955 							incrementpersample=countpersample;
3956 						}
3957 						if (dp->tdir_count!=(uint64)countrequired)
3958 							err=TIFFReadDirEntryErrCount;
3959 						else
3960 							err=TIFFReadDirEntryShortArray(tif,dp,&value);
3961 						if (err!=TIFFReadDirEntryErrOk)
3962 						{
3963 							fip = TIFFFieldWithTag(tif,dp->tdir_tag);
3964 							TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",1);
3965 						}
3966 						else
3967 						{
3968 							TIFFSetField(tif,dp->tdir_tag,value,value+incrementpersample,value+2*incrementpersample);
3969 							_TIFFfree(value);
3970 						}
3971 					}
3972 					break;
3973 /* BEGIN REV 4.0 COMPATIBILITY */
3974 				case TIFFTAG_OSUBFILETYPE:
3975 					{
3976 						uint16 valueo;
3977 						uint32 value;
3978 						if (TIFFReadDirEntryShort(tif,dp,&valueo)==TIFFReadDirEntryErrOk)
3979 						{
3980 							switch (valueo)
3981 							{
3982 								case OFILETYPE_REDUCEDIMAGE: value=FILETYPE_REDUCEDIMAGE; break;
3983 								case OFILETYPE_PAGE: value=FILETYPE_PAGE; break;
3984 								default: value=0; break;
3985 							}
3986 							if (value!=0)
3987 								TIFFSetField(tif,TIFFTAG_SUBFILETYPE,value);
3988 						}
3989 					}
3990 					break;
3991 /* END REV 4.0 COMPATIBILITY */
3992 				default:
3993 					(void) TIFFFetchNormalTag(tif, dp, TRUE);
3994 					break;
3995 				}
3996 			} /* -- if (!dp->tdir_ignore) */
3997 		} /* -- for-loop -- */
3998 
3999         if( tif->tif_mode == O_RDWR &&
4000             tif->tif_dir.td_stripoffset_entry.tdir_tag != 0 &&
4001             tif->tif_dir.td_stripoffset_entry.tdir_count == 0 &&
4002             tif->tif_dir.td_stripoffset_entry.tdir_type == 0 &&
4003             tif->tif_dir.td_stripoffset_entry.tdir_offset.toff_long8 == 0 &&
4004             tif->tif_dir.td_stripbytecount_entry.tdir_tag != 0 &&
4005             tif->tif_dir.td_stripbytecount_entry.tdir_count == 0 &&
4006             tif->tif_dir.td_stripbytecount_entry.tdir_type == 0 &&
4007             tif->tif_dir.td_stripbytecount_entry.tdir_offset.toff_long8 == 0 )
4008         {
4009             /* Directory typically created with TIFFDeferStrileArrayWriting() */
4010             TIFFSetupStrips(tif);
4011         }
4012         else if( !(tif->tif_flags&TIFF_DEFERSTRILELOAD) )
4013         {
4014             if( tif->tif_dir.td_stripoffset_entry.tdir_tag != 0 )
4015             {
4016                 if (!TIFFFetchStripThing(tif,&(tif->tif_dir.td_stripoffset_entry),
4017                                          tif->tif_dir.td_nstrips,
4018                                          &tif->tif_dir.td_stripoffset_p))
4019                 {
4020                     goto bad;
4021                 }
4022             }
4023             if( tif->tif_dir.td_stripbytecount_entry.tdir_tag != 0 )
4024             {
4025                 if (!TIFFFetchStripThing(tif,&(tif->tif_dir.td_stripbytecount_entry),
4026                                          tif->tif_dir.td_nstrips,
4027                                          &tif->tif_dir.td_stripbytecount_p))
4028                 {
4029                     goto bad;
4030                 }
4031             }
4032         }
4033 
4034 	/*
4035 	 * OJPEG hack:
4036 	 * - If a) compression is OJPEG, and b) photometric tag is missing,
4037 	 * then we consistently find that photometric should be YCbCr
4038 	 * - If a) compression is OJPEG, and b) photometric tag says it's RGB,
4039 	 * then we consistently find that the buggy implementation of the
4040 	 * buggy compression scheme matches photometric YCbCr instead.
4041 	 * - If a) compression is OJPEG, and b) bitspersample tag is missing,
4042 	 * then we consistently find bitspersample should be 8.
4043 	 * - If a) compression is OJPEG, b) samplesperpixel tag is missing,
4044 	 * and c) photometric is RGB or YCbCr, then we consistently find
4045 	 * samplesperpixel should be 3
4046 	 * - If a) compression is OJPEG, b) samplesperpixel tag is missing,
4047 	 * and c) photometric is MINISWHITE or MINISBLACK, then we consistently
4048 	 * find samplesperpixel should be 3
4049 	 */
4050 	if (tif->tif_dir.td_compression==COMPRESSION_OJPEG)
4051 	{
4052 		if (!TIFFFieldSet(tif,FIELD_PHOTOMETRIC))
4053 		{
4054 			TIFFWarningExt(tif->tif_clientdata, module,
4055 			    "Photometric tag is missing, assuming data is YCbCr");
4056 			if (!TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,PHOTOMETRIC_YCBCR))
4057 				goto bad;
4058 		}
4059 		else if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB)
4060 		{
4061 			tif->tif_dir.td_photometric=PHOTOMETRIC_YCBCR;
4062 			TIFFWarningExt(tif->tif_clientdata, module,
4063 			    "Photometric tag value assumed incorrect, "
4064 			    "assuming data is YCbCr instead of RGB");
4065 		}
4066 		if (!TIFFFieldSet(tif,FIELD_BITSPERSAMPLE))
4067 		{
4068 			TIFFWarningExt(tif->tif_clientdata,module,
4069 			    "BitsPerSample tag is missing, assuming 8 bits per sample");
4070 			if (!TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,8))
4071 				goto bad;
4072 		}
4073 		if (!TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL))
4074 		{
4075 			if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB)
4076 			{
4077 				TIFFWarningExt(tif->tif_clientdata,module,
4078 				    "SamplesPerPixel tag is missing, "
4079 				    "assuming correct SamplesPerPixel value is 3");
4080 				if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3))
4081 					goto bad;
4082 			}
4083 			if (tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)
4084 			{
4085 				TIFFWarningExt(tif->tif_clientdata,module,
4086 				    "SamplesPerPixel tag is missing, "
4087 				    "applying correct SamplesPerPixel value of 3");
4088 				if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3))
4089 					goto bad;
4090 			}
4091 			else if ((tif->tif_dir.td_photometric==PHOTOMETRIC_MINISWHITE)
4092 				 || (tif->tif_dir.td_photometric==PHOTOMETRIC_MINISBLACK))
4093 			{
4094 				/*
4095 				 * SamplesPerPixel tag is missing, but is not required
4096 				 * by spec.  Assume correct SamplesPerPixel value of 1.
4097 				 */
4098 				if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,1))
4099 					goto bad;
4100 			}
4101 		}
4102 	}
4103 
4104 	/*
4105 	 * Make sure all non-color channels are extrasamples.
4106 	 * If it's not the case, define them as such.
4107 	 */
4108         color_channels = _TIFFGetMaxColorChannels(tif->tif_dir.td_photometric);
4109         if (color_channels && tif->tif_dir.td_samplesperpixel - tif->tif_dir.td_extrasamples > color_channels) {
4110                 uint16 old_extrasamples;
4111                 uint16 *new_sampleinfo;
4112 
4113                 TIFFWarningExt(tif->tif_clientdata,module, "Sum of Photometric type-related "
4114                     "color channels and ExtraSamples doesn't match SamplesPerPixel. "
4115                     "Defining non-color channels as ExtraSamples.");
4116 
4117                 old_extrasamples = tif->tif_dir.td_extrasamples;
4118                 tif->tif_dir.td_extrasamples = (uint16) (tif->tif_dir.td_samplesperpixel - color_channels);
4119 
4120                 // sampleinfo should contain information relative to these new extra samples
4121                 new_sampleinfo = (uint16*) _TIFFcalloc(tif->tif_dir.td_extrasamples, sizeof(uint16));
4122                 if (!new_sampleinfo) {
4123                     TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate memory for "
4124                                 "temporary new sampleinfo array (%d 16 bit elements)",
4125                                 tif->tif_dir.td_extrasamples);
4126                     goto bad;
4127                 }
4128 
4129                 memcpy(new_sampleinfo, tif->tif_dir.td_sampleinfo, old_extrasamples * sizeof(uint16));
4130                 _TIFFsetShortArray(&tif->tif_dir.td_sampleinfo, new_sampleinfo, tif->tif_dir.td_extrasamples);
4131                 _TIFFfree(new_sampleinfo);
4132         }
4133 
4134 	/*
4135 	 * Verify Palette image has a Colormap.
4136 	 */
4137 	if (tif->tif_dir.td_photometric == PHOTOMETRIC_PALETTE &&
4138 	    !TIFFFieldSet(tif, FIELD_COLORMAP)) {
4139 		if ( tif->tif_dir.td_bitspersample>=8 && tif->tif_dir.td_samplesperpixel==3)
4140 			tif->tif_dir.td_photometric = PHOTOMETRIC_RGB;
4141 		else if (tif->tif_dir.td_bitspersample>=8)
4142 			tif->tif_dir.td_photometric = PHOTOMETRIC_MINISBLACK;
4143 		else {
4144 			MissingRequired(tif, "Colormap");
4145 			goto bad;
4146 		}
4147 	}
4148 	/*
4149 	 * OJPEG hack:
4150 	 * We do no further messing with strip/tile offsets/bytecounts in OJPEG
4151 	 * TIFFs
4152 	 */
4153 	if (tif->tif_dir.td_compression!=COMPRESSION_OJPEG)
4154 	{
4155 		/*
4156 		 * Attempt to deal with a missing StripByteCounts tag.
4157 		 */
4158 		if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
4159 			/*
4160 			 * Some manufacturers violate the spec by not giving
4161 			 * the size of the strips.  In this case, assume there
4162 			 * is one uncompressed strip of data.
4163 			 */
4164 			if ((tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG &&
4165 			    tif->tif_dir.td_nstrips > 1) ||
4166 			    (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE &&
4167 			     tif->tif_dir.td_nstrips != (uint32)tif->tif_dir.td_samplesperpixel)) {
4168 			    MissingRequired(tif, "StripByteCounts");
4169 			    goto bad;
4170 			}
4171 			TIFFWarningExt(tif->tif_clientdata, module,
4172 				"TIFF directory is missing required "
4173 				"\"StripByteCounts\" field, calculating from imagelength");
4174 			if (EstimateStripByteCounts(tif, dir, dircount) < 0)
4175 			    goto bad;
4176 
4177 		} else if (tif->tif_dir.td_nstrips == 1
4178                            && !(tif->tif_flags&TIFF_ISTILED)
4179 			   && ByteCountLooksBad(tif)) {
4180 			/*
4181 			 * XXX: Plexus (and others) sometimes give a value of
4182 			 * zero for a tag when they don't know what the
4183 			 * correct value is!  Try and handle the simple case
4184 			 * of estimating the size of a one strip image.
4185 			 */
4186 			TIFFWarningExt(tif->tif_clientdata, module,
4187 			    "Bogus \"StripByteCounts\" field, ignoring and calculating from imagelength");
4188 			if(EstimateStripByteCounts(tif, dir, dircount) < 0)
4189 			    goto bad;
4190 
4191 		} else if (!(tif->tif_flags&TIFF_DEFERSTRILELOAD)
4192 			   && tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG
4193 			   && tif->tif_dir.td_nstrips > 2
4194 			   && tif->tif_dir.td_compression == COMPRESSION_NONE
4195 			   && TIFFGetStrileByteCount(tif, 0) != TIFFGetStrileByteCount(tif, 1)
4196 			   && TIFFGetStrileByteCount(tif, 0) != 0
4197 			   && TIFFGetStrileByteCount(tif, 1) != 0 ) {
4198 			/*
4199 			 * XXX: Some vendors fill StripByteCount array with
4200 			 * absolutely wrong values (it can be equal to
4201 			 * StripOffset array, for example). Catch this case
4202 			 * here.
4203                          *
4204                          * We avoid this check if deferring strile loading
4205                          * as it would always force us to load the strip/tile
4206                          * information.
4207 			 */
4208 			TIFFWarningExt(tif->tif_clientdata, module,
4209 			    "Wrong \"StripByteCounts\" field, ignoring and calculating from imagelength");
4210 			if (EstimateStripByteCounts(tif, dir, dircount) < 0)
4211 			    goto bad;
4212 		}
4213 	}
4214 	if (dir)
4215 	{
4216 		_TIFFfree(dir);
4217 		dir=NULL;
4218 	}
4219 	if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
4220 	{
4221 		if (tif->tif_dir.td_bitspersample>=16)
4222 			tif->tif_dir.td_maxsamplevalue=0xFFFF;
4223 		else
4224 			tif->tif_dir.td_maxsamplevalue = (uint16)((1L<<tif->tif_dir.td_bitspersample)-1);
4225 	}
4226 
4227 #ifdef STRIPBYTECOUNTSORTED_UNUSED
4228 	/*
4229 	 * XXX: We can optimize checking for the strip bounds using the sorted
4230 	 * bytecounts array. See also comments for TIFFAppendToStrip()
4231 	 * function in tif_write.c.
4232 	 */
4233 	if (!(tif->tif_flags&TIFF_DEFERSTRILELOAD) && tif->tif_dir.td_nstrips > 1) {
4234 		uint32 strip;
4235 
4236 		tif->tif_dir.td_stripbytecountsorted = 1;
4237 		for (strip = 1; strip < tif->tif_dir.td_nstrips; strip++) {
4238 			if (TIFFGetStrileOffset(tif, strip - 1) >
4239 			    TIFFGetStrileOffset(tif, strip)) {
4240 				tif->tif_dir.td_stripbytecountsorted = 0;
4241 				break;
4242 			}
4243 		}
4244 	}
4245 #endif
4246 
4247 	/*
4248 	 * An opportunity for compression mode dependent tag fixup
4249 	 */
4250 	(*tif->tif_fixuptags)(tif);
4251 
4252 	/*
4253 	 * Some manufacturers make life difficult by writing
4254 	 * large amounts of uncompressed data as a single strip.
4255 	 * This is contrary to the recommendations of the spec.
4256 	 * The following makes an attempt at breaking such images
4257 	 * into strips closer to the recommended 8k bytes.  A
4258 	 * side effect, however, is that the RowsPerStrip tag
4259 	 * value may be changed.
4260 	 */
4261 	if ((tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
4262 	    (tif->tif_dir.td_nstrips==1)&&
4263 	    (tif->tif_dir.td_compression==COMPRESSION_NONE)&&
4264 	    ((tif->tif_flags&(TIFF_STRIPCHOP|TIFF_ISTILED))==TIFF_STRIPCHOP))
4265         {
4266             ChopUpSingleUncompressedStrip(tif);
4267         }
4268 
4269         /* There are also uncompressed striped files with strips larger than */
4270         /* 2 GB, which make them unfriendly with a lot of code. If possible, */
4271         /* try to expose smaller "virtual" strips. */
4272         if( tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG &&
4273             tif->tif_dir.td_compression == COMPRESSION_NONE &&
4274             (tif->tif_flags&(TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP &&
4275             TIFFStripSize64(tif) > 0x7FFFFFFFUL )
4276         {
4277             TryChopUpUncompressedBigTiff(tif);
4278         }
4279 
4280         /*
4281          * Clear the dirty directory flag.
4282          */
4283 	tif->tif_flags &= ~TIFF_DIRTYDIRECT;
4284 	tif->tif_flags &= ~TIFF_DIRTYSTRIP;
4285 
4286 	/*
4287 	 * Reinitialize i/o since we are starting on a new directory.
4288 	 */
4289 	tif->tif_row = (uint32) -1;
4290 	tif->tif_curstrip = (uint32) -1;
4291 	tif->tif_col = (uint32) -1;
4292 	tif->tif_curtile = (uint32) -1;
4293 	tif->tif_tilesize = (tmsize_t) -1;
4294 
4295 	tif->tif_scanlinesize = TIFFScanlineSize(tif);
4296 	if (!tif->tif_scanlinesize) {
4297 		TIFFErrorExt(tif->tif_clientdata, module,
4298 		    "Cannot handle zero scanline size");
4299 		return (0);
4300 	}
4301 
4302 	if (isTiled(tif)) {
4303 		tif->tif_tilesize = TIFFTileSize(tif);
4304 		if (!tif->tif_tilesize) {
4305 			TIFFErrorExt(tif->tif_clientdata, module,
4306 			     "Cannot handle zero tile size");
4307 			return (0);
4308 		}
4309 	} else {
4310 		if (!TIFFStripSize(tif)) {
4311 			TIFFErrorExt(tif->tif_clientdata, module,
4312 			    "Cannot handle zero strip size");
4313 			return (0);
4314 		}
4315 	}
4316 	return (1);
4317 bad:
4318 	if (dir)
4319 		_TIFFfree(dir);
4320 	return (0);
4321 }
4322 
4323 static void
TIFFReadDirectoryCheckOrder(TIFF * tif,TIFFDirEntry * dir,uint16 dircount)4324 TIFFReadDirectoryCheckOrder(TIFF* tif, TIFFDirEntry* dir, uint16 dircount)
4325 {
4326 	static const char module[] = "TIFFReadDirectoryCheckOrder";
4327 	uint16 m;
4328 	uint16 n;
4329 	TIFFDirEntry* o;
4330 	m=0;
4331 	for (n=0, o=dir; n<dircount; n++, o++)
4332 	{
4333 		if (o->tdir_tag<m)
4334 		{
4335 			TIFFWarningExt(tif->tif_clientdata,module,
4336 			    "Invalid TIFF directory; tags are not sorted in ascending order");
4337 			break;
4338 		}
4339 		m=o->tdir_tag+1;
4340 	}
4341 }
4342 
4343 static TIFFDirEntry*
TIFFReadDirectoryFindEntry(TIFF * tif,TIFFDirEntry * dir,uint16 dircount,uint16 tagid)4344 TIFFReadDirectoryFindEntry(TIFF* tif, TIFFDirEntry* dir, uint16 dircount, uint16 tagid)
4345 {
4346 	TIFFDirEntry* m;
4347 	uint16 n;
4348 	(void) tif;
4349 	for (m=dir, n=0; n<dircount; m++, n++)
4350 	{
4351 		if (m->tdir_tag==tagid)
4352 			return(m);
4353 	}
4354 	return(0);
4355 }
4356 
4357 static void
TIFFReadDirectoryFindFieldInfo(TIFF * tif,uint16 tagid,uint32 * fii)4358 TIFFReadDirectoryFindFieldInfo(TIFF* tif, uint16 tagid, uint32* fii)
4359 {
4360 	int32 ma,mb,mc;
4361 	ma=-1;
4362 	mc=(int32)tif->tif_nfields;
4363 	while (1)
4364 	{
4365 		if (ma+1==mc)
4366 		{
4367 			*fii = FAILED_FII;
4368 			return;
4369 		}
4370 		mb=(ma+mc)/2;
4371 		if (tif->tif_fields[mb]->field_tag==(uint32)tagid)
4372 			break;
4373 		if (tif->tif_fields[mb]->field_tag<(uint32)tagid)
4374 			ma=mb;
4375 		else
4376 			mc=mb;
4377 	}
4378 	while (1)
4379 	{
4380 		if (mb==0)
4381 			break;
4382 		if (tif->tif_fields[mb-1]->field_tag!=(uint32)tagid)
4383 			break;
4384 		mb--;
4385 	}
4386 	*fii=mb;
4387 }
4388 
4389 /*
4390  * Read custom directory from the arbitrary offset.
4391  * The code is very similar to TIFFReadDirectory().
4392  */
4393 int
TIFFReadCustomDirectory(TIFF * tif,toff_t diroff,const TIFFFieldArray * infoarray)4394 TIFFReadCustomDirectory(TIFF* tif, toff_t diroff,
4395 			const TIFFFieldArray* infoarray)
4396 {
4397 	static const char module[] = "TIFFReadCustomDirectory";
4398 	TIFFDirEntry* dir;
4399 	uint16 dircount;
4400 	TIFFDirEntry* dp;
4401 	uint16 di;
4402 	const TIFFField* fip;
4403 	uint32 fii;
4404 	_TIFFSetupFields(tif, infoarray);
4405 	dircount=TIFFFetchDirectory(tif,diroff,&dir,NULL);
4406 	if (!dircount)
4407 	{
4408 		TIFFErrorExt(tif->tif_clientdata,module,
4409 		    "Failed to read custom directory at offset " TIFF_UINT64_FORMAT,diroff);
4410 		return 0;
4411 	}
4412 	TIFFFreeDirectory(tif);
4413 	_TIFFmemset(&tif->tif_dir, 0, sizeof(TIFFDirectory));
4414 	TIFFReadDirectoryCheckOrder(tif,dir,dircount);
4415 	for (di=0, dp=dir; di<dircount; di++, dp++)
4416 	{
4417 		TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii);
4418 		if (fii == FAILED_FII)
4419 		{
4420 			TIFFWarningExt(tif->tif_clientdata, module,
4421 			    "Unknown field with tag %d (0x%x) encountered",
4422 			    dp->tdir_tag, dp->tdir_tag);
4423 			if (!_TIFFMergeFields(tif, _TIFFCreateAnonField(tif,
4424 						dp->tdir_tag,
4425 						(TIFFDataType) dp->tdir_type),
4426 					     1)) {
4427 				TIFFWarningExt(tif->tif_clientdata, module,
4428 				    "Registering anonymous field with tag %d (0x%x) failed",
4429 				    dp->tdir_tag, dp->tdir_tag);
4430 				dp->tdir_ignore = TRUE;
4431 			} else {
4432 				TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii);
4433 				assert( fii != FAILED_FII );
4434 			}
4435 		}
4436 		if (!dp->tdir_ignore)
4437 		{
4438 			fip=tif->tif_fields[fii];
4439 			if (fip->field_bit==FIELD_IGNORE)
4440 				dp->tdir_ignore = TRUE;
4441 			else
4442 			{
4443 				/* check data type */
4444 				while ((fip->field_type!=TIFF_ANY)&&(fip->field_type!=dp->tdir_type))
4445 				{
4446 					fii++;
4447 					if ((fii==tif->tif_nfields)||
4448 					    (tif->tif_fields[fii]->field_tag!=(uint32)dp->tdir_tag))
4449 					{
4450 						fii=0xFFFF;
4451 						break;
4452 					}
4453 					fip=tif->tif_fields[fii];
4454 				}
4455 				if (fii==0xFFFF)
4456 				{
4457 					TIFFWarningExt(tif->tif_clientdata, module,
4458 					    "Wrong data type %d for \"%s\"; tag ignored",
4459 					    dp->tdir_type,fip->field_name);
4460 					dp->tdir_ignore = TRUE;
4461 				}
4462 				else
4463 				{
4464 					/* check count if known in advance */
4465 					if ((fip->field_readcount!=TIFF_VARIABLE)&&
4466 					    (fip->field_readcount!=TIFF_VARIABLE2))
4467 					{
4468 						uint32 expected;
4469 						if (fip->field_readcount==TIFF_SPP)
4470 							expected=(uint32)tif->tif_dir.td_samplesperpixel;
4471 						else
4472 							expected=(uint32)fip->field_readcount;
4473 						if (!CheckDirCount(tif,dp,expected))
4474 							dp->tdir_ignore = TRUE;
4475 					}
4476 				}
4477 			}
4478 			if (!dp->tdir_ignore) {
4479 				switch (dp->tdir_tag)
4480 				{
4481 					case EXIFTAG_SUBJECTDISTANCE:
4482 						(void)TIFFFetchSubjectDistance(tif, dp);
4483 						break;
4484 					default:
4485 						(void)TIFFFetchNormalTag(tif, dp, TRUE);
4486 						break;
4487 				}
4488 			} /*-- if (!dp->tdir_ignore) */
4489 		}
4490 	}
4491 	if (dir)
4492 		_TIFFfree(dir);
4493 	return 1;
4494 }
4495 
4496 /*
4497  * EXIF is important special case of custom IFD, so we have a special
4498  * function to read it.
4499  */
4500 int
TIFFReadEXIFDirectory(TIFF * tif,toff_t diroff)4501 TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff)
4502 {
4503 	const TIFFFieldArray* exifFieldArray;
4504 	exifFieldArray = _TIFFGetExifFields();
4505 	return TIFFReadCustomDirectory(tif, diroff, exifFieldArray);
4506 }
4507 
4508 static int
EstimateStripByteCounts(TIFF * tif,TIFFDirEntry * dir,uint16 dircount)4509 EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount)
4510 {
4511 	static const char module[] = "EstimateStripByteCounts";
4512 
4513 	TIFFDirEntry *dp;
4514 	TIFFDirectory *td = &tif->tif_dir;
4515 	uint32 strip;
4516 
4517     /* Do not try to load stripbytecount as we will compute it */
4518         if( !_TIFFFillStrilesInternal( tif, 0 ) )
4519             return -1;
4520 
4521 	if (td->td_stripbytecount_p)
4522 		_TIFFfree(td->td_stripbytecount_p);
4523 	td->td_stripbytecount_p = (uint64*)
4524 	    _TIFFCheckMalloc(tif, td->td_nstrips, sizeof (uint64),
4525 		"for \"StripByteCounts\" array");
4526         if( td->td_stripbytecount_p == NULL )
4527             return -1;
4528 
4529 	if (td->td_compression != COMPRESSION_NONE) {
4530 		uint64 space;
4531 		uint64 filesize;
4532 		uint16 n;
4533 		filesize = TIFFGetFileSize(tif);
4534 		if (!(tif->tif_flags&TIFF_BIGTIFF))
4535 			space=sizeof(TIFFHeaderClassic)+2+dircount*12+4;
4536 		else
4537 			space=sizeof(TIFFHeaderBig)+8+dircount*20+8;
4538 		/* calculate amount of space used by indirect values */
4539 		for (dp = dir, n = dircount; n > 0; n--, dp++)
4540 		{
4541 			uint32 typewidth;
4542 			uint64 datasize;
4543 			typewidth = TIFFDataWidth((TIFFDataType) dp->tdir_type);
4544 			if (typewidth == 0) {
4545 				TIFFErrorExt(tif->tif_clientdata, module,
4546 				    "Cannot determine size of unknown tag type %d",
4547 				    dp->tdir_type);
4548 				return -1;
4549 			}
4550 			if( dp->tdir_count > TIFF_UINT64_MAX / typewidth )
4551                             return -1;
4552 			datasize=(uint64)typewidth*dp->tdir_count;
4553 			if (!(tif->tif_flags&TIFF_BIGTIFF))
4554 			{
4555 				if (datasize<=4)
4556 					datasize=0;
4557 			}
4558 			else
4559 			{
4560 				if (datasize<=8)
4561 					datasize=0;
4562 			}
4563 			if( space > TIFF_UINT64_MAX - datasize )
4564                             return -1;
4565 			space+=datasize;
4566 		}
4567 		if( filesize < space )
4568                     /* we should perhaps return in error ? */
4569                     space = filesize;
4570                 else
4571                     space = filesize - space;
4572 		if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
4573 			space /= td->td_samplesperpixel;
4574 		for (strip = 0; strip < td->td_nstrips; strip++)
4575 			td->td_stripbytecount_p[strip] = space;
4576 		/*
4577 		 * This gross hack handles the case were the offset to
4578 		 * the last strip is past the place where we think the strip
4579 		 * should begin.  Since a strip of data must be contiguous,
4580 		 * it's safe to assume that we've overestimated the amount
4581 		 * of data in the strip and trim this number back accordingly.
4582 		 */
4583 		strip--;
4584                 if (td->td_stripoffset_p[strip] > TIFF_UINT64_MAX - td->td_stripbytecount_p[strip])
4585                     return -1;
4586 		if (td->td_stripoffset_p[strip]+td->td_stripbytecount_p[strip] > filesize) {
4587                     if( td->td_stripoffset_p[strip] >= filesize ) {
4588                         /* Not sure what we should in that case... */
4589                         td->td_stripbytecount_p[strip] = 0;
4590                     } else {
4591                         td->td_stripbytecount_p[strip] = filesize - td->td_stripoffset_p[strip];
4592                     }
4593                 }
4594 	} else if (isTiled(tif)) {
4595 		uint64 bytespertile = TIFFTileSize64(tif);
4596 
4597 		for (strip = 0; strip < td->td_nstrips; strip++)
4598 		    td->td_stripbytecount_p[strip] = bytespertile;
4599 	} else {
4600 		uint64 rowbytes = TIFFScanlineSize64(tif);
4601 		uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage;
4602 		for (strip = 0; strip < td->td_nstrips; strip++)
4603                 {
4604                     if( rowbytes > 0 && rowsperstrip > TIFF_UINT64_MAX / rowbytes )
4605                         return -1;
4606                     td->td_stripbytecount_p[strip] = rowbytes * rowsperstrip;
4607                 }
4608 	}
4609 	TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
4610 	if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
4611 		td->td_rowsperstrip = td->td_imagelength;
4612 	return 1;
4613 }
4614 
4615 static void
MissingRequired(TIFF * tif,const char * tagname)4616 MissingRequired(TIFF* tif, const char* tagname)
4617 {
4618 	static const char module[] = "MissingRequired";
4619 
4620 	TIFFErrorExt(tif->tif_clientdata, module,
4621 	    "TIFF directory is missing required \"%s\" field",
4622 	    tagname);
4623 }
4624 
4625 /*
4626  * Check the directory offset against the list of already seen directory
4627  * offsets. This is a trick to prevent IFD looping. The one can create TIFF
4628  * file with looped directory pointers. We will maintain a list of already
4629  * seen directories and check every IFD offset against that list.
4630  */
4631 static int
TIFFCheckDirOffset(TIFF * tif,uint64 diroff)4632 TIFFCheckDirOffset(TIFF* tif, uint64 diroff)
4633 {
4634 	uint16 n;
4635 
4636 	if (diroff == 0)			/* no more directories */
4637 		return 0;
4638 	if (tif->tif_dirnumber == 65535) {
4639 	    TIFFErrorExt(tif->tif_clientdata, "TIFFCheckDirOffset",
4640 			 "Cannot handle more than 65535 TIFF directories");
4641 	    return 0;
4642 	}
4643 
4644 	for (n = 0; n < tif->tif_dirnumber && tif->tif_dirlist; n++) {
4645 		if (tif->tif_dirlist[n] == diroff)
4646 			return 0;
4647 	}
4648 
4649 	tif->tif_dirnumber++;
4650 
4651 	if (tif->tif_dirlist == NULL || tif->tif_dirnumber > tif->tif_dirlistsize) {
4652 		uint64* new_dirlist;
4653 
4654 		/*
4655 		 * XXX: Reduce memory allocation granularity of the dirlist
4656 		 * array.
4657 		 */
4658 		new_dirlist = (uint64*)_TIFFCheckRealloc(tif, tif->tif_dirlist,
4659 		    tif->tif_dirnumber, 2 * sizeof(uint64), "for IFD list");
4660 		if (!new_dirlist)
4661 			return 0;
4662 		if( tif->tif_dirnumber >= 32768 )
4663 		    tif->tif_dirlistsize = 65535;
4664 		else
4665 		    tif->tif_dirlistsize = 2 * tif->tif_dirnumber;
4666 		tif->tif_dirlist = new_dirlist;
4667 	}
4668 
4669 	tif->tif_dirlist[tif->tif_dirnumber - 1] = diroff;
4670 
4671 	return 1;
4672 }
4673 
4674 /*
4675  * Check the count field of a directory entry against a known value.  The
4676  * caller is expected to skip/ignore the tag if there is a mismatch.
4677  */
4678 static int
CheckDirCount(TIFF * tif,TIFFDirEntry * dir,uint32 count)4679 CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count)
4680 {
4681 	if ((uint64)count > dir->tdir_count) {
4682 		const TIFFField* fip = TIFFFieldWithTag(tif, dir->tdir_tag);
4683 		TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
4684 	"incorrect count for field \"%s\" (" TIFF_UINT64_FORMAT ", expecting %u); tag ignored",
4685 		    fip ? fip->field_name : "unknown tagname",
4686 		    dir->tdir_count, count);
4687 		return (0);
4688 	} else if ((uint64)count < dir->tdir_count) {
4689 		const TIFFField* fip = TIFFFieldWithTag(tif, dir->tdir_tag);
4690 		TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
4691 	"incorrect count for field \"%s\" (" TIFF_UINT64_FORMAT ", expecting %u); tag trimmed",
4692 		    fip ? fip->field_name : "unknown tagname",
4693 		    dir->tdir_count, count);
4694 		dir->tdir_count = count;
4695 		return (1);
4696 	}
4697 	return (1);
4698 }
4699 
4700 /*
4701  * Read IFD structure from the specified offset. If the pointer to
4702  * nextdiroff variable has been specified, read it too. Function returns a
4703  * number of fields in the directory or 0 if failed.
4704  */
4705 static uint16
TIFFFetchDirectory(TIFF * tif,uint64 diroff,TIFFDirEntry ** pdir,uint64 * nextdiroff)4706 TIFFFetchDirectory(TIFF* tif, uint64 diroff, TIFFDirEntry** pdir,
4707                    uint64 *nextdiroff)
4708 {
4709 	static const char module[] = "TIFFFetchDirectory";
4710 
4711 	void* origdir;
4712 	uint16 dircount16;
4713 	uint32 dirsize;
4714 	TIFFDirEntry* dir;
4715 	uint8* ma;
4716 	TIFFDirEntry* mb;
4717 	uint16 n;
4718 
4719 	assert(pdir);
4720 
4721 	tif->tif_diroff = diroff;
4722 	if (nextdiroff)
4723 		*nextdiroff = 0;
4724 	if (!isMapped(tif)) {
4725 		if (!SeekOK(tif, tif->tif_diroff)) {
4726 			TIFFErrorExt(tif->tif_clientdata, module,
4727 				"%s: Seek error accessing TIFF directory",
4728 				tif->tif_name);
4729 			return 0;
4730 		}
4731 		if (!(tif->tif_flags&TIFF_BIGTIFF))
4732 		{
4733 			if (!ReadOK(tif, &dircount16, sizeof (uint16))) {
4734 				TIFFErrorExt(tif->tif_clientdata, module,
4735 				    "%s: Can not read TIFF directory count",
4736 				    tif->tif_name);
4737 				return 0;
4738 			}
4739 			if (tif->tif_flags & TIFF_SWAB)
4740 				TIFFSwabShort(&dircount16);
4741 			if (dircount16>4096)
4742 			{
4743 				TIFFErrorExt(tif->tif_clientdata, module,
4744 				    "Sanity check on directory count failed, this is probably not a valid IFD offset");
4745 				return 0;
4746 			}
4747 			dirsize = 12;
4748 		} else {
4749 			uint64 dircount64;
4750 			if (!ReadOK(tif, &dircount64, sizeof (uint64))) {
4751 				TIFFErrorExt(tif->tif_clientdata, module,
4752 					"%s: Can not read TIFF directory count",
4753 					tif->tif_name);
4754 				return 0;
4755 			}
4756 			if (tif->tif_flags & TIFF_SWAB)
4757 				TIFFSwabLong8(&dircount64);
4758 			if (dircount64>4096)
4759 			{
4760 				TIFFErrorExt(tif->tif_clientdata, module,
4761 				    "Sanity check on directory count failed, this is probably not a valid IFD offset");
4762 				return 0;
4763 			}
4764 			dircount16 = (uint16)dircount64;
4765 			dirsize = 20;
4766 		}
4767 		origdir = _TIFFCheckMalloc(tif, dircount16,
4768 		    dirsize, "to read TIFF directory");
4769 		if (origdir == NULL)
4770 			return 0;
4771 		if (!ReadOK(tif, origdir, (tmsize_t)(dircount16*dirsize))) {
4772 			TIFFErrorExt(tif->tif_clientdata, module,
4773 				"%.100s: Can not read TIFF directory",
4774 				tif->tif_name);
4775 			_TIFFfree(origdir);
4776 			return 0;
4777 		}
4778 		/*
4779 		 * Read offset to next directory for sequential scans if
4780 		 * needed.
4781 		 */
4782 		if (nextdiroff)
4783 		{
4784 			if (!(tif->tif_flags&TIFF_BIGTIFF))
4785 			{
4786 				uint32 nextdiroff32;
4787 				if (!ReadOK(tif, &nextdiroff32, sizeof(uint32)))
4788 					nextdiroff32 = 0;
4789 				if (tif->tif_flags&TIFF_SWAB)
4790 					TIFFSwabLong(&nextdiroff32);
4791 				*nextdiroff=nextdiroff32;
4792 			} else {
4793 				if (!ReadOK(tif, nextdiroff, sizeof(uint64)))
4794 					*nextdiroff = 0;
4795 				if (tif->tif_flags&TIFF_SWAB)
4796 					TIFFSwabLong8(nextdiroff);
4797 			}
4798 		}
4799 	} else {
4800 		tmsize_t m;
4801 		tmsize_t off;
4802 		if (tif->tif_diroff > (uint64)TIFF_INT64_MAX)
4803 		{
4804 			TIFFErrorExt(tif->tif_clientdata,module,"Can not read TIFF directory count");
4805 			return(0);
4806 		}
4807 		off = (tmsize_t) tif->tif_diroff;
4808 
4809 		/*
4810 		 * Check for integer overflow when validating the dir_off,
4811 		 * otherwise a very high offset may cause an OOB read and
4812 		 * crash the client. Make two comparisons instead of
4813 		 *
4814 		 *  off + sizeof(uint16) > tif->tif_size
4815 		 *
4816 		 * to avoid overflow.
4817 		 */
4818 		if (!(tif->tif_flags&TIFF_BIGTIFF))
4819 		{
4820 			m=off+sizeof(uint16);
4821 			if ((m<off)||(m<(tmsize_t)sizeof(uint16))||(m>tif->tif_size)) {
4822 				TIFFErrorExt(tif->tif_clientdata, module,
4823 					"Can not read TIFF directory count");
4824 				return 0;
4825 			} else {
4826 				_TIFFmemcpy(&dircount16, tif->tif_base + off,
4827 					    sizeof(uint16));
4828 			}
4829 			off += sizeof (uint16);
4830 			if (tif->tif_flags & TIFF_SWAB)
4831 				TIFFSwabShort(&dircount16);
4832 			if (dircount16>4096)
4833 			{
4834 				TIFFErrorExt(tif->tif_clientdata, module,
4835 				    "Sanity check on directory count failed, this is probably not a valid IFD offset");
4836 				return 0;
4837 			}
4838 			dirsize = 12;
4839 		}
4840 		else
4841 		{
4842 			uint64 dircount64;
4843 			m=off+sizeof(uint64);
4844 			if ((m<off)||(m<(tmsize_t)sizeof(uint64))||(m>tif->tif_size)) {
4845 				TIFFErrorExt(tif->tif_clientdata, module,
4846 					"Can not read TIFF directory count");
4847 				return 0;
4848 			} else {
4849 				_TIFFmemcpy(&dircount64, tif->tif_base + off,
4850 					    sizeof(uint64));
4851 			}
4852 			off += sizeof (uint64);
4853 			if (tif->tif_flags & TIFF_SWAB)
4854 				TIFFSwabLong8(&dircount64);
4855 			if (dircount64>4096)
4856 			{
4857 				TIFFErrorExt(tif->tif_clientdata, module,
4858 				    "Sanity check on directory count failed, this is probably not a valid IFD offset");
4859 				return 0;
4860 			}
4861 			dircount16 = (uint16)dircount64;
4862 			dirsize = 20;
4863 		}
4864 		if (dircount16 == 0 )
4865 		{
4866 			TIFFErrorExt(tif->tif_clientdata, module,
4867 			             "Sanity check on directory count failed, zero tag directories not supported");
4868 			return 0;
4869 		}
4870 		origdir = _TIFFCheckMalloc(tif, dircount16,
4871 						dirsize,
4872 						"to read TIFF directory");
4873 		if (origdir == NULL)
4874 			return 0;
4875 		m=off+dircount16*dirsize;
4876 		if ((m<off)||(m<(tmsize_t)(dircount16*dirsize))||(m>tif->tif_size)) {
4877 			TIFFErrorExt(tif->tif_clientdata, module,
4878 				     "Can not read TIFF directory");
4879 			_TIFFfree(origdir);
4880 			return 0;
4881 		} else {
4882 			_TIFFmemcpy(origdir, tif->tif_base + off,
4883 				    dircount16 * dirsize);
4884 		}
4885 		if (nextdiroff) {
4886 			off += dircount16 * dirsize;
4887 			if (!(tif->tif_flags&TIFF_BIGTIFF))
4888 			{
4889 				uint32 nextdiroff32;
4890 				m=off+sizeof(uint32);
4891 				if ((m<off)||(m<(tmsize_t)sizeof(uint32))||(m>tif->tif_size))
4892 					nextdiroff32 = 0;
4893 				else
4894 					_TIFFmemcpy(&nextdiroff32, tif->tif_base + off,
4895 						    sizeof (uint32));
4896 				if (tif->tif_flags&TIFF_SWAB)
4897 					TIFFSwabLong(&nextdiroff32);
4898 				*nextdiroff = nextdiroff32;
4899 			}
4900 			else
4901 			{
4902 				m=off+sizeof(uint64);
4903 				if ((m<off)||(m<(tmsize_t)sizeof(uint64))||(m>tif->tif_size))
4904 					*nextdiroff = 0;
4905 				else
4906 					_TIFFmemcpy(nextdiroff, tif->tif_base + off,
4907 						    sizeof (uint64));
4908 				if (tif->tif_flags&TIFF_SWAB)
4909 					TIFFSwabLong8(nextdiroff);
4910 			}
4911 		}
4912 	}
4913 	dir = (TIFFDirEntry*)_TIFFCheckMalloc(tif, dircount16,
4914 						sizeof(TIFFDirEntry),
4915 						"to read TIFF directory");
4916 	if (dir==0)
4917 	{
4918 		_TIFFfree(origdir);
4919 		return 0;
4920 	}
4921 	ma=(uint8*)origdir;
4922 	mb=dir;
4923 	for (n=0; n<dircount16; n++)
4924 	{
4925 		mb->tdir_ignore = FALSE;
4926 		if (tif->tif_flags&TIFF_SWAB)
4927 			TIFFSwabShort((uint16*)ma);
4928 		mb->tdir_tag=*(uint16*)ma;
4929 		ma+=sizeof(uint16);
4930 		if (tif->tif_flags&TIFF_SWAB)
4931 			TIFFSwabShort((uint16*)ma);
4932 		mb->tdir_type=*(uint16*)ma;
4933 		ma+=sizeof(uint16);
4934 		if (!(tif->tif_flags&TIFF_BIGTIFF))
4935 		{
4936 			if (tif->tif_flags&TIFF_SWAB)
4937 				TIFFSwabLong((uint32*)ma);
4938 			mb->tdir_count=(uint64)(*(uint32*)ma);
4939 			ma+=sizeof(uint32);
4940 			mb->tdir_offset.toff_long8=0;
4941 			*(uint32*)(&mb->tdir_offset)=*(uint32*)ma;
4942 			ma+=sizeof(uint32);
4943 		}
4944 		else
4945 		{
4946 			if (tif->tif_flags&TIFF_SWAB)
4947 				TIFFSwabLong8((uint64*)ma);
4948                         mb->tdir_count=TIFFReadUInt64(ma);
4949 			ma+=sizeof(uint64);
4950 			mb->tdir_offset.toff_long8=TIFFReadUInt64(ma);
4951 			ma+=sizeof(uint64);
4952 		}
4953 		mb++;
4954 	}
4955 	_TIFFfree(origdir);
4956 	*pdir = dir;
4957 	return dircount16;
4958 }
4959 
4960 /*
4961  * Fetch a tag that is not handled by special case code.
4962  */
4963 static int
TIFFFetchNormalTag(TIFF * tif,TIFFDirEntry * dp,int recover)4964 TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover)
4965 {
4966 	static const char module[] = "TIFFFetchNormalTag";
4967 	enum TIFFReadDirEntryErr err;
4968 	uint32 fii;
4969 	const TIFFField* fip = NULL;
4970 	TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii);
4971         if( fii == FAILED_FII )
4972         {
4973             TIFFErrorExt(tif->tif_clientdata, "TIFFFetchNormalTag",
4974                          "No definition found for tag %d",
4975                          dp->tdir_tag);
4976             return 0;
4977         }
4978 	fip=tif->tif_fields[fii];
4979 	assert(fip != NULL); /* should not happen */
4980 	assert(fip->set_field_type!=TIFF_SETGET_OTHER);  /* if so, we shouldn't arrive here but deal with this in specialized code */
4981 	assert(fip->set_field_type!=TIFF_SETGET_INT);    /* if so, we shouldn't arrive here as this is only the case for pseudo-tags */
4982 	err=TIFFReadDirEntryErrOk;
4983 	switch (fip->set_field_type)
4984 	{
4985 		case TIFF_SETGET_UNDEFINED:
4986 			break;
4987 		case TIFF_SETGET_ASCII:
4988 			{
4989 				uint8* data;
4990 				assert(fip->field_passcount==0);
4991 				err=TIFFReadDirEntryByteArray(tif,dp,&data);
4992 				if (err==TIFFReadDirEntryErrOk)
4993 				{
4994 					uint32 mb = 0;
4995 					int n;
4996 					if (data != NULL)
4997 					{
4998 					    uint8* ma = data;
4999 					    while (mb<(uint32)dp->tdir_count)
5000 					    {
5001 					            if (*ma==0)
5002 					                    break;
5003 					            ma++;
5004 					            mb++;
5005 					    }
5006 					}
5007 					if (mb+1<(uint32)dp->tdir_count)
5008 						TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" contains null byte in value; value incorrectly truncated during reading due to implementation limitations",fip->field_name);
5009 					else if (mb+1>(uint32)dp->tdir_count)
5010 					{
5011 						uint8* o;
5012 						TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte",fip->field_name);
5013 						if ((uint32)dp->tdir_count+1!=dp->tdir_count+1)
5014 							o=NULL;
5015 						else
5016 							o=_TIFFmalloc((uint32)dp->tdir_count+1);
5017 						if (o==NULL)
5018 						{
5019 							if (data!=NULL)
5020 								_TIFFfree(data);
5021 							return(0);
5022 						}
5023 						_TIFFmemcpy(o,data,(uint32)dp->tdir_count);
5024 						o[(uint32)dp->tdir_count]=0;
5025 						if (data!=0)
5026 							_TIFFfree(data);
5027 						data=o;
5028 					}
5029 					n=TIFFSetField(tif,dp->tdir_tag,data);
5030 					if (data!=0)
5031 						_TIFFfree(data);
5032 					if (!n)
5033 						return(0);
5034 				}
5035 			}
5036 			break;
5037 		case TIFF_SETGET_UINT8:
5038 			{
5039 				uint8 data=0;
5040 				assert(fip->field_readcount==1);
5041 				assert(fip->field_passcount==0);
5042 				err=TIFFReadDirEntryByte(tif,dp,&data);
5043 				if (err==TIFFReadDirEntryErrOk)
5044 				{
5045 					if (!TIFFSetField(tif,dp->tdir_tag,data))
5046 						return(0);
5047 				}
5048 			}
5049 			break;
5050 		case TIFF_SETGET_UINT16:
5051 			{
5052 				uint16 data;
5053 				assert(fip->field_readcount==1);
5054 				assert(fip->field_passcount==0);
5055 				err=TIFFReadDirEntryShort(tif,dp,&data);
5056 				if (err==TIFFReadDirEntryErrOk)
5057 				{
5058 					if (!TIFFSetField(tif,dp->tdir_tag,data))
5059 						return(0);
5060 				}
5061 			}
5062 			break;
5063 		case TIFF_SETGET_UINT32:
5064 			{
5065 				uint32 data;
5066 				assert(fip->field_readcount==1);
5067 				assert(fip->field_passcount==0);
5068 				err=TIFFReadDirEntryLong(tif,dp,&data);
5069 				if (err==TIFFReadDirEntryErrOk)
5070 				{
5071 					if (!TIFFSetField(tif,dp->tdir_tag,data))
5072 						return(0);
5073 				}
5074 			}
5075 			break;
5076 		case TIFF_SETGET_UINT64:
5077 			{
5078 				uint64 data;
5079 				assert(fip->field_readcount==1);
5080 				assert(fip->field_passcount==0);
5081 				err=TIFFReadDirEntryLong8(tif,dp,&data);
5082 				if (err==TIFFReadDirEntryErrOk)
5083 				{
5084 					if (!TIFFSetField(tif,dp->tdir_tag,data))
5085 						return(0);
5086 				}
5087 			}
5088 			break;
5089 		case TIFF_SETGET_FLOAT:
5090 			{
5091 				float data;
5092 				assert(fip->field_readcount==1);
5093 				assert(fip->field_passcount==0);
5094 				err=TIFFReadDirEntryFloat(tif,dp,&data);
5095 				if (err==TIFFReadDirEntryErrOk)
5096 				{
5097 					if (!TIFFSetField(tif,dp->tdir_tag,data))
5098 						return(0);
5099 				}
5100 			}
5101 			break;
5102 		case TIFF_SETGET_DOUBLE:
5103 			{
5104 				double data;
5105 				assert(fip->field_readcount==1);
5106 				assert(fip->field_passcount==0);
5107 				err=TIFFReadDirEntryDouble(tif,dp,&data);
5108 				if (err==TIFFReadDirEntryErrOk)
5109 				{
5110 					if (!TIFFSetField(tif,dp->tdir_tag,data))
5111 						return(0);
5112 				}
5113 			}
5114 			break;
5115 		case TIFF_SETGET_IFD8:
5116 			{
5117 				uint64 data;
5118 				assert(fip->field_readcount==1);
5119 				assert(fip->field_passcount==0);
5120 				err=TIFFReadDirEntryIfd8(tif,dp,&data);
5121 				if (err==TIFFReadDirEntryErrOk)
5122 				{
5123 					if (!TIFFSetField(tif,dp->tdir_tag,data))
5124 						return(0);
5125 				}
5126 			}
5127 			break;
5128 		case TIFF_SETGET_UINT16_PAIR:
5129 			{
5130 				uint16* data;
5131 				assert(fip->field_readcount==2);
5132 				assert(fip->field_passcount==0);
5133 				if (dp->tdir_count!=2) {
5134 					TIFFWarningExt(tif->tif_clientdata,module,
5135 						       "incorrect count for field \"%s\", expected 2, got %d",
5136 						       fip->field_name,(int)dp->tdir_count);
5137 					return(0);
5138 				}
5139 				err=TIFFReadDirEntryShortArray(tif,dp,&data);
5140 				if (err==TIFFReadDirEntryErrOk)
5141 				{
5142 					int m;
5143 					m=TIFFSetField(tif,dp->tdir_tag,data[0],data[1]);
5144 					_TIFFfree(data);
5145 					if (!m)
5146 						return(0);
5147 				}
5148 			}
5149 			break;
5150 		case TIFF_SETGET_C0_UINT8:
5151 			{
5152 				uint8* data;
5153 				assert(fip->field_readcount>=1);
5154 				assert(fip->field_passcount==0);
5155 				if (dp->tdir_count!=(uint64)fip->field_readcount) {
5156 					TIFFWarningExt(tif->tif_clientdata,module,
5157 						       "incorrect count for field \"%s\", expected %d, got %d",
5158 						       fip->field_name,(int) fip->field_readcount, (int)dp->tdir_count);
5159 					return 0;
5160 				}
5161 				else
5162 				{
5163 					err=TIFFReadDirEntryByteArray(tif,dp,&data);
5164 					if (err==TIFFReadDirEntryErrOk)
5165 					{
5166 						int m;
5167 						m=TIFFSetField(tif,dp->tdir_tag,data);
5168 						if (data!=0)
5169 							_TIFFfree(data);
5170 						if (!m)
5171 							return(0);
5172 					}
5173 				}
5174 			}
5175 			break;
5176 		case TIFF_SETGET_C0_UINT16:
5177 			{
5178 				uint16* data;
5179 				assert(fip->field_readcount>=1);
5180 				assert(fip->field_passcount==0);
5181 				if (dp->tdir_count!=(uint64)fip->field_readcount)
5182                                     /* corrupt file */;
5183 				else
5184 				{
5185 					err=TIFFReadDirEntryShortArray(tif,dp,&data);
5186 					if (err==TIFFReadDirEntryErrOk)
5187 					{
5188 						int m;
5189 						m=TIFFSetField(tif,dp->tdir_tag,data);
5190 						if (data!=0)
5191 							_TIFFfree(data);
5192 						if (!m)
5193 							return(0);
5194 					}
5195 				}
5196 			}
5197 			break;
5198 		case TIFF_SETGET_C0_UINT32:
5199 			{
5200 				uint32* data;
5201 				assert(fip->field_readcount>=1);
5202 				assert(fip->field_passcount==0);
5203 				if (dp->tdir_count!=(uint64)fip->field_readcount)
5204                                     /* corrupt file */;
5205 				else
5206 				{
5207 					err=TIFFReadDirEntryLongArray(tif,dp,&data);
5208 					if (err==TIFFReadDirEntryErrOk)
5209 					{
5210 						int m;
5211 						m=TIFFSetField(tif,dp->tdir_tag,data);
5212 						if (data!=0)
5213 							_TIFFfree(data);
5214 						if (!m)
5215 							return(0);
5216 					}
5217 				}
5218 			}
5219 			break;
5220 		case TIFF_SETGET_C0_FLOAT:
5221 			{
5222 				float* data;
5223 				assert(fip->field_readcount>=1);
5224 				assert(fip->field_passcount==0);
5225 				if (dp->tdir_count!=(uint64)fip->field_readcount)
5226                                     /* corrupt file */;
5227 				else
5228 				{
5229 					err=TIFFReadDirEntryFloatArray(tif,dp,&data);
5230 					if (err==TIFFReadDirEntryErrOk)
5231 					{
5232 						int m;
5233 						m=TIFFSetField(tif,dp->tdir_tag,data);
5234 						if (data!=0)
5235 							_TIFFfree(data);
5236 						if (!m)
5237 							return(0);
5238 					}
5239 				}
5240 			}
5241 			break;
5242 		case TIFF_SETGET_C16_ASCII:
5243 			{
5244 				uint8* data;
5245 				assert(fip->field_readcount==TIFF_VARIABLE);
5246 				assert(fip->field_passcount==1);
5247 				if (dp->tdir_count>0xFFFF)
5248 					err=TIFFReadDirEntryErrCount;
5249 				else
5250 				{
5251 					err=TIFFReadDirEntryByteArray(tif,dp,&data);
5252 					if (err==TIFFReadDirEntryErrOk)
5253 					{
5254 						int m;
5255 						if( data != 0 && dp->tdir_count > 0 && data[dp->tdir_count-1] != '\0' )
5256 						{
5257 						    TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte. Forcing it to be null",fip->field_name);
5258 						    data[dp->tdir_count-1] = '\0';
5259 						}
5260 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5261 						if (data!=0)
5262 							_TIFFfree(data);
5263 						if (!m)
5264 							return(0);
5265 					}
5266 				}
5267 			}
5268 			break;
5269 		case TIFF_SETGET_C16_UINT8:
5270 			{
5271 				uint8* data;
5272 				assert(fip->field_readcount==TIFF_VARIABLE);
5273 				assert(fip->field_passcount==1);
5274 				if (dp->tdir_count>0xFFFF)
5275 					err=TIFFReadDirEntryErrCount;
5276 				else
5277 				{
5278 					err=TIFFReadDirEntryByteArray(tif,dp,&data);
5279 					if (err==TIFFReadDirEntryErrOk)
5280 					{
5281 						int m;
5282 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5283 						if (data!=0)
5284 							_TIFFfree(data);
5285 						if (!m)
5286 							return(0);
5287 					}
5288 				}
5289 			}
5290 			break;
5291 		case TIFF_SETGET_C16_UINT16:
5292 			{
5293 				uint16* data;
5294 				assert(fip->field_readcount==TIFF_VARIABLE);
5295 				assert(fip->field_passcount==1);
5296 				if (dp->tdir_count>0xFFFF)
5297 					err=TIFFReadDirEntryErrCount;
5298 				else
5299 				{
5300 					err=TIFFReadDirEntryShortArray(tif,dp,&data);
5301 					if (err==TIFFReadDirEntryErrOk)
5302 					{
5303 						int m;
5304 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5305 						if (data!=0)
5306 							_TIFFfree(data);
5307 						if (!m)
5308 							return(0);
5309 					}
5310 				}
5311 			}
5312 			break;
5313 		case TIFF_SETGET_C16_UINT32:
5314 			{
5315 				uint32* data;
5316 				assert(fip->field_readcount==TIFF_VARIABLE);
5317 				assert(fip->field_passcount==1);
5318 				if (dp->tdir_count>0xFFFF)
5319 					err=TIFFReadDirEntryErrCount;
5320 				else
5321 				{
5322 					err=TIFFReadDirEntryLongArray(tif,dp,&data);
5323 					if (err==TIFFReadDirEntryErrOk)
5324 					{
5325 						int m;
5326 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5327 						if (data!=0)
5328 							_TIFFfree(data);
5329 						if (!m)
5330 							return(0);
5331 					}
5332 				}
5333 			}
5334 			break;
5335 		case TIFF_SETGET_C16_UINT64:
5336 			{
5337 				uint64* data;
5338 				assert(fip->field_readcount==TIFF_VARIABLE);
5339 				assert(fip->field_passcount==1);
5340 				if (dp->tdir_count>0xFFFF)
5341 					err=TIFFReadDirEntryErrCount;
5342 				else
5343 				{
5344 					err=TIFFReadDirEntryLong8Array(tif,dp,&data);
5345 					if (err==TIFFReadDirEntryErrOk)
5346 					{
5347 						int m;
5348 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5349 						if (data!=0)
5350 							_TIFFfree(data);
5351 						if (!m)
5352 							return(0);
5353 					}
5354 				}
5355 			}
5356 			break;
5357 		case TIFF_SETGET_C16_FLOAT:
5358 			{
5359 				float* data;
5360 				assert(fip->field_readcount==TIFF_VARIABLE);
5361 				assert(fip->field_passcount==1);
5362 				if (dp->tdir_count>0xFFFF)
5363 					err=TIFFReadDirEntryErrCount;
5364 				else
5365 				{
5366 					err=TIFFReadDirEntryFloatArray(tif,dp,&data);
5367 					if (err==TIFFReadDirEntryErrOk)
5368 					{
5369 						int m;
5370 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5371 						if (data!=0)
5372 							_TIFFfree(data);
5373 						if (!m)
5374 							return(0);
5375 					}
5376 				}
5377 			}
5378 			break;
5379 		case TIFF_SETGET_C16_DOUBLE:
5380 			{
5381 				double* data;
5382 				assert(fip->field_readcount==TIFF_VARIABLE);
5383 				assert(fip->field_passcount==1);
5384 				if (dp->tdir_count>0xFFFF)
5385 					err=TIFFReadDirEntryErrCount;
5386 				else
5387 				{
5388 					err=TIFFReadDirEntryDoubleArray(tif,dp,&data);
5389 					if (err==TIFFReadDirEntryErrOk)
5390 					{
5391 						int m;
5392 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5393 						if (data!=0)
5394 							_TIFFfree(data);
5395 						if (!m)
5396 							return(0);
5397 					}
5398 				}
5399 			}
5400 			break;
5401 		case TIFF_SETGET_C16_IFD8:
5402 			{
5403 				uint64* data;
5404 				assert(fip->field_readcount==TIFF_VARIABLE);
5405 				assert(fip->field_passcount==1);
5406 				if (dp->tdir_count>0xFFFF)
5407 					err=TIFFReadDirEntryErrCount;
5408 				else
5409 				{
5410 					err=TIFFReadDirEntryIfd8Array(tif,dp,&data);
5411 					if (err==TIFFReadDirEntryErrOk)
5412 					{
5413 						int m;
5414 						m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
5415 						if (data!=0)
5416 							_TIFFfree(data);
5417 						if (!m)
5418 							return(0);
5419 					}
5420 				}
5421 			}
5422 			break;
5423 		case TIFF_SETGET_C32_ASCII:
5424 			{
5425 				uint8* data;
5426 				assert(fip->field_readcount==TIFF_VARIABLE2);
5427 				assert(fip->field_passcount==1);
5428 				err=TIFFReadDirEntryByteArray(tif,dp,&data);
5429 				if (err==TIFFReadDirEntryErrOk)
5430 				{
5431 					int m;
5432 					if( data != 0 && dp->tdir_count > 0 && data[dp->tdir_count-1] != '\0' )
5433 					{
5434 					    TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte. Forcing it to be null",fip->field_name);
5435                                             data[dp->tdir_count-1] = '\0';
5436 					}
5437 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5438 					if (data!=0)
5439 						_TIFFfree(data);
5440 					if (!m)
5441 						return(0);
5442 				}
5443 			}
5444 			break;
5445 		case TIFF_SETGET_C32_UINT8:
5446 			{
5447 				uint8* data;
5448 				assert(fip->field_readcount==TIFF_VARIABLE2);
5449 				assert(fip->field_passcount==1);
5450 				err=TIFFReadDirEntryByteArray(tif,dp,&data);
5451 				if (err==TIFFReadDirEntryErrOk)
5452 				{
5453 					int m;
5454 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5455 					if (data!=0)
5456 						_TIFFfree(data);
5457 					if (!m)
5458 						return(0);
5459 				}
5460 			}
5461 			break;
5462 		case TIFF_SETGET_C32_SINT8:
5463 			{
5464 				int8* data = NULL;
5465 				assert(fip->field_readcount==TIFF_VARIABLE2);
5466 				assert(fip->field_passcount==1);
5467 				err=TIFFReadDirEntrySbyteArray(tif,dp,&data);
5468 				if (err==TIFFReadDirEntryErrOk)
5469 				{
5470 					int m;
5471 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5472 					if (data!=0)
5473 						_TIFFfree(data);
5474 					if (!m)
5475 						return(0);
5476 				}
5477 			}
5478 			break;
5479 		case TIFF_SETGET_C32_UINT16:
5480 			{
5481 				uint16* data;
5482 				assert(fip->field_readcount==TIFF_VARIABLE2);
5483 				assert(fip->field_passcount==1);
5484 				err=TIFFReadDirEntryShortArray(tif,dp,&data);
5485 				if (err==TIFFReadDirEntryErrOk)
5486 				{
5487 					int m;
5488 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5489 					if (data!=0)
5490 						_TIFFfree(data);
5491 					if (!m)
5492 						return(0);
5493 				}
5494 			}
5495 			break;
5496 		case TIFF_SETGET_C32_SINT16:
5497 			{
5498 				int16* data = NULL;
5499 				assert(fip->field_readcount==TIFF_VARIABLE2);
5500 				assert(fip->field_passcount==1);
5501 				err=TIFFReadDirEntrySshortArray(tif,dp,&data);
5502 				if (err==TIFFReadDirEntryErrOk)
5503 				{
5504 					int m;
5505 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5506 					if (data!=0)
5507 						_TIFFfree(data);
5508 					if (!m)
5509 						return(0);
5510 				}
5511 			}
5512 			break;
5513 		case TIFF_SETGET_C32_UINT32:
5514 			{
5515 				uint32* data;
5516 				assert(fip->field_readcount==TIFF_VARIABLE2);
5517 				assert(fip->field_passcount==1);
5518 				err=TIFFReadDirEntryLongArray(tif,dp,&data);
5519 				if (err==TIFFReadDirEntryErrOk)
5520 				{
5521 					int m;
5522 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5523 					if (data!=0)
5524 						_TIFFfree(data);
5525 					if (!m)
5526 						return(0);
5527 				}
5528 			}
5529 			break;
5530 		case TIFF_SETGET_C32_SINT32:
5531 			{
5532 				int32* data = NULL;
5533 				assert(fip->field_readcount==TIFF_VARIABLE2);
5534 				assert(fip->field_passcount==1);
5535 				err=TIFFReadDirEntrySlongArray(tif,dp,&data);
5536 				if (err==TIFFReadDirEntryErrOk)
5537 				{
5538 					int m;
5539 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5540 					if (data!=0)
5541 						_TIFFfree(data);
5542 					if (!m)
5543 						return(0);
5544 				}
5545 			}
5546 			break;
5547 		case TIFF_SETGET_C32_UINT64:
5548 			{
5549 				uint64* data;
5550 				assert(fip->field_readcount==TIFF_VARIABLE2);
5551 				assert(fip->field_passcount==1);
5552 				err=TIFFReadDirEntryLong8Array(tif,dp,&data);
5553 				if (err==TIFFReadDirEntryErrOk)
5554 				{
5555 					int m;
5556 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5557 					if (data!=0)
5558 						_TIFFfree(data);
5559 					if (!m)
5560 						return(0);
5561 				}
5562 			}
5563 			break;
5564 		case TIFF_SETGET_C32_SINT64:
5565 			{
5566 				int64* data = NULL;
5567 				assert(fip->field_readcount==TIFF_VARIABLE2);
5568 				assert(fip->field_passcount==1);
5569 				err=TIFFReadDirEntrySlong8Array(tif,dp,&data);
5570 				if (err==TIFFReadDirEntryErrOk)
5571 				{
5572 					int m;
5573 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5574 					if (data!=0)
5575 						_TIFFfree(data);
5576 					if (!m)
5577 						return(0);
5578 				}
5579 			}
5580 			break;
5581 		case TIFF_SETGET_C32_FLOAT:
5582 			{
5583 				float* data;
5584 				assert(fip->field_readcount==TIFF_VARIABLE2);
5585 				assert(fip->field_passcount==1);
5586 				err=TIFFReadDirEntryFloatArray(tif,dp,&data);
5587 				if (err==TIFFReadDirEntryErrOk)
5588 				{
5589 					int m;
5590 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5591 					if (data!=0)
5592 						_TIFFfree(data);
5593 					if (!m)
5594 						return(0);
5595 				}
5596 			}
5597 			break;
5598 		case TIFF_SETGET_C32_DOUBLE:
5599 			{
5600 				double* data;
5601 				assert(fip->field_readcount==TIFF_VARIABLE2);
5602 				assert(fip->field_passcount==1);
5603 				err=TIFFReadDirEntryDoubleArray(tif,dp,&data);
5604 				if (err==TIFFReadDirEntryErrOk)
5605 				{
5606 					int m;
5607 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5608 					if (data!=0)
5609 						_TIFFfree(data);
5610 					if (!m)
5611 						return(0);
5612 				}
5613 			}
5614 			break;
5615 		case TIFF_SETGET_C32_IFD8:
5616 			{
5617 				uint64* data;
5618 				assert(fip->field_readcount==TIFF_VARIABLE2);
5619 				assert(fip->field_passcount==1);
5620 				err=TIFFReadDirEntryIfd8Array(tif,dp,&data);
5621 				if (err==TIFFReadDirEntryErrOk)
5622 				{
5623 					int m;
5624 					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
5625 					if (data!=0)
5626 						_TIFFfree(data);
5627 					if (!m)
5628 						return(0);
5629 				}
5630 			}
5631 			break;
5632 		default:
5633 			assert(0);    /* we should never get here */
5634 			break;
5635 	}
5636 	if (err!=TIFFReadDirEntryErrOk)
5637 	{
5638 		TIFFReadDirEntryOutputErr(tif,err,module,fip->field_name,recover);
5639 		return(0);
5640 	}
5641 	return(1);
5642 }
5643 
5644 /*
5645  * Fetch a set of offsets or lengths.
5646  * While this routine says "strips", in fact it's also used for tiles.
5647  */
5648 static int
TIFFFetchStripThing(TIFF * tif,TIFFDirEntry * dir,uint32 nstrips,uint64 ** lpp)5649 TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, uint32 nstrips, uint64** lpp)
5650 {
5651 	static const char module[] = "TIFFFetchStripThing";
5652 	enum TIFFReadDirEntryErr err;
5653 	uint64* data;
5654 	err=TIFFReadDirEntryLong8ArrayWithLimit(tif,dir,&data,nstrips);
5655 	if (err!=TIFFReadDirEntryErrOk)
5656 	{
5657 		const TIFFField* fip = TIFFFieldWithTag(tif,dir->tdir_tag);
5658 		TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",0);
5659 		return(0);
5660 	}
5661 	if (dir->tdir_count<(uint64)nstrips)
5662 	{
5663 		uint64* resizeddata;
5664 		const TIFFField* fip = TIFFFieldWithTag(tif,dir->tdir_tag);
5665 		const char* pszMax = getenv("LIBTIFF_STRILE_ARRAY_MAX_RESIZE_COUNT");
5666 		uint32 max_nstrips = 1000000;
5667 		if( pszMax )
5668 			max_nstrips = (uint32) atoi(pszMax);
5669 		TIFFReadDirEntryOutputErr(tif,TIFFReadDirEntryErrCount,
5670 		            module,
5671 		            fip ? fip->field_name : "unknown tagname",
5672 		            ( nstrips <= max_nstrips ) );
5673 
5674 		if( nstrips > max_nstrips )
5675 		{
5676 			_TIFFfree(data);
5677 			return(0);
5678 		}
5679 
5680 		resizeddata=(uint64*)_TIFFCheckMalloc(tif,nstrips,sizeof(uint64),"for strip array");
5681 		if (resizeddata==0) {
5682 			_TIFFfree(data);
5683 			return(0);
5684 		}
5685                 _TIFFmemcpy(resizeddata,data,(uint32)dir->tdir_count*sizeof(uint64));
5686                 _TIFFmemset(resizeddata+(uint32)dir->tdir_count,0,(nstrips-(uint32)dir->tdir_count)*sizeof(uint64));
5687 		_TIFFfree(data);
5688 		data=resizeddata;
5689 	}
5690 	*lpp=data;
5691 	return(1);
5692 }
5693 
5694 /*
5695  * Fetch and set the SubjectDistance EXIF tag.
5696  */
5697 static int
TIFFFetchSubjectDistance(TIFF * tif,TIFFDirEntry * dir)5698 TIFFFetchSubjectDistance(TIFF* tif, TIFFDirEntry* dir)
5699 {
5700 	static const char module[] = "TIFFFetchSubjectDistance";
5701 	enum TIFFReadDirEntryErr err;
5702 	UInt64Aligned_t m;
5703     m.l=0;
5704 	assert(sizeof(double)==8);
5705 	assert(sizeof(uint64)==8);
5706 	assert(sizeof(uint32)==4);
5707 	if (dir->tdir_count!=1)
5708 		err=TIFFReadDirEntryErrCount;
5709 	else if (dir->tdir_type!=TIFF_RATIONAL)
5710 		err=TIFFReadDirEntryErrType;
5711 	else
5712 	{
5713 		if (!(tif->tif_flags&TIFF_BIGTIFF))
5714 		{
5715 			uint32 offset;
5716 			offset=*(uint32*)(&dir->tdir_offset);
5717 			if (tif->tif_flags&TIFF_SWAB)
5718 				TIFFSwabLong(&offset);
5719 			err=TIFFReadDirEntryData(tif,offset,8,m.i);
5720 		}
5721 		else
5722 		{
5723 			m.l=dir->tdir_offset.toff_long8;
5724 			err=TIFFReadDirEntryErrOk;
5725 		}
5726 	}
5727 	if (err==TIFFReadDirEntryErrOk)
5728 	{
5729 		double n;
5730 		if (tif->tif_flags&TIFF_SWAB)
5731 			TIFFSwabArrayOfLong(m.i,2);
5732 		if (m.i[0]==0)
5733 			n=0.0;
5734 		else if (m.i[0]==0xFFFFFFFF || m.i[1]==0)
5735 			/*
5736 			 * XXX: Numerator 0xFFFFFFFF means that we have infinite
5737 			 * distance. Indicate that with a negative floating point
5738 			 * SubjectDistance value.
5739 			 */
5740 			n=-1.0;
5741 		else
5742 			n=(double)m.i[0]/(double)m.i[1];
5743 		return(TIFFSetField(tif,dir->tdir_tag,n));
5744 	}
5745 	else
5746 	{
5747 		TIFFReadDirEntryOutputErr(tif,err,module,"SubjectDistance",TRUE);
5748 		return(0);
5749 	}
5750 }
5751 
allocChoppedUpStripArrays(TIFF * tif,uint32 nstrips,uint64 stripbytes,uint32 rowsperstrip)5752 static void allocChoppedUpStripArrays(TIFF* tif, uint32 nstrips,
5753                                       uint64 stripbytes, uint32 rowsperstrip)
5754 {
5755     TIFFDirectory *td = &tif->tif_dir;
5756     uint64 bytecount;
5757     uint64 offset;
5758     uint64 last_offset;
5759     uint64 last_bytecount;
5760     uint32 i;
5761     uint64 *newcounts;
5762     uint64 *newoffsets;
5763 
5764     offset = TIFFGetStrileOffset(tif, 0);
5765     last_offset = TIFFGetStrileOffset(tif, td->td_nstrips-1);
5766     last_bytecount = TIFFGetStrileByteCount(tif, td->td_nstrips-1);
5767     if( last_offset > TIFF_UINT64_MAX - last_bytecount ||
5768         last_offset + last_bytecount < offset )
5769     {
5770         return;
5771     }
5772     bytecount = last_offset + last_bytecount - offset;
5773 
5774     newcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),
5775                             "for chopped \"StripByteCounts\" array");
5776     newoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),
5777                             "for chopped \"StripOffsets\" array");
5778     if (newcounts == NULL || newoffsets == NULL) {
5779         /*
5780         * Unable to allocate new strip information, give up and use
5781         * the original one strip information.
5782         */
5783         if (newcounts != NULL)
5784             _TIFFfree(newcounts);
5785         if (newoffsets != NULL)
5786             _TIFFfree(newoffsets);
5787         return;
5788     }
5789 
5790     /*
5791      * Fill the strip information arrays with new bytecounts and offsets
5792      * that reflect the broken-up format.
5793      */
5794     for (i = 0; i < nstrips; i++)
5795     {
5796         if (stripbytes > bytecount)
5797             stripbytes = bytecount;
5798         newcounts[i] = stripbytes;
5799         newoffsets[i] = stripbytes ? offset : 0;
5800         offset += stripbytes;
5801         bytecount -= stripbytes;
5802     }
5803 
5804     /*
5805      * Replace old single strip info with multi-strip info.
5806      */
5807     td->td_stripsperimage = td->td_nstrips = nstrips;
5808     TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
5809 
5810     _TIFFfree(td->td_stripbytecount_p);
5811     _TIFFfree(td->td_stripoffset_p);
5812     td->td_stripbytecount_p = newcounts;
5813     td->td_stripoffset_p = newoffsets;
5814 #ifdef STRIPBYTECOUNTSORTED_UNUSED
5815     td->td_stripbytecountsorted = 1;
5816 #endif
5817     tif->tif_flags |= TIFF_CHOPPEDUPARRAYS;
5818 }
5819 
5820 
5821 /*
5822  * Replace a single strip (tile) of uncompressed data by multiple strips
5823  * (tiles), each approximately STRIP_SIZE_DEFAULT bytes. This is useful for
5824  * dealing with large images or for dealing with machines with a limited
5825  * amount memory.
5826  */
5827 static void
ChopUpSingleUncompressedStrip(TIFF * tif)5828 ChopUpSingleUncompressedStrip(TIFF* tif)
5829 {
5830 	register TIFFDirectory *td = &tif->tif_dir;
5831 	uint64 bytecount;
5832 	uint64 offset;
5833 	uint32 rowblock;
5834 	uint64 rowblockbytes;
5835 	uint64 stripbytes;
5836 	uint32 nstrips;
5837 	uint32 rowsperstrip;
5838 
5839 	bytecount = TIFFGetStrileByteCount(tif, 0);
5840         /* On a newly created file, just re-opened to be filled, we */
5841         /* don't want strip chop to trigger as it is going to cause issues */
5842         /* later ( StripOffsets and StripByteCounts improperly filled) . */
5843         if( bytecount == 0 && tif->tif_mode != O_RDONLY )
5844             return;
5845 	offset = TIFFGetStrileByteCount(tif, 0);
5846 	assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
5847 	if ((td->td_photometric == PHOTOMETRIC_YCBCR)&&
5848 	    (!isUpSampled(tif)))
5849 		rowblock = td->td_ycbcrsubsampling[1];
5850 	else
5851 		rowblock = 1;
5852 	rowblockbytes = TIFFVTileSize64(tif, rowblock);
5853 	/*
5854 	 * Make the rows hold at least one scanline, but fill specified amount
5855 	 * of data if possible.
5856 	 */
5857 	if (rowblockbytes > STRIP_SIZE_DEFAULT) {
5858 		stripbytes = rowblockbytes;
5859 		rowsperstrip = rowblock;
5860 	} else if (rowblockbytes > 0 ) {
5861 		uint32 rowblocksperstrip;
5862 		rowblocksperstrip = (uint32) (STRIP_SIZE_DEFAULT / rowblockbytes);
5863 		rowsperstrip = rowblocksperstrip * rowblock;
5864 		stripbytes = rowblocksperstrip * rowblockbytes;
5865 	}
5866 	else
5867 	    return;
5868 
5869 	/*
5870 	 * never increase the number of rows per strip
5871 	 */
5872 	if (rowsperstrip >= td->td_rowsperstrip)
5873 		return;
5874         nstrips = TIFFhowmany_32(td->td_imagelength, rowsperstrip);
5875         if( nstrips == 0 )
5876             return;
5877 
5878         /* If we are going to allocate a lot of memory, make sure that the */
5879         /* file is as big as needed */
5880         if( tif->tif_mode == O_RDONLY &&
5881             nstrips > 1000000 &&
5882             (offset >= TIFFGetFileSize(tif) ||
5883              stripbytes > (TIFFGetFileSize(tif) - offset) / (nstrips - 1)) )
5884         {
5885             return;
5886         }
5887 
5888         allocChoppedUpStripArrays(tif, nstrips, stripbytes, rowsperstrip);
5889 }
5890 
5891 
5892 /*
5893  * Replace a file with contiguous strips > 2 GB of uncompressed data by
5894  * multiple smaller strips. This is useful for
5895  * dealing with large images or for dealing with machines with a limited
5896  * amount memory.
5897  */
TryChopUpUncompressedBigTiff(TIFF * tif)5898 static void TryChopUpUncompressedBigTiff( TIFF* tif )
5899 {
5900     TIFFDirectory *td = &tif->tif_dir;
5901     uint32 rowblock;
5902     uint64 rowblockbytes;
5903     uint32 i;
5904     uint64 stripsize;
5905     uint32 rowblocksperstrip;
5906     uint32 rowsperstrip;
5907     uint64 stripbytes;
5908     uint32 nstrips;
5909 
5910     stripsize = TIFFStripSize64(tif);
5911 
5912     assert( tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG );
5913     assert( tif->tif_dir.td_compression == COMPRESSION_NONE );
5914     assert( (tif->tif_flags&(TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP );
5915     assert( stripsize > 0x7FFFFFFFUL );
5916 
5917     /* On a newly created file, just re-opened to be filled, we */
5918     /* don't want strip chop to trigger as it is going to cause issues */
5919     /* later ( StripOffsets and StripByteCounts improperly filled) . */
5920     if( TIFFGetStrileByteCount(tif, 0) == 0 && tif->tif_mode != O_RDONLY )
5921         return;
5922 
5923     if ((td->td_photometric == PHOTOMETRIC_YCBCR)&&
5924         (!isUpSampled(tif)))
5925         rowblock = td->td_ycbcrsubsampling[1];
5926     else
5927         rowblock = 1;
5928     rowblockbytes = TIFFVStripSize64(tif, rowblock);
5929     if( rowblockbytes == 0 || rowblockbytes > 0x7FFFFFFFUL )
5930     {
5931         /* In case of file with gigantic width */
5932         return;
5933     }
5934 
5935     /* Check that the strips are contiguous and of the expected size */
5936     for( i = 0; i < td->td_nstrips; i++ )
5937     {
5938         if( i == td->td_nstrips - 1 )
5939         {
5940             if( TIFFGetStrileByteCount(tif, i) < TIFFVStripSize64(
5941                     tif, td->td_imagelength - i * td->td_rowsperstrip ) )
5942             {
5943                 return;
5944             }
5945         }
5946         else
5947         {
5948             if( TIFFGetStrileByteCount(tif, i) != stripsize )
5949             {
5950                 return;
5951             }
5952             if( i > 0 && TIFFGetStrileOffset(tif, i) !=
5953                     TIFFGetStrileOffset(tif, i-1) + TIFFGetStrileByteCount(tif, i-1) )
5954             {
5955                 return;
5956             }
5957         }
5958     }
5959 
5960     /* Aim for 512 MB strips (that will still be manageable by 32 bit builds */
5961     rowblocksperstrip = (uint32) (512 * 1024 * 1024 / rowblockbytes);
5962     if( rowblocksperstrip == 0 )
5963         rowblocksperstrip = 1;
5964     rowsperstrip = rowblocksperstrip * rowblock;
5965     stripbytes = rowblocksperstrip * rowblockbytes;
5966     assert( stripbytes <= 0x7FFFFFFFUL );
5967 
5968     nstrips = TIFFhowmany_32(td->td_imagelength, rowsperstrip);
5969     if( nstrips == 0 )
5970         return;
5971 
5972     /* If we are going to allocate a lot of memory, make sure that the */
5973     /* file is as big as needed */
5974     if( tif->tif_mode == O_RDONLY &&
5975         nstrips > 1000000 )
5976     {
5977         uint64 last_offset = TIFFGetStrileOffset(tif, td->td_nstrips-1);
5978         uint64 filesize = TIFFGetFileSize(tif);
5979         uint64 last_bytecount = TIFFGetStrileByteCount(tif, td->td_nstrips-1);
5980         if( last_offset > filesize ||
5981             last_bytecount > filesize - last_offset )
5982         {
5983             return;
5984         }
5985     }
5986 
5987     allocChoppedUpStripArrays(tif, nstrips, stripbytes, rowsperstrip);
5988 }
5989 
5990 
5991 TIFF_NOSANITIZE_UNSIGNED_INT_OVERFLOW
_TIFFUnsanitizedAddUInt64AndInt(uint64 a,int b)5992 static uint64 _TIFFUnsanitizedAddUInt64AndInt(uint64 a, int b)
5993 {
5994     return a + b;
5995 }
5996 
5997 /* Read the value of [Strip|Tile]Offset or [Strip|Tile]ByteCount around
5998  * strip/tile of number strile. Also fetch the neighbouring values using a
5999  * 4096 byte page size.
6000  */
6001 static
_TIFFPartialReadStripArray(TIFF * tif,TIFFDirEntry * dirent,int strile,uint64 * panVals)6002 int _TIFFPartialReadStripArray( TIFF* tif, TIFFDirEntry* dirent,
6003                                 int strile, uint64* panVals )
6004 {
6005     static const char module[] = "_TIFFPartialReadStripArray";
6006 #define IO_CACHE_PAGE_SIZE 4096
6007 
6008     size_t sizeofval;
6009     const int bSwab = (tif->tif_flags & TIFF_SWAB) != 0;
6010     int sizeofvalint;
6011     uint64 nBaseOffset;
6012     uint64 nOffset;
6013     uint64 nOffsetStartPage;
6014     uint64 nOffsetEndPage;
6015     tmsize_t nToRead;
6016     tmsize_t nRead;
6017     uint64 nLastStripOffset;
6018     int iStartBefore;
6019     int i;
6020     const uint32 arraySize = tif->tif_dir.td_stripoffsetbyteallocsize;
6021     unsigned char buffer[2 * IO_CACHE_PAGE_SIZE];
6022 
6023     assert( dirent->tdir_count > 4 );
6024 
6025     if( dirent->tdir_type == TIFF_SHORT )
6026     {
6027         sizeofval = sizeof(uint16);
6028     }
6029     else if( dirent->tdir_type == TIFF_LONG )
6030     {
6031         sizeofval = sizeof(uint32);
6032     }
6033     else if( dirent->tdir_type == TIFF_LONG8 )
6034     {
6035         sizeofval = sizeof(uint64);
6036     }
6037     else
6038     {
6039         TIFFErrorExt(tif->tif_clientdata, module,
6040                  "Invalid type for [Strip|Tile][Offset/ByteCount] tag");
6041         panVals[strile] = 0;
6042         return 0;
6043     }
6044     sizeofvalint = (int)(sizeofval);
6045 
6046     if( tif->tif_flags&TIFF_BIGTIFF )
6047     {
6048         uint64 offset = dirent->tdir_offset.toff_long8;
6049         if( bSwab )
6050             TIFFSwabLong8(&offset);
6051         nBaseOffset = offset;
6052     }
6053     else
6054     {
6055         uint32 offset = dirent->tdir_offset.toff_long;
6056         if( bSwab )
6057             TIFFSwabLong(&offset);
6058         nBaseOffset = offset;
6059     }
6060     /* To avoid later unsigned integer overflows */
6061     if( nBaseOffset > (uint64)TIFF_INT64_MAX )
6062     {
6063         TIFFErrorExt(tif->tif_clientdata, module,
6064                  "Cannot read offset/size for strile %d", strile);
6065         panVals[strile] = 0;
6066         return 0;
6067     }
6068     nOffset = nBaseOffset + sizeofval * strile;
6069     nOffsetStartPage =
6070         (nOffset / IO_CACHE_PAGE_SIZE) * IO_CACHE_PAGE_SIZE;
6071     nOffsetEndPage = nOffsetStartPage + IO_CACHE_PAGE_SIZE;
6072 
6073     if( nOffset + sizeofval > nOffsetEndPage )
6074         nOffsetEndPage += IO_CACHE_PAGE_SIZE;
6075 #undef IO_CACHE_PAGE_SIZE
6076 
6077     nLastStripOffset = nBaseOffset + arraySize * sizeofval;
6078     if( nLastStripOffset < nOffsetEndPage )
6079         nOffsetEndPage = nLastStripOffset;
6080     if( nOffsetStartPage >= nOffsetEndPage )
6081     {
6082         TIFFErrorExt(tif->tif_clientdata, module,
6083                  "Cannot read offset/size for strile %d", strile);
6084         panVals[strile] = 0;
6085         return 0;
6086     }
6087     if (!SeekOK(tif,nOffsetStartPage))
6088     {
6089         panVals[strile] = 0;
6090         return 0;
6091     }
6092 
6093     nToRead = (tmsize_t)(nOffsetEndPage - nOffsetStartPage);
6094     nRead = TIFFReadFile(tif, buffer, nToRead);
6095     if( nRead < nToRead )
6096     {
6097         TIFFErrorExt(tif->tif_clientdata, module,
6098                  "Cannot read offset/size for strile around ~%d", strile);
6099         return 0;
6100     }
6101     iStartBefore = -(int)((nOffset - nOffsetStartPage) / sizeofval);
6102     if( strile + iStartBefore < 0 )
6103         iStartBefore = -strile;
6104     for( i = iStartBefore;
6105          (uint32)(strile + i) < arraySize &&
6106          _TIFFUnsanitizedAddUInt64AndInt(nOffset, (i + 1) * sizeofvalint) <= nOffsetEndPage;
6107          ++i )
6108     {
6109         if( sizeofval == sizeof(uint16) )
6110         {
6111             uint16 val;
6112             memcpy(&val,
6113                    buffer + (nOffset - nOffsetStartPage) + i * sizeofvalint,
6114                    sizeof(val));
6115             if( bSwab )
6116                 TIFFSwabShort(&val);
6117             panVals[strile + i] = val;
6118         }
6119         else if( sizeofval == sizeof(uint32) )
6120         {
6121             uint32 val;
6122             memcpy(&val,
6123                    buffer + (nOffset - nOffsetStartPage) + i * sizeofvalint,
6124                    sizeof(val));
6125             if( bSwab )
6126                 TIFFSwabLong(&val);
6127             panVals[strile + i] = val;
6128         }
6129         else
6130         {
6131             uint64 val;
6132             memcpy(&val,
6133                    buffer + (nOffset - nOffsetStartPage) + i * sizeofvalint,
6134                    sizeof(val));
6135             if( bSwab )
6136                 TIFFSwabLong8(&val);
6137             panVals[strile + i] = val;
6138         }
6139     }
6140     return 1;
6141 }
6142 
_TIFFFetchStrileValue(TIFF * tif,uint32 strile,TIFFDirEntry * dirent,uint64 ** parray)6143 static int _TIFFFetchStrileValue(TIFF* tif,
6144                                  uint32 strile,
6145                                  TIFFDirEntry* dirent,
6146                                  uint64** parray)
6147 {
6148     static const char module[] = "_TIFFFetchStrileValue";
6149     TIFFDirectory *td = &tif->tif_dir;
6150     if( strile >= dirent->tdir_count )
6151     {
6152         return 0;
6153     }
6154     if( strile >= td->td_stripoffsetbyteallocsize )
6155     {
6156         uint32 nStripArrayAllocBefore = td->td_stripoffsetbyteallocsize;
6157         uint32 nStripArrayAllocNew;
6158         uint64 nArraySize64;
6159         size_t nArraySize;
6160         uint64* offsetArray;
6161         uint64* bytecountArray;
6162 
6163         if( strile > 1000000 )
6164         {
6165             uint64 filesize = TIFFGetFileSize(tif);
6166             /* Avoid excessive memory allocation attempt */
6167             /* For such a big blockid we need at least a TIFF_LONG per strile */
6168             /* for the offset array. */
6169             if( strile > filesize / sizeof(uint32) )
6170             {
6171                 TIFFErrorExt(tif->tif_clientdata, module, "File too short");
6172                 return 0;
6173             }
6174         }
6175 
6176         if( td->td_stripoffsetbyteallocsize == 0 &&
6177             td->td_nstrips < 1024 * 1024 )
6178         {
6179             nStripArrayAllocNew = td->td_nstrips;
6180         }
6181         else
6182         {
6183 #define TIFF_MAX(a,b) (((a)>(b)) ? (a) : (b))
6184 #define TIFF_MIN(a,b) (((a)<(b)) ? (a) : (b))
6185             nStripArrayAllocNew = TIFF_MAX(strile + 1, 1024U * 512U );
6186             if( nStripArrayAllocNew < 0xFFFFFFFFU / 2  )
6187                 nStripArrayAllocNew *= 2;
6188             nStripArrayAllocNew = TIFF_MIN(nStripArrayAllocNew, td->td_nstrips);
6189         }
6190         assert( strile < nStripArrayAllocNew );
6191         nArraySize64 = (uint64)sizeof(uint64) * nStripArrayAllocNew;
6192         nArraySize = (size_t)(nArraySize64);
6193 #if SIZEOF_SIZE_T == 4
6194         if( nArraySize != nArraySize64 )
6195         {
6196             TIFFErrorExt(tif->tif_clientdata, module,
6197                         "Cannot allocate strip offset and bytecount arrays");
6198             return 0;
6199         }
6200 #endif
6201         offsetArray = (uint64*)(
6202             _TIFFrealloc( td->td_stripoffset_p, nArraySize ) );
6203         bytecountArray = (uint64*)(
6204             _TIFFrealloc( td->td_stripbytecount_p, nArraySize ) );
6205         if( offsetArray )
6206             td->td_stripoffset_p = offsetArray;
6207         if( bytecountArray )
6208             td->td_stripbytecount_p = bytecountArray;
6209         if( offsetArray && bytecountArray )
6210         {
6211             td->td_stripoffsetbyteallocsize = nStripArrayAllocNew;
6212             /* Initialize new entries to ~0 / -1 */
6213             memset(td->td_stripoffset_p + nStripArrayAllocBefore,
6214                 0xFF,
6215                 (td->td_stripoffsetbyteallocsize - nStripArrayAllocBefore) * sizeof(uint64) );
6216             memset(td->td_stripbytecount_p + nStripArrayAllocBefore,
6217                 0xFF,
6218                 (td->td_stripoffsetbyteallocsize - nStripArrayAllocBefore) * sizeof(uint64) );
6219         }
6220         else
6221         {
6222             TIFFErrorExt(tif->tif_clientdata, module,
6223                         "Cannot allocate strip offset and bytecount arrays");
6224             _TIFFfree(td->td_stripoffset_p);
6225             td->td_stripoffset_p = NULL;
6226             _TIFFfree(td->td_stripbytecount_p);
6227             td->td_stripbytecount_p = NULL;
6228             td->td_stripoffsetbyteallocsize = 0;
6229         }
6230     }
6231     if( *parray == NULL || strile >= td->td_stripoffsetbyteallocsize )
6232         return 0;
6233 
6234     if( ~((*parray)[strile]) == 0 )
6235     {
6236         if( !_TIFFPartialReadStripArray( tif, dirent, strile, *parray ) )
6237         {
6238             (*parray)[strile] = 0;
6239             return 0;
6240         }
6241     }
6242 
6243     return 1;
6244 }
6245 
_TIFFGetStrileOffsetOrByteCountValue(TIFF * tif,uint32 strile,TIFFDirEntry * dirent,uint64 ** parray,int * pbErr)6246 static uint64 _TIFFGetStrileOffsetOrByteCountValue(TIFF *tif, uint32 strile,
6247                                                    TIFFDirEntry* dirent,
6248                                                    uint64** parray,
6249                                                    int *pbErr)
6250 {
6251     TIFFDirectory *td = &tif->tif_dir;
6252     if( pbErr )
6253         *pbErr = 0;
6254     if( (tif->tif_flags&TIFF_DEFERSTRILELOAD) && !(tif->tif_flags&TIFF_CHOPPEDUPARRAYS) )
6255     {
6256         if( !(tif->tif_flags&TIFF_LAZYSTRILELOAD) ||
6257             /* If the values may fit in the toff_long/toff_long8 member */
6258             /* then use _TIFFFillStriles to simplify _TIFFFetchStrileValue */
6259             dirent->tdir_count <= 4 )
6260         {
6261             if( !_TIFFFillStriles(tif) )
6262             {
6263                 if( pbErr )
6264                     *pbErr = 1;
6265                 /* Do not return, as we want this function to always */
6266                 /* return the same value if called several times with */
6267                 /* the same arguments */
6268             }
6269         }
6270         else
6271         {
6272              if( !_TIFFFetchStrileValue(tif, strile, dirent, parray) )
6273              {
6274                 if( pbErr )
6275                     *pbErr = 1;
6276                  return 0;
6277              }
6278         }
6279     }
6280     if( *parray == NULL || strile >= td->td_nstrips )
6281     {
6282         if( pbErr )
6283             *pbErr = 1;
6284         return 0;
6285     }
6286     return (*parray)[strile];
6287 }
6288 
6289 /* Return the value of the TileOffsets/StripOffsets array for the specified tile/strile */
TIFFGetStrileOffset(TIFF * tif,uint32 strile)6290 uint64 TIFFGetStrileOffset(TIFF *tif, uint32 strile)
6291 {
6292     return TIFFGetStrileOffsetWithErr(tif, strile, NULL);
6293 }
6294 
6295 /* Return the value of the TileOffsets/StripOffsets array for the specified tile/strile */
TIFFGetStrileOffsetWithErr(TIFF * tif,uint32 strile,int * pbErr)6296 uint64 TIFFGetStrileOffsetWithErr(TIFF *tif, uint32 strile, int *pbErr)
6297 {
6298     TIFFDirectory *td = &tif->tif_dir;
6299     return _TIFFGetStrileOffsetOrByteCountValue(tif, strile,
6300                                &(td->td_stripoffset_entry),
6301                                &(td->td_stripoffset_p), pbErr);
6302 }
6303 
6304 /* Return the value of the TileByteCounts/StripByteCounts array for the specified tile/strile */
TIFFGetStrileByteCount(TIFF * tif,uint32 strile)6305 uint64 TIFFGetStrileByteCount(TIFF *tif, uint32 strile)
6306 {
6307     return TIFFGetStrileByteCountWithErr(tif, strile, NULL);
6308 }
6309 
6310 /* Return the value of the TileByteCounts/StripByteCounts array for the specified tile/strile */
TIFFGetStrileByteCountWithErr(TIFF * tif,uint32 strile,int * pbErr)6311 uint64 TIFFGetStrileByteCountWithErr(TIFF *tif, uint32 strile, int *pbErr)
6312 {
6313     TIFFDirectory *td = &tif->tif_dir;
6314     return _TIFFGetStrileOffsetOrByteCountValue(tif, strile,
6315                                &(td->td_stripbytecount_entry),
6316                                &(td->td_stripbytecount_p), pbErr);
6317 }
6318 
6319 
_TIFFFillStriles(TIFF * tif)6320 int _TIFFFillStriles( TIFF *tif )
6321 {
6322     return _TIFFFillStrilesInternal( tif, 1 );
6323 }
6324 
_TIFFFillStrilesInternal(TIFF * tif,int loadStripByteCount)6325 static int _TIFFFillStrilesInternal( TIFF *tif, int loadStripByteCount )
6326 {
6327     register TIFFDirectory *td = &tif->tif_dir;
6328     int return_value = 1;
6329 
6330     /* Do not do anything if TIFF_DEFERSTRILELOAD is not set */
6331     if( !(tif->tif_flags&TIFF_DEFERSTRILELOAD) || (tif->tif_flags&TIFF_CHOPPEDUPARRAYS) != 0 )
6332         return 1;
6333 
6334     if( tif->tif_flags&TIFF_LAZYSTRILELOAD )
6335     {
6336         /* In case of lazy loading, reload completely the arrays */
6337         _TIFFfree(td->td_stripoffset_p);
6338         _TIFFfree(td->td_stripbytecount_p);
6339         td->td_stripoffset_p = NULL;
6340         td->td_stripbytecount_p = NULL;
6341         td->td_stripoffsetbyteallocsize = 0;
6342         tif->tif_flags &= ~TIFF_LAZYSTRILELOAD;
6343     }
6344 
6345     /* If stripoffset array is already loaded, exit with success */
6346     if( td->td_stripoffset_p != NULL )
6347             return 1;
6348 
6349     /* If tdir_count was cancelled, then we already got there, but in error */
6350     if( td->td_stripoffset_entry.tdir_count == 0 )
6351             return 0;
6352 
6353     if (!TIFFFetchStripThing(tif,&(td->td_stripoffset_entry),
6354                                 td->td_nstrips,&td->td_stripoffset_p))
6355     {
6356             return_value = 0;
6357     }
6358 
6359     if (loadStripByteCount &&
6360         !TIFFFetchStripThing(tif,&(td->td_stripbytecount_entry),
6361                                 td->td_nstrips,&td->td_stripbytecount_p))
6362     {
6363             return_value = 0;
6364     }
6365 
6366     _TIFFmemset( &(td->td_stripoffset_entry), 0, sizeof(TIFFDirEntry));
6367     _TIFFmemset( &(td->td_stripbytecount_entry), 0, sizeof(TIFFDirEntry));
6368 
6369 #ifdef STRIPBYTECOUNTSORTED_UNUSED
6370     if (tif->tif_dir.td_nstrips > 1 && return_value == 1 ) {
6371             uint32 strip;
6372 
6373             tif->tif_dir.td_stripbytecountsorted = 1;
6374             for (strip = 1; strip < tif->tif_dir.td_nstrips; strip++) {
6375                     if (tif->tif_dir.td_stripoffset_p[strip - 1] >
6376                         tif->tif_dir.td_stripoffset_p[strip]) {
6377                             tif->tif_dir.td_stripbytecountsorted = 0;
6378                             break;
6379                     }
6380             }
6381     }
6382 #endif
6383 
6384     return return_value;
6385 }
6386 
6387 
6388 /* vim: set ts=8 sts=8 sw=8 noet: */
6389 /*
6390  * Local Variables:
6391  * mode: c
6392  * c-basic-offset: 8
6393  * fill-column: 78
6394  * End:
6395  */
6396