Coverage Report

Created: 2026-02-14 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/frmts/gtiff/libtiff/tif_dirwrite.c
Line
Count
Source
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 Write Support Routines.
29
 */
30
#include "tiffiop.h"
31
#include <float.h> /*--: for Rational2Double */
32
#include <math.h>  /*--: for Rational2Double */
33
34
#ifdef HAVE_IEEEFP
35
#define TIFFCvtNativeToIEEEFloat(tif, n, fp)
36
#define TIFFCvtNativeToIEEEDouble(tif, n, dp)
37
#else
38
/* If your machine does not support IEEE floating point then you will need to
39
 * add support to tif_machdep.c to convert between the native format and
40
 * IEEE format. */
41
extern void TIFFCvtNativeToIEEEFloat(TIFF *tif, uint32_t n, float *fp);
42
extern void TIFFCvtNativeToIEEEDouble(TIFF *tif, uint32_t n, double *dp);
43
#endif
44
45
static int TIFFWriteDirectorySec(TIFF *tif, int isimage, int imagedone,
46
                                 uint64_t *pdiroff);
47
48
static int TIFFWriteDirectoryTagSampleformatArray(TIFF *tif, uint32_t *ndir,
49
                                                  TIFFDirEntry *dir,
50
                                                  uint16_t tag, uint32_t count,
51
                                                  double *value);
52
53
static int TIFFWriteDirectoryTagAscii(TIFF *tif, uint32_t *ndir,
54
                                      TIFFDirEntry *dir, uint16_t tag,
55
                                      uint32_t count, char *value);
56
static int TIFFWriteDirectoryTagUndefinedArray(TIFF *tif, uint32_t *ndir,
57
                                               TIFFDirEntry *dir, uint16_t tag,
58
                                               uint32_t count, uint8_t *value);
59
static int TIFFWriteDirectoryTagByteArray(TIFF *tif, uint32_t *ndir,
60
                                          TIFFDirEntry *dir, uint16_t tag,
61
                                          uint32_t count, uint8_t *value);
62
static int TIFFWriteDirectoryTagSbyteArray(TIFF *tif, uint32_t *ndir,
63
                                           TIFFDirEntry *dir, uint16_t tag,
64
                                           uint32_t count, int8_t *value);
65
static int TIFFWriteDirectoryTagShort(TIFF *tif, uint32_t *ndir,
66
                                      TIFFDirEntry *dir, uint16_t tag,
67
                                      uint16_t value);
68
static int TIFFWriteDirectoryTagShortArray(TIFF *tif, uint32_t *ndir,
69
                                           TIFFDirEntry *dir, uint16_t tag,
70
                                           uint32_t count, uint16_t *value);
71
static int TIFFWriteDirectoryTagShortPerSample(TIFF *tif, uint32_t *ndir,
72
                                               TIFFDirEntry *dir, uint16_t tag,
73
                                               uint16_t value);
74
static int TIFFWriteDirectoryTagSshortArray(TIFF *tif, uint32_t *ndir,
75
                                            TIFFDirEntry *dir, uint16_t tag,
76
                                            uint32_t count, int16_t *value);
77
static int TIFFWriteDirectoryTagLong(TIFF *tif, uint32_t *ndir,
78
                                     TIFFDirEntry *dir, uint16_t tag,
79
                                     uint32_t value);
80
static int TIFFWriteDirectoryTagLongArray(TIFF *tif, uint32_t *ndir,
81
                                          TIFFDirEntry *dir, uint16_t tag,
82
                                          uint32_t count, uint32_t *value);
83
static int TIFFWriteDirectoryTagSlongArray(TIFF *tif, uint32_t *ndir,
84
                                           TIFFDirEntry *dir, uint16_t tag,
85
                                           uint32_t count, int32_t *value);
86
static int TIFFWriteDirectoryTagLong8Array(TIFF *tif, uint32_t *ndir,
87
                                           TIFFDirEntry *dir, uint16_t tag,
88
                                           uint32_t count, uint64_t *value);
89
static int TIFFWriteDirectoryTagSlong8Array(TIFF *tif, uint32_t *ndir,
90
                                            TIFFDirEntry *dir, uint16_t tag,
91
                                            uint32_t count, int64_t *value);
92
static int TIFFWriteDirectoryTagRational(TIFF *tif, uint32_t *ndir,
93
                                         TIFFDirEntry *dir, uint16_t tag,
94
                                         double value);
95
static int TIFFWriteDirectoryTagRationalArray(TIFF *tif, uint32_t *ndir,
96
                                              TIFFDirEntry *dir, uint16_t tag,
97
                                              uint32_t count, float *value);
98
static int TIFFWriteDirectoryTagSrationalArray(TIFF *tif, uint32_t *ndir,
99
                                               TIFFDirEntry *dir, uint16_t tag,
100
                                               uint32_t count, float *value);
101
static int TIFFWriteDirectoryTagFloatArray(TIFF *tif, uint32_t *ndir,
102
                                           TIFFDirEntry *dir, uint16_t tag,
103
                                           uint32_t count, float *value);
104
static int TIFFWriteDirectoryTagDoubleArray(TIFF *tif, uint32_t *ndir,
105
                                            TIFFDirEntry *dir, uint16_t tag,
106
                                            uint32_t count, double *value);
107
static int TIFFWriteDirectoryTagIfdArray(TIFF *tif, uint32_t *ndir,
108
                                         TIFFDirEntry *dir, uint16_t tag,
109
                                         uint32_t count, uint32_t *value);
110
static int TIFFWriteDirectoryTagShortLong(TIFF *tif, uint32_t *ndir,
111
                                          TIFFDirEntry *dir, uint16_t tag,
112
                                          uint32_t value);
113
static int TIFFWriteDirectoryTagLongLong8Array(TIFF *tif, uint32_t *ndir,
114
                                               TIFFDirEntry *dir, uint16_t tag,
115
                                               uint32_t count, uint64_t *value);
116
static int TIFFWriteDirectoryTagIfdIfd8Array(TIFF *tif, uint32_t *ndir,
117
                                             TIFFDirEntry *dir, uint16_t tag,
118
                                             uint32_t count, uint64_t *value);
119
static int TIFFWriteDirectoryTagColormap(TIFF *tif, uint32_t *ndir,
120
                                         TIFFDirEntry *dir);
121
static int TIFFWriteDirectoryTagTransferfunction(TIFF *tif, uint32_t *ndir,
122
                                                 TIFFDirEntry *dir);
123
static int TIFFWriteDirectoryTagSubifd(TIFF *tif, uint32_t *ndir,
124
                                       TIFFDirEntry *dir);
125
126
static int TIFFWriteDirectoryTagCheckedAscii(TIFF *tif, uint32_t *ndir,
127
                                             TIFFDirEntry *dir, uint16_t tag,
128
                                             uint32_t count, char *value);
129
static int TIFFWriteDirectoryTagCheckedUndefinedArray(TIFF *tif, uint32_t *ndir,
130
                                                      TIFFDirEntry *dir,
131
                                                      uint16_t tag,
132
                                                      uint32_t count,
133
                                                      uint8_t *value);
134
static int TIFFWriteDirectoryTagCheckedByteArray(TIFF *tif, uint32_t *ndir,
135
                                                 TIFFDirEntry *dir,
136
                                                 uint16_t tag, uint32_t count,
137
                                                 uint8_t *value);
138
static int TIFFWriteDirectoryTagCheckedSbyteArray(TIFF *tif, uint32_t *ndir,
139
                                                  TIFFDirEntry *dir,
140
                                                  uint16_t tag, uint32_t count,
141
                                                  int8_t *value);
142
static int TIFFWriteDirectoryTagCheckedShort(TIFF *tif, uint32_t *ndir,
143
                                             TIFFDirEntry *dir, uint16_t tag,
144
                                             uint16_t value);
145
static int TIFFWriteDirectoryTagCheckedShortArray(TIFF *tif, uint32_t *ndir,
146
                                                  TIFFDirEntry *dir,
147
                                                  uint16_t tag, uint32_t count,
148
                                                  uint16_t *value);
149
static int TIFFWriteDirectoryTagCheckedSshortArray(TIFF *tif, uint32_t *ndir,
150
                                                   TIFFDirEntry *dir,
151
                                                   uint16_t tag, uint32_t count,
152
                                                   int16_t *value);
153
static int TIFFWriteDirectoryTagCheckedLong(TIFF *tif, uint32_t *ndir,
154
                                            TIFFDirEntry *dir, uint16_t tag,
155
                                            uint32_t value);
156
static int TIFFWriteDirectoryTagCheckedLongArray(TIFF *tif, uint32_t *ndir,
157
                                                 TIFFDirEntry *dir,
158
                                                 uint16_t tag, uint32_t count,
159
                                                 uint32_t *value);
160
static int TIFFWriteDirectoryTagCheckedSlongArray(TIFF *tif, uint32_t *ndir,
161
                                                  TIFFDirEntry *dir,
162
                                                  uint16_t tag, uint32_t count,
163
                                                  int32_t *value);
164
static int TIFFWriteDirectoryTagCheckedLong8Array(TIFF *tif, uint32_t *ndir,
165
                                                  TIFFDirEntry *dir,
166
                                                  uint16_t tag, uint32_t count,
167
                                                  uint64_t *value);
168
static int TIFFWriteDirectoryTagCheckedSlong8Array(TIFF *tif, uint32_t *ndir,
169
                                                   TIFFDirEntry *dir,
170
                                                   uint16_t tag, uint32_t count,
171
                                                   int64_t *value);
172
static int TIFFWriteDirectoryTagCheckedRational(TIFF *tif, uint32_t *ndir,
173
                                                TIFFDirEntry *dir, uint16_t tag,
174
                                                double value);
175
static int TIFFWriteDirectoryTagCheckedRationalArray(TIFF *tif, uint32_t *ndir,
176
                                                     TIFFDirEntry *dir,
177
                                                     uint16_t tag,
178
                                                     uint32_t count,
179
                                                     float *value);
180
static int TIFFWriteDirectoryTagCheckedSrationalArray(TIFF *tif, uint32_t *ndir,
181
                                                      TIFFDirEntry *dir,
182
                                                      uint16_t tag,
183
                                                      uint32_t count,
184
                                                      float *value);
185
186
/*--: Rational2Double: New functions to support true double-precision for custom
187
 * rational tag types. */
188
static int TIFFWriteDirectoryTagRationalDoubleArray(TIFF *tif, uint32_t *ndir,
189
                                                    TIFFDirEntry *dir,
190
                                                    uint16_t tag,
191
                                                    uint32_t count,
192
                                                    double *value);
193
static int TIFFWriteDirectoryTagSrationalDoubleArray(TIFF *tif, uint32_t *ndir,
194
                                                     TIFFDirEntry *dir,
195
                                                     uint16_t tag,
196
                                                     uint32_t count,
197
                                                     double *value);
198
static int
199
TIFFWriteDirectoryTagCheckedRationalDoubleArray(TIFF *tif, uint32_t *ndir,
200
                                                TIFFDirEntry *dir, uint16_t tag,
201
                                                uint32_t count, double *value);
202
static int TIFFWriteDirectoryTagCheckedSrationalDoubleArray(
203
    TIFF *tif, uint32_t *ndir, TIFFDirEntry *dir, uint16_t tag, uint32_t count,
204
    double *value);
205
static void DoubleToRational(double value, uint32_t *num, uint32_t *denom);
206
static void DoubleToSrational(double value, int32_t *num, int32_t *denom);
207
208
static int TIFFWriteDirectoryTagCheckedFloatArray(TIFF *tif, uint32_t *ndir,
209
                                                  TIFFDirEntry *dir,
210
                                                  uint16_t tag, uint32_t count,
211
                                                  float *value);
212
static int TIFFWriteDirectoryTagCheckedDoubleArray(TIFF *tif, uint32_t *ndir,
213
                                                   TIFFDirEntry *dir,
214
                                                   uint16_t tag, uint32_t count,
215
                                                   double *value);
216
static int TIFFWriteDirectoryTagCheckedIfdArray(TIFF *tif, uint32_t *ndir,
217
                                                TIFFDirEntry *dir, uint16_t tag,
218
                                                uint32_t count,
219
                                                uint32_t *value);
220
static int TIFFWriteDirectoryTagCheckedIfd8Array(TIFF *tif, uint32_t *ndir,
221
                                                 TIFFDirEntry *dir,
222
                                                 uint16_t tag, uint32_t count,
223
                                                 uint64_t *value);
224
225
static int TIFFWriteDirectoryTagData(TIFF *tif, uint32_t *ndir,
226
                                     TIFFDirEntry *dir, uint16_t tag,
227
                                     uint16_t datatype, uint32_t count,
228
                                     uint32_t datalength, void *data);
229
230
static int TIFFLinkDirectory(TIFF *);
231
232
/*
233
 * Write the contents of the current directory
234
 * to the specified file.  This routine doesn't
235
 * handle overwriting a directory with auxiliary
236
 * storage that's been changed.
237
 */
238
int TIFFWriteDirectory(TIFF *tif)
239
0
{
240
0
    return TIFFWriteDirectorySec(tif, TRUE, TRUE, NULL);
241
0
}
242
243
/*
244
 * This is an advanced writing function that must be used in a particular
245
 * sequence, and generally together with TIFFForceStrileArrayWriting(),
246
 * to make its intended effect. Its aim is to modify the location
247
 * where the [Strip/Tile][Offsets/ByteCounts] arrays are located in the file.
248
 * More precisely, when TIFFWriteCheck() will be called, the tag entries for
249
 * those arrays will be written with type = count = offset = 0 as a temporary
250
 * value.
251
 *
252
 * Its effect is only valid for the current directory, and before
253
 * TIFFWriteDirectory() is first called, and  will be reset when
254
 * changing directory.
255
 *
256
 * The typical sequence of calls is:
257
 * TIFFOpen()
258
 * [ TIFFCreateDirectory(tif) ]
259
 * Set fields with calls to TIFFSetField(tif, ...)
260
 * TIFFDeferStrileArrayWriting(tif)
261
 * TIFFWriteCheck(tif, ...)
262
 * TIFFWriteDirectory(tif)
263
 * ... potentially create other directories and come back to the above directory
264
 * TIFFForceStrileArrayWriting(tif): emit the arrays at the end of file
265
 *
266
 * Returns 1 in case of success, 0 otherwise.
267
 */
268
int TIFFDeferStrileArrayWriting(TIFF *tif)
269
0
{
270
0
    static const char module[] = "TIFFDeferStrileArrayWriting";
271
0
    if (tif->tif_mode == O_RDONLY)
272
0
    {
273
0
        TIFFErrorExtR(tif, tif->tif_name, "File opened in read-only mode");
274
0
        return 0;
275
0
    }
276
0
    if (tif->tif_diroff != 0)
277
0
    {
278
0
        TIFFErrorExtR(tif, module, "Directory has already been written");
279
0
        return 0;
280
0
    }
281
282
0
    tif->tif_dir.td_deferstrilearraywriting = TRUE;
283
0
    return 1;
284
0
}
285
286
/*
287
 * Similar to TIFFWriteDirectory(), writes the directory out
288
 * but leaves all data structures in memory so that it can be
289
 * written again.  This will make a partially written TIFF file
290
 * readable before it is successfully completed/closed.
291
 */
292
int TIFFCheckpointDirectory(TIFF *tif)
293
0
{
294
0
    int rc;
295
    /* Setup the strips arrays, if they haven't already been. */
296
0
    if (tif->tif_dir.td_stripoffset_p == NULL)
297
0
        (void)TIFFSetupStrips(tif);
298
0
    rc = TIFFWriteDirectorySec(tif, TRUE, FALSE, NULL);
299
0
    (void)TIFFSetWriteOffset(tif, TIFFSeekFile(tif, 0, SEEK_END));
300
0
    return rc;
301
0
}
302
303
int TIFFWriteCustomDirectory(TIFF *tif, uint64_t *pdiroff)
304
0
{
305
0
    return TIFFWriteDirectorySec(tif, FALSE, FALSE, pdiroff);
306
0
}
307
308
/*
309
 * Similar to TIFFWriteDirectorySec(), but if the directory has already
310
 * been written once, it is relocated to the end of the file, in case it
311
 * has changed in size.  Note that this will result in the loss of the
312
 * previously used directory space.
313
 */
314
315
static int TIFFRewriteDirectorySec(TIFF *tif, int isimage, int imagedone,
316
                                   uint64_t *pdiroff)
317
0
{
318
0
    static const char module[] = "TIFFRewriteDirectory";
319
320
    /* We don't need to do anything special if it hasn't been written. */
321
0
    if (tif->tif_diroff == 0)
322
0
        return TIFFWriteDirectory(tif);
323
324
    /*
325
     * Find and zero the pointer to this directory, so that TIFFLinkDirectory
326
     * will cause it to be added after this directories current pre-link.
327
     */
328
0
    uint64_t torewritediroff = tif->tif_diroff;
329
330
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
331
0
    {
332
0
        if (tif->tif_header.classic.tiff_diroff == tif->tif_diroff)
333
0
        {
334
0
            tif->tif_header.classic.tiff_diroff = 0;
335
0
            tif->tif_diroff = 0;
336
337
0
            TIFFSeekFile(tif, 4, SEEK_SET);
338
0
            if (!WriteOK(tif, &(tif->tif_header.classic.tiff_diroff), 4))
339
0
            {
340
0
                TIFFErrorExtR(tif, tif->tif_name, "Error updating TIFF header");
341
0
                return (0);
342
0
            }
343
0
        }
344
0
        else if (tif->tif_diroff > 0xFFFFFFFFU)
345
0
        {
346
0
            TIFFErrorExtR(tif, module,
347
0
                          "tif->tif_diroff exceeds 32 bit range allowed for "
348
0
                          "Classic TIFF");
349
0
            return (0);
350
0
        }
351
0
        else
352
0
        {
353
0
            uint32_t nextdir;
354
0
            nextdir = tif->tif_header.classic.tiff_diroff;
355
0
            while (1)
356
0
            {
357
0
                uint16_t dircount;
358
0
                uint32_t nextnextdir;
359
360
0
                if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, 2))
361
0
                {
362
0
                    TIFFErrorExtR(tif, module,
363
0
                                  "Error fetching directory count");
364
0
                    return (0);
365
0
                }
366
0
                if (tif->tif_flags & TIFF_SWAB)
367
0
                    TIFFSwabShort(&dircount);
368
0
                (void)TIFFSeekFile(tif, nextdir + 2 + dircount * 12, SEEK_SET);
369
0
                if (!ReadOK(tif, &nextnextdir, 4))
370
0
                {
371
0
                    TIFFErrorExtR(tif, module, "Error fetching directory link");
372
0
                    return (0);
373
0
                }
374
0
                if (tif->tif_flags & TIFF_SWAB)
375
0
                    TIFFSwabLong(&nextnextdir);
376
0
                if (nextnextdir == tif->tif_diroff)
377
0
                {
378
0
                    uint32_t m;
379
0
                    m = 0;
380
0
                    (void)TIFFSeekFile(tif, nextdir + 2 + dircount * 12,
381
0
                                       SEEK_SET);
382
0
                    if (!WriteOK(tif, &m, 4))
383
0
                    {
384
0
                        TIFFErrorExtR(tif, module,
385
0
                                      "Error writing directory link");
386
0
                        return (0);
387
0
                    }
388
0
                    tif->tif_diroff = 0;
389
                    /* Force a full-traversal to reach the zeroed pointer */
390
0
                    tif->tif_lastdiroff = 0;
391
0
                    break;
392
0
                }
393
0
                nextdir = nextnextdir;
394
0
            }
395
0
        }
396
        /* Remove skipped offset from IFD loop directory list. */
397
0
        _TIFFRemoveEntryFromDirectoryListByOffset(tif, torewritediroff);
398
0
    }
399
0
    else
400
0
    {
401
0
        if (tif->tif_header.big.tiff_diroff == tif->tif_diroff)
402
0
        {
403
0
            tif->tif_header.big.tiff_diroff = 0;
404
0
            tif->tif_diroff = 0;
405
406
0
            TIFFSeekFile(tif, 8, SEEK_SET);
407
0
            if (!WriteOK(tif, &(tif->tif_header.big.tiff_diroff), 8))
408
0
            {
409
0
                TIFFErrorExtR(tif, tif->tif_name, "Error updating TIFF header");
410
0
                return (0);
411
0
            }
412
0
        }
413
0
        else
414
0
        {
415
0
            uint64_t nextdir;
416
0
            nextdir = tif->tif_header.big.tiff_diroff;
417
0
            while (1)
418
0
            {
419
0
                uint64_t dircount64;
420
0
                uint16_t dircount;
421
0
                uint64_t nextnextdir;
422
423
0
                if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount64, 8))
424
0
                {
425
0
                    TIFFErrorExtR(tif, module,
426
0
                                  "Error fetching directory count");
427
0
                    return (0);
428
0
                }
429
0
                if (tif->tif_flags & TIFF_SWAB)
430
0
                    TIFFSwabLong8(&dircount64);
431
0
                if (dircount64 > 0xFFFF)
432
0
                {
433
0
                    TIFFErrorExtR(tif, module,
434
0
                                  "Sanity check on tag count failed, likely "
435
0
                                  "corrupt TIFF");
436
0
                    return (0);
437
0
                }
438
0
                dircount = (uint16_t)dircount64;
439
0
                (void)TIFFSeekFile(tif, nextdir + 8 + dircount * 20, SEEK_SET);
440
0
                if (!ReadOK(tif, &nextnextdir, 8))
441
0
                {
442
0
                    TIFFErrorExtR(tif, module, "Error fetching directory link");
443
0
                    return (0);
444
0
                }
445
0
                if (tif->tif_flags & TIFF_SWAB)
446
0
                    TIFFSwabLong8(&nextnextdir);
447
0
                if (nextnextdir == tif->tif_diroff)
448
0
                {
449
0
                    uint64_t m;
450
0
                    m = 0;
451
0
                    (void)TIFFSeekFile(tif, nextdir + 8 + dircount * 20,
452
0
                                       SEEK_SET);
453
0
                    if (!WriteOK(tif, &m, 8))
454
0
                    {
455
0
                        TIFFErrorExtR(tif, module,
456
0
                                      "Error writing directory link");
457
0
                        return (0);
458
0
                    }
459
0
                    tif->tif_diroff = 0;
460
                    /* Force a full-traversal to reach the zeroed pointer */
461
0
                    tif->tif_lastdiroff = 0;
462
0
                    break;
463
0
                }
464
0
                nextdir = nextnextdir;
465
0
            }
466
0
        }
467
        /* Remove skipped offset from IFD loop directory list. */
468
0
        _TIFFRemoveEntryFromDirectoryListByOffset(tif, torewritediroff);
469
0
    }
470
471
    /*
472
     * Now use TIFFWriteDirectorySec() normally.
473
     */
