LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_dirwrite.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 879 1608 54.7 %
Date: 2026-04-22 14:22:58 Functions: 40 72 55.6 %

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

Generated by: LCOV version 1.14