Coverage Report

Created: 2025-06-13 06:18

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