474
0
    return TIFFWriteDirectorySec(tif, isimage, imagedone, pdiroff);
475
0
} /*-- TIFFRewriteDirectorySec() --*/
476
477
/*
478
 * Similar to TIFFWriteDirectory(), but if the directory has already
479
 * been written once, it is relocated to the end of the file, in case it
480
 * has changed in size.  Note that this will result in the loss of the
481
 * previously used directory space.
482
 */
483
int TIFFRewriteDirectory(TIFF *tif)
484
0
{
485
0
    return TIFFRewriteDirectorySec(tif, TRUE, TRUE, NULL);
486
0
}
487
488
static int TIFFWriteDirectorySec(TIFF *tif, int isimage, int imagedone,
489
                                 uint64_t *pdiroff)
490
0
{
491
0
    static const char module[] = "TIFFWriteDirectorySec";
492
0
    uint32_t ndir;
493
0
    TIFFDirEntry *dir;
494
0
    uint32_t dirsize;
495
0
    void *dirmem;
496
0
    uint32_t m;
497
0
    if (tif->tif_mode == O_RDONLY)
498
0
        return (1);
499
500
0
    _TIFFFillStriles(tif);
501
502
    /*
503
     * Clear write state so that subsequent images with
504
     * different characteristics get the right buffers
505
     * setup for them.
506
     */
507
0
    if (imagedone)
508
0
    {
509
0
        if (tif->tif_flags & TIFF_POSTENCODE)
510
0
        {
511
0
            tif->tif_flags &= ~TIFF_POSTENCODE;
512
0
            if (!(*tif->tif_postencode)(tif))
513
0
            {
514
0
                TIFFErrorExtR(tif, module,
515
0
                              "Error post-encoding before directory write");
516
0
                return (0);
517
0
            }
518
0
        }
519
0
        (*tif->tif_close)(tif); /* shutdown encoder */
520
        /*
521
         * Flush any data that might have been written
522
         * by the compression close+cleanup routines.  But
523
         * be careful not to write stuff if we didn't add data
524
         * in the previous steps as the "rawcc" data may well be
525
         * a previously read tile/strip in mixed read/write mode.
526
         */
527
0
        if (tif->tif_rawcc > 0 && (tif->tif_flags & TIFF_BEENWRITING) != 0)
528
0
        {
529
0
            if (!TIFFFlushData1(tif))
530
0
            {
531
0
                TIFFErrorExtR(tif, module,
532
0
                              "Error flushing data before directory write");
533
0
                return (0);
534
0
            }
535
0
        }
536
0
        if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata)
537
0
        {
538
0
            _TIFFfreeExt(tif, tif->tif_rawdata);
539
0
            tif->tif_rawdata = NULL;
540
0
            tif->tif_rawcp = NULL;
541
0
            tif->tif_rawcc = 0;
542
0
            tif->tif_rawdatasize = 0;
543
0
            tif->tif_rawdataoff = 0;
544
0
            tif->tif_rawdataloaded = 0;
545
0
        }
546
0
        tif->tif_flags &= ~(TIFF_BEENWRITING | TIFF_BUFFERSETUP);
547
0
    }
548
549
0
    if (TIFFFieldSet(tif, FIELD_COMPRESSION) &&
550
0
        (tif->tif_dir.td_compression == COMPRESSION_DEFLATE))
551
0
    {
552
0
        TIFFWarningExtR(tif, module,
553
0
                        "Creating TIFF with legacy Deflate codec identifier, "
554
0
                        "COMPRESSION_ADOBE_DEFLATE is more widely supported");
555
0
    }
556
0
    dir = NULL;
557
0
    dirmem = NULL;
558
0
    dirsize = 0;
559
0
    while (1)
560
0
    {
561
        /* The first loop only determines "ndir" and uses TIFFLinkDirectory() to
562
         * set the offset at which the IFD is to be written to the file.
563
         * The second loop writes IFD entries to the file. */
564
0
        ndir = 0;
565
0
        if (dir == NULL)
566
0
            tif->tif_dir.td_dirdatasize_write = 0;
567
0
        if (isimage)
568
0
        {
569
            /*-- Step 1: Process named tags for an image with FIELD bits
570
             *           associated. --*/
571
0
            if (TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS))
572
0
            {
573
0
                if (!TIFFWriteDirectoryTagShortLong(tif, &ndir, dir,
574
0
                                                    TIFFTAG_IMAGEWIDTH,
575
0
                                                    tif->tif_dir.td_imagewidth))
576
0
                    goto bad;
577
0
                if (!TIFFWriteDirectoryTagShortLong(
578
0
                        tif, &ndir, dir, TIFFTAG_IMAGELENGTH,
579
0
                        tif->tif_dir.td_imagelength))
580
0
                    goto bad;
581
0
            }
582
0
            if (TIFFFieldSet(tif, FIELD_TILEDIMENSIONS))
583
0
            {
584
0
                if (!TIFFWriteDirectoryTagShortLong(tif, &ndir, dir,
585
0
                                                    TIFFTAG_TILEWIDTH,
586
0
                                                    tif->tif_dir.td_tilewidth))
587
0
                    goto bad;
588
0
                if (!TIFFWriteDirectoryTagShortLong(tif, &ndir, dir,
589
0
                                                    TIFFTAG_TILELENGTH,
590
0
                                                    tif->tif_dir.td_tilelength))
591
0
                    goto bad;
592
0
            }
593
0
            if (TIFFFieldSet(tif, FIELD_RESOLUTION))
594
0
            {
595
0
                if (!TIFFWriteDirectoryTagRational(tif, &ndir, dir,
596
0
                                                   TIFFTAG_XRESOLUTION,
597
0
                                                   tif->tif_dir.td_xresolution))
598
0
                    goto bad;
599
0
                if (!TIFFWriteDirectoryTagRational(tif, &ndir, dir,
600
0
                                                   TIFFTAG_YRESOLUTION,
601
0
                                                   tif->tif_dir.td_yresolution))
602
0
                    goto bad;
603
0
            }
604
0
            if (TIFFFieldSet(tif, FIELD_POSITION))
605
0
            {
606
0
                if (!TIFFWriteDirectoryTagRational(tif, &ndir, dir,
607
0
                                                   TIFFTAG_XPOSITION,
608
0
                                                   tif->tif_dir.td_xposition))
609
0
                    goto bad;
610
0
                if (!TIFFWriteDirectoryTagRational(tif, &ndir, dir,
611
0
                                                   TIFFTAG_YPOSITION,
612
0
                                                   tif->tif_dir.td_yposition))
613
0
                    goto bad;
614
0
            }
615
0
            if (TIFFFieldSet(tif, FIELD_SUBFILETYPE))
616
0
            {
617
0
                if (!TIFFWriteDirectoryTagLong(tif, &ndir, dir,
618
0
                                               TIFFTAG_SUBFILETYPE,
619
0
                                               tif->tif_dir.td_subfiletype))
620
0
                    goto bad;
621
0
            }
622
0
            if (TIFFFieldSet(tif, FIELD_BITSPERSAMPLE))
623
0
            {
624
0
                if (!TIFFWriteDirectoryTagShortPerSample(
625
0
                        tif, &ndir, dir, TIFFTAG_BITSPERSAMPLE,
626
0
                        tif->tif_dir.td_bitspersample))
627
0
                    goto bad;
628
0
            }
629
0
            if (TIFFFieldSet(tif, FIELD_COMPRESSION))
630
0
            {
631
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
632
0
                                                TIFFTAG_COMPRESSION,
633
0
                                                tif->tif_dir.td_compression))
634
0
                    goto bad;
635
0
            }
636
0
            if (TIFFFieldSet(tif, FIELD_PHOTOMETRIC))
637
0
            {
638
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
639
0
                                                TIFFTAG_PHOTOMETRIC,
640
0
                                                tif->tif_dir.td_photometric))
641
0
                    goto bad;
642
0
            }
643
0
            if (TIFFFieldSet(tif, FIELD_THRESHHOLDING))
644
0
            {
645
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
646
0
                                                TIFFTAG_THRESHHOLDING,
647
0
                                                tif->tif_dir.td_threshholding))
648
0
                    goto bad;
649
0
            }
650
0
            if (TIFFFieldSet(tif, FIELD_FILLORDER))
651
0
            {
652
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
653
0
                                                TIFFTAG_FILLORDER,
654
0
                                                tif->tif_dir.td_fillorder))
655
0
                    goto bad;
656
0
            }
657
0
            if (TIFFFieldSet(tif, FIELD_ORIENTATION))
658
0
            {
659
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
660
0
                                                TIFFTAG_ORIENTATION,
661
0
                                                tif->tif_dir.td_orientation))
662
0
                    goto bad;
663
0
            }
664
0
            if (TIFFFieldSet(tif, FIELD_SAMPLESPERPIXEL))
665
0
            {
666
0
                if (!TIFFWriteDirectoryTagShort(
667
0
                        tif, &ndir, dir, TIFFTAG_SAMPLESPERPIXEL,
668
0
                        tif->tif_dir.td_samplesperpixel))
669
0
                    goto bad;
670
0
            }
671
0
            if (TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
672
0
            {
673
0
                if (!TIFFWriteDirectoryTagShortLong(
674
0
                        tif, &ndir, dir, TIFFTAG_ROWSPERSTRIP,
675
0
                        tif->tif_dir.td_rowsperstrip))
676
0
                    goto bad;
677
0
            }
678
0
            if (TIFFFieldSet(tif, FIELD_MINSAMPLEVALUE))
679
0
            {
680
0
                if (!TIFFWriteDirectoryTagShortPerSample(
681
0
                        tif, &ndir, dir, TIFFTAG_MINSAMPLEVALUE,
682
0
                        tif->tif_dir.td_minsamplevalue))
683
0
                    goto bad;
684
0
            }
685
0
            if (TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
686
0
            {
687
0
                if (!TIFFWriteDirectoryTagShortPerSample(
688
0
                        tif, &ndir, dir, TIFFTAG_MAXSAMPLEVALUE,
689
0
                        tif->tif_dir.td_maxsamplevalue))
690
0
                    goto bad;
691
0
            }
692
0
            if (TIFFFieldSet(tif, FIELD_PLANARCONFIG))
693
0
            {
694
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
695
0
                                                TIFFTAG_PLANARCONFIG,
696
0
                                                tif->tif_dir.td_planarconfig))
697
0
                    goto bad;
698
0
            }
699
0
            if (TIFFFieldSet(tif, FIELD_RESOLUTIONUNIT))
700
0
            {
701
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
702
0
                                                TIFFTAG_RESOLUTIONUNIT,
703
0
                                                tif->tif_dir.td_resolutionunit))
704
0
                    goto bad;
705
0
            }
706
0
            if (TIFFFieldSet(tif, FIELD_PAGENUMBER))
707
0
            {
708
0
                if (!TIFFWriteDirectoryTagShortArray(
709
0
                        tif, &ndir, dir, TIFFTAG_PAGENUMBER, 2,
710
0
                        &tif->tif_dir.td_pagenumber[0]))
711
0
                    goto bad;
712
0
            }
713
0
            if (TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS))
714
0
            {
715
                /*  Check td_stripbytecount_p for NULL pointer (bug#749) */
716
0
                if (tif->tif_dir.td_stripbytecount_p == NULL)
717
0
                {
718
0
                    TIFFErrorExtR(
719
0
                        tif, module,
720
0
                        "StripByteCount array is not set, pointer is NULL");
721
0
                    goto bad;
722
0
                }
723
0
                if (!isTiled(tif))
724
0
                {
725
0
                    if (!TIFFWriteDirectoryTagLongLong8Array(
726
0
                            tif, &ndir, dir, TIFFTAG_STRIPBYTECOUNTS,
727
0
                            tif->tif_dir.td_nstrips,
728
0
                            tif->tif_dir.td_stripbytecount_p))
729
0
                        goto bad;
730
0
                }
731
0
                else
732
0
                {
733
0
                    if (!TIFFWriteDirectoryTagLongLong8Array(
734
0
                            tif, &ndir, dir, TIFFTAG_TILEBYTECOUNTS,
735
0
                            tif->tif_dir.td_nstrips,
736
0
                            tif->tif_dir.td_stripbytecount_p))
737
0
                        goto bad;
738
0
                }
739
0
            }
740
0
            if (TIFFFieldSet(tif, FIELD_STRIPOFFSETS))
741
0
            {
742
                /*  Check td_stripoffset_p for NULL pointer (bug#749) */
743
0
                if (tif->tif_dir.td_stripoffset_p == NULL)
744
0
                {
745
0
                    TIFFErrorExtR(
746
0
                        tif, module,
747
0
                        "StripByteOffset array is not set, pointer is NULL");
748
0
                    goto bad;
749
0
                }
750
0
                if (!isTiled(tif))
751
0
                {
752
                    /* td_stripoffset_p might be NULL in an odd OJPEG case. See
753
                     *  tif_dirread.c around line 3634.
754
                     * XXX: OJPEG hack.
755
                     * If a) compression is OJPEG, b) it's not a tiled TIFF,
756
                     * and c) the number of strips is 1,
757
                     * then we tolerate the absence of stripoffsets tag,
758
                     * because, presumably, all required data is in the
759
                     * JpegInterchangeFormat stream.
760
                     * We can get here when using tiffset on such a file.
761
                     * See http://bugzilla.maptools.org/show_bug.cgi?id=2500
762
                     */
763
0
                    if (tif->tif_dir.td_stripoffset_p != NULL &&
764
0
                        !TIFFWriteDirectoryTagLongLong8Array(
765
0
                            tif, &ndir, dir, TIFFTAG_STRIPOFFSETS,
766
0
                            tif->tif_dir.td_nstrips,
767
0
                            tif->tif_dir.td_stripoffset_p))
768
0
                        goto bad;
769
0
                }
770
0
                else
771
0
                {
772
0
                    if (!TIFFWriteDirectoryTagLongLong8Array(
773
0
                            tif, &ndir, dir, TIFFTAG_TILEOFFSETS,
774
0
                            tif->tif_dir.td_nstrips,
775
0
                            tif->tif_dir.td_stripoffset_p))
776
0
                        goto bad;
777
0
                }
778
0
            }
779
0
            if (TIFFFieldSet(tif, FIELD_COLORMAP))
780
0
            {
781
0
                if (!TIFFWriteDirectoryTagColormap(tif, &ndir, dir))
782
0
                    goto bad;
783
0
            }
784
0
            if (TIFFFieldSet(tif, FIELD_EXTRASAMPLES))
785
0
            {
786
0
                if (tif->tif_dir.td_extrasamples)
787
0
                {
788
0
                    uint16_t na;
789
0
                    uint16_t *nb;
790
0
                    TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &na, &nb);
791
0
                    if (!TIFFWriteDirectoryTagShortArray(
792
0
                            tif, &ndir, dir, TIFFTAG_EXTRASAMPLES, na, nb))
793
0
                        goto bad;
794
0
                }
795
0
            }
796
0
            if (TIFFFieldSet(tif, FIELD_SAMPLEFORMAT))
797
0
            {
798
0
                if (!TIFFWriteDirectoryTagShortPerSample(
799
0
                        tif, &ndir, dir, TIFFTAG_SAMPLEFORMAT,
800
0
                        tif->tif_dir.td_sampleformat))
801
0
                    goto bad;
802
0
            }
803
0
            if (TIFFFieldSet(tif, FIELD_SMINSAMPLEVALUE))
804
0
            {
805
0
                if (!TIFFWriteDirectoryTagSampleformatArray(
806
0
                        tif, &ndir, dir, TIFFTAG_SMINSAMPLEVALUE,
807
0
                        tif->tif_dir.td_samplesperpixel,
808
0
                        tif->tif_dir.td_sminsamplevalue))
809
0
                    goto bad;
810
0
            }
811
0
            if (TIFFFieldSet(tif, FIELD_SMAXSAMPLEVALUE))
812
0
            {
813
0
                if (!TIFFWriteDirectoryTagSampleformatArray(
814
0
                        tif, &ndir, dir, TIFFTAG_SMAXSAMPLEVALUE,
815
0
                        tif->tif_dir.td_samplesperpixel,
816
0
                        tif->tif_dir.td_smaxsamplevalue))
817
0
                    goto bad;
818
0
            }
819
0
            if (TIFFFieldSet(tif, FIELD_IMAGEDEPTH))
820
0
            {
821
0
                if (!TIFFWriteDirectoryTagLong(tif, &ndir, dir,
822
0
                                               TIFFTAG_IMAGEDEPTH,
823
0
                                               tif->tif_dir.td_imagedepth))
824
0
                    goto bad;
825
0
            }
826
0
            if (TIFFFieldSet(tif, FIELD_TILEDEPTH))
827
0
            {
828
0
                if (!TIFFWriteDirectoryTagLong(tif, &ndir, dir,
829
0
                                               TIFFTAG_TILEDEPTH,
830
0
                                               tif->tif_dir.td_tiledepth))
831
0
                    goto bad;
832
0
            }
833
0
            if (TIFFFieldSet(tif, FIELD_HALFTONEHINTS))
834
0
            {
835
0
                if (!TIFFWriteDirectoryTagShortArray(
836
0
                        tif, &ndir, dir, TIFFTAG_HALFTONEHINTS, 2,
837
0
                        &tif->tif_dir.td_halftonehints[0]))
838
0
                    goto bad;
839
0
            }
840
0
            if (TIFFFieldSet(tif, FIELD_YCBCRSUBSAMPLING))
841
0
            {
842
0
                if (!TIFFWriteDirectoryTagShortArray(
843
0
                        tif, &ndir, dir, TIFFTAG_YCBCRSUBSAMPLING, 2,
844
0
                        &tif->tif_dir.td_ycbcrsubsampling[0]))
845
0
                    goto bad;
846
0
            }
847
0
            if (TIFFFieldSet(tif, FIELD_YCBCRPOSITIONING))
848
0
            {
849
0
                if (!TIFFWriteDirectoryTagShort(
850
0
                        tif, &ndir, dir, TIFFTAG_YCBCRPOSITIONING,
851
0
                        tif->tif_dir.td_ycbcrpositioning))
852
0
                    goto bad;
853
0
            }
854
0
            if (TIFFFieldSet(tif, FIELD_REFBLACKWHITE))
855
0
            {
856
0
                if (!TIFFWriteDirectoryTagRationalArray(
857
0
                        tif, &ndir, dir, TIFFTAG_REFERENCEBLACKWHITE, 6,
858
0
                        tif->tif_dir.td_refblackwhite))
859
0
                    goto bad;
860
0
            }
861
0
            if (TIFFFieldSet(tif, FIELD_TRANSFERFUNCTION))
862
0
            {
863
0
                if (!TIFFWriteDirectoryTagTransferfunction(tif, &ndir, dir))
864
0
                    goto bad;
865
0
            }
866
0
            if (TIFFFieldSet(tif, FIELD_INKNAMES))
867
0
            {
868
0
                if (!TIFFWriteDirectoryTagAscii(
869
0
                        tif, &ndir, dir, TIFFTAG_INKNAMES,
870
0
                        tif->tif_dir.td_inknameslen, tif->tif_dir.td_inknames))
871
0
                    goto bad;
872
0
            }
873
0
            if (TIFFFieldSet(tif, FIELD_NUMBEROFINKS))
874
0
            {
875
0
                if (!TIFFWriteDirectoryTagShort(tif, &ndir, dir,
876
0
                                                TIFFTAG_NUMBEROFINKS,
877
0
                                                tif->tif_dir.td_numberofinks))
878
0
                    goto bad;
879
0
            }
880
0
            if (TIFFFieldSet(tif, FIELD_SUBIFD))
881
0
            {
882
0
                if (!TIFFWriteDirectoryTagSubifd(tif, &ndir, dir))
883
0
                    goto bad;
884
0
            }
885
            /*-- Step 2: Process named tags for an image with FIELD bits
886
                         added by a codec.
887
                         Attention: There is only code for some field_types,
888
                         which are actually used by current codecs. --*/
