Coverage Report

Created: 2025-12-31 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/frmts/gtiff/libtiff/tif_open.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1988-1997 Sam Leffler
3
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
4
 *
5
 * Permission to use, copy, modify, distribute, and sell this software and
6
 * its documentation for any purpose is hereby granted without fee, provided
7
 * that (i) the above copyright notices and this permission notice appear in
8
 * all copies of the software and related documentation, and (ii) the names of
9
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10
 * publicity relating to the software without the specific, prior written
11
 * permission of Sam Leffler and Silicon Graphics.
12
 *
13
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16
 *
17
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22
 * OF THIS SOFTWARE.
23
 */
24
25
/*
26
 * TIFF Library.
27
 */
28
29
#ifdef TIFF_DO_NOT_USE_NON_EXT_ALLOC_FUNCTIONS
30
#undef TIFF_DO_NOT_USE_NON_EXT_ALLOC_FUNCTIONS
31
#endif
32
33
#include "tiffiop.h"
34
#include <assert.h>
35
#include <limits.h>
36
37
/*
38
 * Dummy functions to fill the omitted client procedures.
39
 */
40
int _tiffDummyMapProc(thandle_t fd, void **pbase, toff_t *psize)
41
0
{
42
0
    (void)fd;
43
0
    (void)pbase;
44
0
    (void)psize;
45
0
    return (0);
46
0
}
47
48
void _tiffDummyUnmapProc(thandle_t fd, void *base, toff_t size)
49
0
{
50
0
    (void)fd;
51
0
    (void)base;
52
0
    (void)size;
53
0
}
54
55
int _TIFFgetMode(TIFFOpenOptions *opts, thandle_t clientdata, const char *mode,
56
                 const char *module)
57
0
{
58
0
    int m = -1;
59
60
0
    switch (mode[0])
61
0
    {
62
0
        case 'r':
63
0
            m = O_RDONLY;
64
0
            if (mode[1] == '+')
65
0
                m = O_RDWR;
66
0
            break;
67
0
        case 'w':
68
0
        case 'a':
69
0
            m = O_RDWR | O_CREAT;
70
0
            if (mode[0] == 'w')
71
0
                m |= O_TRUNC;
72
0
            break;
73
0
        default:
74
0
            _TIFFErrorEarly(opts, clientdata, module, "\"%s\": Bad mode", mode);
75
0
            break;
76
0
    }
77
0
    return (m);
78
0
}
79
80
TIFFOpenOptions *TIFFOpenOptionsAlloc(void)
81
0
{
82
0
    TIFFOpenOptions *opts =
83
0
        (TIFFOpenOptions *)_TIFFcalloc(1, sizeof(TIFFOpenOptions));
84
0
    return opts;
85
0
}
86
87
0
void TIFFOpenOptionsFree(TIFFOpenOptions *opts) { _TIFFfree(opts); }
88
89
/** Define a limit in bytes for a single memory allocation done by libtiff.
90
 *  If max_single_mem_alloc is set to 0, which is the default, no other limit
91
 *  that the underlying _TIFFmalloc() or
92
 *  TIFFOpenOptionsSetMaxCumulatedMemAlloc() will be applied.
93
 */
94
void TIFFOpenOptionsSetMaxSingleMemAlloc(TIFFOpenOptions *opts,
95
                                         tmsize_t max_single_mem_alloc)
96
0
{
97
0
    opts->max_single_mem_alloc = max_single_mem_alloc;
98
0
}
99
100
/** Define a limit in bytes for the cumulated memory allocations done by libtiff
101
 *  on a given TIFF handle.
102
 *  If max_cumulated_mem_alloc is set to 0, which is the default, no other limit
103
 *  that the underlying _TIFFmalloc() or
104
 *  TIFFOpenOptionsSetMaxSingleMemAlloc() will be applied.
105
 */
106
void TIFFOpenOptionsSetMaxCumulatedMemAlloc(TIFFOpenOptions *opts,
107
                                            tmsize_t max_cumulated_mem_alloc)
108
0
{
109
0
    opts->max_cumulated_mem_alloc = max_cumulated_mem_alloc;
110
0
}
111
112
/** Whether a warning should be emitted when encountering a unknown tag.
113
 * Default is FALSE since libtiff 4.7.1
114
 */
115
void TIFFOpenOptionsSetWarnAboutUnknownTags(TIFFOpenOptions *opts,
116
                                            int warn_about_unknown_tags)
117
0
{
118
0
    opts->warn_about_unknown_tags = warn_about_unknown_tags;
119
0
}
120
121
void TIFFOpenOptionsSetErrorHandlerExtR(TIFFOpenOptions *opts,
122
                                        TIFFErrorHandlerExtR handler,
123
                                        void *errorhandler_user_data)
124
0
{
125
0
    opts->errorhandler = handler;
126
0
    opts->errorhandler_user_data = errorhandler_user_data;
127
0
}
128
129
void TIFFOpenOptionsSetWarningHandlerExtR(TIFFOpenOptions *opts,
130
                                          TIFFErrorHandlerExtR handler,
131
                                          void *warnhandler_user_data)
132
0
{
133
0
    opts->warnhandler = handler;
134
0
    opts->warnhandler_user_data = warnhandler_user_data;
135
0
}
136
137
static void _TIFFEmitErrorAboveMaxSingleMemAlloc(TIFF *tif,
138
                                                 const char *pszFunction,
139
                                                 tmsize_t s)
