Merge XFA to PDFium master at 4dc95e7 on 10/28/2014
[pdfium.git] / core / src / fxcodec / fx_tiff / tiff_v403 / tif_dir.c
1 /* $Id: tif_dir.c,v 1.113 2012-06-14 20:32:53 fwarmerdam Exp $ */
2
3 /*
4  * Copyright (c) 1988-1997 Sam Leffler
5  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and 
8  * its documentation for any purpose is hereby granted without fee, provided
9  * that (i) the above copyright notices and this permission notice appear in
10  * all copies of the software and related documentation, and (ii) the names of
11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
12  * publicity relating to the software without the specific, prior written
13  * permission of Sam Leffler and Silicon Graphics.
14  * 
15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
18  * 
19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
24  * OF THIS SOFTWARE.
25  */
26
27 /*
28  * TIFF Library.
29  *
30  * Directory Tag Get & Set Routines.
31  * (and also some miscellaneous stuff)
32  */
33 #if (!defined(_FPDFAPI_MINI_) || defined(_TIFF_DECODER_)) && !defined(_USE_ADDIN_) && !defined _FX_NO_ANSIC_ && !defined(_FX_EMB_NOUSE_DECODER_)
34 #include "tiffiop.h"
35
36 /*
37  * These are used in the backwards compatibility code...
38  */
39 #define DATATYPE_VOID           0       /* !untyped data */
40 #define DATATYPE_INT            1       /* !signed integer data */
41 #define DATATYPE_UINT           2       /* !unsigned integer data */
42 #define DATATYPE_IEEEFP         3       /* !IEEE floating point data */
43
44 static void
45 setByteArray(void** vpp, void* vp, size_t nmemb, size_t elem_size)
46 {
47         if (*vpp)
48                 _TIFFfree(*vpp), *vpp = 0;
49         if (vp) {
50                 tmsize_t bytes = (tmsize_t)(nmemb * elem_size);
51                 if (elem_size && bytes / elem_size == nmemb)
52                         *vpp = (void*) _TIFFmalloc(bytes);
53                 if (*vpp)
54                         _TIFFmemcpy(*vpp, vp, bytes);
55         }
56 }
57 void _TIFFsetByteArray(void** vpp, void* vp, uint32 n)
58     { setByteArray(vpp, vp, n, 1); }
59 void _TIFFsetString(char** cpp, char* cp)
60     { setByteArray((void**) cpp, (void*) cp, strlen(cp)+1, 1); }
61 void _TIFFsetNString(char** cpp, char* cp, uint32 n)
62     { setByteArray((void**) cpp, (void*) cp, n, 1); }
63 void _TIFFsetShortArray(uint16** wpp, uint16* wp, uint32 n)
64     { setByteArray((void**) wpp, (void*) wp, n, sizeof (uint16)); }
65 void _TIFFsetLongArray(uint32** lpp, uint32* lp, uint32 n)
66     { setByteArray((void**) lpp, (void*) lp, n, sizeof (uint32)); }
67 void _TIFFsetLong8Array(uint64** lpp, uint64* lp, uint32 n)
68     { setByteArray((void**) lpp, (void*) lp, n, sizeof (uint64)); }
69 void _TIFFsetFloatArray(float** fpp, float* fp, uint32 n)
70     { setByteArray((void**) fpp, (void*) fp, n, sizeof (float)); }
71 void _TIFFsetDoubleArray(double** dpp, double* dp, uint32 n)
72     { setByteArray((void**) dpp, (void*) dp, n, sizeof (double)); }
73
74 static void
75 setDoubleArrayOneValue(double** vpp, double value, size_t nmemb)
76 {
77         if (*vpp)
78                 _TIFFfree(*vpp);
79         *vpp = _TIFFmalloc(nmemb*sizeof(double));
80         if (*vpp)
81         {
82                 while (nmemb--)
83                         ((double*)*vpp)[nmemb] = value;
84         }
85 }
86
87 /*
88  * Install extra samples information.
89  */
90 static int
91 setExtraSamples(TIFFDirectory* td, va_list ap, uint32* v)
92 {
93 /* XXX: Unassociated alpha data == 999 is a known Corel Draw bug, see below */
94 #define EXTRASAMPLE_COREL_UNASSALPHA 999 
95
96         uint16* va;
97         uint32 i;
98
99         *v = (uint16) va_arg(ap, uint16_vap);
100         if ((uint16) *v > td->td_samplesperpixel)
101                 return 0;
102         va = va_arg(ap, uint16*);
103         if (*v > 0 && va == NULL)               /* typically missing param */
104                 return 0;
105         for (i = 0; i < *v; i++) {
106                 if (va[i] > EXTRASAMPLE_UNASSALPHA) {
107                         /*
108                          * XXX: Corel Draw is known to produce incorrect
109                          * ExtraSamples tags which must be patched here if we
110                          * want to be able to open some of the damaged TIFF
111                          * files: 
112                          */
113                         if (va[i] == EXTRASAMPLE_COREL_UNASSALPHA)
114                                 va[i] = EXTRASAMPLE_UNASSALPHA;
115                         else
116                                 return 0;
117                 }
118         }
119         td->td_extrasamples = (uint16) *v;
120         _TIFFsetShortArray(&td->td_sampleinfo, va, td->td_extrasamples);
121         return 1;
122
123 #undef EXTRASAMPLE_COREL_UNASSALPHA
124 }
125
126 /*
127  * Confirm we have "samplesperpixel" ink names separated by \0.  Returns 
128  * zero if the ink names are not as expected.
129  */
130 static uint32
131 checkInkNamesString(TIFF* tif, uint32 slen, const char* s)
132 {
133         TIFFDirectory* td = &tif->tif_dir;
134         uint16 i = td->td_samplesperpixel;
135
136         if (slen > 0) {
137                 const char* ep = s+slen;
138                 const char* cp = s;
139                 for (; i > 0; i--) {
140                         for (; cp < ep && *cp != '\0'; cp++) {}
141                         if (cp >= ep)
142                                 goto bad;
143                         cp++;                           /* skip \0 */
144                 }
145                 return ((uint32)(cp-s));
146         }
147 bad:
148         TIFFErrorExt(tif->tif_clientdata, "TIFFSetField",
149             "%s: Invalid InkNames value; expecting %d names, found %d",
150             tif->tif_name,
151             td->td_samplesperpixel,
152             td->td_samplesperpixel-i);
153         return (0);
154 }
155
156 static int
157 _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
158 {
159         static const char module[] = "_TIFFVSetField";
160
161         TIFFDirectory* td = &tif->tif_dir;
162         int status = 1;
163         uint32 v32, i, v;
164         char* s;
165         const TIFFField *fip = TIFFFindField(tif, tag, TIFF_ANY);
166         uint32 standard_tag = tag;
167
168         /*
169          * We want to force the custom code to be used for custom
170          * fields even if the tag happens to match a well known 
171          * one - important for reinterpreted handling of standard
172          * tag values in custom directories (ie. EXIF) 
173          */
174         if (fip->field_bit == FIELD_CUSTOM) {
175                 standard_tag = 0;
176         }
177
178         switch (standard_tag) {
179         case TIFFTAG_SUBFILETYPE:
180                 td->td_subfiletype = (uint32) va_arg(ap, uint32);
181                 break;
182         case TIFFTAG_IMAGEWIDTH:
183                 td->td_imagewidth = (uint32) va_arg(ap, uint32);
184                 break;
185         case TIFFTAG_IMAGELENGTH:
186                 td->td_imagelength = (uint32) va_arg(ap, uint32);
187                 break;
188         case TIFFTAG_BITSPERSAMPLE:
189                 td->td_bitspersample = (uint16) va_arg(ap, uint16_vap);
190                 /*
191                  * If the data require post-decoding processing to byte-swap
192                  * samples, set it up here.  Note that since tags are required
193                  * to be ordered, compression code can override this behaviour
194                  * in the setup method if it wants to roll the post decoding
195                  * work in with its normal work.
196                  */
197                 if (tif->tif_flags & TIFF_SWAB) {
198                         if (td->td_bitspersample == 8)
199                                 tif->tif_postdecode = _TIFFNoPostDecode;
200                         else if (td->td_bitspersample == 16)
201                                 tif->tif_postdecode = _TIFFSwab16BitData;
202                         else if (td->td_bitspersample == 24)
203                                 tif->tif_postdecode = _TIFFSwab24BitData;
204                         else if (td->td_bitspersample == 32)
205                                 tif->tif_postdecode = _TIFFSwab32BitData;
206                         else if (td->td_bitspersample == 64)
207                                 tif->tif_postdecode = _TIFFSwab64BitData;
208                         else if (td->td_bitspersample == 128) /* two 64's */
209                                 tif->tif_postdecode = _TIFFSwab64BitData;
210                 }
211                 break;
212         case TIFFTAG_COMPRESSION:
213                 v = (uint16) va_arg(ap, uint16_vap);
214                 /*
215                  * If we're changing the compression scheme, the notify the
216                  * previous module so that it can cleanup any state it's
217                  * setup.
218                  */
219                 if (TIFFFieldSet(tif, FIELD_COMPRESSION)) {
220                         if ((uint32)td->td_compression == v)
221                                 break;
222                         (*tif->tif_cleanup)(tif);
223                         tif->tif_flags &= ~TIFF_CODERSETUP;
224                 }
225                 /*
226                  * Setup new compression routine state.
227                  */
228                 if( (status = TIFFSetCompressionScheme(tif, v)) != 0 )
229                     td->td_compression = (uint16) v;
230                 else
231                     status = 0;
232                 break;
233         case TIFFTAG_PHOTOMETRIC:
234                 td->td_photometric = (uint16) va_arg(ap, uint16_vap);
235                 break;
236         case TIFFTAG_THRESHHOLDING:
237                 td->td_threshholding = (uint16) va_arg(ap, uint16_vap);
238                 break;
239         case TIFFTAG_FILLORDER:
240                 v = (uint16) va_arg(ap, uint16_vap);
241                 if (v != FILLORDER_LSB2MSB && v != FILLORDER_MSB2LSB)
242                         goto badvalue;
243                 td->td_fillorder = (uint16) v;
244                 break;
245         case TIFFTAG_ORIENTATION:
246                 v = (uint16) va_arg(ap, uint16_vap);
247                 if (v < ORIENTATION_TOPLEFT || ORIENTATION_LEFTBOT < v)
248                         goto badvalue;
249                 else
250                         td->td_orientation = (uint16) v;
251                 break;
252         case TIFFTAG_SAMPLESPERPIXEL:
253                 v = (uint16) va_arg(ap, uint16_vap);
254                 if (v == 0)
255                         goto badvalue;
256                 td->td_samplesperpixel = (uint16) v;
257                 break;
258         case TIFFTAG_ROWSPERSTRIP:
259                 v32 = (uint32) va_arg(ap, uint32);
260                 if (v32 == 0)
261                         goto badvalue32;
262                 td->td_rowsperstrip = v32;
263                 if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
264                         td->td_tilelength = v32;
265                         td->td_tilewidth = td->td_imagewidth;
266                 }
267                 break;
268         case TIFFTAG_MINSAMPLEVALUE:
269                 td->td_minsamplevalue = (uint16) va_arg(ap, uint16_vap);
270                 break;
271         case TIFFTAG_MAXSAMPLEVALUE:
272                 td->td_maxsamplevalue = (uint16) va_arg(ap, uint16_vap);
273                 break;
274         case TIFFTAG_SMINSAMPLEVALUE:
275                 if (tif->tif_flags & TIFF_PERSAMPLE)
276                         _TIFFsetDoubleArray(&td->td_sminsamplevalue, va_arg(ap, double*), td->td_samplesperpixel);
277                 else
278                         setDoubleArrayOneValue(&td->td_sminsamplevalue, va_arg(ap, double), td->td_samplesperpixel);
279                 break;
280         case TIFFTAG_SMAXSAMPLEVALUE:
281                 if (tif->tif_flags & TIFF_PERSAMPLE)
282                         _TIFFsetDoubleArray(&td->td_smaxsamplevalue, va_arg(ap, double*), td->td_samplesperpixel);
283                 else
284                         setDoubleArrayOneValue(&td->td_smaxsamplevalue, va_arg(ap, double), td->td_samplesperpixel);
285                 break;
286         case TIFFTAG_XRESOLUTION:
287                 td->td_xresolution = (float) va_arg(ap, double);
288                 break;
289         case TIFFTAG_YRESOLUTION:
290                 td->td_yresolution = (float) va_arg(ap, double);
291                 break;
292         case TIFFTAG_PLANARCONFIG:
293                 v = (uint16) va_arg(ap, uint16_vap);
294                 if (v != PLANARCONFIG_CONTIG && v != PLANARCONFIG_SEPARATE)
295                         goto badvalue;
296                 td->td_planarconfig = (uint16) v;
297                 break;
298         case TIFFTAG_XPOSITION:
299                 td->td_xposition = (float) va_arg(ap, double);
300                 break;
301         case TIFFTAG_YPOSITION:
302                 td->td_yposition = (float) va_arg(ap, double);
303                 break;
304         case TIFFTAG_RESOLUTIONUNIT:
305                 v = (uint16) va_arg(ap, uint16_vap);
306                 if (v < RESUNIT_NONE || RESUNIT_CENTIMETER < v)
307                         goto badvalue;
308                 td->td_resolutionunit = (uint16) v;
309                 break;
310         case TIFFTAG_PAGENUMBER:
311                 td->td_pagenumber[0] = (uint16) va_arg(ap, uint16_vap);
312                 td->td_pagenumber[1] = (uint16) va_arg(ap, uint16_vap);
313                 break;
314         case TIFFTAG_HALFTONEHINTS:
315                 td->td_halftonehints[0] = (uint16) va_arg(ap, uint16_vap);
316                 td->td_halftonehints[1] = (uint16) va_arg(ap, uint16_vap);
317                 break;
318         case TIFFTAG_COLORMAP:
319                 v32 = (uint32)(1L<<td->td_bitspersample);
320                 _TIFFsetShortArray(&td->td_colormap[0], va_arg(ap, uint16*), v32);
321                 _TIFFsetShortArray(&td->td_colormap[1], va_arg(ap, uint16*), v32);
322                 _TIFFsetShortArray(&td->td_colormap[2], va_arg(ap, uint16*), v32);
323                 break;
324         case TIFFTAG_EXTRASAMPLES:
325                 if (!setExtraSamples(td, ap, &v))
326                         goto badvalue;
327                 break;
328         case TIFFTAG_MATTEING:
329                 td->td_extrasamples =  (((uint16) va_arg(ap, uint16_vap)) != 0);
330                 if (td->td_extrasamples) {
331                         uint16 sv = EXTRASAMPLE_ASSOCALPHA;
332                         _TIFFsetShortArray(&td->td_sampleinfo, &sv, 1);
333                 }
334                 break;
335         case TIFFTAG_TILEWIDTH:
336                 v32 = (uint32) va_arg(ap, uint32);
337                 if (v32 % 16) {
338                         if (tif->tif_mode != O_RDONLY)
339                                 goto badvalue32;
340                         TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
341                                 "Nonstandard tile width %d, convert file", v32);
342                 }
343                 td->td_tilewidth = v32;
344                 tif->tif_flags |= TIFF_ISTILED;
345                 break;
346         case TIFFTAG_TILELENGTH:
347                 v32 = (uint32) va_arg(ap, uint32);
348                 if (v32 % 16) {
349                         if (tif->tif_mode != O_RDONLY)
350                                 goto badvalue32;
351                         TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
352                             "Nonstandard tile length %d, convert file", v32);
353                 }
354                 td->td_tilelength = v32;
355                 tif->tif_flags |= TIFF_ISTILED;
356                 break;
357         case TIFFTAG_TILEDEPTH:
358                 v32 = (uint32) va_arg(ap, uint32);
359                 if (v32 == 0)
360                         goto badvalue32;
361                 td->td_tiledepth = v32;
362                 break;
363         case TIFFTAG_DATATYPE:
364                 v = (uint16) va_arg(ap, uint16_vap);
365                 switch (v) {
366                 case DATATYPE_VOID:     v = SAMPLEFORMAT_VOID;  break;
367                 case DATATYPE_INT:      v = SAMPLEFORMAT_INT;   break;
368                 case DATATYPE_UINT:     v = SAMPLEFORMAT_UINT;  break;
369                 case DATATYPE_IEEEFP:   v = SAMPLEFORMAT_IEEEFP;break;
370                 default:                goto badvalue;
371                 }
372                 td->td_sampleformat = (uint16) v;
373                 break;
374         case TIFFTAG_SAMPLEFORMAT:
375                 v = (uint16) va_arg(ap, uint16_vap);
376                 if (v < SAMPLEFORMAT_UINT || SAMPLEFORMAT_COMPLEXIEEEFP < v)
377                         goto badvalue;
378                 td->td_sampleformat = (uint16) v;
379
380                 /*  Try to fix up the SWAB function for complex data. */
381                 if( td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT
382                     && td->td_bitspersample == 32
383                     && tif->tif_postdecode == _TIFFSwab32BitData )
384                     tif->tif_postdecode = _TIFFSwab16BitData;
385                 else if( (td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT
386                           || td->td_sampleformat == SAMPLEFORMAT_COMPLEXIEEEFP)
387                          && td->td_bitspersample == 64
388                          && tif->tif_postdecode == _TIFFSwab64BitData )
389                     tif->tif_postdecode = _TIFFSwab32BitData;
390                 break;
391         case TIFFTAG_IMAGEDEPTH:
392                 td->td_imagedepth = (uint32) va_arg(ap, uint32);
393                 break;
394         case TIFFTAG_SUBIFD:
395                 if ((tif->tif_flags & TIFF_INSUBIFD) == 0) {
396                         td->td_nsubifd = (uint16) va_arg(ap, uint16_vap);
397                         _TIFFsetLong8Array(&td->td_subifd, (uint64*) va_arg(ap, uint64*),
398                             (long) td->td_nsubifd);
399                 } else {
400                         TIFFErrorExt(tif->tif_clientdata, module,
401                                      "%s: Sorry, cannot nest SubIFDs",
402                                      tif->tif_name);
403                         status = 0;
404                 }
405                 break;
406         case TIFFTAG_YCBCRPOSITIONING:
407                 td->td_ycbcrpositioning = (uint16) va_arg(ap, uint16_vap);
408                 break;
409         case TIFFTAG_YCBCRSUBSAMPLING:
410                 td->td_ycbcrsubsampling[0] = (uint16) va_arg(ap, uint16_vap);
411                 td->td_ycbcrsubsampling[1] = (uint16) va_arg(ap, uint16_vap);
412                 break;
413         case TIFFTAG_TRANSFERFUNCTION:
414                 v = (td->td_samplesperpixel - td->td_extrasamples) > 1 ? 3 : 1;
415                 for (i = 0; i < v; i++)
416                         _TIFFsetShortArray(&td->td_transferfunction[i],
417                             va_arg(ap, uint16*), 1L<<td->td_bitspersample);
418                 break;
419         case TIFFTAG_REFERENCEBLACKWHITE:
420                 /* XXX should check for null range */
421                 _TIFFsetFloatArray(&td->td_refblackwhite, va_arg(ap, float*), 6);
422                 break;
423         case TIFFTAG_INKNAMES:
424                 v = (uint16) va_arg(ap, uint16_vap);
425                 s = va_arg(ap, char*);
426                 v = checkInkNamesString(tif, v, s);
427                 status = v > 0;
428                 if( v > 0 ) {
429                         _TIFFsetNString(&td->td_inknames, s, v);
430                         td->td_inknameslen = v;
431                 }
432                 break;
433         case TIFFTAG_PERSAMPLE:
434                 v = (uint16) va_arg(ap, uint16_vap);
435                 if( v == PERSAMPLE_MULTI )
436                         tif->tif_flags |= TIFF_PERSAMPLE;
437                 else
438                         tif->tif_flags &= ~TIFF_PERSAMPLE;
439                 break;
440         default: {
441                 TIFFTagValue *tv;
442                 int tv_size, iCustom;
443
444                 /*
445                  * This can happen if multiple images are open with different
446                  * codecs which have private tags.  The global tag information
447                  * table may then have tags that are valid for one file but not
448                  * the other. If the client tries to set a tag that is not valid
449                  * for the image's codec then we'll arrive here.  This
450                  * happens, for example, when tiffcp is used to convert between
451                  * compression schemes and codec-specific tags are blindly copied.
452                  */
453                 if(fip == NULL || fip->field_bit != FIELD_CUSTOM) {
454                         TIFFErrorExt(tif->tif_clientdata, module,
455                             "%s: Invalid %stag \"%s\" (not supported by codec)",
456                             tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "",
457                             fip ? fip->field_name : "Unknown");
458                         status = 0;
459                         break;
460                 }
461
462                 /*
463                  * Find the existing entry for this custom value.
464                  */
465                 tv = NULL;
466                 for (iCustom = 0; iCustom < td->td_customValueCount; iCustom++) {
467                         if (td->td_customValues[iCustom].info->field_tag == tag) {
468                                 tv = td->td_customValues + iCustom;
469                                 if (tv->value != NULL) {
470                                         _TIFFfree(tv->value);
471                                         tv->value = NULL;
472                                 }
473                                 break;
474                         }
475                 }
476
477                 /*
478                  * Grow the custom list if the entry was not found.
479                  */
480                 if(tv == NULL) {
481                         TIFFTagValue *new_customValues;
482
483                         td->td_customValueCount++;
484                         new_customValues = (TIFFTagValue *)
485                             _TIFFrealloc(td->td_customValues,
486                             sizeof(TIFFTagValue) * td->td_customValueCount);
487                         if (!new_customValues) {
488                                 TIFFErrorExt(tif->tif_clientdata, module,
489                                     "%s: Failed to allocate space for list of custom values",
490                                     tif->tif_name);
491                                 status = 0;
492                                 goto end;
493                         }
494
495                         td->td_customValues = new_customValues;
496
497                         tv = td->td_customValues + (td->td_customValueCount - 1);
498                         tv->info = fip;
499                         tv->value = NULL;
500                         tv->count = 0;
501                 }
502
503                 /*
504                  * Set custom value ... save a copy of the custom tag value.
505                  */
506                 tv_size = _TIFFDataSize(fip->field_type);
507                 if (tv_size == 0) {
508                         status = 0;
509                         TIFFErrorExt(tif->tif_clientdata, module,
510                             "%s: Bad field type %d for \"%s\"",
511                             tif->tif_name, fip->field_type,
512                             fip->field_name);
513                         goto end;
514                 }
515
516                 if (fip->field_type == TIFF_ASCII)
517                 {
518                         uint32 ma;
519                         char* mb;
520                         if (fip->field_passcount)
521                         {
522                                 assert(fip->field_writecount==TIFF_VARIABLE2);
523                                 ma=(uint32)va_arg(ap,uint32);
524                                 mb=(char*)va_arg(ap,char*);
525                         }
526                         else
527                         {
528                                 mb=(char*)va_arg(ap,char*);
529                                 ma=(uint32)(strlen(mb)+1);
530                         }
531                         tv->count=ma;
532                         setByteArray(&tv->value,mb,ma,1);
533                 }
534                 else
535                 {
536                         if (fip->field_passcount) {
537                                 if (fip->field_writecount == TIFF_VARIABLE2)
538                                         tv->count = (uint32) va_arg(ap, uint32);
539                                 else
540                                         tv->count = (int) va_arg(ap, int);
541                         } else if (fip->field_writecount == TIFF_VARIABLE
542                            || fip->field_writecount == TIFF_VARIABLE2)
543                                 tv->count = 1;
544                         else if (fip->field_writecount == TIFF_SPP)
545                                 tv->count = td->td_samplesperpixel;
546                         else
547                                 tv->count = fip->field_writecount;
548
549                         if (tv->count == 0) {
550                                 status = 0;
551                                 TIFFErrorExt(tif->tif_clientdata, module,
552                                              "%s: Null count for \"%s\" (type "
553                                              "%d, writecount %d, passcount %d)",
554                                              tif->tif_name,
555                                              fip->field_name,
556                                              fip->field_type,
557                                              fip->field_writecount,
558                                              fip->field_passcount);
559                                 goto end;
560                         }
561
562                         tv->value = _TIFFCheckMalloc(tif, tv->count, tv_size,
563                             "custom tag binary object");
564                         if (!tv->value) {
565                                 status = 0;
566                                 goto end;
567                         }
568
569                         if (fip->field_tag == TIFFTAG_DOTRANGE 
570                             && strcmp(fip->field_name,"DotRange") == 0) {
571                                 /* TODO: This is an evil exception and should not have been
572                                    handled this way ... likely best if we move it into
573                                    the directory structure with an explicit field in 
574                                    libtiff 4.1 and assign it a FIELD_ value */
575                                 uint16 v[2];
576                                 v[0] = (uint16)va_arg(ap, int);
577                                 v[1] = (uint16)va_arg(ap, int);
578                                 _TIFFmemcpy(tv->value, &v, 4);
579                         }
580
581                         else if (fip->field_passcount
582                                   || fip->field_writecount == TIFF_VARIABLE
583                                   || fip->field_writecount == TIFF_VARIABLE2
584                                   || fip->field_writecount == TIFF_SPP
585                                   || tv->count > 1) {
586                                 _TIFFmemcpy(tv->value, va_arg(ap, void *),
587                                     tv->count * tv_size);
588                         } else {
589                                 char *val = (char *)tv->value;
590                                 assert( tv->count == 1 );
591
592                                 switch (fip->field_type) {
593                                 case TIFF_BYTE:
594                                 case TIFF_UNDEFINED:
595                                         {
596                                                 uint8 v = (uint8)va_arg(ap, int);
597                                                 _TIFFmemcpy(val, &v, tv_size);
598                                         }
599                                         break;
600                                 case TIFF_SBYTE:
601                                         {
602                                                 int8 v = (int8)va_arg(ap, int);
603                                                 _TIFFmemcpy(val, &v, tv_size);
604                                         }
605                                         break;
606                                 case TIFF_SHORT:
607                                         {
608                                                 uint16 v = (uint16)va_arg(ap, int);
609                                                 _TIFFmemcpy(val, &v, tv_size);
610                                         }
611                                         break;
612                                 case TIFF_SSHORT:
613                                         {
614                                                 int16 v = (int16)va_arg(ap, int);
615                                                 _TIFFmemcpy(val, &v, tv_size);
616                                         }
617                                         break;
618                                 case TIFF_LONG:
619                                 case TIFF_IFD:
620                                         {
621                                                 uint32 v = va_arg(ap, uint32);
622                                                 _TIFFmemcpy(val, &v, tv_size);
623                                         }
624                                         break;
625                                 case TIFF_SLONG:
626                                         {
627                                                 int32 v = va_arg(ap, int32);
628                                                 _TIFFmemcpy(val, &v, tv_size);
629                                         }
630                                         break;
631                                 case TIFF_LONG8:
632                                 case TIFF_IFD8:
633                                         {
634                                                 uint64 v = va_arg(ap, uint64);
635                                                 _TIFFmemcpy(val, &v, tv_size);
636                                         }
637                                         break;
638                                 case TIFF_SLONG8:
639                                         {
640                                                 int64 v = va_arg(ap, int64);
641                                                 _TIFFmemcpy(val, &v, tv_size);
642                                         }
643                                         break;
644                                 case TIFF_RATIONAL:
645                                 case TIFF_SRATIONAL:
646                                 case TIFF_FLOAT:
647                                         {
648                                                 float v = (float)va_arg(ap, double);
649                                                 _TIFFmemcpy(val, &v, tv_size);
650                                         }
651                                         break;
652                                 case TIFF_DOUBLE:
653                                         {
654                                                 double v = va_arg(ap, double);
655                                                 _TIFFmemcpy(val, &v, tv_size);
656                                         }
657                                         break;
658                                 default:
659                                         _TIFFmemset(val, 0, tv_size);
660                                         status = 0;
661                                         break;
662                                 }
663                         }
664                 }
665         }
666         }
667         if (status) {
668                 const TIFFField* fip=TIFFFieldWithTag(tif,tag);
669                 if (fip)                
670                         TIFFSetFieldBit(tif, fip->field_bit);
671                 tif->tif_flags |= TIFF_DIRTYDIRECT;
672         }
673
674 end:
675         va_end(ap);
676         return (status);
677 badvalue:
678         {
679                 const TIFFField* fip=TIFFFieldWithTag(tif,tag);
680                 TIFFErrorExt(tif->tif_clientdata, module,
681                      "%s: Bad value %u for \"%s\" tag",
682                      tif->tif_name, v,
683                      fip ? fip->field_name : "Unknown");
684                 va_end(ap);
685         }
686         return (0);
687 badvalue32:
688         {
689                 const TIFFField* fip=TIFFFieldWithTag(tif,tag);
690                 TIFFErrorExt(tif->tif_clientdata, module,
691                      "%s: Bad value %u for \"%s\" tag",
692                      tif->tif_name, v32,
693                      fip ? fip->field_name : "Unknown");
694                 va_end(ap);
695         }
696         return (0);
697 }
698
699 /*
700  * Return 1/0 according to whether or not
701  * it is permissible to set the tag's value.
702  * Note that we allow ImageLength to be changed
703  * so that we can append and extend to images.
704  * Any other tag may not be altered once writing
705  * has commenced, unless its value has no effect
706  * on the format of the data that is written.
707  */
708 static int
709 OkToChangeTag(TIFF* tif, uint32 tag)
710 {
711         const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
712         if (!fip) {                     /* unknown tag */
713                 TIFFErrorExt(tif->tif_clientdata, "TIFFSetField", "%s: Unknown %stag %u",
714                     tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "", tag);
715                 return (0);
716         }
717         if (tag != TIFFTAG_IMAGELENGTH && (tif->tif_flags & TIFF_BEENWRITING) &&
718             !fip->field_oktochange) {
719                 /*
720                  * Consult info table to see if tag can be changed
721                  * after we've started writing.  We only allow changes
722                  * to those tags that don't/shouldn't affect the
723                  * compression and/or format of the data.
724                  */
725                 TIFFErrorExt(tif->tif_clientdata, "TIFFSetField",
726                     "%s: Cannot modify tag \"%s\" while writing",
727                     tif->tif_name, fip->field_name);
728                 return (0);
729         }
730         return (1);
731 }
732
733 /*
734  * Record the value of a field in the
735  * internal directory structure.  The
736  * field will be written to the file
737  * when/if the directory structure is
738  * updated.
739  */
740 int
741 TIFFSetField(TIFF* tif, uint32 tag, ...)
742 {
743         va_list ap;
744         int status;
745
746         va_start(ap, tag);
747         status = TIFFVSetField(tif, tag, ap);
748         va_end(ap);
749         return (status);
750 }
751
752 /*
753  * Clear the contents of the field in the internal structure.
754  */
755 int
756 TIFFUnsetField(TIFF* tif, uint32 tag)
757 {
758     const TIFFField *fip =  TIFFFieldWithTag(tif, tag);
759     TIFFDirectory* td = &tif->tif_dir;
760
761     if( !fip )
762         return 0;
763
764     if( fip->field_bit != FIELD_CUSTOM )
765         TIFFClrFieldBit(tif, fip->field_bit);
766     else
767     {
768         TIFFTagValue *tv = NULL;
769         int i;
770
771         for (i = 0; i < td->td_customValueCount; i++) {
772                 
773             tv = td->td_customValues + i;
774             if( tv->info->field_tag == tag )
775                 break;
776         }
777
778         if( i < td->td_customValueCount )
779         {
780             _TIFFfree(tv->value);
781             for( ; i < td->td_customValueCount-1; i++) {
782                 td->td_customValues[i] = td->td_customValues[i+1];
783             }
784             td->td_customValueCount--;
785         }
786     }
787         
788     tif->tif_flags |= TIFF_DIRTYDIRECT;
789
790     return (1);
791 }
792
793 /*
794  * Like TIFFSetField, but taking a varargs
795  * parameter list.  This routine is useful
796  * for building higher-level interfaces on
797  * top of the library.
798  */
799 int
800 TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
801 {
802         return OkToChangeTag(tif, tag) ?
803             (*tif->tif_tagmethods.vsetfield)(tif, tag, ap) : 0;
804 }
805
806 static int
807 _TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
808 {
809         TIFFDirectory* td = &tif->tif_dir;
810         int ret_val = 1;
811         uint32 standard_tag = tag;
812         const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
813         
814         /*
815          * We want to force the custom code to be used for custom
816          * fields even if the tag happens to match a well known 
817          * one - important for reinterpreted handling of standard
818          * tag values in custom directories (ie. EXIF) 
819          */
820         if (fip->field_bit == FIELD_CUSTOM) {
821                 standard_tag = 0;
822         }
823
824         switch (standard_tag) {
825                 case TIFFTAG_SUBFILETYPE:
826                         *va_arg(ap, uint32*) = td->td_subfiletype;
827                         break;
828                 case TIFFTAG_IMAGEWIDTH:
829                         *va_arg(ap, uint32*) = td->td_imagewidth;
830                         break;
831                 case TIFFTAG_IMAGELENGTH:
832                         *va_arg(ap, uint32*) = td->td_imagelength;
833                         break;
834                 case TIFFTAG_BITSPERSAMPLE:
835                         *va_arg(ap, uint16*) = td->td_bitspersample;
836                         break;
837                 case TIFFTAG_COMPRESSION:
838                         *va_arg(ap, uint16*) = td->td_compression;
839                         break;
840                 case TIFFTAG_PHOTOMETRIC:
841                         *va_arg(ap, uint16*) = td->td_photometric;
842                         break;
843                 case TIFFTAG_THRESHHOLDING:
844                         *va_arg(ap, uint16*) = td->td_threshholding;
845                         break;
846                 case TIFFTAG_FILLORDER:
847                         *va_arg(ap, uint16*) = td->td_fillorder;
848                         break;
849                 case TIFFTAG_ORIENTATION:
850                         *va_arg(ap, uint16*) = td->td_orientation;
851                         break;
852                 case TIFFTAG_SAMPLESPERPIXEL:
853                         *va_arg(ap, uint16*) = td->td_samplesperpixel;
854                         break;
855                 case TIFFTAG_ROWSPERSTRIP:
856                         *va_arg(ap, uint32*) = td->td_rowsperstrip;
857                         break;
858                 case TIFFTAG_MINSAMPLEVALUE:
859                         *va_arg(ap, uint16*) = td->td_minsamplevalue;
860                         break;
861                 case TIFFTAG_MAXSAMPLEVALUE:
862                         *va_arg(ap, uint16*) = td->td_maxsamplevalue;
863                         break;
864                 case TIFFTAG_SMINSAMPLEVALUE:
865                         if (tif->tif_flags & TIFF_PERSAMPLE)
866                                 *va_arg(ap, double**) = td->td_sminsamplevalue;
867                         else
868                         {
869                                 /* libtiff historially treats this as a single value. */
870                                 uint16 i;
871                                 double v = td->td_sminsamplevalue[0];
872                                 for (i=1; i < td->td_samplesperpixel; ++i)
873                                         if( td->td_sminsamplevalue[i] < v )
874                                                 v = td->td_sminsamplevalue[i];
875                                 *va_arg(ap, double*) = v;
876                         }
877                         break;
878                 case TIFFTAG_SMAXSAMPLEVALUE:
879                         if (tif->tif_flags & TIFF_PERSAMPLE)
880                                 *va_arg(ap, double**) = td->td_smaxsamplevalue;
881                         else
882                         {
883                                 /* libtiff historially treats this as a single value. */
884                                 uint16 i;
885                                 double v = td->td_smaxsamplevalue[0];
886                                 for (i=1; i < td->td_samplesperpixel; ++i)
887                                         if( td->td_smaxsamplevalue[i] > v )
888                                                 v = td->td_smaxsamplevalue[i];
889                                 *va_arg(ap, double*) = v;
890                         }
891                         break;
892                 case TIFFTAG_XRESOLUTION:
893                         *va_arg(ap, float*) = td->td_xresolution;
894                         break;
895                 case TIFFTAG_YRESOLUTION:
896                         *va_arg(ap, float*) = td->td_yresolution;
897                         break;
898                 case TIFFTAG_PLANARCONFIG:
899                         *va_arg(ap, uint16*) = td->td_planarconfig;
900                         break;
901                 case TIFFTAG_XPOSITION:
902                         *va_arg(ap, float*) = td->td_xposition;
903                         break;
904                 case TIFFTAG_YPOSITION:
905                         *va_arg(ap, float*) = td->td_yposition;
906                         break;
907                 case TIFFTAG_RESOLUTIONUNIT:
908                         *va_arg(ap, uint16*) = td->td_resolutionunit;
909                         break;
910                 case TIFFTAG_PAGENUMBER:
911                         *va_arg(ap, uint16*) = td->td_pagenumber[0];
912                         *va_arg(ap, uint16*) = td->td_pagenumber[1];
913                         break;
914                 case TIFFTAG_HALFTONEHINTS:
915                         *va_arg(ap, uint16*) = td->td_halftonehints[0];
916                         *va_arg(ap, uint16*) = td->td_halftonehints[1];
917                         break;
918                 case TIFFTAG_COLORMAP:
919                         *va_arg(ap, uint16**) = td->td_colormap[0];
920                         *va_arg(ap, uint16**) = td->td_colormap[1];
921                         *va_arg(ap, uint16**) = td->td_colormap[2];
922                         break;
923                 case TIFFTAG_STRIPOFFSETS:
924                 case TIFFTAG_TILEOFFSETS:
925                         _TIFFFillStriles( tif );
926                         *va_arg(ap, uint64**) = td->td_stripoffset;
927                         break;
928                 case TIFFTAG_STRIPBYTECOUNTS:
929                 case TIFFTAG_TILEBYTECOUNTS:
930                         _TIFFFillStriles( tif );
931                         *va_arg(ap, uint64**) = td->td_stripbytecount;
932                         break;
933                 case TIFFTAG_MATTEING:
934                         *va_arg(ap, uint16*) =
935                             (td->td_extrasamples == 1 &&
936                             td->td_sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
937                         break;
938                 case TIFFTAG_EXTRASAMPLES:
939                         *va_arg(ap, uint16*) = td->td_extrasamples;
940                         *va_arg(ap, uint16**) = td->td_sampleinfo;
941                         break;
942                 case TIFFTAG_TILEWIDTH:
943                         *va_arg(ap, uint32*) = td->td_tilewidth;
944                         break;
945                 case TIFFTAG_TILELENGTH:
946                         *va_arg(ap, uint32*) = td->td_tilelength;
947                         break;
948                 case TIFFTAG_TILEDEPTH:
949                         *va_arg(ap, uint32*) = td->td_tiledepth;
950                         break;
951                 case TIFFTAG_DATATYPE:
952                         switch (td->td_sampleformat) {
953                                 case SAMPLEFORMAT_UINT:
954                                         *va_arg(ap, uint16*) = DATATYPE_UINT;
955                                         break;
956                                 case SAMPLEFORMAT_INT:
957                                         *va_arg(ap, uint16*) = DATATYPE_INT;
958                                         break;
959                                 case SAMPLEFORMAT_IEEEFP:
960                                         *va_arg(ap, uint16*) = DATATYPE_IEEEFP;
961                                         break;
962                                 case SAMPLEFORMAT_VOID:
963                                         *va_arg(ap, uint16*) = DATATYPE_VOID;
964                                         break;
965                         }
966                         break;
967                 case TIFFTAG_SAMPLEFORMAT:
968                         *va_arg(ap, uint16*) = td->td_sampleformat;
969                         break;
970                 case TIFFTAG_IMAGEDEPTH:
971                         *va_arg(ap, uint32*) = td->td_imagedepth;
972                         break;
973                 case TIFFTAG_SUBIFD:
974                         *va_arg(ap, uint16*) = td->td_nsubifd;
975                         *va_arg(ap, uint64**) = td->td_subifd;
976                         break;
977                 case TIFFTAG_YCBCRPOSITIONING:
978                         *va_arg(ap, uint16*) = td->td_ycbcrpositioning;
979                         break;
980                 case TIFFTAG_YCBCRSUBSAMPLING:
981                         *va_arg(ap, uint16*) = td->td_ycbcrsubsampling[0];
982                         *va_arg(ap, uint16*) = td->td_ycbcrsubsampling[1];
983                         break;
984                 case TIFFTAG_TRANSFERFUNCTION:
985                         *va_arg(ap, uint16**) = td->td_transferfunction[0];
986                         if (td->td_samplesperpixel - td->td_extrasamples > 1) {
987                                 *va_arg(ap, uint16**) = td->td_transferfunction[1];
988                                 *va_arg(ap, uint16**) = td->td_transferfunction[2];
989                         }
990                         break;
991                 case TIFFTAG_REFERENCEBLACKWHITE:
992                         *va_arg(ap, float**) = td->td_refblackwhite;
993                         break;
994                 case TIFFTAG_INKNAMES:
995                         *va_arg(ap, char**) = td->td_inknames;
996                         break;
997                 default:
998                         {
999                                 int i;
1000
1001                                 /*
1002                                  * This can happen if multiple images are open
1003                                  * with different codecs which have private
1004                                  * tags.  The global tag information table may
1005                                  * then have tags that are valid for one file
1006                                  * but not the other. If the client tries to
1007                                  * get a tag that is not valid for the image's
1008                                  * codec then we'll arrive here.
1009                                  */
1010                                 if( fip == NULL || fip->field_bit != FIELD_CUSTOM )
1011                                 {
1012                                         TIFFErrorExt(tif->tif_clientdata, "_TIFFVGetField",
1013                                             "%s: Invalid %stag \"%s\" "
1014                                             "(not supported by codec)",
1015                                             tif->tif_name,
1016                                             isPseudoTag(tag) ? "pseudo-" : "",
1017                                             fip ? fip->field_name : "Unknown");
1018                                         ret_val = 0;
1019                                         break;
1020                                 }
1021
1022                                 /*
1023                                  * Do we have a custom value?
1024                                  */
1025                                 ret_val = 0;
1026                                 for (i = 0; i < td->td_customValueCount; i++) {
1027                                         TIFFTagValue *tv = td->td_customValues + i;
1028
1029                                         if (tv->info->field_tag != tag)
1030                                                 continue;
1031
1032                                         if (fip->field_passcount) {
1033                                                 if (fip->field_readcount == TIFF_VARIABLE2)
1034                                                         *va_arg(ap, uint32*) = (uint32)tv->count;
1035                                                 else  /* Assume TIFF_VARIABLE */
1036                                                         *va_arg(ap, uint16*) = (uint16)tv->count;
1037                                                 *va_arg(ap, void **) = tv->value;
1038                                                 ret_val = 1;
1039                                         } else if (fip->field_tag == TIFFTAG_DOTRANGE
1040                                                    && strcmp(fip->field_name,"DotRange") == 0) {
1041                                                 /* TODO: This is an evil exception and should not have been
1042                                                    handled this way ... likely best if we move it into
1043                                                    the directory structure with an explicit field in 
1044                                                    libtiff 4.1 and assign it a FIELD_ value */
1045                                                 *va_arg(ap, uint16*) = ((uint16 *)tv->value)[0];
1046                                                 *va_arg(ap, uint16*) = ((uint16 *)tv->value)[1];
1047                                                 ret_val = 1;
1048                                         } else {
1049                                                 if (fip->field_type == TIFF_ASCII
1050                                                     || fip->field_readcount == TIFF_VARIABLE
1051                                                     || fip->field_readcount == TIFF_VARIABLE2
1052                                                     || fip->field_readcount == TIFF_SPP
1053                                                     || tv->count > 1) {
1054                                                         *va_arg(ap, void **) = tv->value;
1055                                                         ret_val = 1;
1056                                                 } else {
1057                                                         char *val = (char *)tv->value;
1058                                                         assert( tv->count == 1 );
1059                                                         switch (fip->field_type) {
1060                                                         case TIFF_BYTE:
1061                                                         case TIFF_UNDEFINED:
1062                                                                 *va_arg(ap, uint8*) =
1063                                                                         *(uint8 *)val;
1064                                                                 ret_val = 1;
1065                                                                 break;
1066                                                         case TIFF_SBYTE:
1067                                                                 *va_arg(ap, int8*) =
1068                                                                         *(int8 *)val;
1069                                                                 ret_val = 1;
1070                                                                 break;
1071                                                         case TIFF_SHORT:
1072                                                                 *va_arg(ap, uint16*) =
1073                                                                         *(uint16 *)val;
1074                                                                 ret_val = 1;
1075                                                                 break;
1076                                                         case TIFF_SSHORT:
1077                                                                 *va_arg(ap, int16*) =
1078                                                                         *(int16 *)val;
1079                                                                 ret_val = 1;
1080                                                                 break;
1081                                                         case TIFF_LONG:
1082                                                         case TIFF_IFD:
1083                                                                 *va_arg(ap, uint32*) =
1084                                                                         *(uint32 *)val;
1085                                                                 ret_val = 1;
1086                                                                 break;
1087                                                         case TIFF_SLONG:
1088                                                                 *va_arg(ap, int32*) =
1089                                                                         *(int32 *)val;
1090                                                                 ret_val = 1;
1091                                                                 break;
1092                                                         case TIFF_LONG8:
1093                                                         case TIFF_IFD8:
1094                                                                 *va_arg(ap, uint64*) =
1095                                                                         *(uint64 *)val;
1096                                                                 ret_val = 1;
1097                                                                 break;
1098                                                         case TIFF_SLONG8:
1099                                                                 *va_arg(ap, int64*) =
1100                                                                         *(int64 *)val;
1101                                                                 ret_val = 1;
1102                                                                 break;
1103                                                         case TIFF_RATIONAL:
1104                                                         case TIFF_SRATIONAL:
1105                                                         case TIFF_FLOAT:
1106                                                                 *va_arg(ap, float*) =
1107                                                                         *(float *)val;
1108                                                                 ret_val = 1;
1109                                                                 break;
1110                                                         case TIFF_DOUBLE:
1111                                                                 *va_arg(ap, double*) =
1112                                                                         *(double *)val;
1113                                                                 ret_val = 1;
1114                                                                 break;
1115                                                         default:
1116                                                                 ret_val = 0;
1117                                                                 break;
1118                                                         }
1119                                                 }
1120                                         }
1121                                         break;
1122                                 }
1123                         }
1124         }
1125         return(ret_val);
1126 }
1127
1128 /*
1129  * Return the value of a field in the
1130  * internal directory structure.
1131  */
1132 int
1133 TIFFGetField(TIFF* tif, uint32 tag, ...)
1134 {
1135         int status;
1136         va_list ap;
1137
1138         va_start(ap, tag);
1139         status = TIFFVGetField(tif, tag, ap);
1140         va_end(ap);
1141         return (status);
1142 }
1143
1144 /*
1145  * Like TIFFGetField, but taking a varargs
1146  * parameter list.  This routine is useful
1147  * for building higher-level interfaces on
1148  * top of the library.
1149  */
1150 int
1151 TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
1152 {
1153         const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
1154         return (fip && (isPseudoTag(tag) || TIFFFieldSet(tif, fip->field_bit)) ?
1155             (*tif->tif_tagmethods.vgetfield)(tif, tag, ap) : 0);
1156 }
1157
1158 #define CleanupField(member) {          \
1159     if (td->member) {                   \
1160         _TIFFfree(td->member);          \
1161         td->member = 0;                 \
1162     }                                   \
1163 }
1164
1165 /*
1166  * Release storage associated with a directory.
1167  */
1168 void
1169 TIFFFreeDirectory(TIFF* tif)
1170 {
1171         TIFFDirectory *td = &tif->tif_dir;
1172         int            i;
1173
1174         _TIFFmemset(td->td_fieldsset, 0, FIELD_SETLONGS);
1175         CleanupField(td_sminsamplevalue);
1176         CleanupField(td_smaxsamplevalue);
1177         CleanupField(td_colormap[0]);
1178         CleanupField(td_colormap[1]);
1179         CleanupField(td_colormap[2]);
1180         CleanupField(td_sampleinfo);
1181         CleanupField(td_subifd);
1182         CleanupField(td_inknames);
1183         CleanupField(td_refblackwhite);
1184         CleanupField(td_transferfunction[0]);
1185         CleanupField(td_transferfunction[1]);
1186         CleanupField(td_transferfunction[2]);
1187         CleanupField(td_stripoffset);
1188         CleanupField(td_stripbytecount);
1189         TIFFClrFieldBit(tif, FIELD_YCBCRSUBSAMPLING);
1190         TIFFClrFieldBit(tif, FIELD_YCBCRPOSITIONING);
1191
1192         /* Cleanup custom tag values */
1193         for( i = 0; i < td->td_customValueCount; i++ ) {
1194                 if (td->td_customValues[i].value)
1195                         _TIFFfree(td->td_customValues[i].value);
1196         }
1197
1198         td->td_customValueCount = 0;
1199         CleanupField(td_customValues);
1200
1201 #if defined(DEFER_STRILE_LOAD)
1202         _TIFFmemset( &(td->td_stripoffset_entry), 0, sizeof(TIFFDirEntry));
1203         _TIFFmemset( &(td->td_stripbytecount_entry), 0, sizeof(TIFFDirEntry));
1204 #endif        
1205 }
1206 #undef CleanupField
1207
1208 /*
1209  * Client Tag extension support (from Niles Ritter).
1210  */
1211 static TIFFExtendProc _TIFFextender = (TIFFExtendProc) NULL;
1212
1213 TIFFExtendProc
1214 TIFFSetTagExtender(TIFFExtendProc extender)
1215 {
1216         TIFFExtendProc prev = _TIFFextender;
1217         _TIFFextender = extender;
1218         return (prev);
1219 }
1220
1221 /*
1222  * Setup for a new directory.  Should we automatically call
1223  * TIFFWriteDirectory() if the current one is dirty?
1224  *
1225  * The newly created directory will not exist on the file till
1226  * TIFFWriteDirectory(), TIFFFlush() or TIFFClose() is called.
1227  */
1228 int
1229 TIFFCreateDirectory(TIFF* tif)
1230 {
1231         TIFFDefaultDirectory(tif);
1232         tif->tif_diroff = 0;
1233         tif->tif_nextdiroff = 0;
1234         tif->tif_curoff = 0;
1235         tif->tif_row = (uint32) -1;
1236         tif->tif_curstrip = (uint32) -1;
1237
1238         return 0;
1239 }
1240
1241 int
1242 TIFFCreateCustomDirectory(TIFF* tif, const TIFFFieldArray* infoarray)
1243 {
1244         TIFFDefaultDirectory(tif);
1245
1246         /*
1247          * Reset the field definitions to match the application provided list. 
1248          * Hopefully TIFFDefaultDirectory() won't have done anything irreversable
1249          * based on it's assumption this is an image directory.
1250          */
1251         _TIFFSetupFields(tif, infoarray);
1252
1253         tif->tif_diroff = 0;
1254         tif->tif_nextdiroff = 0;
1255         tif->tif_curoff = 0;
1256         tif->tif_row = (uint32) -1;
1257         tif->tif_curstrip = (uint32) -1;
1258
1259         return 0;
1260 }
1261
1262 int
1263 TIFFCreateEXIFDirectory(TIFF* tif)
1264 {
1265         const TIFFFieldArray* exifFieldArray;
1266         exifFieldArray = _TIFFGetExifFields();
1267         return TIFFCreateCustomDirectory(tif, exifFieldArray);
1268 }
1269
1270 /*
1271  * Setup a default directory structure.
1272  */
1273 int
1274 TIFFDefaultDirectory(TIFF* tif)
1275 {
1276         register TIFFDirectory* td = &tif->tif_dir;
1277         const TIFFFieldArray* tiffFieldArray;
1278
1279         tiffFieldArray = _TIFFGetFields();
1280         _TIFFSetupFields(tif, tiffFieldArray);   
1281
1282         _TIFFmemset(td, 0, sizeof (*td));
1283         td->td_fillorder = FILLORDER_MSB2LSB;
1284         td->td_bitspersample = 1;
1285         td->td_threshholding = THRESHHOLD_BILEVEL;
1286         td->td_orientation = ORIENTATION_TOPLEFT;
1287         td->td_samplesperpixel = 1;
1288         td->td_rowsperstrip = (uint32) -1;
1289         td->td_tilewidth = 0;
1290         td->td_tilelength = 0;
1291         td->td_tiledepth = 1;
1292         td->td_stripbytecountsorted = 1; /* Our own arrays always sorted. */  
1293         td->td_resolutionunit = RESUNIT_INCH;
1294         td->td_sampleformat = SAMPLEFORMAT_UINT;
1295         td->td_imagedepth = 1;
1296         td->td_ycbcrsubsampling[0] = 2;
1297         td->td_ycbcrsubsampling[1] = 2;
1298         td->td_ycbcrpositioning = YCBCRPOSITION_CENTERED;
1299         tif->tif_postdecode = _TIFFNoPostDecode;  
1300         tif->tif_foundfield = NULL;
1301         tif->tif_tagmethods.vsetfield = _TIFFVSetField;  
1302         tif->tif_tagmethods.vgetfield = _TIFFVGetField;
1303         tif->tif_tagmethods.printdir = NULL;
1304         /*
1305          *  Give client code a chance to install their own
1306          *  tag extensions & methods, prior to compression overloads.
1307          */
1308         if (_TIFFextender)
1309                 (*_TIFFextender)(tif);
1310         (void) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
1311         /*
1312          * NB: The directory is marked dirty as a result of setting
1313          * up the default compression scheme.  However, this really
1314          * isn't correct -- we want TIFF_DIRTYDIRECT to be set only
1315          * if the user does something.  We could just do the setup
1316          * by hand, but it seems better to use the normal mechanism
1317          * (i.e. TIFFSetField).
1318          */
1319         tif->tif_flags &= ~TIFF_DIRTYDIRECT;
1320
1321         /*
1322          * As per http://bugzilla.remotesensing.org/show_bug.cgi?id=19
1323          * we clear the ISTILED flag when setting up a new directory.
1324          * Should we also be clearing stuff like INSUBIFD?
1325          */
1326         tif->tif_flags &= ~TIFF_ISTILED;
1327
1328         return (1);
1329 }
1330
1331 static int
1332 TIFFAdvanceDirectory(TIFF* tif, uint64* nextdir, uint64* off)
1333 {
1334         static const char module[] = "TIFFAdvanceDirectory";
1335         if (isMapped(tif))
1336         {
1337                 uint64 poff=*nextdir;
1338                 if (!(tif->tif_flags&TIFF_BIGTIFF))
1339                 {
1340                         tmsize_t poffa,poffb,poffc,poffd;
1341                         uint16 dircount;
1342                         uint32 nextdir32;
1343                         poffa=(tmsize_t)poff;
1344                         poffb=poffa+sizeof(uint16);
1345                         if (((uint64)poffa!=poff)||(poffb<poffa)||(poffb<(tmsize_t)sizeof(uint16))||(poffb>tif->tif_size))
1346                         {
1347                                 TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory count");
1348                                 return(0);
1349                         }
1350                         _TIFFmemcpy(&dircount,tif->tif_base+poffa,sizeof(uint16));
1351                         if (tif->tif_flags&TIFF_SWAB)
1352                                 TIFFSwabShort(&dircount);
1353                         poffc=poffb+dircount*12;
1354                         poffd=poffc+sizeof(uint32);
1355                         if ((poffc<poffb)||(poffc<dircount*12)||(poffd<poffc)||(poffd<(tmsize_t)sizeof(uint32))||(poffd>tif->tif_size))
1356                         {
1357                                 TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory link");
1358                                 return(0);
1359                         }
1360                         if (off!=NULL)
1361                                 *off=(uint64)poffc;
1362                         _TIFFmemcpy(&nextdir32,tif->tif_base+poffc,sizeof(uint32));
1363                         if (tif->tif_flags&TIFF_SWAB)
1364                                 TIFFSwabLong(&nextdir32);
1365                         *nextdir=nextdir32;
1366                 }
1367                 else
1368                 {
1369                         tmsize_t poffa,poffb,poffc,poffd;
1370                         uint64 dircount64;
1371                         uint16 dircount16;
1372                         poffa=(tmsize_t)poff;
1373                         poffb=poffa+sizeof(uint64);
1374                         if (((uint64)poffa!=poff)||(poffb<poffa)||(poffb<(tmsize_t)sizeof(uint64))||(poffb>tif->tif_size))
1375                         {
1376                                 TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory count");
1377                                 return(0);
1378                         }
1379                         _TIFFmemcpy(&dircount64,tif->tif_base+poffa,sizeof(uint64));
1380                         if (tif->tif_flags&TIFF_SWAB)
1381                                 TIFFSwabLong8(&dircount64);
1382                         if (dircount64>0xFFFF)
1383                         {
1384                                 TIFFErrorExt(tif->tif_clientdata,module,"Sanity check on directory count failed");
1385                                 return(0);
1386                         }
1387                         dircount16=(uint16)dircount64;
1388                         poffc=poffb+dircount16*20;
1389                         poffd=poffc+sizeof(uint64);
1390                         if ((poffc<poffb)||(poffc<dircount16*20)||(poffd<poffc)||(poffd<(tmsize_t)sizeof(uint64))||(poffd>tif->tif_size))
1391                         {
1392                                 TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory link");
1393                                 return(0);
1394                         }
1395                         if (off!=NULL)
1396                                 *off=(uint64)poffc;
1397                         _TIFFmemcpy(nextdir,tif->tif_base+poffc,sizeof(uint64));
1398                         if (tif->tif_flags&TIFF_SWAB)
1399                                 TIFFSwabLong8(nextdir);
1400                 }
1401                 return(1);
1402         }
1403         else
1404         {
1405                 if (!(tif->tif_flags&TIFF_BIGTIFF))
1406                 {
1407                         uint16 dircount;
1408                         uint32 nextdir32;
1409                         if (!SeekOK(tif, *nextdir) ||
1410                             !ReadOK(tif, &dircount, sizeof (uint16))) {
1411                                 TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory count",
1412                                     tif->tif_name);
1413                                 return (0);
1414                         }
1415                         if (tif->tif_flags & TIFF_SWAB)
1416                                 TIFFSwabShort(&dircount);
1417                         if (off != NULL)
1418                                 *off = TIFFSeekFile(tif,
1419                                     dircount*12, SEEK_CUR);
1420                         else
1421                                 (void) TIFFSeekFile(tif,
1422                                     dircount*12, SEEK_CUR);
1423                         if (!ReadOK(tif, &nextdir32, sizeof (uint32))) {
1424                                 TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory link",
1425                                     tif->tif_name);
1426                                 return (0);
1427                         }
1428                         if (tif->tif_flags & TIFF_SWAB)
1429                                 TIFFSwabLong(&nextdir32);
1430                         *nextdir=nextdir32;
1431                 }
1432                 else
1433                 {
1434                         uint64 dircount64;
1435                         uint16 dircount16;
1436                         if (!SeekOK(tif, *nextdir) ||
1437                             !ReadOK(tif, &dircount64, sizeof (uint64))) {
1438                                 TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory count",
1439                                     tif->tif_name);
1440                                 return (0);
1441                         }
1442                         if (tif->tif_flags & TIFF_SWAB)
1443                                 TIFFSwabLong8(&dircount64);
1444                         if (dircount64>0xFFFF)
1445                         {
1446                                 TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count");
1447                                 return(0);
1448                         }
1449                         dircount16 = (uint16)dircount64;
1450                         if (off != NULL)
1451                                 *off = TIFFSeekFile(tif,
1452                                     dircount16*20, SEEK_CUR);
1453                         else
1454                                 (void) TIFFSeekFile(tif,
1455                                     dircount16*20, SEEK_CUR);
1456                         if (!ReadOK(tif, nextdir, sizeof (uint64))) {
1457                                 TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory link",
1458                                     tif->tif_name);
1459                                 return (0);
1460                         }
1461                         if (tif->tif_flags & TIFF_SWAB)
1462                                 TIFFSwabLong8(nextdir);
1463                 }
1464                 return (1);
1465         }
1466 }
1467
1468 /*
1469  * Count the number of directories in a file.
1470  */
1471 uint16
1472 TIFFNumberOfDirectories(TIFF* tif)
1473 {
1474         uint64 nextdir;
1475         uint16 n;
1476         if (!(tif->tif_flags&TIFF_BIGTIFF))
1477                 nextdir = tif->tif_header.classic.tiff_diroff;
1478         else
1479                 nextdir = tif->tif_header.big.tiff_diroff;
1480         n = 0;
1481         while (nextdir != 0 && TIFFAdvanceDirectory(tif, &nextdir, NULL))
1482                 n++;
1483         return (n);
1484 }
1485
1486 /*
1487  * Set the n-th directory as the current directory.
1488  * NB: Directories are numbered starting at 0.
1489  */
1490 int
1491 TIFFSetDirectory(TIFF* tif, uint16 dirn)
1492 {
1493         uint64 nextdir;
1494         uint16 n;
1495
1496         if (!(tif->tif_flags&TIFF_BIGTIFF))
1497                 nextdir = tif->tif_header.classic.tiff_diroff;
1498         else
1499                 nextdir = tif->tif_header.big.tiff_diroff;
1500         for (n = dirn; n > 0 && nextdir != 0; n--)
1501                 if (!TIFFAdvanceDirectory(tif, &nextdir, NULL))
1502                         return (0);
1503         tif->tif_nextdiroff = nextdir;
1504         /*
1505          * Set curdir to the actual directory index.  The
1506          * -1 is because TIFFReadDirectory will increment
1507          * tif_curdir after successfully reading the directory.
1508          */
1509         tif->tif_curdir = (dirn - n) - 1;
1510         /*
1511          * Reset tif_dirnumber counter and start new list of seen directories.
1512          * We need this to prevent IFD loops.
1513          */
1514         tif->tif_dirnumber = 0;
1515         return (TIFFReadDirectory(tif));
1516 }
1517
1518 /*
1519  * Set the current directory to be the directory
1520  * located at the specified file offset.  This interface
1521  * is used mainly to access directories linked with
1522  * the SubIFD tag (e.g. thumbnail images).
1523  */
1524 int
1525 TIFFSetSubDirectory(TIFF* tif, uint64 diroff)
1526 {
1527         tif->tif_nextdiroff = diroff;
1528         /*
1529          * Reset tif_dirnumber counter and start new list of seen directories.
1530          * We need this to prevent IFD loops.
1531          */
1532         tif->tif_dirnumber = 0;
1533         return (TIFFReadDirectory(tif));
1534 }
1535
1536 /*
1537  * Return file offset of the current directory.
1538  */
1539 uint64
1540 TIFFCurrentDirOffset(TIFF* tif)
1541 {
1542         return (tif->tif_diroff);
1543 }
1544
1545 /*
1546  * Return an indication of whether or not we are
1547  * at the last directory in the file.
1548  */
1549 int
1550 TIFFLastDirectory(TIFF* tif)
1551 {
1552         return (tif->tif_nextdiroff == 0);
1553 }
1554
1555 /*
1556  * Unlink the specified directory from the directory chain.
1557  */
1558 int
1559 TIFFUnlinkDirectory(TIFF* tif, uint16 dirn)
1560 {
1561         static const char module[] = "TIFFUnlinkDirectory";
1562         uint64 nextdir;
1563         uint64 off;
1564         uint16 n;
1565
1566         if (tif->tif_mode == O_RDONLY) {
1567                 TIFFErrorExt(tif->tif_clientdata, module,
1568                              "Can not unlink directory in read-only file");
1569                 return (0);
1570         }
1571         /*
1572          * Go to the directory before the one we want
1573          * to unlink and nab the offset of the link
1574          * field we'll need to patch.
1575          */
1576         if (!(tif->tif_flags&TIFF_BIGTIFF))
1577         {
1578                 nextdir = tif->tif_header.classic.tiff_diroff;
1579                 off = 4;
1580         }
1581         else
1582         {
1583                 nextdir = tif->tif_header.big.tiff_diroff;
1584                 off = 8;
1585         }
1586         for (n = dirn-1; n > 0; n--) {
1587                 if (nextdir == 0) {
1588                         TIFFErrorExt(tif->tif_clientdata, module, "Directory %d does not exist", dirn);
1589                         return (0);
1590                 }
1591                 if (!TIFFAdvanceDirectory(tif, &nextdir, &off))
1592                         return (0);
1593         }
1594         /*
1595          * Advance to the directory to be unlinked and fetch
1596          * the offset of the directory that follows.
1597          */
1598         if (!TIFFAdvanceDirectory(tif, &nextdir, NULL))
1599                 return (0);
1600         /*
1601          * Go back and patch the link field of the preceding
1602          * directory to point to the offset of the directory
1603          * that follows.
1604          */
1605         (void) TIFFSeekFile(tif, off, SEEK_SET);
1606         if (!(tif->tif_flags&TIFF_BIGTIFF))
1607         {
1608                 uint32 nextdir32;
1609                 nextdir32=(uint32)nextdir;
1610                 assert((uint64)nextdir32==nextdir);
1611                 if (tif->tif_flags & TIFF_SWAB)
1612                         TIFFSwabLong(&nextdir32);
1613                 if (!WriteOK(tif, &nextdir32, sizeof (uint32))) {
1614                         TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link");
1615                         return (0);
1616                 }
1617         }
1618         else
1619         {
1620                 if (tif->tif_flags & TIFF_SWAB)
1621                         TIFFSwabLong8(&nextdir);
1622                 if (!WriteOK(tif, &nextdir, sizeof (uint64))) {
1623                         TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link");
1624                         return (0);
1625                 }
1626         }
1627         /*
1628          * Leave directory state setup safely.  We don't have
1629          * facilities for doing inserting and removing directories,
1630          * so it's safest to just invalidate everything.  This
1631          * means that the caller can only append to the directory
1632          * chain.
1633          */
1634         (*tif->tif_cleanup)(tif);
1635         if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
1636                 _TIFFfree(tif->tif_rawdata);
1637                 tif->tif_rawdata = NULL;
1638                 tif->tif_rawcc = 0;
1639                 tif->tif_rawdataoff = 0;
1640                 tif->tif_rawdataloaded = 0;
1641         }
1642         tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP|TIFF_POSTENCODE|TIFF_BUF4WRITE);
1643         TIFFFreeDirectory(tif);
1644         TIFFDefaultDirectory(tif);
1645         tif->tif_diroff = 0;                    /* force link on next write */
1646         tif->tif_nextdiroff = 0;                /* next write must be at end */
1647         tif->tif_curoff = 0;
1648         tif->tif_row = (uint32) -1;
1649         tif->tif_curstrip = (uint32) -1;
1650         return (1);
1651 }
1652
1653 /* vim: set ts=8 sts=8 sw=8 noet: */
1654 /*
1655  * Local Variables:
1656  * mode: c
1657  * c-basic-offset: 8
1658  * fill-column: 78
1659  * End:
1660  */
1661 #endif
1662