889
0
            {
890
0
                uint32_t n;
891
0
                for (n = 0; n < tif->tif_nfields; n++)
892
0
                {
893
0
                    const TIFFField *o;
894
0
                    o = tif->tif_fields[n];
895
0
                    if ((o->field_bit >= FIELD_CODEC) &&
896
0
                        (TIFFFieldSet(tif, o->field_bit)))
897
0
                    {
898
0
                        switch (o->set_get_field_type)
899
0
                        {
900
0
                            case TIFF_SETGET_ASCII:
901
0
                            {
902
0
                                uint32_t pa;
903
0
                                char *pb;
904
0
                                assert(o->field_type == TIFF_ASCII);
905
0
                                assert(o->field_readcount == TIFF_VARIABLE);
906
0
                                assert(o->field_passcount == 0);
907
0
                                TIFFGetField(tif, o->field_tag, &pb);
908
0
                                pa = (uint32_t)(strlen(pb) + 1);
909
0
                                if (!TIFFWriteDirectoryTagAscii(
910
0
                                        tif, &ndir, dir, (uint16_t)o->field_tag,
911
0
                                        pa, pb))
912
0
                                    goto bad;
913
0
                            }
914
0
                            break;
915
0
                            case TIFF_SETGET_UINT16:
916
0
                            {
917
0
                                uint16_t p;
918
0
                                assert(o->field_type == TIFF_SHORT);
919
0
                                assert(o->field_readcount == 1);
920
0
                                assert(o->field_passcount == 0);
921
0
                                TIFFGetField(tif, o->field_tag, &p);
922
0
                                if (!TIFFWriteDirectoryTagShort(
923
0
                                        tif, &ndir, dir, (uint16_t)o->field_tag,
924
0
                                        p))
925
0
                                    goto bad;
926
0
                            }
927
0
                            break;
928
0
                            case TIFF_SETGET_UINT32:
929
0
                            {
930
0
                                uint32_t p;
931
0
                                assert(o->field_type == TIFF_LONG);
932
0
                                assert(o->field_readcount == 1);
933
0
                                assert(o->field_passcount == 0);
934
0
                                TIFFGetField(tif, o->field_tag, &p);
935
0
                                if (!TIFFWriteDirectoryTagLong(
936
0
                                        tif, &ndir, dir, (uint16_t)o->field_tag,
937
0
                                        p))
938
0
                                    goto bad;
939
0
                            }
940
0
                            break;
941
0
                            case TIFF_SETGET_C32_UINT8:
942
0
                            {
943
0
                                uint32_t pa;
944
0
                                void *pb;
945
0
                                assert(o->field_type == TIFF_UNDEFINED);
946
0
                                assert(o->field_readcount == TIFF_VARIABLE2);
947
0
                                assert(o->field_passcount == 1);
948
0
                                TIFFGetField(tif, o->field_tag, &pa, &pb);
949
0
                                if (!TIFFWriteDirectoryTagUndefinedArray(
950
0
                                        tif, &ndir, dir, (uint16_t)o->field_tag,
951
0
                                        pa, (uint8_t *)pb))
952
0
                                    goto bad;
953
0
                            }
954
0
                            break;
955
0
                            case TIFF_SETGET_UNDEFINED:
956
0
                            case TIFF_SETGET_SINT8:
957
0
                            case TIFF_SETGET_SINT16:
958
0
                            case TIFF_SETGET_SINT32:
959
0
                            case TIFF_SETGET_UINT64:
960
0
                            case TIFF_SETGET_SINT64:
961
0
                            case TIFF_SETGET_FLOAT:
962
0
                            case TIFF_SETGET_DOUBLE:
963
0
                            case TIFF_SETGET_IFD8:
964
0
                            case TIFF_SETGET_INT:
965
0
                            case TIFF_SETGET_UINT16_PAIR:
966
0
                            case TIFF_SETGET_C0_ASCII:
967
0
                            case TIFF_SETGET_C0_UINT8:
968
0
                            case TIFF_SETGET_C0_SINT8:
969
0
                            case TIFF_SETGET_C0_UINT16:
970
0
                            case TIFF_SETGET_C0_SINT16:
971
0
                            case TIFF_SETGET_C0_UINT32:
972
0
                            case TIFF_SETGET_C0_SINT32:
973
0
                            case TIFF_SETGET_C0_UINT64:
974
0
                            case TIFF_SETGET_C0_SINT64:
975
0
                            case TIFF_SETGET_C0_FLOAT:
976
0
                            case TIFF_SETGET_C0_DOUBLE:
977
0
                            case TIFF_SETGET_C0_IFD8:
978
0
                            case TIFF_SETGET_C16_ASCII:
979
0
                            case TIFF_SETGET_C16_UINT8:
980
0
                            case TIFF_SETGET_C16_SINT8:
981
0
                            case TIFF_SETGET_C16_UINT16:
982
0
                            case TIFF_SETGET_C16_SINT16:
983
0
                            case TIFF_SETGET_C16_UINT32:
984
0
                            case TIFF_SETGET_C16_SINT32:
985
0
                            case TIFF_SETGET_C16_UINT64:
986
0
                            case TIFF_SETGET_C16_SINT64:
987
0
                            case TIFF_SETGET_C16_FLOAT:
988
0
                            case TIFF_SETGET_C16_DOUBLE:
989
0
                            case TIFF_SETGET_C16_IFD8:
990
0
                            case TIFF_SETGET_C32_ASCII:
991
0
                            case TIFF_SETGET_C32_SINT8:
992
0
                            case TIFF_SETGET_C32_UINT16:
993
0
                            case TIFF_SETGET_C32_SINT16:
994
0
                            case TIFF_SETGET_C32_UINT32:
995
0
                            case TIFF_SETGET_C32_SINT32:
996
0
                            case TIFF_SETGET_C32_UINT64:
997
0
                            case TIFF_SETGET_C32_SINT64:
998
0
                            case TIFF_SETGET_C32_FLOAT:
999
0
                            case TIFF_SETGET_C32_DOUBLE:
1000
0
                            case TIFF_SETGET_C32_IFD8:
1001
0
                            case TIFF_SETGET_UINT8:
1002
0
                            case TIFF_SETGET_OTHER:
1003
0
                            default:
1004
0
                                TIFFErrorExtR(
1005
0
                                    tif, module,
1006
0
                                    "Cannot write tag %" PRIu32 " (%s)",
1007
0
                                    TIFFFieldTag(o),
1008
0
                                    o->field_name ? o->field_name : "unknown");
1009
0
                                goto bad;
1010
0
                        }
1011
0
                    }
1012
0
                }
1013
0
            }
1014
0
        }
1015
        /*-- Step 3: Process custom tags without FIELD bit for an image
1016
         *           or for custom IFDs (e.g. EXIF) with !isimage. --*/
1017
0
        for (m = 0; m < (uint32_t)(tif->tif_dir.td_customValueCount); m++)
1018
0
        {
1019
0
            uint16_t tag =
1020
0
                (uint16_t)tif->tif_dir.td_customValues[m].info->field_tag;
1021
0
            uint32_t count = tif->tif_dir.td_customValues[m].count;
1022
0
            switch (tif->tif_dir.td_customValues[m].info->field_type)
1023
0
            {
1024
0
                case TIFF_ASCII:
1025
0
                    if (!TIFFWriteDirectoryTagAscii(
1026
0
                            tif, &ndir, dir, tag, count,
1027
0
                            (char *)tif->tif_dir.td_customValues[m].value))
1028
0
                        goto bad;
1029
0
                    break;
1030
0
                case TIFF_UNDEFINED:
1031
0
                    if (!TIFFWriteDirectoryTagUndefinedArray(
1032
0
                            tif, &ndir, dir, tag, count,
1033
0
                            (uint8_t *)tif->tif_dir.td_customValues[m].value))
1034
0
                        goto bad;
1035
0
                    break;
1036
0
                case TIFF_BYTE:
1037
0
                    if (!TIFFWriteDirectoryTagByteArray(
1038
0
                            tif, &ndir, dir, tag, count,
1039
0
                            (uint8_t *)tif->tif_dir.td_customValues[m].value))
1040
0
                        goto bad;
1041
0
                    break;
1042
0
                case TIFF_SBYTE:
1043
0
                    if (!TIFFWriteDirectoryTagSbyteArray(
1044
0
                            tif, &ndir, dir, tag, count,
1045
0
                            (int8_t *)tif->tif_dir.td_customValues[m].value))
1046
0
                        goto bad;
1047
0
                    break;
1048
0
                case TIFF_SHORT:
1049
0
                    if (!TIFFWriteDirectoryTagShortArray(
1050
0
                            tif, &ndir, dir, tag, count,
1051
0
                            (uint16_t *)tif->tif_dir.td_customValues[m].value))
1052
0
                        goto bad;
1053
0
                    break;
1054
0
                case TIFF_SSHORT:
1055
0
                    if (!TIFFWriteDirectoryTagSshortArray(
1056
0
                            tif, &ndir, dir, tag, count,
1057
0
                            (int16_t *)tif->tif_dir.td_customValues[m].value))
1058
0
                        goto bad;
1059
0
                    break;
1060
0
                case TIFF_LONG:
1061
0
                    if (!TIFFWriteDirectoryTagLongArray(
1062
0
                            tif, &ndir, dir, tag, count,
1063
0
                            (uint32_t *)tif->tif_dir.td_customValues[m].value))
1064
0
                        goto bad;
1065
0
                    break;
1066
0
                case TIFF_SLONG:
1067
0
                    if (!TIFFWriteDirectoryTagSlongArray(
1068
0
                            tif, &ndir, dir, tag, count,
1069
0
                            (int32_t *)tif->tif_dir.td_customValues[m].value))
1070
0
                        goto bad;
1071
0
                    break;
1072
0
                case TIFF_LONG8:
1073
0
                    if (!TIFFWriteDirectoryTagLong8Array(
1074
0
                            tif, &ndir, dir, tag, count,
1075
0
                            (uint64_t *)tif->tif_dir.td_customValues[m].value))
1076
0
                        goto bad;
1077
0
                    break;
1078
0
                case TIFF_SLONG8:
1079
0
                    if (!TIFFWriteDirectoryTagSlong8Array(
1080
0
                            tif, &ndir, dir, tag, count,
1081
0
                            (int64_t *)tif->tif_dir.td_customValues[m].value))
1082
0
                        goto bad;
1083
0
                    break;
1084
0
                case TIFF_RATIONAL:
1085
0
                {
1086
                    /*-- Rational2Double: For Rationals evaluate
1087
                     * "set_get_field_type" to determine internal storage size.
1088
                     */
1089
0
                    int tv_size;
1090
0
                    tv_size = TIFFFieldSetGetSize(
1091
0
                        tif->tif_dir.td_customValues[m].info);
1092
0
                    if (tv_size == 8)
1093
0
                    {
1094
0
                        if (!TIFFWriteDirectoryTagRationalDoubleArray(
1095
0
                                tif, &ndir, dir, tag, count,
1096
0
                                (double *)tif->tif_dir.td_customValues[m].value))
1097
0
                            goto bad;
1098
0
                    }
1099
0
                    else
1100
0
                    {
1101
                        /*-- default should be tv_size == 4 */
1102
0
                        if (!TIFFWriteDirectoryTagRationalArray(
1103
0
                                tif, &ndir, dir, tag, count,
1104
0
                                (float *)tif->tif_dir.td_customValues[m].value))
1105
0
                            goto bad;
1106
                        /*-- ToDo: After Testing, this should be removed and
1107
                         * tv_size==4 should be set as default. */
1108
0
                        if (tv_size != 4)
1109
0
                        {
1110
0
                            TIFFErrorExtR(
1111
0
                                tif, "TIFFLib: _TIFFWriteDirectorySec()",
1112
0
                                "Rational2Double: .set_get_field_type is "
1113
0
                                "not 4 but %d",
1114
0
                                tv_size);
1115
0
                        }
1116
0
                    }
1117
0
                }
1118
0
                break;
1119
0
                case TIFF_SRATIONAL:
1120
0
                {
1121
                    /*-- Rational2Double: For Rationals evaluate
1122
                     * "set_get_field_type" to determine internal storage size.
1123
                     */
1124
0
                    int tv_size;
1125
0
                    tv_size = TIFFFieldSetGetSize(
1126
0
                        tif->tif_dir.td_customValues[m].info);
1127
0
                    if (tv_size == 8)
1128
0
                    {
1129
0
                        if (!TIFFWriteDirectoryTagSrationalDoubleArray(
1130
0
                                tif, &ndir, dir, tag, count,
1131
0
                                (double *)tif->tif_dir.td_customValues[m].value))
1132
0
                            goto bad;
1133
0
                    }
1134
0
                    else
1135
0
                    {
1136
                        /*-- default should be tv_size == 4 */
1137
0
                        if (!TIFFWriteDirectoryTagSrationalArray(
1138
0
                                tif, &ndir, dir, tag, count,
1139
0
                                (float *)tif->tif_dir.td_customValues[m].value))
1140
0
                            goto bad;
1141
                        /*-- ToDo: After Testing, this should be removed and
1142
                         * tv_size==4 should be set as default. */
1143
0
                        if (tv_size != 4)
1144
0
                        {
1145
0
                            TIFFErrorExtR(
1146
0
                                tif, "TIFFLib: _TIFFWriteDirectorySec()",
1147
0
                                "Rational2Double: .set_get_field_type is "
1148
0
                                "not 4 but %d",
1149
0
                                tv_size);
1150
0
                        }
1151
0
                    }
1152
0
                }
1153
0
                break;
1154
0
                case TIFF_FLOAT:
1155
0
                    if (!TIFFWriteDirectoryTagFloatArray(
1156
0
                            tif, &ndir, dir, tag, count,
1157
0
                            (float *)tif->tif_dir.td_customValues[m].value))
1158
0
                        goto bad;
1159
0
                    break;
1160
0
                case TIFF_DOUBLE:
1161
0
                    if (!TIFFWriteDirectoryTagDoubleArray(
1162
0
                            tif, &ndir, dir, tag, count,
1163
0
                            (double *)tif->tif_dir.td_customValues[m].value))
1164
0
                        goto bad;
1165
0
                    break;
1166
0
                case TIFF_IFD:
1167
0
                    if (!TIFFWriteDirectoryTagIfdArray(
1168
0
                            tif, &ndir, dir, tag, count,
1169
0
                            (uint32_t *)tif->tif_dir.td_customValues[m].value))
1170
0
                        goto bad;
1171
0
                    break;
1172
0
                case TIFF_IFD8:
1173
0
                    if (!TIFFWriteDirectoryTagIfdIfd8Array(
1174
0
                            tif, &ndir, dir, tag, count,
1175
0
                            (uint64_t *)tif->tif_dir.td_customValues[m].value))
1176
0
                        goto bad;
1177
0
                    break;
1178
0
                case TIFF_NOTYPE:
1179
0
                default:
1180
0
                    assert(0); /* we should never get here */
1181
0
                    break;
1182
0
            }
1183
0
        }
1184
        /* "break" if IFD has been written above in second pass.*/
1185
0
        if (dir != NULL)
1186
0
            break;
1187
1188
        /* Evaluate IFD data size: Finally, add the size of the IFD tag entries
1189
         * themselves. */
1190
0
        if (!(tif->tif_flags & TIFF_BIGTIFF))
1191
0
            tif->tif_dir.td_dirdatasize_write += 2 + ndir * 12 + 4;
1192
0
        else
1193
0
            tif->tif_dir.td_dirdatasize_write += 8 + ndir * 20 + 8;
1194
1195
        /* Setup a new directory within first pass. */
1196
0
        dir = (TIFFDirEntry *)_TIFFmallocExt(tif, ndir * sizeof(TIFFDirEntry));
1197
0
        if (dir == NULL)
1198
0
        {
1199
0
            TIFFErrorExtR(tif, module, "Out of memory");
1200
0
            goto bad;
1201
0
        }
1202
0
        if (isimage)
1203
0
        {
1204
            /* Check, weather the IFD to be written is new or an already written
1205
             * IFD can be overwritten or needs to be re-written to a different
1206
             * location in the file because the IFD is extended with additional
1207
             * tags or the IFD data size is increased.
1208
             * - tif_diroff == 0, if a new directory has to be linked.
1209
             * - tif_diroff != 0, IFD has been re-read from file and will be
1210
             *   overwritten or re-written.
1211
             */
1212
0
            if (tif->tif_diroff == 0)
1213
0
            {
1214
0
                if (!TIFFLinkDirectory(tif))
1215
0
                    goto bad;
1216
0
            }
1217
0
            else if (tif->tif_dir.td_dirdatasize_write >
1218
0
                     tif->tif_dir.td_dirdatasize_read)
1219
0
            {
1220
0
                if (dir != NULL)
1221
0
                {
1222
0
                    _TIFFfreeExt(tif, dir);
1223
0
                    dir = NULL;
1224
0
                }
1225
0
                if (!TIFFRewriteDirectorySec(tif, isimage, imagedone, pdiroff))
1226
0
                    goto bad;
1227
0
                return (1);
1228
0
            }
1229
0
        }
1230
0
        else
1231
0
        {
1232
            /* For !isimage, which means custom-IFD like EXIFIFD or
1233
             * checkpointing an IFD, determine whether to overwrite or append at
1234
             * the end of the file.
1235
             */
1236
0
            if (!((tif->tif_dir.td_dirdatasize_read > 0) &&
1237
0
                  (tif->tif_dir.td_dirdatasize_write <=
1238
0
                   tif->tif_dir.td_dirdatasize_read)))
1239
0
            {
1240
                /* Append at end of file and increment to an even offset. */
1241
0
                tif->tif_diroff =
1242
0
                    (TIFFSeekFile(tif, 0, SEEK_END) + 1) & (~((toff_t)1));
1243
0
            }
1244
0
        }
1245
        /* Return IFD offset */
1246
0
        if (pdiroff != NULL)
1247
0
            *pdiroff = tif->tif_diroff;
1248
0
        if (!(tif->tif_flags & TIFF_BIGTIFF))
1249
0
            dirsize = 2 + ndir * 12 + 4;
1250
0
        else
1251
0
            dirsize = 8 + ndir * 20 + 8;
1252
        /* Append IFD data stright after the IFD tag entries.
1253
         * Data that does not fit into an IFD tag entry is written to the file
1254
         * in the second pass of the while loop. That offset is stored in "dir".
1255
         */
1256
0
        tif->tif_dataoff = tif->tif_diroff + dirsize;
1257
0
        if (!(tif->tif_flags & TIFF_BIGTIFF))
1258
0
            tif->tif_dataoff = (uint32_t)tif->tif_dataoff;
1259
0
        if ((tif->tif_dataoff < tif->tif_diroff) ||
1260
0
            (tif->tif_dataoff < (uint64_t)dirsize))
1261
0
        {
1262
0
            TIFFErrorExtR(tif, module, "Maximum TIFF file size exceeded");
1263
0
            goto bad;
1264
0
        }
1265
0
        if (tif->tif_dataoff & 1)
1266
0
            tif->tif_dataoff++;
1267
0
    } /* while() */
1268
0
    if (isimage)
1269
0
    {
1270
        /* For SubIFDs remember offset of SubIFD tag within main IFD.
1271
         * However, might be already done in TIFFWriteDirectoryTagSubifd() if
1272
         * there are more than one SubIFD. */
1273
0
        if (TIFFFieldSet(tif, FIELD_SUBIFD) && (tif->tif_subifdoff == 0))
1274
0
        {
1275
0
            uint32_t na;
1276
0
            TIFFDirEntry *nb;
1277
0
            for (na = 0, nb = dir;; na++, nb++)
1278
0
            {
1279
0
                if (na == ndir)
1280
0
                {
1281
0
                    TIFFErrorExtR(tif, module, "Cannot find SubIFD tag");
1282
0
                    goto bad;
1283
0
                }
1284
0
                if (nb->tdir_tag == TIFFTAG_SUBIFD)
1285
0
                    break;
1286
0
            }
1287
0
            if (!(tif->tif_flags & TIFF_BIGTIFF))
1288
0
                tif->tif_subifdoff = tif->tif_diroff + 2 + na * 12 + 8;
1289
0
            else
1290
0
                tif->tif_subifdoff = tif->tif_diroff + 8 + na * 20 + 12;
1291
0
        }
1292
0
    }
1293
    /* Copy/swab IFD entries from "dir" into "dirmem",
1294
     * which is then written to file. */
1295
0
    dirmem = _TIFFmallocExt(tif, dirsize);
1296
0
    if (dirmem == NULL)
1297
0
    {
1298
0
        TIFFErrorExtR(tif, module, "Out of memory");
1299
0
        goto bad;
1300
0
    }
1301
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
1302
0
    {
1303
0
        uint8_t *n;
1304
0
        uint32_t nTmp;
1305
0
        TIFFDirEntry *o;
1306
0
        n = (uint8_t *)dirmem;
1307
0
        *(uint16_t *)n = (uint16_t)ndir;
1308
0
        if (tif->tif_flags & TIFF_SWAB)
1309
0
            TIFFSwabShort((uint16_t *)n);
1310
0
        n += 2;
1311
0
        o = dir;
1312
0
        for (m = 0; m < ndir; m++)
1313
0
        {
1314
0
            *(uint16_t *)n = o->tdir_tag;
1315
0
            if (tif->tif_flags & TIFF_SWAB)
1316
0
                TIFFSwabShort((uint16_t *)n);
1317
0
            n += 2;
1318
0
            *(uint16_t *)n = o->tdir_type;
1319
0
            if (tif->tif_flags & TIFF_SWAB)
1320
0
                TIFFSwabShort((uint16_t *)n);
1321
0
            n += 2;
1322
0
            nTmp = (uint32_t)o->tdir_count;
1323
0
            _TIFFmemcpy(n, &nTmp, 4);
1324
0
            if (tif->tif_flags & TIFF_SWAB)
1325
0
                TIFFSwabLong((uint32_t *)n);
1326
0
            n += 4;
1327
            /* This is correct. The data has been */
1328
            /* swabbed previously in TIFFWriteDirectoryTagData */
1329
0
            _TIFFmemcpy(n, &o->tdir_offset, 4);
1330
0
            n += 4;
1331
0
            o++;
1332
0
        }
1333
0
        nTmp = (uint32_t)tif->tif_nextdiroff;
1334
0
        if (tif->tif_flags & TIFF_SWAB)
1335
0
            TIFFSwabLong(&nTmp);
1336
0
        _TIFFmemcpy(n, &nTmp, 4);
1337
0
    }
1338
0
    else
1339
0
    {
1340
0
        uint8_t *n;
1341
0
        TIFFDirEntry *o;
1342
0
        n = (uint8_t *)dirmem;
1343
0
        *(uint64_t *)n = ndir;
1344
0
        if (tif->tif_flags & TIFF_SWAB)
1345
0
            TIFFSwabLong8((uint64_t *)n);
1346
0
        n += 8;
1347
0
        o = dir;
1348
0
        for (m = 0; m < ndir; m++)
1349
0
        {
1350
0
            *(uint16_t *)n = o->tdir_tag;
1351
0
            if (tif->tif_flags & TIFF_SWAB)
1352
0
                TIFFSwabShort((uint16_t *)n);
1353
0
            n += 2;
1354
0
            *(uint16_t *)n = o->tdir_type;
1355
0
            if (tif->tif_flags & TIFF_SWAB)
1356
0
                TIFFSwabShort((uint16_t *)n);
1357
0
            n += 2;
1358
0
            _TIFFmemcpy(n, &o->tdir_count, 8);
1359
0
            if (tif->tif_flags & TIFF_SWAB)
1360
0
                TIFFSwabLong8((uint64_t *)n);
1361
0
            n += 8;
1362
0
            _TIFFmemcpy(n, &o->tdir_offset, 8);
1363
0
            n += 8;
1364
0
            o++;
1365
0
        }
1366
0
        _TIFFmemcpy(n, &tif->tif_nextdiroff, 8);
1367
0
        if (tif->tif_flags & TIFF_SWAB)
1368
0
            TIFFSwabLong8((uint64_t *)n);
1369
0
    }
1370
0
    _TIFFfreeExt(tif, dir);
1371
0
    dir = NULL;
1372
0
    if (!SeekOK(tif, tif->tif_diroff))
1373
0
    {
1374
0
        TIFFErrorExtR(tif, module,
1375
0
                      "IO error writing directory at seek to offset");
1376
0
        goto bad;
1377
0
    }
1378
0
    if (!WriteOK(tif, dirmem, (tmsize_t)dirsize))
1379
0
    {
1380
0
        TIFFErrorExtR(tif, module, "IO error writing directory");
1381
0
        goto bad;
1382
0
    }
1383
0
    _TIFFfreeExt(tif, dirmem);
1384
1385
    /* Increment tif_curdir if IFD wasn't already written to file and no error
1386
     * occurred during IFD writing above. */
1387
0
    if (isimage && !tif->tif_dir.td_iswrittentofile)
1388
0
    {
1389
0
        if (!((tif->tif_flags & TIFF_INSUBIFD) &&
1390
0
              !(TIFFFieldSet(tif, FIELD_SUBIFD))))
1391
0
        {
1392
            /*-- Normal main-IFD case --*/
1393
0
            if (tif->tif_curdircount != TIFF_NON_EXISTENT_DIR_NUMBER)
1394
0
            {
1395
0
                tif->tif_curdir = tif->tif_curdircount;
1396
0
            }
1397
0
            else
1398
0
            {
1399
                /*ToDo SU: NEW_IFD_CURDIR_INCREMENTING:  Delete this
1400
                 * unexpected case after some testing time. */
1401
                /* Attention: tif->tif_curdircount is already set within
1402
                 * TIFFNumberOfDirectories() */
1403
0
                tif->tif_curdircount = TIFFNumberOfDirectories(tif);
1404
0
                tif->tif_curdir = tif->tif_curdircount;
1405
0
                TIFFErrorExtR(
1406
0
                    tif, module,
1407
0
                    "tif_curdircount is TIFF_NON_EXISTENT_DIR_NUMBER, "
1408
0
                    "not expected !! Line %d",
1409
0
                    __LINE__);
1410
0
                goto bad;
1411
0
            }
1412
0
        }
1413
0
        else
1414
0
        {
1415
            /*-- SubIFD case -- */
1416
            /* tif_curdir is always set to 0 for all SubIFDs. */
1417
0
            tif->tif_curdir = 0;
1418
0
        }
1419
0
    }