140
0
{
141
0
    TIFFErrorExtR(tif, pszFunction,
142
0
                  "Memory allocation of %" PRIu64
143
0
                  " bytes is beyond the %" PRIu64
144
0
                  " byte limit defined in open options",
145
0
                  (uint64_t)s, (uint64_t)tif->tif_max_single_mem_alloc);
146
0
}
147
148
static void _TIFFEmitErrorAboveMaxCumulatedMemAlloc(TIFF *tif,
149
                                                    const char *pszFunction,
150
                                                    tmsize_t s)
151
0
{
152
0
    TIFFErrorExtR(tif, pszFunction,
153
0
                  "Cumulated memory allocation of %" PRIu64 " + %" PRIu64
154
0
                  " bytes is beyond the %" PRIu64
155
0
                  " cumulated byte limit defined in open options",
156
0
                  (uint64_t)tif->tif_cur_cumulated_mem_alloc, (uint64_t)s,
157
0
                  (uint64_t)tif->tif_max_cumulated_mem_alloc);
158
0
}
159
160
/* When allocating memory, we write at the beginning of the buffer it size.
161
 * This allows us to keep track of the total memory allocated when we
162
 * malloc/calloc/realloc and free. In theory we need just SIZEOF_SIZE_T bytes
163
 * for that, but on x86_64, allocations of more than 16 bytes are aligned on
164
 * 16 bytes. Hence using 2 * SIZEOF_SIZE_T.
165
 * It is critical that _TIFFmallocExt/_TIFFcallocExt/_TIFFreallocExt are
166
 * paired with _TIFFfreeExt.
167
 * CMakeLists.txt defines TIFF_DO_NOT_USE_NON_EXT_ALLOC_FUNCTIONS, which in
168
 * turn disables the definition of the non Ext version in tiffio.h
169
 */
170
0
#define LEADING_AREA_TO_STORE_ALLOC_SIZE (2 * SIZEOF_SIZE_T)
171
172
/** malloc() version that takes into account memory-specific open options */
173
void *_TIFFmallocExt(TIFF *tif, tmsize_t s)
174
0
{
175
0
    if (tif != NULL && tif->tif_max_single_mem_alloc > 0 &&
176
0
        s > tif->tif_max_single_mem_alloc)
177
0
    {
178
0
        _TIFFEmitErrorAboveMaxSingleMemAlloc(tif, "_TIFFmallocExt", s);
179
0
        return NULL;
180
0
    }
181
0
    if (tif != NULL && tif->tif_max_cumulated_mem_alloc > 0)
182
0
    {
183
0
        if (s > tif->tif_max_cumulated_mem_alloc -
184
0
                    tif->tif_cur_cumulated_mem_alloc ||
185
0
            s > TIFF_TMSIZE_T_MAX - LEADING_AREA_TO_STORE_ALLOC_SIZE)
186
0
        {
187
0
            _TIFFEmitErrorAboveMaxCumulatedMemAlloc(tif, "_TIFFmallocExt", s);
188
0
            return NULL;
189
0
        }
190
0
        void *ptr = _TIFFmalloc(LEADING_AREA_TO_STORE_ALLOC_SIZE + s);
191
0
        if (!ptr)
192
0
            return NULL;
193
0
        tif->tif_cur_cumulated_mem_alloc += s;
194
0
        memcpy(ptr, &s, sizeof(s));
195
0
        return (char *)ptr + LEADING_AREA_TO_STORE_ALLOC_SIZE;
196
0
    }
197
0
    return _TIFFmalloc(s);
198
0
}
199
200
/** calloc() version that takes into account memory-specific open options */
201
void *_TIFFcallocExt(TIFF *tif, tmsize_t nmemb, tmsize_t siz)
202
0
{
203
0
    if (nmemb <= 0 || siz <= 0 || nmemb > TIFF_TMSIZE_T_MAX / siz)
204
0
        return NULL;
205
0
    if (tif != NULL && tif->tif_max_single_mem_alloc > 0)
206
0
    {
207
0
        if (nmemb * siz > tif->tif_max_single_mem_alloc)
208
0
        {
209
0
            _TIFFEmitErrorAboveMaxSingleMemAlloc(tif, "_TIFFcallocExt",
210
0
                                                 nmemb * siz);
211
0
            return NULL;
212
0
        }
213
0
    }
214
0
    if (tif != NULL && tif->tif_max_cumulated_mem_alloc > 0)
215
0
    {
216
0
        const tmsize_t s = nmemb * siz;
217
0
        if (s > tif->tif_max_cumulated_mem_alloc -
218
0
                    tif->tif_cur_cumulated_mem_alloc ||
219
0
            s > TIFF_TMSIZE_T_MAX - LEADING_AREA_TO_STORE_ALLOC_SIZE)
220
0
        {
221
0
            _TIFFEmitErrorAboveMaxCumulatedMemAlloc(tif, "_TIFFcallocExt", s);
222
0
            return NULL;
223
0
        }
224
0
        void *ptr = _TIFFcalloc(LEADING_AREA_TO_STORE_ALLOC_SIZE + s, 1);
225
0
        if (!ptr)
226
0
            return NULL;
227
0
        tif->tif_cur_cumulated_mem_alloc += s;
228
0
        memcpy(ptr, &s, sizeof(s));
229
0
        return (char *)ptr + LEADING_AREA_TO_STORE_ALLOC_SIZE;
230
0
    }
231
0
    return _TIFFcalloc(nmemb, siz);
232
0
}
233
234
/** realloc() version that takes into account memory-specific open options */
235
void *_TIFFreallocExt(TIFF *tif, void *p, tmsize_t s)
236
0
{
237
0
    if (tif != NULL && tif->tif_max_single_mem_alloc > 0 &&
238
0
        s > tif->tif_max_single_mem_alloc)
239
0
    {
240
0
        _TIFFEmitErrorAboveMaxSingleMemAlloc(tif, "_TIFFreallocExt", s);
241
0
        return NULL;
242
0
    }
243
0
    if (tif != NULL && tif->tif_max_cumulated_mem_alloc > 0)
244
0
    {
245
0
        void *oldPtr = p;
246
0
        tmsize_t oldSize = 0;
247
0
        if (p)
248
0
        {
249
0
            oldPtr = (char *)p - LEADING_AREA_TO_STORE_ALLOC_SIZE;
250
0
            memcpy(&oldSize, oldPtr, sizeof(oldSize));
251
0
            assert(oldSize <= tif->tif_cur_cumulated_mem_alloc);
252
0
        }
253
0
        if (s > oldSize &&
254
0
            (s > tif->tif_max_cumulated_mem_alloc -
255
0
                     (tif->tif_cur_cumulated_mem_alloc - oldSize) ||
256
0
             s > TIFF_TMSIZE_T_MAX - LEADING_AREA_TO_STORE_ALLOC_SIZE))
257
0
        {
258
0
            _TIFFEmitErrorAboveMaxCumulatedMemAlloc(tif, "_TIFFreallocExt",
259
0
                                                    s - oldSize);
260
0
            return NULL;
261
0
        }
262
0
        void *newPtr =
263
0
            _TIFFrealloc(oldPtr, LEADING_AREA_TO_STORE_ALLOC_SIZE + s);
264
0
        if (newPtr == NULL)
265
0
            return NULL;
266
0
        tif->tif_cur_cumulated_mem_alloc -= oldSize;
267
0
        tif->tif_cur_cumulated_mem_alloc += s;
268
0
        memcpy(newPtr, &s, sizeof(s));
269
0
        return (char *)newPtr + LEADING_AREA_TO_STORE_ALLOC_SIZE;
270
0
    }
271
0
    return _TIFFrealloc(p, s);
272
0
}
273
274
/** free() version that takes into account memory-specific open options */
275
void _TIFFfreeExt(TIFF *tif, void *p)
276
0
{
277
0
    if (p != NULL && tif != NULL && tif->tif_max_cumulated_mem_alloc > 0)
278
0
    {
279
0
        void *oldPtr = (char *)p - LEADING_AREA_TO_STORE_ALLOC_SIZE;
280
0
        tmsize_t oldSize;
281
0
        memcpy(&oldSize, oldPtr, sizeof(oldSize));
282
0
        assert(oldSize <= tif->tif_cur_cumulated_mem_alloc);
283
0
        tif->tif_cur_cumulated_mem_alloc -= oldSize;
284
0
        p = oldPtr;
285
0
    }
286
0
    _TIFFfree(p);
287
0
}
288
289
TIFF *TIFFClientOpen(const char *name, const char *mode, thandle_t clientdata,
290
                     TIFFReadWriteProc readproc, TIFFReadWriteProc writeproc,
291
                     TIFFSeekProc seekproc, TIFFCloseProc closeproc,
292
                     TIFFSizeProc sizeproc, TIFFMapFileProc mapproc,
293
                     TIFFUnmapFileProc unmapproc)