1420
    /* Increment tif_curdircount only if main-IFD of an image was not already
1421
     * present on file. */
1422
    /* Check in combination with (... && !(TIFFFieldSet(tif, FIELD_SUBIFD)))
1423
     * is necessary here because TIFF_INSUBIFD was already set above for the
1424
     * next SubIFD when this main-IFD (with FIELD_SUBIFD) is currently being
1425
     * written. */
1426
0
    if (isimage && !tif->tif_dir.td_iswrittentofile &&
1427
0
        !((tif->tif_flags & TIFF_INSUBIFD) &&
1428
0
          !(TIFFFieldSet(tif, FIELD_SUBIFD))))
1429
0
        tif->tif_curdircount++;
1430
1431
0
    tif->tif_dir.td_iswrittentofile = TRUE;
1432
1433
    /* Reset SubIFD writing stage after last SubIFD has been written. */
1434
0
    if (imagedone && (tif->tif_flags & TIFF_INSUBIFD) && tif->tif_nsubifd == 0)
1435
0
        tif->tif_flags &= ~TIFF_INSUBIFD;
1436
1437
    /* Add or update this directory to the IFD list. */
1438
0
    if (!_TIFFCheckDirNumberAndOffset(tif, tif->tif_curdir, tif->tif_diroff))
1439
0
    {
1440
0
        TIFFErrorExtR(tif, module,
1441
0
                      "Starting directory %u at offset 0x%" PRIx64 " (%" PRIu64
1442
0
                      ") might cause an IFD loop",
1443
0
                      tif->tif_curdir, tif->tif_diroff, tif->tif_diroff);
1444
0
    }
1445
1446
0
    if (imagedone)
1447
0
    {
1448
0
        TIFFFreeDirectory(tif);
1449
0
        tif->tif_flags &= ~TIFF_DIRTYDIRECT;
1450
0
        tif->tif_flags &= ~TIFF_DIRTYSTRIP;
1451
        /* Reset directory-related state for subsequent directories. */
1452
0
        TIFFCreateDirectory(tif);
1453
0
    }
1454
0
    else
1455
0
    {
1456
        /* IFD is only checkpointed to file (or a custom IFD like EXIF is
1457
         * written), thus set IFD data size written to file. */
1458
0
        tif->tif_dir.td_dirdatasize_read = tif->tif_dir.td_dirdatasize_write;
1459
0
    }
1460
0
    return (1);
1461
0
bad:
1462
0
    if (dir != NULL)
1463
0
        _TIFFfreeExt(tif, dir);
1464
0
    if (dirmem != NULL)
1465
0
        _TIFFfreeExt(tif, dirmem);
1466
0
    return (0);
1467
0
}
1468
1469
static int8_t TIFFClampDoubleToInt8(double val)
1470
0
{
1471
0
    if (val > 127)
1472
0
        return 127;
1473
0
    if (val < -128 || val != val)
1474
0
        return -128;
1475
0
    return (int8_t)val;
1476
0
}
1477
1478
static int16_t TIFFClampDoubleToInt16(double val)
1479
0
{
1480
0
    if (val > 32767)
1481
0
        return 32767;
1482
0
    if (val < -32768 || val != val)
1483
0
        return -32768;
1484
0
    return (int16_t)val;
1485
0
}
1486
1487
static int32_t TIFFClampDoubleToInt32(double val)
1488
0
{
1489
0
    if (val > 0x7FFFFFFF)
1490
0
        return 0x7FFFFFFF;
1491
0
    if (val < -0x7FFFFFFF - 1 || val != val)
1492
0
        return -0x7FFFFFFF - 1;
1493
0
    return (int32_t)val;
1494
0
}
1495
1496
static uint8_t TIFFClampDoubleToUInt8(double val)
1497
0
{
1498
0
    if (val < 0)
1499
0
        return 0;
1500
0
    if (val > 255 || val != val)
1501
0
        return 255;
1502
0
    return (uint8_t)val;
1503
0
}
1504
1505
static uint16_t TIFFClampDoubleToUInt16(double val)
1506
0
{
1507
0
    if (val < 0)
1508
0
        return 0;
1509
0
    if (val > 65535 || val != val)
1510
0
        return 65535;
1511
0
    return (uint16_t)val;
1512
0
}
1513
1514
static uint32_t TIFFClampDoubleToUInt32(double val)
1515
0
{
1516
0
    if (val < 0)
1517
0
        return 0;
1518
0
    if (val > 0xFFFFFFFFU || val != val)
1519
0
        return 0xFFFFFFFFU;
1520
0
    return (uint32_t)val;
1521
0
}
1522
1523
static int TIFFWriteDirectoryTagSampleformatArray(TIFF *tif, uint32_t *ndir,
1524
                                                  TIFFDirEntry *dir,
1525
                                                  uint16_t tag, uint32_t count,
1526
                                                  double *value)
1527
0
{
1528
0
    static const char module[] = "TIFFWriteDirectoryTagSampleformatArray";
1529
0
    void *conv;
1530
0
    uint32_t i;
1531
0
    int ok;
1532
0
    conv = _TIFFmallocExt(tif, count * sizeof(double));
1533
0
    if (conv == NULL)
1534
0
    {
1535
0
        TIFFErrorExtR(tif, module, "Out of memory");
1536
0
        return (0);
1537
0
    }
1538
1539
0
    switch (tif->tif_dir.td_sampleformat)
1540
0
    {
1541
0
        case SAMPLEFORMAT_IEEEFP:
1542
0
            if (tif->tif_dir.td_bitspersample <= 32)
1543
0
            {
1544
0
                for (i = 0; i < count; ++i)
1545
0
                    ((float *)conv)[i] = _TIFFClampDoubleToFloat(value[i]);
1546
0
                ok = TIFFWriteDirectoryTagFloatArray(tif, ndir, dir, tag, count,
1547
0
                                                     (float *)conv);
1548
0
            }
1549
0
            else
1550
0
            {
1551
0
                ok = TIFFWriteDirectoryTagDoubleArray(tif, ndir, dir, tag,
1552
0
                                                      count, value);
1553
0
            }
1554
0
            break;
1555
0
        case SAMPLEFORMAT_INT:
1556
0
            if (tif->tif_dir.td_bitspersample <= 8)
1557
0
            {
1558
0
                for (i = 0; i < count; ++i)
1559
0
                    ((int8_t *)conv)[i] = TIFFClampDoubleToInt8(value[i]);
1560
0
                ok = TIFFWriteDirectoryTagSbyteArray(tif, ndir, dir, tag, count,
1561
0
                                                     (int8_t *)conv);
1562
0
            }
1563
0
            else if (tif->tif_dir.td_bitspersample <= 16)
1564
0
            {
1565
0
                for (i = 0; i < count; ++i)
1566
0
                    ((int16_t *)conv)[i] = TIFFClampDoubleToInt16(value[i]);
1567
0
                ok = TIFFWriteDirectoryTagSshortArray(tif, ndir, dir, tag,
1568
0
                                                      count, (int16_t *)conv);
1569
0
            }
1570
0
            else
1571
0
            {
1572
0
                for (i = 0; i < count; ++i)
1573
0
                    ((int32_t *)conv)[i] = TIFFClampDoubleToInt32(value[i]);
1574
0
                ok = TIFFWriteDirectoryTagSlongArray(tif, ndir, dir, tag, count,
1575
0
                                                     (int32_t *)conv);
1576
0
            }
1577
0
            break;
1578
0
        case SAMPLEFORMAT_UINT:
1579
0
            if (tif->tif_dir.td_bitspersample <= 8)
1580
0
            {
1581
0
                for (i = 0; i < count; ++i)
1582
0
                    ((uint8_t *)conv)[i] = TIFFClampDoubleToUInt8(value[i]);
1583
0
                ok = TIFFWriteDirectoryTagByteArray(tif, ndir, dir, tag, count,
1584
0
                                                    (uint8_t *)conv);
1585
0
            }
1586
0
            else if (tif->tif_dir.td_bitspersample <= 16)
1587
0
            {
1588
0
                for (i = 0; i < count; ++i)
1589
0
                    ((uint16_t *)conv)[i] = TIFFClampDoubleToUInt16(value[i]);
1590
0
                ok = TIFFWriteDirectoryTagShortArray(tif, ndir, dir, tag, count,
1591
0
                                                     (uint16_t *)conv);
1592
0
            }
1593
0
            else
1594
0
            {
1595
0
                for (i = 0; i < count; ++i)
1596
0
                    ((uint32_t *)conv)[i] = TIFFClampDoubleToUInt32(value[i]);
1597
0
                ok = TIFFWriteDirectoryTagLongArray(tif, ndir, dir, tag, count,
1598
0
                                                    (uint32_t *)conv);
1599
0
            }
1600
0
            break;
1601
0
        default:
1602
0
            ok = 0;
1603
0
    }
1604
1605
0
    _TIFFfreeExt(tif, conv);
1606
0
    return (ok);
1607
0
}
1608
1609
static int TIFFWriteDirectoryTagAscii(TIFF *tif, uint32_t *ndir,
1610
                                      TIFFDirEntry *dir, uint16_t tag,
1611
                                      uint32_t count, char *value)
1612
0
{
1613
0
    return (
1614
0
        TIFFWriteDirectoryTagCheckedAscii(tif, ndir, dir, tag, count, value));
1615
0
}
1616
1617
static int TIFFWriteDirectoryTagUndefinedArray(TIFF *tif, uint32_t *ndir,
1618
                                               TIFFDirEntry *dir, uint16_t tag,
1619
                                               uint32_t count, uint8_t *value)
1620
0
{
1621
0
    return (TIFFWriteDirectoryTagCheckedUndefinedArray(tif, ndir, dir, tag,
1622
0
                                                       count, value));
1623
0
}
1624
1625
static int TIFFWriteDirectoryTagByteArray(TIFF *tif, uint32_t *ndir,
1626
                                          TIFFDirEntry *dir, uint16_t tag,
1627
                                          uint32_t count, uint8_t *value)
1628
0
{
1629
0
    return (TIFFWriteDirectoryTagCheckedByteArray(tif, ndir, dir, tag, count,
1630
0
                                                  value));
1631
0
}
1632
1633
static int TIFFWriteDirectoryTagSbyteArray(TIFF *tif, uint32_t *ndir,
1634
                                           TIFFDirEntry *dir, uint16_t tag,
1635
                                           uint32_t count, int8_t *value)
1636
0
{
1637
0
    return (TIFFWriteDirectoryTagCheckedSbyteArray(tif, ndir, dir, tag, count,
1638
0
                                                   value));
1639
0
}
1640
1641
static int TIFFWriteDirectoryTagShort(TIFF *tif, uint32_t *ndir,
1642
                                      TIFFDirEntry *dir, uint16_t tag,
1643
                                      uint16_t value)
1644
0
{
1645
0
    return (TIFFWriteDirectoryTagCheckedShort(tif, ndir, dir, tag, value));
1646
0
}
1647
1648
static int TIFFWriteDirectoryTagShortArray(TIFF *tif, uint32_t *ndir,
1649
                                           TIFFDirEntry *dir, uint16_t tag,
1650
                                           uint32_t count, uint16_t *value)
1651
0
{
1652
0
    return (TIFFWriteDirectoryTagCheckedShortArray(tif, ndir, dir, tag, count,
1653
0
                                                   value));
1654
0
}
1655
1656
static int TIFFWriteDirectoryTagShortPerSample(TIFF *tif, uint32_t *ndir,
1657
                                               TIFFDirEntry *dir, uint16_t tag,
1658
                                               uint16_t value)
1659
0
{
1660
0
    static const char module[] = "TIFFWriteDirectoryTagShortPerSample";
1661
0
    uint16_t *m;
1662
0
    uint16_t *na;
1663
0
    uint16_t nb;
1664
0
    int o;
1665
0
    if (dir == NULL)
1666
0
    {
1667
        /* only evaluate IFD data size and inc. ndir */
1668
0
        return (TIFFWriteDirectoryTagCheckedShortArray(
1669
0
            tif, ndir, dir, tag, tif->tif_dir.td_samplesperpixel, NULL));
1670
0
    }
1671
0
    m = (uint16_t *)_TIFFmallocExt(tif, tif->tif_dir.td_samplesperpixel * sizeof(uint16_t));
1672
0
    if (m == NULL)
1673
0
    {
1674
0
        TIFFErrorExtR(tif, module, "Out of memory");
1675
0
        return (0);
1676
0
    }
1677
0
    for (na = m, nb = 0; nb < tif->tif_dir.td_samplesperpixel; na++, nb++)
1678
0
        *na = value;
1679
0
    o = TIFFWriteDirectoryTagCheckedShortArray(
1680
0
        tif, ndir, dir, tag, tif->tif_dir.td_samplesperpixel, m);
1681
0
    _TIFFfreeExt(tif, m);
1682
0
    return (o);
1683
0
}
1684
1685
static int TIFFWriteDirectoryTagSshortArray(TIFF *tif, uint32_t *ndir,
1686
                                            TIFFDirEntry *dir, uint16_t tag,
1687
                                            uint32_t count, int16_t *value)
1688
0
{
1689
0
    return (TIFFWriteDirectoryTagCheckedSshortArray(tif, ndir, dir, tag, count,
1690
0
                                                    value));
1691
0
}
1692
1693
static int TIFFWriteDirectoryTagLong(TIFF *tif, uint32_t *ndir,
1694
                                     TIFFDirEntry *dir, uint16_t tag,
1695
                                     uint32_t value)
1696
0
{
1697
0
    return (TIFFWriteDirectoryTagCheckedLong(tif, ndir, dir, tag, value));
1698
0
}
1699
1700
static int TIFFWriteDirectoryTagLongArray(TIFF *tif, uint32_t *ndir,
1701
                                          TIFFDirEntry *dir, uint16_t tag,
1702
                                          uint32_t count, uint32_t *value)
1703
0
{
1704
0
    return (TIFFWriteDirectoryTagCheckedLongArray(tif, ndir, dir, tag, count,
1705
0
                                                  value));
1706
0
}
1707
1708
static int TIFFWriteDirectoryTagSlongArray(TIFF *tif, uint32_t *ndir,
1709
                                           TIFFDirEntry *dir, uint16_t tag,
1710
                                           uint32_t count, int32_t *value)
1711
0
{
1712
0
    return (TIFFWriteDirectoryTagCheckedSlongArray(tif, ndir, dir, tag, count,
1713
0
                                                   value));
1714
0
}
1715
1716
/************************************************************************/
1717
/*                 TIFFWriteDirectoryTagLong8Array()                    */
1718
/*                                                                      */
1719
/*      Write either Long8 or Long array depending on file type.        */
1720
/************************************************************************/
1721
static int TIFFWriteDirectoryTagLong8Array(TIFF *tif, uint32_t *ndir,
1722
                                           TIFFDirEntry *dir, uint16_t tag,
1723
                                           uint32_t count, uint64_t *value)
1724
0
{
1725
0
    static const char module[] = "TIFFWriteDirectoryTagLong8Array";
1726
0
    uint64_t *ma;
1727
0
    uint32_t mb;
1728
0
    uint32_t *p;
1729
0
    uint32_t *q;
1730
0
    int o;
1731
1732
    /* We always write Long8 for BigTIFF, no checking needed. */
1733
0
    if (tif->tif_flags & TIFF_BIGTIFF)
1734
0
        return (TIFFWriteDirectoryTagCheckedLong8Array(tif, ndir, dir, tag,
1735
0
                                                       count, value));
1736
1737
    /*
1738
    ** For classic tiff we want to verify everything is in range for long
1739
    ** and convert to long format.
1740
    */
1741
0
    p = (uint32_t *)_TIFFmallocExt(tif, count * sizeof(uint32_t));
1742
0
    if (p == NULL)
1743
0
    {
1744
0
        TIFFErrorExtR(tif, module, "Out of memory");
1745
0
        return (0);
1746
0
    }
1747
1748
0
    for (q = p, ma = value, mb = 0; mb < count; ma++, mb++, q++)
1749
0
    {
1750
0
        if (*ma > 0xFFFFFFFF)
1751
0
        {
1752
0
            TIFFErrorExtR(tif, module,
1753
0
                          "Attempt to write unsigned long value %" PRIu64
1754
0
                          " larger than 0xFFFFFFFF for tag %d in Classic TIFF "
1755
0
                          "file. TIFF file writing aborted",
1756
0
                          *ma, tag);
1757
0
            _TIFFfreeExt(tif, p);
1758
0
            return (0);
1759
0
        }
1760
0
        *q = (uint32_t)(*ma);
1761
0
    }
1762
1763
0
    o = TIFFWriteDirectoryTagCheckedLongArray(tif, ndir, dir, tag, count, p);
1764
0
    _TIFFfreeExt(tif, p);
1765
1766
0
    return (o);
1767
0
}
1768
1769
/************************************************************************/
1770
/*                 TIFFWriteDirectoryTagSlong8Array()                   */
1771
/*                                                                      */
1772
/*      Write either SLong8 or SLong array depending on file type.      */
1773
/************************************************************************/
1774
static int TIFFWriteDirectoryTagSlong8Array(TIFF *tif, uint32_t *ndir,
1775
                                            TIFFDirEntry *dir, uint16_t tag,
1776
                                            uint32_t count, int64_t *value)
1777
0
{
1778
0
    static const char module[] = "TIFFWriteDirectoryTagSlong8Array";
1779
0
    int64_t *ma;
1780
0
    uint32_t mb;
1781
0
    int32_t *p;
1782
0
    int32_t *q;
1783
0
    int o;
1784
1785
    /* We always write SLong8 for BigTIFF, no checking needed. */
1786
0
    if (tif->tif_flags & TIFF_BIGTIFF)
1787
0
        return (TIFFWriteDirectoryTagCheckedSlong8Array(tif, ndir, dir, tag,
1788
0
                                                        count, value));
1789
1790
    /*
1791
    ** For classic tiff we want to verify everything is in range for signed-long
1792
    ** and convert to signed-long format.
1793
    */
1794
0
    p = (int32_t *)_TIFFmallocExt(tif, count * sizeof(uint32_t));
1795
0
    if (p == NULL)
1796
0
    {
1797
0
        TIFFErrorExtR(tif, module, "Out of memory");
1798
0
        return (0);
1799
0
    }
1800
1801
0
    for (q = p, ma = value, mb = 0; mb < count; ma++, mb++, q++)
1802
0
    {
1803
0
        if (*ma > (2147483647))
1804
0
        {
1805
0
            TIFFErrorExtR(tif, module,
1806
0
                          "Attempt to write signed long value %" PRIi64
1807
0
                          " larger than 0x7FFFFFFF (2147483647) for tag %d in "
1808
0
                          "Classic TIFF file. TIFF writing to file aborted",
1809
0
                          *ma, tag);
1810
0
            _TIFFfreeExt(tif, p);
1811
0
            return (0);
1812
0
        }
1813
0
        else if (*ma < (-2147483647 - 1))
1814
0
        {
1815
0
            TIFFErrorExtR(tif, module,
1816
0
                          "Attempt to write signed long value %" PRIi64
1817
0
                          " smaller than 0x80000000 (-2147483648) for tag %d "
1818
0
                          "in Classic TIFF file. TIFF writing to file aborted",
1819
0
                          *ma, tag);
1820
0
            _TIFFfreeExt(tif, p);
1821
0
            return (0);
1822
0
        }
1823
0
        *q = (int32_t)(*ma);
1824
0
    }
1825
1826
0
    o = TIFFWriteDirectoryTagCheckedSlongArray(tif, ndir, dir, tag, count, p);
1827
0
    _TIFFfreeExt(tif, p);
1828
1829
0
    return (o);
1830
0
}
1831
1832
static int TIFFWriteDirectoryTagRational(TIFF *tif, uint32_t *ndir,
1833
                                         TIFFDirEntry *dir, uint16_t tag,
1834
                                         double value)
1835
0
{
1836
0
    return (TIFFWriteDirectoryTagCheckedRational(tif, ndir, dir, tag, value));
1837
0
}
1838
1839
static int TIFFWriteDirectoryTagRationalArray(TIFF *tif, uint32_t *ndir,
1840
                                              TIFFDirEntry *dir, uint16_t tag,
1841
                                              uint32_t count, float *value)
1842
0
{
1843
0
    return (TIFFWriteDirectoryTagCheckedRationalArray(tif, ndir, dir, tag,
1844
0
                                                      count, value));
1845
0
}
1846
1847
static int TIFFWriteDirectoryTagSrationalArray(TIFF *tif, uint32_t *ndir,
1848
                                               TIFFDirEntry *dir, uint16_t tag,
1849
                                               uint32_t count, float *value)
1850
0
{
1851
0
    return (TIFFWriteDirectoryTagCheckedSrationalArray(tif, ndir, dir, tag,
1852
0
                                                       count, value));
1853
0
}
1854
1855
/*-- Rational2Double: additional write functions */
1856
static int TIFFWriteDirectoryTagRationalDoubleArray(TIFF *tif, uint32_t *ndir,
1857
                                                    TIFFDirEntry *dir,
1858
                                                    uint16_t tag,
1859
                                                    uint32_t count,
1860
                                                    double *value)
1861
0
{
1862
0
    return (TIFFWriteDirectoryTagCheckedRationalDoubleArray(tif, ndir, dir, tag,
1863
0
                                                            count, value));
1864
0
}
1865
1866
static int TIFFWriteDirectoryTagSrationalDoubleArray(TIFF *tif, uint32_t *ndir,
1867
                                                     TIFFDirEntry *dir,
1868
                                                     uint16_t tag,
1869
                                                     uint32_t count,
1870
                                                     double *value)
1871
0
{
1872
0
    return (TIFFWriteDirectoryTagCheckedSrationalDoubleArray(
1873
0
        tif, ndir, dir, tag, count, value));
1874
0
}
1875
1876
static int TIFFWriteDirectoryTagFloatArray(TIFF *tif, uint32_t *ndir,
1877
                                           TIFFDirEntry *dir, uint16_t tag,
1878
                                           uint32_t count, float *value)
1879
0
{
1880
0
    return (TIFFWriteDirectoryTagCheckedFloatArray(tif, ndir, dir, tag, count,
1881
0
                                                   value));
1882
0
}
1883
1884
static int TIFFWriteDirectoryTagDoubleArray(TIFF *tif, uint32_t *ndir,
1885
                                            TIFFDirEntry *dir, uint16_t tag,
1886
                                            uint32_t count, double *value)
1887
0
{
1888
0
    return (TIFFWriteDirectoryTagCheckedDoubleArray(tif, ndir, dir, tag, count,
1889
0
                                                    value));
1890
0
}
1891
1892
static int TIFFWriteDirectoryTagIfdArray(TIFF *tif, uint32_t *ndir,
1893
                                         TIFFDirEntry *dir, uint16_t tag,
1894
                                         uint32_t count, uint32_t *value)
1895
0
{
1896
0
    return (TIFFWriteDirectoryTagCheckedIfdArray(tif, ndir, dir, tag, count,
1897
0
                                                 value));
1898
0
}
1899
1900
static int TIFFWriteDirectoryTagShortLong(TIFF *tif, uint32_t *ndir,
1901
                                          TIFFDirEntry *dir, uint16_t tag,
1902
                                          uint32_t value)
1903
0
{
1904
0
    if (value <= 0xFFFF)
1905
0
        return (TIFFWriteDirectoryTagCheckedShort(tif, ndir, dir, tag,
1906
0
                                                  (uint16_t)value));
1907
0
    else
1908
0
        return (TIFFWriteDirectoryTagCheckedLong(tif, ndir, dir, tag, value));
1909
0
}
1910
1911
static int _WriteAsType(TIFF *tif, uint64_t strile_size,
1912
                        uint64_t uncompressed_threshold)
1913
0
{
1914
0
    const uint16_t compression = tif->tif_dir.td_compression;
1915
0
    if (compression == COMPRESSION_NONE)
1916
0
    {
1917
0
        return strile_size > uncompressed_threshold;
1918
0
    }
1919
0
    else if (compression == COMPRESSION_JPEG ||
1920
0
             compression == COMPRESSION_LZW ||
1921
0
             compression == COMPRESSION_ADOBE_DEFLATE ||
1922
0
             compression == COMPRESSION_DEFLATE ||
1923
0
             compression == COMPRESSION_LZMA ||
1924
0
             compression == COMPRESSION_LERC ||
1925
0
             compression == COMPRESSION_ZSTD ||
1926
0
             compression == COMPRESSION_WEBP || compression == COMPRESSION_JXL)
1927
0
    {
1928
        /* For a few select compression types, we assume that in the worst */
1929
        /* case the compressed size will be 10 times the uncompressed size. */
1930
        /* This is overly pessismistic ! */
1931
0
        return strile_size >= uncompressed_threshold / 10;
1932
0
    }
1933
0
    return 1;
1934
0
}
1935
1936
static int WriteAsLong8(TIFF *tif, uint64_t strile_size)
1937
0
{
1938
0
    return _WriteAsType(tif, strile_size, 0xFFFFFFFFU);
1939
0
}
1940
1941
static int WriteAsLong4(TIFF *tif, uint64_t strile_size)
1942
0
{
1943
0
    return _WriteAsType(tif, strile_size, 0xFFFFU);
1944
0
}
1945
1946
/************************************************************************/
1947
/*                TIFFWriteDirectoryTagLongLong8Array()                 */
1948
/*                                                                      */
1949
/*      Write out LONG8 array and write a SHORT/LONG/LONG8 depending    */
1950
/*      on strile size and Classic/BigTIFF mode.                        */
1951
/************************************************************************/
1952
1953
static int TIFFWriteDirectoryTagLongLong8Array(TIFF *tif, uint32_t *ndir,
1954
                                               TIFFDirEntry *dir, uint16_t tag,
1955
                                               uint32_t count, uint64_t *value)
1956
0
{
1957
0
    static const char module[] = "TIFFWriteDirectoryTagLongLong8Array";
1958
0
    int o;
1959
0
    int write_aslong4;
1960
1961
0
    if (tif->tif_dir.td_deferstrilearraywriting)
1962
0
    {
1963
0
        if (dir == NULL)
1964
0
        {
1965
            /* This is just a counting pass to count IFD entries.
1966
             * For deferstrilearraywriting no extra bytes will be written
1967
             * into IFD space. */
1968
0
            (*ndir)++;
1969
0
            return 1;
1970
0
        }
1971
0
        return TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_NOTYPE, 0, 0,
1972
0
                                         NULL);
1973
0
    }
1974
1975
0
    if (tif->tif_flags & TIFF_BIGTIFF)
1976
0
    {
1977
0
        int write_aslong8 = 1;
1978
        /* In the case of ByteCounts array, we may be able to write them on LONG
1979
         * if the strip/tilesize is not too big. Also do that for count > 1 in
1980
         * the case someone would want to create a single-strip file with a
1981
         * growing height, in which case using LONG8 will be safer. */
1982
0
        if (count > 1 && tag == TIFFTAG_STRIPBYTECOUNTS)
1983
0
        {
1984
0
            write_aslong8 = WriteAsLong8(tif, TIFFStripSize64(tif));
1985
0
        }
1986
0
        else if (count > 1 && tag == TIFFTAG_TILEBYTECOUNTS)
1987
0
        {
1988
0
            write_aslong8 = WriteAsLong8(tif, TIFFTileSize64(tif));
1989
0
        }
1990
0
        if (write_aslong8)
1991
0
        {
1992
0
            return TIFFWriteDirectoryTagCheckedLong8Array(tif, ndir, dir, tag,
1993
0
                                                          count, value);
1994
0
        }
1995
0
    }
1996
1997
0
    write_aslong4 = 1;
1998
0
    if (count > 1 && tag == TIFFTAG_STRIPBYTECOUNTS)
1999
0
    {
2000
0
        write_aslong4 = WriteAsLong4(tif, TIFFStripSize64(tif));
2001
0
    }
2002
0
    else if (count > 1 && tag == TIFFTAG_TILEBYTECOUNTS)
2003
0
    {
2004
0
        write_aslong4 = WriteAsLong4(tif, TIFFTileSize64(tif));
2005
0
    }
2006
0
    if (write_aslong4)
2007
0
    {
2008
        /*
2009
        ** For classic tiff we want to verify everything is in range for LONG
2010
        ** and convert to long format.
2011
        */
2012
2013
0
        uint32_t *p = (uint32_t *)_TIFFmallocExt(tif, count * sizeof(uint32_t));
2014
0
        uint32_t *q;
2015
0
        uint64_t *ma;
2016
0
        uint32_t mb;
2017
2018
0
        if (p == NULL)
2019
0
        {
2020
0
            TIFFErrorExtR(tif, module, "Out of memory");
2021
0
            return (0);
2022
0
        }
2023
2024
0
        for (q = p, ma = value, mb = 0; mb < count; ma++, mb++, q++)
2025
0
        {
2026
0
            if (*ma > 0xFFFFFFFF)
2027
0
            {
2028
0
                TIFFErrorExtR(tif, module,
2029
0
                              "Attempt to write value larger than 0xFFFFFFFF "
2030
0
                              "in LONG array.");
2031
0
                _TIFFfreeExt(tif, p);
2032
0
                return (0);
2033
0
            }
2034
0
            *q = (uint32_t)(*ma);
2035
0
        }
2036
2037
0
        o = TIFFWriteDirectoryTagCheckedLongArray(tif, ndir, dir, tag, count,
2038
0
                                                  p);
2039
0
        _TIFFfreeExt(tif, p);
2040
0
    }
2041
0
    else
2042
0
    {
2043
0
        uint16_t *p = (uint16_t *)_TIFFmallocExt(tif, count * sizeof(uint16_t));
2044
0
        uint16_t *q;
2045
0
        uint64_t *ma;
2046
0
        uint32_t mb;
2047
2048
0
        if (p == NULL)
2049
0
        {
2050
0
            TIFFErrorExtR(tif, module, "Out of memory");
2051
0
            return (0);
2052
0
        }
2053
2054
0
        for (q = p, ma = value, mb = 0; mb < count; ma++, mb++, q++)
2055
0
        {
2056
0
            if (*ma > 0xFFFF)
2057
0
            {
2058
                /* Should not happen normally given the check we did before */
2059
0
                TIFFErrorExtR(tif, module,
2060
0
                              "Attempt to write value larger than 0xFFFF in "
2061
0
                              "SHORT array.");
2062
0
                _TIFFfreeExt(tif, p);
2063
0
                return (0);
2064
0
            }
2065
0
            *q = (uint16_t)(*ma);
2066
0
        }
2067
2068
0
        o = TIFFWriteDirectoryTagCheckedShortArray(tif, ndir, dir, tag, count,
2069
0
                                                   p);
2070
0
        _TIFFfreeExt(tif, p);
2071
0
    }
2072
2073
0
    return (o);
2074
0
}
2075
2076
/************************************************************************/
2077
/*                 TIFFWriteDirectoryTagIfdIfd8Array()                  */
2078
/*                                                                      */
2079
/*      Write either IFD8 or IFD array depending on file type.          */
2080
/************************************************************************/
2081
2082
static int TIFFWriteDirectoryTagIfdIfd8Array(TIFF *tif, uint32_t *ndir,
2083
                                             TIFFDirEntry *dir, uint16_t tag,
2084
                                             uint32_t count, uint64_t *value)
2085
0
{
2086
0
    static const char module[] = "TIFFWriteDirectoryTagIfdIfd8Array";
2087
0
    uint64_t *ma;
2088
0
    uint32_t mb;
2089
0
    uint32_t *p;
2090
0
    uint32_t *q;
2091
0
    int o;
2092
2093
    /* We always write IFD8 for BigTIFF, no checking needed. */
2094
0
    if (tif->tif_flags & TIFF_BIGTIFF)
2095
0
        return TIFFWriteDirectoryTagCheckedIfd8Array(tif, ndir, dir, tag, count,
2096
0
                                                     value);
2097
2098
    /*
2099
    ** For classic tiff we want to verify everything is in range for IFD
2100
    ** and convert to long format.
2101
    */
2102
2103
0
    p = (uint32_t *)_TIFFmallocExt(tif, count * sizeof(uint32_t));
2104
0
    if (p == NULL)
2105
0
    {
2106
0
        TIFFErrorExtR(tif, module, "Out of memory");
2107
0
        return (0);
2108
0
    }
2109
2110
0
    for (q = p, ma = value, mb = 0; mb < count; ma++, mb++, q++)
2111
0
    {
2112
0
        if (*ma > 0xFFFFFFFF)
2113
0
        {
2114
0
            TIFFErrorExtR(tif, module,
2115
0
                          "Attempt to write value larger than 0xFFFFFFFF in "
2116
0
                          "Classic TIFF file.");
2117
0
            _TIFFfreeExt(tif, p);
2118
0
            return (0);
2119
0
        }
2120
0
        *q = (uint32_t)(*ma);
2121
0
    }
2122
2123
0
    o = TIFFWriteDirectoryTagCheckedIfdArray(tif, ndir, dir, tag, count, p);
2124
0
    _TIFFfreeExt(tif, p);
2125
2126
0
    return (o);
2127
0
}
2128
2129
/*
2130
 * Auxiliary function to determine the IFD data size to be written to the file.
2131
 * The IFD data size is finally the size of the IFD tag entries plus the IFD
2132
 * data that is written directly after the IFD tag entries.
2133
 */
2134
static void EvaluateIFDdatasizeWrite(TIFF *tif, uint32_t count,
2135
                                     uint32_t typesize, uint32_t *ndir)
2136
0
{
2137
0
    uint64_t datalength = (uint64_t)count * typesize;
2138
0
    if (datalength > ((tif->tif_flags & TIFF_BIGTIFF) ? 0x8U : 0x4U))
2139
0
    {
2140
        /* LibTIFF increments write address to an even offset, thus datalength
2141
         * written is also incremented. */
2142
0
        if (datalength & 1)
2143
0
            datalength++;
2144
0
        tif->tif_dir.td_dirdatasize_write += datalength;
2145
0
    }
2146
0
    (*ndir)++;
2147
0
}
2148
2149
static int TIFFWriteDirectoryTagColormap(TIFF *tif, uint32_t *ndir,
2150
                                         TIFFDirEntry *dir)
2151
0
{
2152
0
    static const char module[] = "TIFFWriteDirectoryTagColormap";
2153
0
    uint32_t m;
2154
0
    uint16_t *n;
2155
0
    int o;
2156
0
    m = (1 << tif->tif_dir.td_bitspersample);
2157
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2158
0
    {
2159
0
        EvaluateIFDdatasizeWrite(tif, 3 * m, sizeof(uint16_t), ndir);
2160
0
        return 1;
2161
0
    }
2162
2163
0
    n = (uint16_t *)_TIFFmallocExt(tif, 3 * m * sizeof(uint16_t));
2164
0
    if (n == NULL)
2165
0
    {
2166
0
        TIFFErrorExtR(tif, module, "Out of memory");
2167
0
        return (0);
2168
0
    }
2169
0
    _TIFFmemcpy(&n[0], tif->tif_dir.td_colormap[0], m * sizeof(uint16_t));
2170
0
    _TIFFmemcpy(&n[m], tif->tif_dir.td_colormap[1], m * sizeof(uint16_t));
2171
0
    _TIFFmemcpy(&n[2 * m], tif->tif_dir.td_colormap[2], m * sizeof(uint16_t));
2172
0
    o = TIFFWriteDirectoryTagCheckedShortArray(tif, ndir, dir, TIFFTAG_COLORMAP,
2173
0
                                               3 * m, n);
2174
0
    _TIFFfreeExt(tif, n);
2175
0
    return (o);
2176
0
}
2177
2178
static int TIFFWriteDirectoryTagTransferfunction(TIFF *tif, uint32_t *ndir,
2179
                                                 TIFFDirEntry *dir)
2180
0
{
2181
0
    static const char module[] = "TIFFWriteDirectoryTagTransferfunction";
2182
0
    uint32_t m;
2183
0
    uint16_t n;
2184
0
    uint16_t *o;
2185
0
    int p;
2186
    /* TIFFTAG_TRANSFERFUNCTION expects (1 or 3) pointer to arrays with
2187
     *  (1 << BitsPerSample) * uint16_t values.
2188
     */
2189
0
    m = (1 << tif->tif_dir.td_bitspersample);
2190
    /* clang-format off */
2191
0
    n = (tif->tif_dir.td_samplesperpixel - tif->tif_dir.td_extrasamples) > 1 ? 3 : 1;
2192
    /* clang-format on */
2193
2194
    /* Check for proper number of transferfunctions */
2195
0
    for (int i = 0; i < n; i++)
2196
0
    {
2197
0
        if (tif->tif_dir.td_transferfunction[i] == NULL)
2198
0
        {
2199
0
            TIFFWarningExtR(tif, module,
2200
0
                            "Too few TransferFunctions provided. Tag "
2201
0
                            "not written to file");
2202
0
            return (1); /* Not an error; only tag is not written. */
2203
0
        }
2204
0
    }
2205
    /*
2206
     * Check if the table can be written as a single column,
2207
     * or if it must be written as 3 columns.  Note that we
2208
     * write a 3-column tag if there are 2 samples/pixel and
2209
     * a single column of data won't suffice--hmm.
2210
     */
2211
0
    if (n == 3)
2212
0
    {
2213
0
        if (!_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],
2214
0
                         tif->tif_dir.td_transferfunction[2],
2215
0
                         m * sizeof(uint16_t)) &&
2216
0
            !_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],
2217
0
                         tif->tif_dir.td_transferfunction[1],
2218
0
                         m * sizeof(uint16_t)))
2219
0
            n = 1;
2220
0
    }
2221
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2222
0
    {
2223
0
        EvaluateIFDdatasizeWrite(tif, n * m, 2, ndir);
2224
0
        return 1;
2225
0
    }
2226
2227
0
    o = (uint16_t *)_TIFFmallocExt(tif, n * m * sizeof(uint16_t));
2228
0
    if (o == NULL)
2229
0
    {
2230
0
        TIFFErrorExtR(tif, module, "Out of memory");
2231
0
        return (0);
2232
0
    }
2233
0
    _TIFFmemcpy(&o[0], tif->tif_dir.td_transferfunction[0],
2234
0
                m * sizeof(uint16_t));
2235
0
    if (n > 1)
2236
0
        _TIFFmemcpy(&o[m], tif->tif_dir.td_transferfunction[1],
2237
0
                    m * sizeof(uint16_t));
2238
0
    if (n > 2)
2239
0
        _TIFFmemcpy(&o[2 * m], tif->tif_dir.td_transferfunction[2],
2240
0
                    m * sizeof(uint16_t));
2241
0
    p = TIFFWriteDirectoryTagCheckedShortArray(
2242
0
        tif, ndir, dir, TIFFTAG_TRANSFERFUNCTION, n * m, o);
2243
0
    _TIFFfreeExt(tif, o);
2244
0
    return (p);
2245
0
}
2246
2247
static int TIFFWriteDirectoryTagSubifd(TIFF *tif, uint32_t *ndir,
2248
                                       TIFFDirEntry *dir)
2249
0
{
2250
0
    static const char module[] = "TIFFWriteDirectoryTagSubifd";
2251
0
    uint64_t m;
2252
0
    int n;
2253
0
    if (tif->tif_dir.td_nsubifd == 0)
2254
0
        return (1);
2255
0
    m = tif->tif_dataoff;
2256
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
2257
0
    {
2258
0
        uint32_t *o;
2259
0
        uint64_t *pa;
2260
0
        uint32_t *pb;
2261
0
        uint16_t p;
2262
0
        o = (uint32_t *)_TIFFmallocExt(tif, tif->tif_dir.td_nsubifd * sizeof(uint32_t));
2263
0
        if (o == NULL)
2264
0
        {
2265
0
            TIFFErrorExtR(tif, module, "Out of memory");
2266
0
            return (0);
2267
0
        }
2268
0
        pa = tif->tif_dir.td_subifd;
2269
0
        pb = o;
2270
0
        for (p = 0; p < tif->tif_dir.td_nsubifd; p++)
2271
0
        {
2272
0
            assert(pa != 0);
2273
2274
            /* Could happen if an classicTIFF has a SubIFD of type LONG8 (which
2275
             * is illegal) */
2276
0
            if (*pa > 0xFFFFFFFFUL)
2277
0
            {
2278
0
                TIFFErrorExtR(tif, module, "Illegal value for SubIFD tag");
2279
0
                _TIFFfreeExt(tif, o);
2280
0
                return (0);
2281
0
            }
2282
0
            *pb++ = (uint32_t)(*pa++);
2283
0
        }
2284
0
        n = TIFFWriteDirectoryTagCheckedIfdArray(tif, ndir, dir, TIFFTAG_SUBIFD,
2285
0
                                                 tif->tif_dir.td_nsubifd, o);
2286
0
        _TIFFfreeExt(tif, o);
2287
0
    }
2288
0
    else
2289
0
        n = TIFFWriteDirectoryTagCheckedIfd8Array(
2290
0
            tif, ndir, dir, TIFFTAG_SUBIFD, tif->tif_dir.td_nsubifd,
2291
0
            tif->tif_dir.td_subifd);
2292
2293
0
    if (dir == NULL)
2294
        /* Just have evaluated IFD data size and incremented ndir
2295
         * above in sub-functions. */
2296
0
        return (n);
2297
2298
0
    if (!n)
2299
0
        return (0);
2300
    /*
2301
     * Total hack: if this directory includes a SubIFD
2302
     * tag then force the next <n> directories to be
2303
     * written as ``sub directories'' of this one.  This
2304
     * is used to write things like thumbnails and
2305
     * image masks that one wants to keep out of the
2306
     * normal directory linkage access mechanism.
2307
     */
2308
0
    tif->tif_flags |= TIFF_INSUBIFD;
2309
0
    tif->tif_nsubifd = tif->tif_dir.td_nsubifd;
2310
0
    if (tif->tif_dir.td_nsubifd == 1)
2311
0
        tif->tif_subifdoff = 0;
2312
0
    else
2313
0
        tif->tif_subifdoff = m;
2314
0
    return (1);
2315
0
}
2316
2317
static int TIFFWriteDirectoryTagCheckedAscii(TIFF *tif, uint32_t *ndir,
2318
                                             TIFFDirEntry *dir, uint16_t tag,
2319
                                             uint32_t count, char *value)
2320
0
{
2321
0
    assert(sizeof(char) == 1);
2322
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2323
0
    {
2324
0
        EvaluateIFDdatasizeWrite(tif, count, 1, ndir);
2325
0
        return 1;
2326
0
    }
2327
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_ASCII, count,
2328
0
                                      count, value));
2329
0
}
2330
2331
static int TIFFWriteDirectoryTagCheckedUndefinedArray(TIFF *tif, uint32_t *ndir,
2332
                                                      TIFFDirEntry *dir,
2333
                                                      uint16_t tag,
2334
                                                      uint32_t count,
2335
                                                      uint8_t *value)
2336
0
{
2337
0
    assert(sizeof(uint8_t) == 1);
2338
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2339
0
    {
2340
0
        EvaluateIFDdatasizeWrite(tif, count, 1, ndir);
2341
0
        return 1;
2342
0
    }
2343
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_UNDEFINED,
2344
0
                                      count, count, value));
2345
0
}
2346
2347
static int TIFFWriteDirectoryTagCheckedByteArray(TIFF *tif, uint32_t *ndir,
2348
                                                 TIFFDirEntry *dir,
2349
                                                 uint16_t tag, uint32_t count,
2350
                                                 uint8_t *value)
2351
0
{
2352
0
    assert(sizeof(uint8_t) == 1);
2353
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2354
0
    {
2355
0
        EvaluateIFDdatasizeWrite(tif, count, 1, ndir);
2356
0
        return 1;
2357
0
    }
2358
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_BYTE, count,
2359
0
                                      count, value));
2360
0
}
2361
2362
static int TIFFWriteDirectoryTagCheckedSbyteArray(TIFF *tif, uint32_t *ndir,
2363
                                                  TIFFDirEntry *dir,
2364
                                                  uint16_t tag, uint32_t count,
2365
                                                  int8_t *value)
2366
0
{
2367
0
    assert(sizeof(int8_t) == 1);
2368
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2369
0
    {
2370
0
        EvaluateIFDdatasizeWrite(tif, count, 1, ndir);
2371
0
        return 1;
2372
0
    }
2373
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SBYTE, count,
2374
0
                                      count, value));
2375
0
}
2376
2377
static int TIFFWriteDirectoryTagCheckedShort(TIFF *tif, uint32_t *ndir,
2378
                                             TIFFDirEntry *dir, uint16_t tag,
2379
                                             uint16_t value)