294
0
{
295
0
    return TIFFClientOpenExt(name, mode, clientdata, readproc, writeproc,
296
0
                             seekproc, closeproc, sizeproc, mapproc, unmapproc,
297
0
                             NULL);
298
0
}
299
300
TIFF *TIFFClientOpenExt(const char *name, const char *mode,
301
                        thandle_t clientdata, TIFFReadWriteProc readproc,
302
                        TIFFReadWriteProc writeproc, TIFFSeekProc seekproc,
303
                        TIFFCloseProc closeproc, TIFFSizeProc sizeproc,
304
                        TIFFMapFileProc mapproc, TIFFUnmapFileProc unmapproc,
305
                        TIFFOpenOptions *opts)
306
0
{
307
0
    static const char module[] = "TIFFClientOpenExt";
308
0
    TIFF *tif;
309
0
    int m;
310
0
    const char *cp;
311
0
    tmsize_t size_to_alloc;
312
313
    /* The following are configuration checks. They should be redundant, but
314
     * should not compile to any actual code in an optimised release build
315
     * anyway. If any of them fail, (makefile-based or other) configuration is
316
     * not correct */
317
0
    assert(sizeof(uint8_t) == 1);
318
0
    assert(sizeof(int8_t) == 1);
319
0
    assert(sizeof(uint16_t) == 2);
320
0
    assert(sizeof(int16_t) == 2);
321
0
    assert(sizeof(uint32_t) == 4);
322
0
    assert(sizeof(int32_t) == 4);
323
0
    assert(sizeof(uint64_t) == 8);
324
0
    assert(sizeof(int64_t) == 8);
325
0
    {
326
0
        union
327
0
        {
328
0
            uint8_t a8[2];
329
0
            uint16_t a16;
330
0
        } n;
331
0
        n.a8[0] = 1;
332
0
        n.a8[1] = 0;
333
0
        (void)n;
334
#ifdef WORDS_BIGENDIAN
335
        assert(n.a16 == 256);
336
#else
337
0
        assert(n.a16 == 1);
338
0
#endif
339
0
    }
340
341
0
    m = _TIFFgetMode(opts, clientdata, mode, module);
342
0
    if (m == -1)
343
0
        goto bad2;
344
0
    size_to_alloc = (tmsize_t)(sizeof(TIFF) + strlen(name) + 1);
345
0
    if (opts && opts->max_single_mem_alloc > 0 &&
346
0
        size_to_alloc > opts->max_single_mem_alloc)
347
0
    {
348
0
        _TIFFErrorEarly(opts, clientdata, module,
349
0
                        "%s: Memory allocation of %" PRIu64
350
0
                        " bytes is beyond the %" PRIu64
351
0
                        " byte limit defined in open options",
352
0
                        name, (uint64_t)size_to_alloc,
353
0
                        (uint64_t)opts->max_single_mem_alloc);
354
0
        goto bad2;
355
0
    }
356
0
    if (opts && opts->max_cumulated_mem_alloc > 0 &&
357
0
        size_to_alloc > opts->max_cumulated_mem_alloc)
358
0
    {
359
0
        _TIFFErrorEarly(opts, clientdata, module,
360
0
                        "%s: Memory allocation of %" PRIu64
361
0
                        " bytes is beyond the %" PRIu64
362
0
                        " cumulated byte limit defined in open options",
363
0
                        name, (uint64_t)size_to_alloc,
364
0
                        (uint64_t)opts->max_cumulated_mem_alloc);
365
0
        goto bad2;
366
0
    }
367
0
    tif = (TIFF *)_TIFFmallocExt(NULL, size_to_alloc);
368
0
    if (tif == NULL)
369
0
    {
370
0
        _TIFFErrorEarly(opts, clientdata, module,
371
0
                        "%s: Out of memory (TIFF structure)", name);
372
0
        goto bad2;
373
0
    }
374
0
    _TIFFmemset(tif, 0, sizeof(*tif));
375
0
    tif->tif_name = (char *)tif + sizeof(TIFF);
376
0
    strcpy(tif->tif_name, name);
377
0
    tif->tif_mode = m & ~(O_CREAT | O_TRUNC);
378
0
    tif->tif_curdir = TIFF_NON_EXISTENT_DIR_NUMBER; /* non-existent directory */
379
0
    tif->tif_curdircount = TIFF_NON_EXISTENT_DIR_NUMBER;
380
0
    tif->tif_curoff = 0;
381
0
    tif->tif_curstrip = (uint32_t)-1; /* invalid strip */
382
0
    tif->tif_row = (uint32_t)-1;      /* read/write pre-increment */
383
0
    tif->tif_clientdata = clientdata;
384
0
    tif->tif_readproc = readproc;
385
0
    tif->tif_writeproc = writeproc;
386
0
    tif->tif_seekproc = seekproc;
387
0
    tif->tif_closeproc = closeproc;
388
0
    tif->tif_sizeproc = sizeproc;
389
0
    tif->tif_mapproc = mapproc ? mapproc : _tiffDummyMapProc;
390
0
    tif->tif_unmapproc = unmapproc ? unmapproc : _tiffDummyUnmapProc;
391
0
    if (opts)
392
0
    {
393
0
        tif->tif_errorhandler = opts->errorhandler;
394
0
        tif->tif_errorhandler_user_data = opts->errorhandler_user_data;
395
0
        tif->tif_warnhandler = opts->warnhandler;
396
0
        tif->tif_warnhandler_user_data = opts->warnhandler_user_data;
397
0
        tif->tif_max_single_mem_alloc = opts->max_single_mem_alloc;
398
0
        tif->tif_max_cumulated_mem_alloc = opts->max_cumulated_mem_alloc;
399
0
        tif->tif_warn_about_unknown_tags = opts->warn_about_unknown_tags;
400
0
    }
401
402
0
    if (!readproc || !writeproc || !seekproc || !closeproc || !sizeproc)
403
0
    {
404
0
        TIFFErrorExtR(tif, module,
405
0
                      "One of the client procedures is NULL pointer.");
406
0
        _TIFFfreeExt(NULL, tif);
407
0
        goto bad2;
408
0
    }
409
410
0
    _TIFFSetDefaultCompressionState(tif); /* setup default state */
411
    /*
412
     * Default is to return data MSB2LSB and enable the
413
     * use of memory-mapped files and strip chopping when
414
     * a file is opened read-only.
415
     */
416
0
    tif->tif_flags = FILLORDER_MSB2LSB;
417
0
    if (m == O_RDONLY)
418
0
        tif->tif_flags |= TIFF_MAPPED;
419
420
0
#ifdef STRIPCHOP_DEFAULT
421
0
    if (m == O_RDONLY || m == O_RDWR)
422
0
        tif->tif_flags |= STRIPCHOP_DEFAULT;
423
0
#endif
424
425
    /*
426
     * Process library-specific flags in the open mode string.
427
     * The following flags may be used to control intrinsic library
428
     * behavior that may or may not be desirable (usually for
429
     * compatibility with some application that claims to support
430
     * TIFF but only supports some brain dead idea of what the
431
     * vendor thinks TIFF is):
432
     *
433
     * 'l' use little-endian byte order for creating a file
434
     * 'b' use big-endian byte order for creating a file
435
     * 'L' read/write information using LSB2MSB bit order
436
     * 'B' read/write information using MSB2LSB bit order
437
     * 'H' read/write information using host bit order
438
     * 'M' enable use of memory-mapped files when supported
439
     * 'm' disable use of memory-mapped files
440
     * 'C' enable strip chopping support when reading
441
     * 'c' disable strip chopping support
442
     * 'h' read TIFF header only, do not load the first IFD
443
     * '4' ClassicTIFF for creating a file (default)
444
     * '8' BigTIFF for creating a file
445
     * 'D' enable use of deferred strip/tile offset/bytecount array loading.
446
     * 'O' on-demand loading of values instead of whole array loading (implies
447
     * D)
448
     *
449
     * The use of the 'l' and 'b' flags is strongly discouraged.
450
     * These flags are provided solely because numerous vendors,
451
     * typically on the PC, do not correctly support TIFF; they
452
     * only support the Intel little-endian byte order.  This
453
     * support is not configured by default because it supports
454
     * the violation of the TIFF spec that says that readers *MUST*
455
     * support both byte orders.  It is strongly recommended that
456
     * you not use this feature except to deal with busted apps
457
     * that write invalid TIFF.  And even in those cases you should
458
     * bang on the vendors to fix their software.
459
     *
460
     * The 'L', 'B', and 'H' flags are intended for applications
461
     * that can optimize operations on data by using a particular
462
     * bit order.  By default the library returns data in MSB2LSB
463
     * bit order for compatibility with older versions of this
464
     * library.  Returning data in the bit order of the native CPU
465
     * makes the most sense but also requires applications to check
466
     * the value of the FillOrder tag; something they probably do
467
     * not do right now.
468
     *
469
     * The 'M' and 'm' flags are provided because some virtual memory
470
     * systems exhibit poor behavior when large images are mapped.
471
     * These options permit clients to control the use of memory-mapped
472
     * files on a per-file basis.
473
     *
474
     * The 'C' and 'c' flags are provided because the library support
475
     * for chopping up large strips into multiple smaller strips is not
476
     * application-transparent and as such can cause problems.  The 'c'
477
     * option permits applications that only want to look at the tags,
478
     * for example, to get the unadulterated TIFF tag information.
479
     */
480
0
    for (cp = mode; *cp; cp++)
481
0
        switch (*cp)
482
0
        {
483
0
            case 'b':
484
0
#ifndef WORDS_BIGENDIAN
485
0
                if (m & O_CREAT)
486
0
                    tif->tif_flags |= TIFF_SWAB;
487
0
#endif
488
0
                break;
489
0
            case 'l':
490
#ifdef WORDS_BIGENDIAN
491
                if ((m & O_CREAT))
492
                    tif->tif_flags |= TIFF_SWAB;
493
#endif
494
0
                break;
495
0
            case 'B':
496
0
                tif->tif_flags =
497
0
                    (tif->tif_flags & ~TIFF_FILLORDER) | FILLORDER_MSB2LSB;
498
0
                break;
499
0
            case 'L':
500
0
                tif->tif_flags =
501
0
                    (tif->tif_flags & ~TIFF_FILLORDER) | FILLORDER_LSB2MSB;
502
0
                break;
503
0
            case 'H':
504
0
                TIFFWarningExtR(tif, name,
505
0
                                "H(ost) mode is deprecated. Since "
506
0
                                "libtiff 4.5.1, it is an alias of 'B' / "
507
0
                                "FILLORDER_MSB2LSB.");
508
0
                tif->tif_flags =
509
0
                    (tif->tif_flags & ~TIFF_FILLORDER) | FILLORDER_MSB2LSB;
510
0
                break;
511
0
            case 'M':
512
0
                if (m == O_RDONLY)
513
0
                    tif->tif_flags |= TIFF_MAPPED;
514
0
                break;
515
0
            case 'm':
516
0
                if (m == O_RDONLY)
517
0
                    tif->tif_flags &= ~TIFF_MAPPED;
518
0
                break;
519
0
            case 'C':
520
0
                if (m == O_RDONLY)
521
0
                    tif->tif_flags |= TIFF_STRIPCHOP;
522
0
                break;
523
0
            case 'c':
524
0
                if (m == O_RDONLY)
525
0
                    tif->tif_flags &= ~TIFF_STRIPCHOP;
526
0
                break;
527
0
            case 'h':
528
0
                tif->tif_flags |= TIFF_HEADERONLY;
529
0
                break;
530
0
            case '8':
531
0
                if (m & O_CREAT)
532
0
                    tif->tif_flags |= TIFF_BIGTIFF;
533
0
                break;
534
0
            case 'D':
535
0
                tif->tif_flags |= TIFF_DEFERSTRILELOAD;
536
0
                break;
537
0
            case 'O':
538
0
                if (m == O_RDONLY)
539
0
                    tif->tif_flags |=
540
0
                        (TIFF_LAZYSTRILELOAD_ASKED | TIFF_DEFERSTRILELOAD);
541
0
                break;
542
0
        }
543
544
#ifdef DEFER_STRILE_LOAD
545
    /* Compatibility with old DEFER_STRILE_LOAD compilation flag */
546
    /* Probably unneeded, since to the best of my knowledge (E. Rouault) */
547
    /* GDAL was the only user of this, and will now use the new 'D' flag */
548
    tif->tif_flags |= TIFF_DEFERSTRILELOAD;
549
#endif
550
551
    /*
552
     * Read in TIFF header.
553
     */
554
0
    if ((m & O_TRUNC) ||
555
0
        !ReadOK(tif, &tif->tif_header, sizeof(TIFFHeaderClassic)))
556
0
    {
557
0
        if (tif->tif_mode == O_RDONLY)
558
0
        {
559
0
            TIFFErrorExtR(tif, name, "Cannot read TIFF header");
560
0
            goto bad;
561
0
        }
562
        /*
563
         * Setup header and write.
564
         */
565
#ifdef WORDS_BIGENDIAN
566
        tif->tif_header.common.tiff_magic =
567
            (tif->tif_flags & TIFF_SWAB) ? TIFF_LITTLEENDIAN : TIFF_BIGENDIAN;
568
#else
569
0
        tif->tif_header.common.tiff_magic =
570
0
            (tif->tif_flags & TIFF_SWAB) ? TIFF_BIGENDIAN : TIFF_LITTLEENDIAN;
571
0
#endif
572
0
        TIFFHeaderUnion tif_header_swapped;
573
0
        if (!(tif->tif_flags & TIFF_BIGTIFF))
574
0
        {
575
0
            tif->tif_header.common.tiff_version = TIFF_VERSION_CLASSIC;
576
0
            tif->tif_header.classic.tiff_diroff = 0;
577
0
            tif->tif_header_size = sizeof(TIFFHeaderClassic);
578
            /* Swapped copy for writing */
579
0
            _TIFFmemcpy(&tif_header_swapped, &tif->tif_header,
580
0
                        sizeof(TIFFHeaderUnion));
581
0
            if (tif->tif_flags & TIFF_SWAB)
582
0
                TIFFSwabShort(&tif_header_swapped.common.tiff_version);
583
0
        }
584
0
        else
585
0
        {
586
0
            tif->tif_header.common.tiff_version = TIFF_VERSION_BIG;
587
0
            tif->tif_header.big.tiff_offsetsize = 8;
588
0
            tif->tif_header.big.tiff_unused = 0;
589
0
            tif->tif_header.big.tiff_diroff = 0;
590
0
            tif->tif_header_size = sizeof(TIFFHeaderBig);
591
            /* Swapped copy for writing */
592
0
            _TIFFmemcpy(&tif_header_swapped, &tif->tif_header,
593
0
                        sizeof(TIFFHeaderUnion));
594
0
            if (tif->tif_flags & TIFF_SWAB)
595
0
            {
596
0
                TIFFSwabShort(&tif_header_swapped.common.tiff_version);
597
0
                TIFFSwabShort(&tif_header_swapped.big.tiff_offsetsize);
598
0
            }
599
0
        }
600
        /*
601
         * The doc for "fopen" for some STD_C_LIBs says that if you
602
         * open a file for modify ("+"), then you must fseek (or
603
         * fflush?) between any freads and fwrites.  This is not
604
         * necessary on most systems, but has been shown to be needed
605
         * on Solaris.
606
         */
607
0
        TIFFSeekFile(tif, 0, SEEK_SET);
608
0
        if (!WriteOK(tif, &tif_header_swapped,
609
0
                     (tmsize_t)(tif->tif_header_size)))
610
0
        {
611
0
            TIFFErrorExtR(tif, name, "Error writing TIFF header");
612
0
            goto bad;
613
0
        }
614
        /*
615
         * Setup default directory.
616
         */
617
0
        if (!TIFFDefaultDirectory(tif))
618
0
            goto bad;
619
0
        tif->tif_diroff = 0;
620
0
        tif->tif_lastdiroff = 0;
621
0
        tif->tif_setdirectory_force_absolute = FALSE;
622
        /* tif_curdircount = 0 means 'empty file opened for writing, but no IFD
623
         * written yet' */
624
0
        tif->tif_curdircount = 0;
625
0
        return (tif);
626
0
    }
627
628
    /*
629
     * Setup the byte order handling according to the opened file for reading.
630
     */
631
0
    if (tif->tif_header.common.tiff_magic != TIFF_BIGENDIAN &&
632
0
        tif->tif_header.common.tiff_magic != TIFF_LITTLEENDIAN
633
#if MDI_SUPPORT
634
        &&
635
#if HOST_BIGENDIAN
636
        tif->tif_header.common.tiff_magic != MDI_BIGENDIAN
637
#else
638
        tif->tif_header.common.tiff_magic != MDI_LITTLEENDIAN
639
#endif
640
    )
641
    {
642
        TIFFErrorExtR(tif, name,
643
                      "Not a TIFF or MDI file, bad magic number %" PRIu16
644
                      " (0x%" PRIx16 ")",
645
#else
646
0
    )
647
0
    {
648
0
        TIFFErrorExtR(tif, name,
649
0
                      "Not a TIFF file, bad magic number %" PRIu16
650
0
                      " (0x%" PRIx16 ")",
651
0
#endif
652
0
                      tif->tif_header.common.tiff_magic,
653
0
                      tif->tif_header.common.tiff_magic);
654
0
        goto bad;
655
0
    }
656
0
    if (tif->tif_header.common.tiff_magic == TIFF_BIGENDIAN)
657
0
    {
658
0
#ifndef WORDS_BIGENDIAN
659
0
        tif->tif_flags |= TIFF_SWAB;
660
0
#endif
661
0
    }
662
0
    else
663
0
    {
664
#ifdef WORDS_BIGENDIAN
665
        tif->tif_flags |= TIFF_SWAB;
666
#endif
667
0
    }
668
0
    if (tif->tif_flags & TIFF_SWAB)
669
0
        TIFFSwabShort(&tif->tif_header.common.tiff_version);
670
0
    if ((tif->tif_header.common.tiff_version != TIFF_VERSION_CLASSIC) &&
671
0
        (tif->tif_header.common.tiff_version != TIFF_VERSION_BIG))
672
0
    {
673
0
        TIFFErrorExtR(tif, name,
674
0
                      "Not a TIFF file, bad version number %" PRIu16
675
0
                      " (0x%" PRIx16 ")",
676
0
                      tif->tif_header.common.tiff_version,
677
0
                      tif->tif_header.common.tiff_version);
678
0
        goto bad;
679
0
    }
680
0
    if (tif->tif_header.common.tiff_version == TIFF_VERSION_CLASSIC)
681
0
    {
682
0
        if (tif->tif_flags & TIFF_SWAB)
683
0
            TIFFSwabLong(&tif->tif_header.classic.tiff_diroff);
684
0
        tif->tif_header_size = sizeof(TIFFHeaderClassic);
685
0
    }
686
0
    else
687
0
    {
688
0
        if (!ReadOK(tif,
689
0
                    ((uint8_t *)(&tif->tif_header) + sizeof(TIFFHeaderClassic)),
690
0
                    (sizeof(TIFFHeaderBig) - sizeof(TIFFHeaderClassic))))
691
0
        {
692
0
            TIFFErrorExtR(tif, name, "Cannot read TIFF header");
693
0
            goto bad;
694
0
        }
695
0
        if (tif->tif_flags & TIFF_SWAB)
696
0
        {
697
0
            TIFFSwabShort(&tif->tif_header.big.tiff_offsetsize);
698
0
            TIFFSwabLong8(&tif->tif_header.big.tiff_diroff);
699
0
        }
700
0
        if (tif->tif_header.big.tiff_offsetsize != 8)
701
0
        {
702
0
            TIFFErrorExtR(tif, name,
703
0
                          "Not a TIFF file, bad BigTIFF offsetsize %" PRIu16
704
0
                          " (0x%" PRIx16 ")",
705
0
                          tif->tif_header.big.tiff_offsetsize,
706
0
                          tif->tif_header.big.tiff_offsetsize);
707
0
            goto bad;
708
0
        }
709
0
        if (tif->tif_header.big.tiff_unused != 0)
710
0
        {
711
0
            TIFFErrorExtR(tif, name,
712
0
                          "Not a TIFF file, bad BigTIFF unused %" PRIu16
713
0
                          " (0x%" PRIx16 ")",
714
0
                          tif->tif_header.big.tiff_unused,
715
0
                          tif->tif_header.big.tiff_unused);
716
0
            goto bad;
717
0
        }
718
0
        tif->tif_header_size = sizeof(TIFFHeaderBig);
719
0
        tif->tif_flags |= TIFF_BIGTIFF;
720
0
    }
721
0
    tif->tif_flags |= TIFF_MYBUFFER;
722
0
    tif->tif_rawcp = tif->tif_rawdata = 0;
723
0
    tif->tif_rawdatasize = 0;
724
0
    tif->tif_rawdataoff = 0;
725
0
    tif->tif_rawdataloaded = 0;
726
727
0
    switch (mode[0])
728
0
    {
729
0
        case 'r':
730
0
            if (!(tif->tif_flags & TIFF_BIGTIFF))
731
0
                tif->tif_nextdiroff = tif->tif_header.classic.tiff_diroff;
732
0
            else
733
0
                tif->tif_nextdiroff = tif->tif_header.big.tiff_diroff;
734
            /*
735
             * Try to use a memory-mapped file if the client
736
             * has not explicitly suppressed usage with the
737
             * 'm' flag in the open mode (see above).
738
             */
739
0
            if (tif->tif_flags & TIFF_MAPPED)
740
0
            {
741
0
                toff_t n;
742
0
                if (TIFFMapFileContents(tif, (void **)(&tif->tif_base), &n))
743
0
                {
744
0
                    tif->tif_size = (tmsize_t)n;
745
0
                    assert((toff_t)tif->tif_size == n);
746
0
                }
747
0
                else
748
0
                    tif->tif_flags &= ~TIFF_MAPPED;
749
0
            }
750
            /*
751
             * Sometimes we do not want to read the first directory (for
752
             * example, it may be broken) and want to proceed to other
753
             * directories. I this case we use the TIFF_HEADERONLY flag to open
754
             * file and return immediately after reading TIFF header.
755
             * However, the pointer to TIFFSetField() and TIFFGetField()
756
             * (i.e. tif->tif_tagmethods.vsetfield and
757
             * tif->tif_tagmethods.vgetfield) need to be initialized, which is
758
             * done in TIFFDefaultDirectory().
759
             */
760
0
            if (tif->tif_flags & TIFF_HEADERONLY)
761
0
            {
762
0
                if (!TIFFDefaultDirectory(tif))
763
0
                    goto bad;
764
0
                return (tif);
765
0
            }
766
767
            /*
768
             * Setup initial directory.
769
             */
770
0
            if (TIFFReadDirectory(tif))
771
0
            {
772
0
                return (tif);
773
0
            }
774
0
            break;
775
0
        case 'a':
776
            /*
777
             * New directories are automatically append
778
             * to the end of the directory chain when they
779
             * are written out (see TIFFWriteDirectory).
780
             */
781
0
            if (!TIFFDefaultDirectory(tif))
782
0
                goto bad;
783
0
            return (tif);
784
0
    }
785
0
bad:
786
0
    tif->tif_mode = O_RDONLY; /* XXX avoid flush */
787
0
    TIFFCleanup(tif);
788
0
bad2:
789
0
    return ((TIFF *)0);
790
0
}
791
792
/*
793
 * Query functions to access private data.
794
 */
795
796
/*
797
 * Return open file's name.
798
 */
799
0
const char *TIFFFileName(TIFF *tif) { return (tif->tif_name); }
800
801
/*
802
 * Set the file name.
803
 */
804
const char *TIFFSetFileName(TIFF *tif, const char *name)
805
0
{
806
0
    const char *old_name = tif->tif_name;
807
0
    tif->tif_name = (char *)name;
808
0
    return (old_name);
809
0
}
810
811
/*
812
 * Return open file's I/O descriptor.
813
 */
814
0
int TIFFFileno(TIFF *tif) { return (tif->tif_fd); }
815
816
/*
817
 * Set open file's I/O descriptor, and return previous value.
818
 */
819
int TIFFSetFileno(TIFF *tif, int fd)
820
0
{
821
0
    int old_fd = tif->tif_fd;
822
0
    tif->tif_fd = fd;
823
0
    return old_fd;
824
0
}
825
826
/*
827
 * Return open file's clientdata.
828
 */
829
0
thandle_t TIFFClientdata(TIFF *tif) { return (tif->tif_clientdata); }
830
831
/*
832
 * Set open file's clientdata, and return previous value.
833
 */
834
thandle_t TIFFSetClientdata(TIFF *tif, thandle_t newvalue)
835
0
{
836
0
    thandle_t m = tif->tif_clientdata;
837
0
    tif->tif_clientdata = newvalue;
838
0
    return m;
839
0
}
840
841
/*
842
 * Return read/write mode.
843
 */
844
0
int TIFFGetMode(TIFF *tif) { return (tif->tif_mode); }
845
846
/*
847
 * Return read/write mode.
848
 */
849
int TIFFSetMode(TIFF *tif, int mode)
850
0
{
851
0
    int old_mode = tif->tif_mode;
852
0
    tif->tif_mode = mode;
853
0
    return (old_mode);
854
0
}
855
856
/*
857
 * Return nonzero if file is organized in
858
 * tiles; zero if organized as strips.
859
 */
860
0
int TIFFIsTiled(TIFF *tif) { return (isTiled(tif)); }
861
862
/*
863
 * Return current row being read/written.
864
 */
865
0
uint32_t TIFFCurrentRow(TIFF *tif) { return (tif->tif_row); }
866
867
/*
868
 * Return index of the current directory.
869
 */
870
0
tdir_t TIFFCurrentDirectory(TIFF *tif) { return (tif->tif_curdir); }
871
872
/*
873
 * Return current strip.
874
 */
875
0
uint32_t TIFFCurrentStrip(TIFF *tif) { return (tif->tif_curstrip); }
876
877
/*
878
 * Return current tile.
879
 */
880
0
uint32_t TIFFCurrentTile(TIFF *tif) { return (tif->tif_curtile); }
881
882
/*
883
 * Return nonzero if the file has byte-swapped data.
884
 */
885
0
int TIFFIsByteSwapped(TIFF *tif) { return ((tif->tif_flags & TIFF_SWAB) != 0); }
886
887
/*
888
 * Return nonzero if the data is returned up-sampled.
889
 */
890
0
int TIFFIsUpSampled(TIFF *tif) { return (isUpSampled(tif)); }
891
892
/*
893
 * Return nonzero if the data is returned in MSB-to-LSB bit order.
894
 */
895
0
int TIFFIsMSB2LSB(TIFF *tif) { return (isFillOrder(tif, FILLORDER_MSB2LSB)); }
896
897
/*
898
 * Return nonzero if given file was written in big-endian order.
899
 */
900
int TIFFIsBigEndian(TIFF *tif)
901
0
{
902
0
    return (tif->tif_header.common.tiff_magic == TIFF_BIGENDIAN);
903
0
}
904
905
/*
906
 * Return nonzero if given file is BigTIFF style.
907
 */
908
0
int TIFFIsBigTIFF(TIFF *tif) { return ((tif->tif_flags & TIFF_BIGTIFF) != 0); }
909
910
/*
911
 * Return pointer to file read method.
912
 */
913
0
TIFFReadWriteProc TIFFGetReadProc(TIFF *tif) { return (tif->tif_readproc); }
914
915
/*
916
 * Return pointer to file write method.
917
 */
918
0
TIFFReadWriteProc TIFFGetWriteProc(TIFF *tif) { return (tif->tif_writeproc); }
919
920
/*
921
 * Return pointer to file seek method.
922
 */
923
0
TIFFSeekProc TIFFGetSeekProc(TIFF *tif) { return (tif->tif_seekproc); }
924
925
/*
926
 * Return pointer to file close method.
927
 */
928
0
TIFFCloseProc TIFFGetCloseProc(TIFF *tif) { return (tif->tif_closeproc); }
929
930
/*
931
 * Return pointer to file size requesting method.
932
 */
933
0
TIFFSizeProc TIFFGetSizeProc(TIFF *tif) { return (tif->tif_sizeproc); }
934
935
/*
936
 * Return pointer to memory mapping method.
937
 */
938
0
TIFFMapFileProc TIFFGetMapFileProc(TIFF *tif) { return (tif->tif_mapproc); }
939
940
/*
941
 * Return pointer to memory unmapping method.
942
 */
943
TIFFUnmapFileProc TIFFGetUnmapFileProc(TIFF *tif)
944
0
{
945
0
    return (tif->tif_unmapproc);
946
0
}