2380
0
{
2381
0
    uint16_t m;
2382
0
    assert(sizeof(uint16_t) == 2);
2383
0
    if (dir == NULL)
2384
0
    {
2385
        /* No additional data to IFD data size just increment ndir. */
2386
0
        (*ndir)++;
2387
0
        return 1;
2388
0
    }
2389
0
    m = value;
2390
0
    if (tif->tif_flags & TIFF_SWAB)
2391
0
        TIFFSwabShort(&m);
2392
0
    return (
2393
0
        TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SHORT, 1, 2, &m));
2394
0
}
2395
2396
static int TIFFWriteDirectoryTagCheckedShortArray(TIFF *tif, uint32_t *ndir,
2397
                                                  TIFFDirEntry *dir,
2398
                                                  uint16_t tag, uint32_t count,
2399
                                                  uint16_t *value)
2400
0
{
2401
0
    assert(count < 0x80000000);
2402
0
    assert(sizeof(uint16_t) == 2);
2403
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2404
0
    {
2405
0
        EvaluateIFDdatasizeWrite(tif, count, 2, ndir);
2406
0
        return 1;
2407
0
    }
2408
0
    if (tif->tif_flags & TIFF_SWAB)
2409
0
        TIFFSwabArrayOfShort(value, count);
2410
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SHORT, count,
2411
0
                                      count * 2, value));
2412
0
}
2413
2414
static int TIFFWriteDirectoryTagCheckedSshortArray(TIFF *tif, uint32_t *ndir,
2415
                                                   TIFFDirEntry *dir,
2416
                                                   uint16_t tag, uint32_t count,
2417
                                                   int16_t *value)
2418
0
{
2419
0
    assert(count < 0x80000000);
2420
0
    assert(sizeof(int16_t) == 2);
2421
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2422
0
    {
2423
0
        EvaluateIFDdatasizeWrite(tif, count, 2, ndir);
2424
0
        return 1;
2425
0
    }
2426
0
    if (tif->tif_flags & TIFF_SWAB)
2427
0
        TIFFSwabArrayOfShort((uint16_t *)value, count);
2428
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SSHORT, count,
2429
0
                                      count * 2, value));
2430
0
}
2431
2432
static int TIFFWriteDirectoryTagCheckedLong(TIFF *tif, uint32_t *ndir,
2433
                                            TIFFDirEntry *dir, uint16_t tag,
2434
                                            uint32_t value)
2435
0
{
2436
0
    uint32_t m;
2437
0
    assert(sizeof(uint32_t) == 4);
2438
0
    if (dir == NULL)
2439
0
    {
2440
        /* No additional data to IFD data size just increment ndir. */
2441
0
        (*ndir)++;
2442
0
        return 1;
2443
0
    }
2444
0
    m = value;
2445
0
    if (tif->tif_flags & TIFF_SWAB)
2446
0
        TIFFSwabLong(&m);
2447
0
    return (
2448
0
        TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_LONG, 1, 4, &m));
2449
0
}
2450
2451
static int TIFFWriteDirectoryTagCheckedLongArray(TIFF *tif, uint32_t *ndir,
2452
                                                 TIFFDirEntry *dir,
2453
                                                 uint16_t tag, uint32_t count,
2454
                                                 uint32_t *value)
2455
0
{
2456
0
    assert(count < 0x40000000);
2457
0
    assert(sizeof(uint32_t) == 4);
2458
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2459
0
    {
2460
0
        EvaluateIFDdatasizeWrite(tif, count, 4, ndir);
2461
0
        return 1;
2462
0
    }
2463
0
    if (tif->tif_flags & TIFF_SWAB)
2464
0
        TIFFSwabArrayOfLong(value, count);
2465
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_LONG, count,
2466
0
                                      count * 4, value));
2467
0
}
2468
2469
static int TIFFWriteDirectoryTagCheckedSlongArray(TIFF *tif, uint32_t *ndir,
2470
                                                  TIFFDirEntry *dir,
2471
                                                  uint16_t tag, uint32_t count,
2472
                                                  int32_t *value)
2473
0
{
2474
0
    assert(count < 0x40000000);
2475
0
    assert(sizeof(int32_t) == 4);
2476
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2477
0
    {
2478
0
        EvaluateIFDdatasizeWrite(tif, count, 4, ndir);
2479
0
        return 1;
2480
0
    }
2481
0
    if (tif->tif_flags & TIFF_SWAB)
2482
0
        TIFFSwabArrayOfLong((uint32_t *)value, count);
2483
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SLONG, count,
2484
0
                                      count * 4, value));
2485
0
}
2486
2487
static int TIFFWriteDirectoryTagCheckedLong8Array(TIFF *tif, uint32_t *ndir,
2488
                                                  TIFFDirEntry *dir,
2489
                                                  uint16_t tag, uint32_t count,
2490
                                                  uint64_t *value)
2491
0
{
2492
0
    assert(count < 0x20000000);
2493
0
    assert(sizeof(uint64_t) == 8);
2494
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
2495
0
    {
2496
0
        TIFFErrorExtR(tif, "TIFFWriteDirectoryTagCheckedLong8Array",
2497
0
                      "LONG8 not allowed for ClassicTIFF");
2498
0
        return (0);
2499
0
    }
2500
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2501
0
    {
2502
0
        EvaluateIFDdatasizeWrite(tif, count, 8, ndir);
2503
0
        return 1;
2504
0
    }
2505
0
    if (tif->tif_flags & TIFF_SWAB)
2506
0
        TIFFSwabArrayOfLong8(value, count);
2507
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_LONG8, count,
2508
0
                                      count * 8, value));
2509
0
}
2510
2511
static int TIFFWriteDirectoryTagCheckedSlong8Array(TIFF *tif, uint32_t *ndir,
2512
                                                   TIFFDirEntry *dir,
2513
                                                   uint16_t tag, uint32_t count,
2514
                                                   int64_t *value)
2515
0
{
2516
0
    assert(count < 0x20000000);
2517
0
    assert(sizeof(int64_t) == 8);
2518
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
2519
0
    {
2520
0
        TIFFErrorExtR(tif, "TIFFWriteDirectoryTagCheckedSlong8Array",
2521
0
                      "SLONG8 not allowed for ClassicTIFF");
2522
0
        return (0);
2523
0
    }
2524
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2525
0
    {
2526
0
        EvaluateIFDdatasizeWrite(tif, count, 8, ndir);
2527
0
        return 1;
2528
0
    }
2529
0
    if (tif->tif_flags & TIFF_SWAB)
2530
0
        TIFFSwabArrayOfLong8((uint64_t *)value, count);
2531
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SLONG8, count,
2532
0
                                      count * 8, value));
2533
0
}
2534
2535
static int TIFFWriteDirectoryTagCheckedRational(TIFF *tif, uint32_t *ndir,
2536
                                                TIFFDirEntry *dir, uint16_t tag,
2537
                                                double value)
2538
0
{
2539
0
    static const char module[] = "TIFFWriteDirectoryTagCheckedRational";
2540
0
    uint32_t m[2];
2541
0
    assert(sizeof(uint32_t) == 4);
2542
0
    if (value < 0)
2543
0
    {
2544
0
        TIFFErrorExtR(tif, module, "Negative value is illegal");
2545
0
        return 0;
2546
0
    }
2547
0
    else if (value != value)
2548
0
    {
2549
0
        TIFFErrorExtR(tif, module, "Not-a-number value is illegal");
2550
0
        return 0;
2551
0
    }
2552
2553
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2554
0
    {
2555
0
        tif->tif_dir.td_dirdatasize_write +=
2556
0
            (tif->tif_flags & TIFF_BIGTIFF) ? 0 : 0x8U;
2557
0
        (*ndir)++;
2558
0
        return 1;
2559
0
    }
2560
2561
0
    DoubleToRational(value, &m[0], &m[1]);
2562
2563
0
    if (tif->tif_flags & TIFF_SWAB)
2564
0
    {
2565
0
        TIFFSwabLong(&m[0]);
2566
0
        TIFFSwabLong(&m[1]);
2567
0
    }
2568
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_RATIONAL, 1, 8,
2569
0
                                      &m[0]));
2570
0
}
2571
2572
static int TIFFWriteDirectoryTagCheckedRationalArray(TIFF *tif, uint32_t *ndir,
2573
                                                     TIFFDirEntry *dir,
2574
                                                     uint16_t tag,
2575
                                                     uint32_t count,
2576
                                                     float *value)
2577
0
{
2578
0
    static const char module[] = "TIFFWriteDirectoryTagCheckedRationalArray";
2579
0
    uint32_t *m;
2580
0
    float *na;
2581
0
    uint32_t *nb;
2582
0
    uint32_t nc;
2583
0
    int o;
2584
0
    assert(sizeof(uint32_t) == 4);
2585
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2586
0
    {
2587
0
        EvaluateIFDdatasizeWrite(tif, count * 2, sizeof(uint32_t), ndir);
2588
0
        return 1;
2589
0
    }
2590
0
    m = (uint32_t *)_TIFFmallocExt(tif, count * 2 * sizeof(uint32_t));
2591
0
    if (m == NULL)
2592
0
    {
2593
0
        TIFFErrorExtR(tif, module, "Out of memory");
2594
0
        return (0);
2595
0
    }
2596
0
    for (na = value, nb = m, nc = 0; nc < count; na++, nb += 2, nc++)
2597
0
    {
2598
0
        DoubleToRational(*na, &nb[0], &nb[1]);
2599
0
    }
2600
0
    if (tif->tif_flags & TIFF_SWAB)
2601
0
        TIFFSwabArrayOfLong(m, count * 2);
2602
0
    o = TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_RATIONAL, count,
2603
0
                                  count * 8, &m[0]);
2604
0
    _TIFFfreeExt(tif, m);
2605
0
    return (o);
2606
0
}
2607
2608
static int TIFFWriteDirectoryTagCheckedSrationalArray(TIFF *tif, uint32_t *ndir,
2609
                                                      TIFFDirEntry *dir,
2610
                                                      uint16_t tag,
2611
                                                      uint32_t count,
2612
                                                      float *value)
2613
0
{
2614
0
    static const char module[] = "TIFFWriteDirectoryTagCheckedSrationalArray";
2615
0
    int32_t *m;
2616
0
    float *na;
2617
0
    int32_t *nb;
2618
0
    uint32_t nc;
2619
0
    int o;
2620
0
    assert(sizeof(int32_t) == 4);
2621
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2622
0
    {
2623
0
        EvaluateIFDdatasizeWrite(tif, count * 2, sizeof(int32_t), ndir);
2624
0
        return 1;
2625
0
    }
2626
0
    m = (int32_t *)_TIFFmallocExt(tif, count * 2 * sizeof(int32_t));
2627
0
    if (m == NULL)
2628
0
    {
2629
0
        TIFFErrorExtR(tif, module, "Out of memory");
2630
0
        return (0);
2631
0
    }
2632
0
    for (na = value, nb = m, nc = 0; nc < count; na++, nb += 2, nc++)
2633
0
    {
2634
0
        DoubleToSrational(*na, &nb[0], &nb[1]);
2635
0
    }
2636
0
    if (tif->tif_flags & TIFF_SWAB)
2637
0
        TIFFSwabArrayOfLong((uint32_t *)m, count * 2);
2638
0
    o = TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SRATIONAL, count,
2639
0
                                  count * 8, &m[0]);
2640
0
    _TIFFfreeExt(tif, m);
2641
0
    return (o);
2642
0
}
2643
2644
/*-- Rational2Double: additional write functions for double arrays */
2645
static int
2646
TIFFWriteDirectoryTagCheckedRationalDoubleArray(TIFF *tif, uint32_t *ndir,
2647
                                                TIFFDirEntry *dir, uint16_t tag,
2648
                                                uint32_t count, double *value)
2649
0
{
2650
0
    static const char module[] =
2651
0
        "TIFFWriteDirectoryTagCheckedRationalDoubleArray";
2652
0
    uint32_t *m;
2653
0
    double *na;
2654
0
    uint32_t *nb;
2655
0
    uint32_t nc;
2656
0
    int o;
2657
0
    assert(sizeof(uint32_t) == 4);
2658
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2659
0
    {
2660
0
        EvaluateIFDdatasizeWrite(tif, count * 2, sizeof(uint32_t), ndir);
2661
0
        return 1;
2662
0
    }
2663
0
    m = (uint32_t *)_TIFFmallocExt(tif, count * 2 * sizeof(uint32_t));
2664
0
    if (m == NULL)
2665
0
    {
2666
0
        TIFFErrorExtR(tif, module, "Out of memory");
2667
0
        return (0);
2668
0
    }
2669
0
    for (na = value, nb = m, nc = 0; nc < count; na++, nb += 2, nc++)
2670
0
    {
2671
0
        DoubleToRational(*na, &nb[0], &nb[1]);
2672
0
    }
2673
0
    if (tif->tif_flags & TIFF_SWAB)
2674
0
        TIFFSwabArrayOfLong(m, count * 2);
2675
0
    o = TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_RATIONAL, count,
2676
0
                                  count * 8, &m[0]);
2677
0
    _TIFFfreeExt(tif, m);
2678
0
    return (o);
2679
0
} /*-- TIFFWriteDirectoryTagCheckedRationalDoubleArray() ------- */
2680
2681
static int TIFFWriteDirectoryTagCheckedSrationalDoubleArray(
2682
    TIFF *tif, uint32_t *ndir, TIFFDirEntry *dir, uint16_t tag, uint32_t count,
2683
    double *value)
2684
0
{
2685
0
    static const char module[] =
2686
0
        "TIFFWriteDirectoryTagCheckedSrationalDoubleArray";
2687
0
    int32_t *m;
2688
0
    double *na;
2689
0
    int32_t *nb;
2690
0
    uint32_t nc;
2691
0
    int o;
2692
0
    assert(sizeof(int32_t) == 4);
2693
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
2694
0
    {
2695
0
        EvaluateIFDdatasizeWrite(tif, count * 2, sizeof(int32_t), ndir);
2696
0
        return 1;
2697
0
    }
2698
0
    m = (int32_t *)_TIFFmallocExt(tif, count * 2 * sizeof(int32_t));
2699
0
    if (m == NULL)
2700
0
    {
2701
0
        TIFFErrorExtR(tif, module, "Out of memory");
2702
0
        return (0);
2703
0
    }
2704
0
    for (na = value, nb = m, nc = 0; nc < count; na++, nb += 2, nc++)
2705
0
    {
2706
0
        DoubleToSrational(*na, &nb[0], &nb[1]);
2707
0
    }
2708
0
    if (tif->tif_flags & TIFF_SWAB)
2709
0
        TIFFSwabArrayOfLong((uint32_t *)m, count * 2);
2710
0
    o = TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_SRATIONAL, count,
2711
0
                                  count * 8, &m[0]);
2712
0
    _TIFFfreeExt(tif, m);
2713
0
    return (o);
2714
0
} /*--- TIFFWriteDirectoryTagCheckedSrationalDoubleArray() -------- */
2715
2716
/** -----  Rational2Double: Double To Rational Conversion
2717
----------------------------------------------------------
2718
* There is a mathematical theorem to convert real numbers into a rational
2719
(integer fraction) number.
2720
* This is called "continuous fraction" which uses the Euclidean algorithm to
2721
find the greatest common divisor (GCD).
2722
*  (ref. e.g. https://de.wikipedia.org/wiki/Kettenbruch or
2723
https://en.wikipedia.org/wiki/Continued_fraction
2724
*             https://en.wikipedia.org/wiki/Euclidean_algorithm)
2725
* The following functions implement the
2726
* - ToRationalEuclideanGCD()    auxiliary function which mainly
2727
implements euclidean GCD
2728
* - DoubleToRational()      conversion function for un-signed
2729
rationals
2730
* - DoubleToSrational()     conversion function for signed rationals
2731
------------------------------------------------------------------------------------------------------------------*/
2732
2733
/**---- ToRationalEuclideanGCD() -----------------------------------------
2734
* Calculates the rational fractional of a double input value
2735
* using the Euclidean algorithm to find the greatest common divisor (GCD)
2736
------------------------------------------------------------------------*/
2737
static void ToRationalEuclideanGCD(double value, int blnUseSignedRange,
2738
                                   int blnUseSmallRange, uint64_t *ullNum,
2739
                                   uint64_t *ullDenom)
2740
0
{
2741
    /* Internally, the integer variables can be bigger than the external ones,
2742
     * as long as the result will fit into the external variable size.
2743
     */
2744
0
    uint64_t numSum[3] = {0, 1, 0}, denomSum[3] = {1, 0, 0};
2745
0
    uint64_t aux, bigNum, bigDenom;
2746
0
    uint64_t returnLimit;
2747
0
    int i;
2748
0
    uint64_t nMax;
2749
0
    double fMax;
2750
0
    unsigned long maxDenom;
2751
    /*-- nMax and fMax defines the initial accuracy of the starting fractional,
2752
     *   or better, the highest used integer numbers used within the starting
2753
     * fractional (bigNum/bigDenom). There are two approaches, which can
2754
     * accidentally lead to different accuracies just depending on the value.
2755
     *   Therefore, blnUseSmallRange steers this behavior.
2756
     *   For long long nMax = ((9223372036854775807-1)/2); for long nMax =
2757
     * ((2147483647-1)/2);
2758
     */
2759
0
    if (blnUseSmallRange)
2760
0
    {
2761
0
        nMax = (uint64_t)((2147483647 - 1) / 2); /* for ULONG range */
2762
0
    }
2763
0
    else
2764
0
    {
2765
0
        nMax = ((9223372036854775807 - 1) / 2); /* for ULLONG range */
2766
0
    }
2767
0
    fMax = (double)nMax;
2768
2769
    /*-- For the Euclidean GCD define the denominator range, so that it stays
2770
     * within size of unsigned long variables. maxDenom should be LONG_MAX for
2771
     * negative values and ULONG_MAX for positive ones. Also the final returned
2772
     * value of ullNum and ullDenom is limited according to signed- or
2773
     * unsigned-range.
2774
     */
2775
0
    if (blnUseSignedRange)
2776
0
    {
2777
0
        maxDenom = 2147483647UL; /*LONG_MAX = 0x7FFFFFFFUL*/
2778
0
        returnLimit = maxDenom;
2779
0
    }
2780
0
    else
2781
0
    {
2782
0
        maxDenom = 0xFFFFFFFFUL; /*ULONG_MAX = 0xFFFFFFFFUL*/
2783
0
        returnLimit = maxDenom;
2784
0
    }
2785
2786
    /*-- First generate a rational fraction (bigNum/bigDenom) which represents
2787
     *the value as a rational number with the highest accuracy. Therefore,
2788
     *uint64_t (uint64_t) is needed. This rational fraction is then reduced
2789
     *using the Euclidean algorithm to find the greatest common divisor (GCD).
2790
     *   bigNum   = big numinator of value without fraction (or cut residual
2791
     *fraction) bigDenom = big denominator of value
2792
     *-- Break-criteria so that uint64_t cast to "bigNum" introduces no error
2793
     *and bigDenom has no overflow, and stop with enlargement of fraction when
2794
     *the double-value of it reaches an integer number without fractional part.
2795
     */
2796
0
    bigDenom = 1;
2797
0
    while ((value != floor(value)) && (value < fMax) && (bigDenom < nMax))
2798
0
    {
2799
0
        bigDenom <<= 1;
2800
0
        value *= 2;
2801
0
    }
2802
0
    bigNum = (uint64_t)value;
2803
2804
    /*-- Start Euclidean algorithm to find the greatest common divisor (GCD) --
2805
     */
2806
0
#define MAX_ITERATIONS 64
2807
0
    for (i = 0; i < MAX_ITERATIONS; i++)
2808
0
    {
2809
0
        uint64_t val;
2810
        /* if bigDenom is not zero, calculate integer part of fraction. */
2811
0
        if (bigDenom == 0)
2812
0
        {
2813
0
            break;
2814
0
        }
2815
0
        val = bigNum / bigDenom;
2816
2817
        /* Set bigDenom to reminder of bigNum/bigDenom and bigNum to previous
2818
         * denominator bigDenom. */
2819
0
        aux = bigNum;
2820
0
        bigNum = bigDenom;
2821
0
        bigDenom = aux % bigDenom;
2822
2823
        /* calculate next denominator and check for its given maximum */
2824
0
        aux = val;
2825
0
        if (denomSum[1] * val + denomSum[0] >= maxDenom)
2826
0
        {
2827
0
            aux = (maxDenom - denomSum[0]) / denomSum[1];
2828
0
            if (aux * 2 >= val || denomSum[1] >= maxDenom)
2829
0
                i = (MAX_ITERATIONS +
2830
0
                     1); /* exit but execute rest of for-loop */
2831
0
            else
2832
0
                break;
2833
0
        }
2834
        /* calculate next numerator to numSum2 and save previous one to numSum0;
2835
         * numSum1 just copy of numSum2. */
2836
0
        numSum[2] = aux * numSum[1] + numSum[0];
2837
0
        numSum[0] = numSum[1];
2838
0
        numSum[1] = numSum[2];
2839
        /* calculate next denominator to denomSum2 and save previous one to
2840
         * denomSum0; denomSum1 just copy of denomSum2. */
2841
0
        denomSum[2] = aux * denomSum[1] + denomSum[0];
2842
0
        denomSum[0] = denomSum[1];
2843
0
        denomSum[1] = denomSum[2];
2844
0
    }
2845
2846
    /*-- Check and adapt for final variable size and return values; reduces
2847
     * internal accuracy; denominator is kept in ULONG-range with maxDenom -- */
2848
0
    while (numSum[1] > returnLimit || denomSum[1] > returnLimit)
2849
0
    {
2850
0
        numSum[1] = numSum[1] / 2;
2851
0
        denomSum[1] = denomSum[1] / 2;
2852
0
    }
2853
2854
    /* return values */
2855
0
    *ullNum = numSum[1];
2856
0
    *ullDenom = denomSum[1];
2857
2858
0
} /*-- ToRationalEuclideanGCD() -------------- */
2859
2860
/**---- DoubleToRational() -----------------------------------------------
2861
* Calculates the rational fractional of a double input value
2862
* for UN-SIGNED rationals,
2863
* using the Euclidean algorithm to find the greatest common divisor (GCD)
2864
------------------------------------------------------------------------*/
2865
static void DoubleToRational(double value, uint32_t *num, uint32_t *denom)
2866
0
{
2867
    /*---- UN-SIGNED RATIONAL ---- */
2868
0
    double dblDiff, dblDiff2;
2869
0
    uint64_t ullNum, ullDenom, ullNum2, ullDenom2;
2870
2871
    /*-- Check for negative values. If so it is an error. */
2872
    /* Test written that way to catch NaN */
2873
0
    if (!(value >= 0))
2874
0
    {
2875
0
        *num = *denom = 0;
2876
0
        TIFFErrorExt(0, "TIFFLib: DoubleToRational()",
2877
0
                     " Negative Value for Unsigned Rational given.");
2878
0
        return;
2879
0
    }
2880
2881
    /*-- Check for too big numbers (> ULONG_MAX) -- */
2882
0
    if (value > 0xFFFFFFFFUL)
2883
0
    {
2884
0
        *num = 0xFFFFFFFFU;
2885
0
        *denom = 0;
2886
0
        return;
2887
0
    }
2888
    /*-- Check for easy integer numbers -- */
2889
0
    if (value == (uint32_t)(value))
2890
0
    {
2891
0
        *num = (uint32_t)value;
2892
0
        *denom = 1;
2893
0
        return;
2894
0
    }
2895
    /*-- Check for too small numbers for "unsigned long" type rationals -- */
2896
0
    if (value < 1.0 / (double)0xFFFFFFFFUL)
2897
0
    {
2898
0
        *num = 0;
2899
0
        *denom = 0xFFFFFFFFU;
2900
0
        return;
2901
0
    }
2902
2903
    /*-- There are two approaches using the Euclidean algorithm,
2904
     *   which can accidentally lead to different accuracies just depending on
2905
     * the value. Try both and define which one was better.
2906
     */
2907
0
    ToRationalEuclideanGCD(value, FALSE, FALSE, &ullNum, &ullDenom);
2908
0
    ToRationalEuclideanGCD(value, FALSE, TRUE, &ullNum2, &ullDenom2);
2909
    /*-- Double-Check, that returned values fit into ULONG :*/
2910
0
    if (ullNum > 0xFFFFFFFFUL || ullDenom > 0xFFFFFFFFUL ||
2911
0
        ullNum2 > 0xFFFFFFFFUL || ullDenom2 > 0xFFFFFFFFUL)
2912
0
    {
2913
0
        TIFFErrorExt(0, "TIFFLib: DoubleToRational()",
2914
0
                     " Num or Denom exceeds ULONG: val=%14.6f, num=%12" PRIu64
2915
0
                     ", denom=%12" PRIu64 " | num2=%12" PRIu64
2916
0
                     ", denom2=%12" PRIu64 "",
2917
0
                     value, ullNum, ullDenom, ullNum2, ullDenom2);
2918
0
        assert(0);
2919
0
    }
2920
2921
    /* Check, which one has higher accuracy and take that. */
2922
0
    dblDiff = fabs(value - ((double)ullNum / (double)ullDenom));
2923
0
    dblDiff2 = fabs(value - ((double)ullNum2 / (double)ullDenom2));
2924
0
    if (dblDiff < dblDiff2)
2925
0
    {
2926
0
        *num = (uint32_t)ullNum;
2927
0
        *denom = (uint32_t)ullDenom;
2928
0
    }
2929
0
    else
2930
0
    {
2931
0
        *num = (uint32_t)ullNum2;
2932
0
        *denom = (uint32_t)ullDenom2;
2933
0
    }
2934
0
} /*-- DoubleToRational() -------------- */
2935
2936
/**---- DoubleToSrational() -----------------------------------------------
2937
* Calculates the rational fractional of a double input value
2938
* for SIGNED rationals,
2939
* using the Euclidean algorithm to find the greatest common divisor (GCD)
2940
------------------------------------------------------------------------*/
2941
static void DoubleToSrational(double value, int32_t *num, int32_t *denom)
2942
0
{
2943
    /*---- SIGNED RATIONAL ----*/
2944
0
    int neg = 1;
2945
0
    double dblDiff, dblDiff2;
2946
0
    uint64_t ullNum, ullDenom, ullNum2, ullDenom2;
2947
2948
    /*-- Check for negative values and use then the positive one for internal
2949
     * calculations, but take the sign into account before returning. */
2950
0
    if (value < 0)
2951
0
    {
2952
0
        neg = -1;
2953
0
        value = -value;
2954
0
    }
2955
2956
    /*-- Check for too big numbers (> LONG_MAX) -- */
2957
0
    if (value > 0x7FFFFFFFL)
2958
0
    {
2959
0
        *num = 0x7FFFFFFFL;
2960
0
        *denom = 0;
2961
0
        return;
2962
0
    }
2963
    /*-- Check for easy numbers -- */
2964
0
    if (value == (int32_t)(value))
2965
0
    {
2966
0
        *num = (int32_t)(neg * value);
2967
0
        *denom = 1;
2968
0
        return;
2969
0
    }
2970
    /*-- Check for too small numbers for "long" type rationals -- */
2971
0
    if (value < 1.0 / (double)0x7FFFFFFFL)
2972
0
    {
2973
0
        *num = 0;
2974
0
        *denom = 0x7FFFFFFFL;
2975
0
        return;
2976
0
    }
2977
2978
    /*-- There are two approaches using the Euclidean algorithm,
2979
     *   which can accidentally lead to different accuracies just depending on
2980
     * the value. Try both and define which one was better. Furthermore, set
2981
     * behavior of ToRationalEuclideanGCD() to the range of signed-long.
2982
     */
2983
0
    ToRationalEuclideanGCD(value, TRUE, FALSE, &ullNum, &ullDenom);
2984
0
    ToRationalEuclideanGCD(value, TRUE, TRUE, &ullNum2, &ullDenom2);
2985
    /*-- Double-Check, that returned values fit into LONG :*/
2986
0
    if (ullNum > 0x7FFFFFFFL || ullDenom > 0x7FFFFFFFL ||
2987
0
        ullNum2 > 0x7FFFFFFFL || ullDenom2 > 0x7FFFFFFFL)
2988
0
    {
2989
0
        TIFFErrorExt(0, "TIFFLib: DoubleToSrational()",
2990
0
                     " Num or Denom exceeds LONG: val=%14.6f, num=%12" PRIu64
2991
0
                     ", denom=%12" PRIu64 " | num2=%12" PRIu64
2992
0
                     ", denom2=%12" PRIu64 "",
2993
0
                     neg * value, ullNum, ullDenom, ullNum2, ullDenom2);
2994
0
        assert(0);
2995
0
    }
2996
2997
    /* Check, which one has higher accuracy and take that. */
2998
0
    dblDiff = fabs(value - ((double)ullNum / (double)ullDenom));
2999
0
    dblDiff2 = fabs(value - ((double)ullNum2 / (double)ullDenom2));
3000
0
    if (dblDiff < dblDiff2)
3001
0
    {
3002
0
        *num = (int32_t)(neg * (long)ullNum);
3003
0
        *denom = (int32_t)ullDenom;
3004
0
    }
3005
0
    else
3006
0
    {
3007
0
        *num = (int32_t)(neg * (long)ullNum2);
3008
0
        *denom = (int32_t)ullDenom2;
3009
0
    }
3010
0
} /*-- DoubleToSrational() --------------*/
3011
3012
static int TIFFWriteDirectoryTagCheckedFloatArray(TIFF *tif, uint32_t *ndir,
3013
                                                  TIFFDirEntry *dir,
3014
                                                  uint16_t tag, uint32_t count,
3015
                                                  float *value)
3016
0
{
3017
0
    assert(count < 0x40000000);
3018
0
    assert(sizeof(float) == 4);
3019
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
3020
0
    {
3021
0
        EvaluateIFDdatasizeWrite(tif, count, 4, ndir);
3022
0
        return 1;
3023
0
    }
3024
0
    TIFFCvtNativeToIEEEFloat(tif, count, value);
3025
0
    if (tif->tif_flags & TIFF_SWAB)
3026
0
        TIFFSwabArrayOfFloat(value, count);
3027
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_FLOAT, count,
3028
0
                                      count * 4, value));
3029
0
}
3030
3031
static int TIFFWriteDirectoryTagCheckedDoubleArray(TIFF *tif, uint32_t *ndir,
3032
                                                   TIFFDirEntry *dir,
3033
                                                   uint16_t tag, uint32_t count,
3034
                                                   double *value)
3035
0
{
3036
0
    assert(count < 0x20000000);
3037
0
    assert(sizeof(double) == 8);
3038
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
3039
0
    {
3040
0
        EvaluateIFDdatasizeWrite(tif, count, 8, ndir);
3041
0
        return 1;
3042
0
    }
3043
0
    TIFFCvtNativeToIEEEDouble(tif, count, value);
3044
0
    if (tif->tif_flags & TIFF_SWAB)
3045
0
        TIFFSwabArrayOfDouble(value, count);
3046
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_DOUBLE, count,
3047
0
                                      count * 8, value));
3048
0
}
3049
3050
static int TIFFWriteDirectoryTagCheckedIfdArray(TIFF *tif, uint32_t *ndir,
3051
                                                TIFFDirEntry *dir, uint16_t tag,
3052
                                                uint32_t count, uint32_t *value)
3053
0
{
3054
0
    assert(count < 0x40000000);
3055
0
    assert(sizeof(uint32_t) == 4);
3056
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
3057
0
    {
3058
0
        EvaluateIFDdatasizeWrite(tif, count, 4, ndir);
3059
0
        return 1;
3060
0
    }
3061
0
    if (tif->tif_flags & TIFF_SWAB)
3062
0
        TIFFSwabArrayOfLong(value, count);
3063
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_IFD, count,
3064
0
                                      count * 4, value));
3065
0
}
3066
3067
static int TIFFWriteDirectoryTagCheckedIfd8Array(TIFF *tif, uint32_t *ndir,
3068
                                                 TIFFDirEntry *dir,
3069
                                                 uint16_t tag, uint32_t count,
3070
                                                 uint64_t *value)
3071
0
{
3072
0
    assert(count < 0x20000000);
3073
0
    assert(sizeof(uint64_t) == 8);
3074
0
    assert(tif->tif_flags & TIFF_BIGTIFF);
3075
0
    if (dir == NULL) /* Just evaluate IFD data size and increment ndir. */
3076
0
    {
3077
0
        EvaluateIFDdatasizeWrite(tif, count, 8, ndir);
3078
0
        return 1;
3079
0
    }
3080
0
    if (tif->tif_flags & TIFF_SWAB)
3081
0
        TIFFSwabArrayOfLong8(value, count);
3082
0
    return (TIFFWriteDirectoryTagData(tif, ndir, dir, tag, TIFF_IFD8, count,
3083
0
                                      count * 8, value));
3084
0
}
3085
3086
static int TIFFWriteDirectoryTagData(TIFF *tif, uint32_t *ndir,
3087
                                     TIFFDirEntry *dir, uint16_t tag,
3088
                                     uint16_t datatype, uint32_t count,
3089
                                     uint32_t datalength, void *data)
3090
0
{
3091
0
    static const char module[] = "TIFFWriteDirectoryTagData";
3092
0
    uint32_t m;
3093
0
    m = 0;
3094
0
    while (m < (*ndir))
3095
0
    {
3096
0
        assert(dir[m].tdir_tag != tag);
3097
0
        if (dir[m].tdir_tag > tag)
3098
0
            break;
3099
0
        m++;
3100
0
    }
3101
0
    if (m < (*ndir))
3102
0
    {
3103
0
        uint32_t n;
3104
0
        for (n = *ndir; n > m; n--)
3105
0
            dir[n] = dir[n - 1];
3106
0
    }
3107
0
    dir[m].tdir_tag = tag;
3108
0
    dir[m].tdir_type = datatype;
3109
0
    dir[m].tdir_count = count;
3110
0
    dir[m].tdir_offset.toff_long8 = 0;
3111
0
    if (datalength <= ((tif->tif_flags & TIFF_BIGTIFF) ? 0x8U : 0x4U))
3112
0
    {
3113
0
        if (data && datalength)
3114
0
        {
3115
0
            _TIFFmemcpy(&dir[m].tdir_offset, data, datalength);
3116
0
        }
3117
0
    }
3118
0
    else
3119
0
    {
3120
0
        uint64_t na, nb;
3121
0
        na = tif->tif_dataoff;
3122
0
        nb = na + datalength;
3123
0
        if (!(tif->tif_flags & TIFF_BIGTIFF))
3124
0
            nb = (uint32_t)nb;
3125
0
        if ((nb < na) || (nb < datalength))
3126
0
        {
3127
0
            TIFFErrorExtR(tif, module, "Maximum TIFF file size exceeded");
3128
0
            return (0);
3129
0
        }
3130
0
        if (!SeekOK(tif, na))
3131
0
        {
3132
0
            TIFFErrorExtR(tif, module, "IO error writing tag data");
3133
0
            return (0);
3134
0
        }
3135
0
        if (datalength >= 0x80000000UL)
3136
0
        {
3137
0
            TIFFErrorExtR(tif, module,
3138
0
                          "libtiff does not allow writing more than 2147483647 "
3139
0
                          "bytes in a tag");
3140
0
            return (0);
3141
0
        }
3142
0
        if (!WriteOK(tif, data, (tmsize_t)datalength))
3143
0
        {
3144
0
            TIFFErrorExtR(tif, module, "IO error writing tag data");
3145
0
            return (0);
3146
0
        }
3147
0
        tif->tif_dataoff = nb;
3148
0
        if (tif->tif_dataoff & 1)
3149
0
            tif->tif_dataoff++;
3150
0
        if (!(tif->tif_flags & TIFF_BIGTIFF))
3151
0
        {
3152
0
            uint32_t o;
3153
0
            o = (uint32_t)na;
3154
0
            if (tif->tif_flags & TIFF_SWAB)
3155
0
                TIFFSwabLong(&o);
3156
0
            _TIFFmemcpy(&dir[m].tdir_offset, &o, 4);
3157
0
        }
3158
0
        else
3159
0
        {
3160
0
            dir[m].tdir_offset.toff_long8 = na;
3161
0
            if (tif->tif_flags & TIFF_SWAB)
3162
0
                TIFFSwabLong8(&dir[m].tdir_offset.toff_long8);
3163
0
        }
3164
0
    }
3165
0
    (*ndir)++;
3166
0
    return (1);
3167
0
}
3168
3169
/*
3170
 * Link the current directory into the directory chain for the file.
3171
 */
3172
static int TIFFLinkDirectory(TIFF *tif)
3173
0
{
3174
0
    static const char module[] = "TIFFLinkDirectory";
3175
3176
0
    tif->tif_diroff = (TIFFSeekFile(tif, 0, SEEK_END) + 1) & (~((toff_t)1));
3177
3178
    /*
3179
     * Handle SubIFDs
3180
     */
3181
0
    if (tif->tif_flags & TIFF_INSUBIFD)
3182
0
    {
3183
0
        if (!(tif->tif_flags & TIFF_BIGTIFF))
3184
0
        {
3185
0
            uint32_t m;
3186
0
            m = (uint32_t)tif->tif_diroff;
3187
0
            if (tif->tif_flags & TIFF_SWAB)
3188
0
                TIFFSwabLong(&m);
3189
0
            (void)TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET);
3190
0
            if (!WriteOK(tif, &m, 4))
3191
0
            {
3192
0
                TIFFErrorExtR(tif, module,
3193
0
                              "Error writing SubIFD directory link");
3194
0
                return (0);
3195
0
            }
3196
3197
            /*
3198
             * Advance to the next SubIFD or, if this is
3199
             * the last one configured, reverting back to the
3200
             * normal directory linkage is done in TIFFWriteDirectorySec()
3201
             * by tif->tif_flags &= ~TIFF_INSUBIFD;.
3202
             */
3203
0
            if (--tif->tif_nsubifd)
3204
0
                tif->tif_subifdoff += 4;
3205
0
            return (1);
3206
0
        }
3207
0
        else
3208
0
        {
3209
0
            uint64_t m;
3210
0
            m = tif->tif_diroff;
3211
0
            if (tif->tif_flags & TIFF_SWAB)
3212
0
                TIFFSwabLong8(&m);
3213
0
            (void)TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET);
3214
0
            if (!WriteOK(tif, &m, 8))
3215
0
            {
3216
0
                TIFFErrorExtR(tif, module,
3217
0
                              "Error writing SubIFD directory link");
3218
0
                return (0);
3219
0
            }
3220
3221
            /*
3222
             * Advance to the next SubIFD or, if this is
3223
             * the last one configured, reverting back to the
3224
             * normal directory linkage is done in TIFFWriteDirectorySec()
3225
             * by tif->tif_flags &= ~TIFF_INSUBIFD;.
3226
             */
3227
0
            if (--tif->tif_nsubifd)
3228
0
                tif->tif_subifdoff += 8;
3229
0
            return (1);
3230
0
        }
3231
0
    }
3232
3233
    /*
3234
     * Handle main-IFDs
3235
     */
3236
0
    tdir_t ndir = 1; /* count current number of main-IFDs */
3237
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
3238
0
    {
3239
0
        uint32_t m;
3240
0
        uint32_t nextdir;
3241
0
        m = (uint32_t)(tif->tif_diroff);
3242
0
        if (tif->tif_flags & TIFF_SWAB)
3243
0
            TIFFSwabLong(&m);
3244
0
        if (tif->tif_header.classic.tiff_diroff == 0)
3245
0
        {
3246
            /*
3247
             * First directory, overwrite offset in header.
3248
             */
3249
0
            tif->tif_header.classic.tiff_diroff = (uint32_t)tif->tif_diroff;
3250
0
            tif->tif_lastdiroff = tif->tif_diroff;
3251
0
            (void)TIFFSeekFile(tif, 4, SEEK_SET);
3252
0
            if (!WriteOK(tif, &m, 4))
3253
0
            {
3254
0
                TIFFErrorExtR(tif, tif->tif_name, "Error writing TIFF header");
3255
0
                return (0);
3256
0
            }
3257
0
            if (!tif->tif_dir.td_iswrittentofile)
3258
0
                tif->tif_curdircount = 0;
3259
0
            return (1);
3260
0
        }
3261
        /*
3262
         * Not the first directory, search to the last and append.
3263
         */
3264
0
        tdir_t dirn = 0;
3265
0
        if (tif->tif_lastdiroff != 0 &&
3266
0
            _TIFFGetDirNumberFromOffset(tif, tif->tif_lastdiroff, &dirn))
3267
0
        {
3268
            /* Start searching from the lastely written IFD. Thus get its IFD
3269
             * number. */
3270
0
            nextdir = (uint32_t)tif->tif_lastdiroff;
3271
0
            ndir = dirn + 1;
3272
0
        }
3273
0
        else
3274
0
        {
3275
0
            nextdir = tif->tif_header.classic.tiff_diroff;
3276
0
            ndir = 1; /* start searching from the first IFD */
3277
0
        }
3278
3279
0
        while (1)
3280
0
        {
3281
0
            uint16_t dircount;
3282
0
            uint32_t nextnextdir;
3283
3284
0
            if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, 2))
3285
0
            {
3286
0
                TIFFErrorExtR(tif, module, "Error fetching directory count");
3287
0
                return (0);
3288
0
            }
3289
0
            if (tif->tif_flags & TIFF_SWAB)
3290
0
                TIFFSwabShort(&dircount);
3291
0
            (void)TIFFSeekFile(tif, nextdir + 2 + dircount * 12, SEEK_SET);
3292
0
            if (!ReadOK(tif, &nextnextdir, 4))
3293
0
            {
3294
0
                TIFFErrorExtR(tif, module, "Error fetching directory link");
3295
0
                return (0);
3296
0
            }
3297
0
            if (tif->tif_flags & TIFF_SWAB)
3298
0
                TIFFSwabLong(&nextnextdir);
3299
0
            if (nextnextdir == 0)
3300
0
            {
3301
0
                (void)TIFFSeekFile(tif, nextdir + 2 + dircount * 12, SEEK_SET);
3302
0
                if (!WriteOK(tif, &m, 4))
3303
0
                {
3304
0
                    TIFFErrorExtR(tif, module, "Error writing directory link");
3305
0
                    return (0);
3306
0
                }
3307
0
                tif->tif_lastdiroff = tif->tif_diroff;
3308
0
                break;
3309
0
            }
3310
0
            nextdir = nextnextdir;
3311
0
            ndir++;
3312
0
        }
3313
0
    }
3314
0
    else
3315
0
    {
3316
        /*- BigTIFF -*/
3317
0
        uint64_t m;
3318
0
        uint64_t nextdir;
3319
0
        m = tif->tif_diroff;
3320
0
        if (tif->tif_flags & TIFF_SWAB)
3321
0
            TIFFSwabLong8(&m);
3322
0
        if (tif->tif_header.big.tiff_diroff == 0)
3323
0
        {
3324
            /*
3325
             * First directory, overwrite offset in header.
3326
             */
3327
0
            tif->tif_header.big.tiff_diroff = tif->tif_diroff;
3328
0
            tif->tif_lastdiroff = tif->tif_diroff;
3329
0
            (void)TIFFSeekFile(tif, 8, SEEK_SET);
3330
0
            if (!WriteOK(tif, &m, 8))
3331
0
            {
3332
0
                TIFFErrorExtR(tif, tif->tif_name, "Error writing TIFF header");
3333
0
                return (0);
3334
0
            }
3335
0
            if (!tif->tif_dir.td_iswrittentofile)
3336
0
                tif->tif_curdircount = 0;
3337
0
            return (1);
3338
0
        }
3339
        /*
3340
         * Not the first directory, search to the last and append.
3341
         */
3342
0
        tdir_t dirn = 0;
3343
0
        if (tif->tif_lastdiroff != 0 &&
3344
0
            _TIFFGetDirNumberFromOffset(tif, tif->tif_lastdiroff, &dirn))
3345
0
        {
3346
            /* Start searching from the lastely written IFD. Thus get its IFD
3347
             * number. */
3348
0
            nextdir = tif->tif_lastdiroff;
3349
0
            ndir = dirn + 1;
3350
0
        }
3351
0
        else
3352
0
        {
3353
0
            nextdir = tif->tif_header.big.tiff_diroff;
3354
0
            ndir = 1; /* start searching from the first IFD */
3355
0
        }
3356
0
        while (1)
3357
0
        {
3358
0
            uint64_t dircount64;
3359
0
            uint16_t dircount;
3360
0
            uint64_t nextnextdir;
3361
3362
0
            if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount64, 8))
3363
0
            {
3364
0
                TIFFErrorExtR(tif, module, "Error fetching directory count");
3365
0
                return (0);
3366
0
            }
3367
0
            if (tif->tif_flags & TIFF_SWAB)
3368
0
                TIFFSwabLong8(&dircount64);
3369
0
            if (dircount64 > 0xFFFF)
3370
0
            {
3371
0
                TIFFErrorExtR(tif, module,
3372
0
                              "Sanity check on tag count failed, "
3373
0
                              "likely corrupt TIFF");
3374
0
                return (0);
3375
0
            }
3376
0
            dircount = (uint16_t)dircount64;
3377
0
            (void)TIFFSeekFile(tif, nextdir + 8 + dircount * 20, SEEK_SET);
3378
0
            if (!ReadOK(tif, &nextnextdir, 8))
3379
0
            {
3380
0
                TIFFErrorExtR(tif, module, "Error fetching directory link");
3381
0
                return (0);
3382
0
            }
3383
0
            if (tif->tif_flags & TIFF_SWAB)
3384
0
                TIFFSwabLong8(&nextnextdir);
3385
0
            if (nextnextdir == 0)
3386
0
            {
3387
0
                (void)TIFFSeekFile(tif, nextdir + 8 + dircount * 20, SEEK_SET);
3388
0
                if (!WriteOK(tif, &m, 8))
3389
0
                {
3390
0
                    TIFFErrorExtR(tif, module, "Error writing directory link");
3391
0
                    return (0);
3392
0
                }
3393
0
                tif->tif_lastdiroff = tif->tif_diroff;
3394
0
                break;
3395
0
            }
3396
0
            nextdir = nextnextdir;
3397
0
            ndir++;
3398
0
        }
3399
0
    }
3400
    /* Offset of next IFD is written to file.
3401
     * Update number of main-IFDs in file.
3402
     * However, tif_curdircount shall count only newly written main-IFDs with
3403
     * entries and not only number of linked offsets! Thus, tif_curdircount is
3404
     * incremented at the end of TIFFWriteDirectorySec().
3405
     * TIFF_NON_EXISTENT_DIR_NUMBER means 'dont know number of IFDs'
3406
     * 0 means 'empty file opened for writing, but no IFD written yet' */
3407
0
    if (!tif->tif_dir.td_iswrittentofile && !(tif->tif_flags & TIFF_INSUBIFD))
3408
0
    {
3409
0
        tif->tif_curdircount = ndir;
3410
0
    }
3411
0
    return (1);
3412
0
}
3413
3414
/************************************************************************/
3415
/*                          TIFFRewriteField()                          */
3416
/*                                                                      */
3417
/*      Rewrite a field in the directory on disk without regard to      */
3418
/*      updating the TIFF directory structure in memory.  Currently     */
3419
/*      only supported for field that already exist in the on-disk      */
3420
/*      directory.  Mainly used for updating stripoffset /              */
3421
/*      stripbytecount values after the directory is already on         */
3422
/*      disk.                                                           */
3423
/*                                                                      */
3424
/*      Returns zero on failure, and one on success.                    */
3425
/************************************************************************/
3426
3427
int _TIFFRewriteField(TIFF *tif, uint16_t tag, TIFFDataType in_datatype,
3428
                      tmsize_t count, void *data)
3429
0
{
3430
0
    static const char module[] = "TIFFResetField";
3431
    /* const TIFFField* fip = NULL; */
3432
0
    uint16_t dircount;
3433
0
    tmsize_t dirsize;
3434
0
    uint8_t direntry_raw[20];
3435
0
    uint16_t entry_tag = 0;
3436
0
    uint16_t entry_type = 0;
3437
0
    uint64_t entry_count = 0;
3438
0
    uint64_t entry_offset = 0;
3439
0
    int value_in_entry = 0;
3440
0
    uint64_t read_offset;
3441
0
    uint8_t *buf_to_write = NULL;
3442
0
    TIFFDataType datatype;
3443
3444
    /* -------------------------------------------------------------------- */
3445
    /*      Find field definition.                                          */
3446
    /* -------------------------------------------------------------------- */
3447
0
    /*fip =*/TIFFFindField(tif, tag, TIFF_ANY);
3448
3449
    /* -------------------------------------------------------------------- */
3450
    /*      Do some checking this is a straight forward case.               */
3451
    /* -------------------------------------------------------------------- */
3452
0
    if (isMapped(tif))
3453
0
    {
3454
0
        TIFFErrorExtR(tif, module,
3455
0
                      "Memory mapped files not currently supported for "
3456
0
                      "this operation.");
3457
0
        return 0;
3458
0
    }
3459
3460
0
    if (tif->tif_diroff == 0)
3461
0
    {
3462
0
        TIFFErrorExtR(
3463
0
            tif, module,
3464
0
            "Attempt to reset field on directory not already on disk.");
3465
0
        return 0;
3466
0
    }
3467
3468
    /* -------------------------------------------------------------------- */
3469
    /*      Read the directory entry count.                                 */
3470
    /* -------------------------------------------------------------------- */
3471
0
    if (!SeekOK(tif, tif->tif_diroff))
3472
0
    {
3473
0
        TIFFErrorExtR(tif, module, "%s: Seek error accessing TIFF directory",
3474
0
                      tif->tif_name);
3475
0
        return 0;
3476
0
    }
3477
3478
0
    read_offset = tif->tif_diroff;
3479
3480
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
3481
0
    {
3482
0
        if (!ReadOK(tif, &dircount, sizeof(uint16_t)))
3483
0
        {
3484
0
            TIFFErrorExtR(tif, module, "%s: Can not read TIFF directory count",
3485
0
                          tif->tif_name);
3486
0
            return 0;
3487
0
        }
3488
0
        if (tif->tif_flags & TIFF_SWAB)
3489
0
            TIFFSwabShort(&dircount);
3490
0
        dirsize = 12;
3491
0
        read_offset += 2;
3492
0
    }
3493
0
    else
3494
0
    {
3495
0
        uint64_t dircount64;
3496
0
        if (!ReadOK(tif, &dircount64, sizeof(uint64_t)))
3497
0
        {
3498
0
            TIFFErrorExtR(tif, module, "%s: Can not read TIFF directory count",
3499
0
                          tif->tif_name);
3500
0
            return 0;
3501
0
        }
3502
0
        if (tif->tif_flags & TIFF_SWAB)
3503
0
            TIFFSwabLong8(&dircount64);
3504
0
        dircount = (uint16_t)dircount64;
3505
0
        dirsize = 20;
3506
0
        read_offset += 8;
3507
0
    }
3508
3509
    /* -------------------------------------------------------------------- */
3510
    /*      Read through directory to find target tag.                      */
3511
    /* -------------------------------------------------------------------- */
3512
0
    while (dircount > 0)
3513
0
    {
3514
0
        if (!ReadOK(tif, direntry_raw, dirsize))
3515
0
        {
3516
0
            TIFFErrorExtR(tif, module, "%s: Can not read TIFF directory entry.",
3517
0
                          tif->tif_name);
3518
0
            return 0;
3519
0
        }
3520
3521
0
        memcpy(&entry_tag, direntry_raw + 0, sizeof(uint16_t));
3522
0
        if (tif->tif_flags & TIFF_SWAB)
3523
0
            TIFFSwabShort(&entry_tag);
3524
3525
0
        if (entry_tag == tag)
3526
0
            break;
3527
3528
0
        read_offset += dirsize;
3529
0
    }
3530
3531
0
    if (entry_tag != tag)
3532
0
    {
3533
0
        TIFFErrorExtR(tif, module, "%s: Could not find tag %" PRIu16 ".",
3534
0
                      tif->tif_name, tag);
3535
0
        return 0;
3536
0
    }
3537
3538
    /* -------------------------------------------------------------------- */
3539
    /*      Extract the type, count and offset for this entry.              */
3540
    /* -------------------------------------------------------------------- */
3541
0
    memcpy(&entry_type, direntry_raw + 2, sizeof(uint16_t));
3542
0
    if (tif->tif_flags & TIFF_SWAB)
3543
0
        TIFFSwabShort(&entry_type);
3544
3545
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
3546
0
    {
3547
0
        uint32_t value;
3548
3549
0
        memcpy(&value, direntry_raw + 4, sizeof(uint32_t));
3550
0
        if (tif->tif_flags & TIFF_SWAB)
3551
0
            TIFFSwabLong(&value);
3552
0
        entry_count = value;
3553
3554
0
        memcpy(&value, direntry_raw + 8, sizeof(uint32_t));
3555
0
        if (tif->tif_flags & TIFF_SWAB)
3556
0
            TIFFSwabLong(&value);
3557
0
        entry_offset = value;
3558
0
    }
3559
0
    else
3560
0
    {
3561
0
        memcpy(&entry_count, direntry_raw + 4, sizeof(uint64_t));
3562
0
        if (tif->tif_flags & TIFF_SWAB)
3563
0
            TIFFSwabLong8(&entry_count);
3564
3565
0
        memcpy(&entry_offset, direntry_raw + 12, sizeof(uint64_t));
3566
0
        if (tif->tif_flags & TIFF_SWAB)
3567
0
            TIFFSwabLong8(&entry_offset);
3568
0
    }
3569
3570
    /* -------------------------------------------------------------------- */
3571
    /*      When a dummy tag was written due to TIFFDeferStrileArrayWriting() */
3572
    /* -------------------------------------------------------------------- */
3573
0
    if (entry_offset == 0 && entry_count == 0 && entry_type == 0)
3574
0
    {
3575
0
        if (tag == TIFFTAG_TILEOFFSETS || tag == TIFFTAG_STRIPOFFSETS)
3576
0
        {
3577
0
            entry_type =
3578
0
                (tif->tif_flags & TIFF_BIGTIFF) ? TIFF_LONG8 : TIFF_LONG;
3579
0
        }
3580
0
        else
3581
0
        {
3582
0
            int write_aslong8 = 1;
3583
0
            if (count > 1 && tag == TIFFTAG_STRIPBYTECOUNTS)
3584
0
            {
3585
0
                write_aslong8 = WriteAsLong8(tif, TIFFStripSize64(tif));
3586
0
            }
3587
0
            else if (count > 1 && tag == TIFFTAG_TILEBYTECOUNTS)
3588
0
            {
3589
0
                write_aslong8 = WriteAsLong8(tif, TIFFTileSize64(tif));
3590
0
            }
3591
0
            if (write_aslong8)
3592
0
            {
3593
0
                entry_type = TIFF_LONG8;
3594
0
            }
3595
0
            else
3596
0
            {
3597
0
                int write_aslong4 = 1;
3598
0
                if (count > 1 && tag == TIFFTAG_STRIPBYTECOUNTS)
3599
0
                {
3600
0
                    write_aslong4 = WriteAsLong4(tif, TIFFStripSize64(tif));
3601
0
                }
3602
0
                else if (count > 1 && tag == TIFFTAG_TILEBYTECOUNTS)
3603
0
                {
3604
0
                    write_aslong4 = WriteAsLong4(tif, TIFFTileSize64(tif));
3605
0
                }
3606
0
                if (write_aslong4)
3607
0
                {
3608
0
                    entry_type = TIFF_LONG;
3609
0
                }
3610
0
                else
3611
0
                {
3612
0
                    entry_type = TIFF_SHORT;
3613
0
                }
3614
0
            }
3615
0
        }
3616
0
    }
3617
3618
    /* -------------------------------------------------------------------- */
3619
    /*      What data type do we want to write this as?                     */
3620
    /* -------------------------------------------------------------------- */
3621
0
    if (TIFFDataWidth(in_datatype) == 8 && !(tif->tif_flags & TIFF_BIGTIFF))
3622
0
    {
3623
0
        if (in_datatype == TIFF_LONG8)
3624
0
            datatype = entry_type == TIFF_SHORT ? TIFF_SHORT : TIFF_LONG;
3625
0
        else if (in_datatype == TIFF_SLONG8)
3626
0
            datatype = TIFF_SLONG;
3627
0
        else if (in_datatype == TIFF_IFD8)
3628
0
            datatype = TIFF_IFD;
3629
0
        else
3630
0
            datatype = in_datatype;
3631
0
    }
3632
0
    else
3633
0
    {
3634
0
        if (in_datatype == TIFF_LONG8 &&
3635
0
            (entry_type == TIFF_SHORT || entry_type == TIFF_LONG ||
3636
0
             entry_type == TIFF_LONG8))
3637
0
            datatype = (TIFFDataType)entry_type;
3638
0
        else if (in_datatype == TIFF_SLONG8 &&
3639
0
                 (entry_type == TIFF_SLONG || entry_type == TIFF_SLONG8))
3640
0
            datatype = (TIFFDataType)entry_type;
3641
0
        else if (in_datatype == TIFF_IFD8 &&
3642
0
                 (entry_type == TIFF_IFD || entry_type == TIFF_IFD8))
3643
0
            datatype = (TIFFDataType)entry_type;
3644
0
        else
3645
0
            datatype = in_datatype;
3646
0
    }
3647
3648
    /* -------------------------------------------------------------------- */
3649
    /*      Prepare buffer of actual data to write.  This includes          */
3650
    /*      swabbing as needed.                                             */
3651
    /* -------------------------------------------------------------------- */
3652
0
    buf_to_write = (uint8_t *)_TIFFCheckMalloc(
3653
0
        tif, count, TIFFDataWidth(datatype), "for field buffer.");
3654
0
    if (!buf_to_write)
3655
0
        return 0;
3656
3657
0
    if (datatype == in_datatype)
3658
0
        memcpy(buf_to_write, data, count * TIFFDataWidth(datatype));
3659
0
    else if (datatype == TIFF_SLONG && in_datatype == TIFF_SLONG8)
3660
0
    {
3661
0
        tmsize_t i;
3662
3663
0
        for (i = 0; i < count; i++)
3664
0
        {
3665
0
            ((int32_t *)buf_to_write)[i] = (int32_t)((int64_t *)data)[i];
3666
0
            if ((int64_t)((int32_t *)buf_to_write)[i] != ((int64_t *)data)[i])
3667
0
            {
3668
0
                _TIFFfreeExt(tif, buf_to_write);
3669
0
                TIFFErrorExtR(tif, module,
3670
0
                              "Value exceeds 32bit range of output type.");
3671
0
                return 0;
3672
0
            }
3673
0
        }
3674
0
    }
3675
0
    else if ((datatype == TIFF_LONG && in_datatype == TIFF_LONG8) ||
3676
0
             (datatype == TIFF_IFD && in_datatype == TIFF_IFD8))
3677
0
    {
3678
0
        tmsize_t i;
3679
3680
0
        for (i = 0; i < count; i++)
3681
0
        {
3682
0
            ((uint32_t *)buf_to_write)[i] = (uint32_t)((uint64_t *)data)[i];
3683
0
            if ((uint64_t)((uint32_t *)buf_to_write)[i] !=
3684
0
                ((uint64_t *)data)[i])
3685
0
            {
3686
0
                _TIFFfreeExt(tif, buf_to_write);
3687
0
                TIFFErrorExtR(tif, module,
3688
0
                              "Value exceeds 32bit range of output type.");
3689
0
                return 0;
3690
0
            }
3691
0
        }
3692
0
    }
3693
0
    else if (datatype == TIFF_SHORT && in_datatype == TIFF_LONG8)
3694
0
    {
3695
0
        tmsize_t i;
3696
3697
0
        for (i = 0; i < count; i++)
3698
0
        {
3699
0
            ((uint16_t *)buf_to_write)[i] = (uint16_t)((uint64_t *)data)[i];
3700
0
            if ((uint64_t)((uint16_t *)buf_to_write)[i] !=
3701
0
                ((uint64_t *)data)[i])
3702
0
            {
3703
0
                _TIFFfreeExt(tif, buf_to_write);
3704
0
                TIFFErrorExtR(tif, module,
3705
0
                              "Value exceeds 16bit range of output type.");
3706
0
                return 0;
3707
0
            }
3708
0
        }
3709
0
    }
3710
0
    else
3711
0
    {
3712
0
        TIFFErrorExtR(tif, module, "Unhandled type conversion.");
3713
0
        return 0;
3714
0
    }
3715
3716
0
    if (TIFFDataWidth(datatype) > 1 && (tif->tif_flags & TIFF_SWAB))
3717
0
    {
3718
0
        if (TIFFDataWidth(datatype) == 2)
3719
0
            TIFFSwabArrayOfShort((uint16_t *)buf_to_write, count);
3720
0
        else if (TIFFDataWidth(datatype) == 4)
3721
0
            TIFFSwabArrayOfLong((uint32_t *)buf_to_write, count);
3722
0
        else if (TIFFDataWidth(datatype) == 8)
3723
0
            TIFFSwabArrayOfLong8((uint64_t *)buf_to_write, count);
3724
0
    }
3725
3726
    /* -------------------------------------------------------------------- */
3727
    /*      Is this a value that fits into the directory entry?             */
3728
    /* -------------------------------------------------------------------- */
3729
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
3730
0
    {
3731
0
        if (TIFFDataWidth(datatype) * count <= 4)
3732
0
        {
3733
0
            entry_offset = read_offset + 8;
3734
0
            value_in_entry = 1;
3735
0
        }
3736
0
    }
3737
0
    else
3738
0
    {
3739
0
        if (TIFFDataWidth(datatype) * count <= 8)
3740
0
        {
3741
0
            entry_offset = read_offset + 12;
3742
0
            value_in_entry = 1;
3743
0
        }
3744
0
    }
3745
3746
0
    if ((tag == TIFFTAG_TILEOFFSETS || tag == TIFFTAG_STRIPOFFSETS) &&
3747
0
        tif->tif_dir.td_stripoffset_entry.tdir_count == 0 &&
3748
0
        tif->tif_dir.td_stripoffset_entry.tdir_type == 0 &&
3749
0
        tif->tif_dir.td_stripoffset_entry.tdir_offset.toff_long8 == 0)
3750
0
    {
3751
0
        tif->tif_dir.td_stripoffset_entry.tdir_type = datatype;
3752
0
        tif->tif_dir.td_stripoffset_entry.tdir_count = count;
3753
0
    }
3754
0
    else if ((tag == TIFFTAG_TILEBYTECOUNTS ||
3755
0
              tag == TIFFTAG_STRIPBYTECOUNTS) &&
3756
0
             tif->tif_dir.td_stripbytecount_entry.tdir_count == 0 &&
3757
0
             tif->tif_dir.td_stripbytecount_entry.tdir_type == 0 &&
3758
0
             tif->tif_dir.td_stripbytecount_entry.tdir_offset.toff_long8 == 0)
3759
0
    {
3760
0
        tif->tif_dir.td_stripbytecount_entry.tdir_type = datatype;
3761
0
        tif->tif_dir.td_stripbytecount_entry.tdir_count = count;
3762
0
    }
3763
3764
    /* -------------------------------------------------------------------- */
3765
    /*      If the tag type, and count match, then we just write it out     */
3766
    /*      over the old values without altering the directory entry at     */
3767
    /*      all.                                                            */
3768
    /* -------------------------------------------------------------------- */
3769
0
    if (entry_count == (uint64_t)count && entry_type == (uint16_t)datatype)
3770
0
    {
3771
0
        if (!SeekOK(tif, entry_offset))
3772
0
        {
3773
0
            _TIFFfreeExt(tif, buf_to_write);
3774
0
            TIFFErrorExtR(tif, module,
3775
0
                          "%s: Seek error accessing TIFF directory",
3776
0
                          tif->tif_name);
3777
0
            return 0;
3778
0
        }
3779
0
        if (!WriteOK(tif, buf_to_write, count * TIFFDataWidth(datatype)))
3780
0
        {
3781
0
            _TIFFfreeExt(tif, buf_to_write);
3782
0
            TIFFErrorExtR(tif, module, "Error writing directory link");
3783
0
            return (0);
3784
0
        }
3785
3786
0
        _TIFFfreeExt(tif, buf_to_write);
3787
0
        return 1;
3788
0
    }
3789
3790
    /* -------------------------------------------------------------------- */
3791
    /*      Otherwise, we write the new tag data at the end of the file.    */
3792
    /* -------------------------------------------------------------------- */
3793
0
    if (!value_in_entry)
3794
0
    {
3795
0
        entry_offset = TIFFSeekFile(tif, 0, SEEK_END);
3796
3797
0
        if (!WriteOK(tif, buf_to_write, count * TIFFDataWidth(datatype)))
3798
0
        {
3799
0
            _TIFFfreeExt(tif, buf_to_write);
3800
0
            TIFFErrorExtR(tif, module, "Error writing directory link");
3801
0
            return (0);
3802
0
        }
3803
0
    }
3804
0
    else
3805
0
    {
3806
0
        if (count * TIFFDataWidth(datatype) == 4)
3807
0
        {
3808
0
            uint32_t value;
3809
0
            memcpy(&value, buf_to_write, count * TIFFDataWidth(datatype));
3810
0
            entry_offset = value;
3811
0
        }
3812
0
        else
3813
0
        {
3814
0
            memcpy(&entry_offset, buf_to_write,
3815
0
                   count * TIFFDataWidth(datatype));
3816
0
        }
3817
0
    }
3818
3819
0
    _TIFFfreeExt(tif, buf_to_write);
3820
0
    buf_to_write = 0;
3821
3822
    /* -------------------------------------------------------------------- */
3823
    /*      Adjust the directory entry.                                     */
3824
    /* -------------------------------------------------------------------- */
3825
0
    entry_type = datatype;
3826
0
    entry_count = (uint64_t)count;
3827
0
    memcpy(direntry_raw + 2, &entry_type, sizeof(uint16_t));
3828
0
    if (tif->tif_flags & TIFF_SWAB)
3829
0
        TIFFSwabShort((uint16_t *)(direntry_raw + 2));
3830
3831
0
    if (!(tif->tif_flags & TIFF_BIGTIFF))
3832
0
    {
3833
0
        uint32_t value;
3834
3835
0
        value = (uint32_t)entry_count;
3836
0
        memcpy(direntry_raw + 4, &value, sizeof(uint32_t));
3837
0
        if (tif->tif_flags & TIFF_SWAB)
3838
0
            TIFFSwabLong((uint32_t *)(direntry_raw + 4));
3839
3840
0
        value = (uint32_t)entry_offset;
3841
0
        memcpy(direntry_raw + 8, &value, sizeof(uint32_t));
3842
0
        if (tif->tif_flags & TIFF_SWAB)
3843
0
            TIFFSwabLong((uint32_t *)(direntry_raw + 8));
3844
0
    }
3845
0
    else
3846
0
    {
3847
0
        memcpy(direntry_raw + 4, &entry_count, sizeof(uint64_t));
3848
0
        if (tif->tif_flags & TIFF_SWAB)
3849
0
            TIFFSwabLong8((uint64_t *)(direntry_raw + 4));
3850
3851
0
        memcpy(direntry_raw + 12, &entry_offset, sizeof(uint64_t));
3852
0
        if (tif->tif_flags & TIFF_SWAB)
3853
0
            TIFFSwabLong8((uint64_t *)(direntry_raw + 12));
3854
0
    }
3855
3856
    /* -------------------------------------------------------------------- */
3857
    /*      Write the directory entry out to disk.                          */
3858
    /* -------------------------------------------------------------------- */
3859
0
    if (!SeekOK(tif, read_offset))
3860
0
    {
3861
0
        TIFFErrorExtR(tif, module, "%s: Seek error accessing TIFF directory",
3862
0
                      tif->tif_name);
3863
0
        return 0;
3864
0
    }
3865
3866
0
    if (!WriteOK(tif, direntry_raw, dirsize))
3867
0
    {
3868
0
        TIFFErrorExtR(tif, module, "%s: Can not write TIFF directory entry.",
3869
0
                      tif->tif_name);
3870
0
        return 0;
3871
0
    }
3872
3873
0
    return 1;
3874
0
}