LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_write.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 264 507 52.1 %
Date: 2026-12-05 15:13:29 Functions: 12 14 85.7 %

          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             :  * Scanline-oriented Write Support
      29             :  */
      30             : /**
      31             :  * @file tif_write.c
      32             :  * @brief Transfer image bytes through raw buffers and codec methods.
      33             :  */
      34             : 
      35             : #include "tiffiop.h"
      36             : 
      37             : #include <assert.h>
      38             : #include <stdio.h>
      39             : 
      40             : /**
      41             :  * @brief Local repeat of the NOSTRIP sentinel defined in tif_dir.h.
      42             :  * @ingroup libtiff_private_image_transfers
      43             :  */
      44             : #define NOSTRIP ((uint32_t)(-1)) /* undefined state */
      45             : 
      46             : /**
      47             :  * @brief Reuse write preparation or check strip organisation.
      48             :  * @ingroup libtiff_private_image_transfers
      49             :  *
      50             :  * Short-circuits when TIFF_BEENWRITING is already set, so the organisation
      51             :  * is not checked again; otherwise calls TIFFWriteCheck() with tiles = 0,
      52             :  * which can allocate and change handle state. tif is evaluated up to twice.
      53             :  *
      54             :  * @param[in,out] tif Non-NULL live handle with matching current geometry
      55             :  * and codec methods; serialise access externally.
      56             :  * @param[in] module Diagnostic context evaluated only when preparation
      57             :  * runs.
      58             :  * @return Nonzero for prior been-writing state or successful preparation.
      59             :  */
      60             : #define WRITECHECKSTRIPS(tif, module)                                          \
      61             :     (((tif)->tif_flags & TIFF_BEENWRITING) || TIFFWriteCheck((tif), 0, module))
      62             : /**
      63             :  * @brief Reuse write preparation or check tile organisation.
      64             :  * @ingroup libtiff_private_image_transfers
      65             :  *
      66             :  * Short-circuits when TIFF_BEENWRITING is already set, so the organisation
      67             :  * is not checked again; otherwise calls TIFFWriteCheck() with tiles = 1,
      68             :  * which can allocate and change handle state. tif is evaluated up to twice.
      69             :  *
      70             :  * @param[in,out] tif Non-NULL live handle with matching current geometry
      71             :  * and codec methods; serialise access externally.
      72             :  * @param[in] module Diagnostic context evaluated only when preparation
      73             :  * runs.
      74             :  * @return Nonzero for prior been-writing state or successful preparation.
      75             :  */
      76             : #define WRITECHECKTILES(tif, module)                                           \
      77             :     (((tif)->tif_flags & TIFF_BEENWRITING) || TIFFWriteCheck((tif), 1, module))
      78             : /**
      79             :  * @brief Reuse an output buffer or allocate default encoding storage.
      80             :  * @ingroup libtiff_private_image_transfers
      81             :  *
      82             :  * Short-circuits when TIFF_BUFFERSETUP is set and tif_rawdata is non-NULL;
      83             :  * otherwise calls TIFFWriteBufferSetup() with a NULL buffer and default
      84             :  * size, which allocates a handle-owned buffer. tif is evaluated up to three
      85             :  * times.
      86             :  *
      87             :  * @param[in,out] tif Non-NULL live handle with matching current geometry
      88             :  * and codec methods; serialise access externally.
      89             :  * @return Nonzero for usable prior storage or successful setup.
      90             :  */
      91             : #define BUFFERCHECK(tif)                                                       \
      92             :     ((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) ||            \
      93             :      TIFFWriteBufferSetup((tif), NULL, (tmsize_t)(-1)))
      94             : 
      95             : static int TIFFGrowStrips(TIFF *tif, uint32_t delta, const char *module);
      96             : static int TIFFAppendToStrip(TIFF *tif, uint32_t strip, uint8_t *data,
      97             :                              tmsize_t cc);
      98             : 
      99       57252 : int TIFFWriteScanline(TIFF *tif, void *buf, uint32_t row, uint16_t sample)
     100             : {
     101             :     static const char module[] = "TIFFWriteScanline";
     102             :     TIFFDirectory *td;
     103       57252 :     int status, imagegrew = 0;
     104             :     uint32_t strip;
     105             : 
     106       57252 :     if (!WRITECHECKSTRIPS(tif, module))
     107           0 :         return (-1);
     108             :     /*
     109             :      * Handle delayed allocation of data buffer.  This
     110             :      * permits it to be sized more intelligently (using
     111             :      * directory information).
     112             :      */
     113       57252 :     if (!BUFFERCHECK(tif))
     114           0 :         return (-1);
     115       57252 :     tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/
     116             : 
     117       57252 :     td = &tif->tif_dir;
     118             :     /*
     119             :      * Extend image length if needed
     120             :      * (but only for PlanarConfig=1).
     121             :      */
     122       57252 :     if (row >= td->td_imagelength)
     123             :     { /* extend image */
     124           0 :         if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
     125             :         {
     126           0 :             TIFFErrorExtR(
     127             :                 tif, module,
     128             :                 "Can not change \"ImageLength\" when using separate planes");
     129           0 :             return (-1);
     130             :         }
     131           0 :         td->td_imagelength = row + 1;
     132           0 :         imagegrew = 1;
     133             :     }
     134             :     /*
     135             :      * Calculate strip and check for crossings.
     136             :      */
     137       57252 :     if (td->td_rowsperstrip == 0)
     138             :     {
     139           0 :         TIFFErrorExtR(tif, module,
     140             :                       "Cannot compute strip: RowsPerStrip is zero");
     141           0 :         return (-1);
     142             :     }
     143       57252 :     if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
     144             :     {
     145             :         uint64_t sample_offset;
     146             :         uint64_t strip64;
     147       15000 :         if (sample >= td->td_samplesperpixel)
     148             :         {
     149           0 :             TIFFErrorExtR(tif, module, "%lu: Sample out of range, max %lu",
     150             :                           (unsigned long)sample,
     151           0 :                           (unsigned long)td->td_samplesperpixel);
     152           0 :             return (-1);
     153             :         }
     154             :         sample_offset =
     155       15000 :             _TIFFMultiply64(tif, sample, td->td_stripsperimage, module);
     156       15000 :         if (sample_offset == 0 && sample != 0 && td->td_stripsperimage != 0)
     157           0 :             return (-1);
     158             :         strip64 =
     159       15000 :             _TIFFAdd64(tif, sample_offset, row / td->td_rowsperstrip, module);
     160       15000 :         if (strip64 == 0 &&
     161        5000 :             (sample_offset != 0 || (row / td->td_rowsperstrip) != 0))
     162           0 :             return (-1);
     163       15000 :         strip = _TIFFCastUInt64ToUInt32(tif, strip64, module);
     164       15000 :         if (strip == 0 && strip64 != 0)
     165           0 :             return (-1);
     166             :     }
     167             :     else
     168       42252 :         strip = row / td->td_rowsperstrip;
     169             :     /*
     170             :      * Check strip array to make sure there's space. We don't support
     171             :      * dynamically growing files that have data organized in separate
     172             :      * bitplanes because it's too painful.  In that case we require that
     173             :      * the imagelength be set properly before the first write (so that the
     174             :      * strips array will be fully allocated above).
     175             :      */
     176       57252 :     if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module))
     177           0 :         return (-1);
     178       57252 :     if (strip != tif->tif_dir.td_curstrip)
     179             :     {
     180             :         /*
     181             :          * Changing strips -- flush any data present.
     182             :          */
     183          11 :         if (!TIFFFlushData(tif))
     184           0 :             return (-1);
     185          11 :         tif->tif_dir.td_curstrip = strip;
     186             :         /*
     187             :          * Watch out for a growing image.  The value of strips/image
     188             :          * will initially be 1 (since it can't be deduced until the
     189             :          * imagelength is known).
     190             :          */
     191          11 :         if (strip >= td->td_stripsperimage && imagegrew)
     192           0 :             td->td_stripsperimage =
     193           0 :                 TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
     194          11 :         if (td->td_stripsperimage == 0)
     195             :         {
     196           0 :             TIFFErrorExtR(tif, module, "Zero strips per image");
     197           0 :             return (-1);
     198             :         }
     199          11 :         if (TIFFSafeModMul32(tif, module, strip, td->td_stripsperimage,
     200             :                              td->td_rowsperstrip, tif->tif_dir.td_row))
     201           0 :             return (-1);
     202          11 :         if ((tif->tif_flags & TIFF_CODERSETUP) == 0)
     203             :         {
     204           9 :             if (!(*tif->tif_setupencode)(tif))
     205           0 :                 return (-1);
     206           9 :             tif->tif_flags |= TIFF_CODERSETUP;
     207             :         }
     208             : 
     209          11 :         tif->tif_rawcc = 0;
     210          11 :         tif->tif_rawcp = tif->tif_rawdata;
     211             : 
     212             :         /* this informs TIFFAppendToStrip() we have changed strip */
     213          11 :         tif->tif_curoff = 0;
     214             : 
     215          11 :         if (!(*tif->tif_preencode)(tif, sample))
     216           0 :             return (-1);
     217          11 :         tif->tif_flags |= TIFF_POSTENCODE;
     218             :     }
     219             :     /*
     220             :      * Ensure the write is either sequential or at the
     221             :      * beginning of a strip (or that we can randomly
     222             :      * access the data -- i.e. no encoding).
     223             :      */
     224       57252 :     if (row != tif->tif_dir.td_row)
     225             :     {
     226           0 :         if (row < tif->tif_dir.td_row)
     227             :         {
     228             :             /*
     229             :              * Moving backwards within the same strip:
     230             :              * backup to the start and then decode
     231             :              * forward (below).
     232             :              */
     233             :             /* Coverity Scan warns about a potential division by zero given
     234             :              * an above check against zero, but I believe this is a false
     235             :              * positive.
     236             :              */
     237           0 :             assert(td->td_stripsperimage != 0);
     238           0 :             if (TIFFSafeModMul32(tif, module, strip, td->td_stripsperimage,
     239             :                                  td->td_rowsperstrip, tif->tif_dir.td_row))
     240           0 :                 return (-1);
     241           0 :             tif->tif_rawcp = tif->tif_rawdata;
     242             :         }
     243             :         /*
     244             :          * Seek forward to the desired row.
     245             :          */
     246           0 :         if (!(*tif->tif_seek)(tif, row - tif->tif_dir.td_row))
     247           0 :             return (-1);
     248           0 :         tif->tif_dir.td_row = row;
     249             :     }
     250             : 
     251             :     /* swab if needed - note that source buffer will be altered */
     252       57252 :     if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode,
     253             :                                     tif->tif_dir.td_scanlinesize, module))
     254           0 :         return (-1);
     255       57252 :     tif->tif_postdecode(tif, (uint8_t *)buf, tif->tif_dir.td_scanlinesize);
     256             : 
     257       57252 :     status = (*tif->tif_encoderow)(tif, (uint8_t *)buf,
     258             :                                    tif->tif_dir.td_scanlinesize, sample);
     259             : 
     260             :     /* we are now poised at the beginning of the next row */
     261       57252 :     tif->tif_dir.td_row = row + 1;
     262       57252 :     return (status);
     263             : }
     264             : /**
     265             :  * @brief Reserve raw output capacity for a possible strile rewrite.
     266             :  * @ingroup libtiff_private_image_transfers
     267             :  *
     268             :  * Requires a valid count array/index. Can replace output buffering with a
     269             :  * rounded owned allocation larger than the previous stored count plus
     270             :  * safety margin, even if a borrowed buffer was attached.
     271             :  * Byte-count-plus-margin and casts rely on representable metadata; not
     272             :  * general overflow validation. Old raw contents can be lost. The only
     273             :  * effects are TIFFWriteBufferSetup() replacing the raw buffer and
     274             :  * diagnostics; no client I/O. If that allocation fails, the previous raw
     275             :  * buffer has already been released and tif_rawdata is NULL. See
     276             :  * @ref image_transfers.
     277             :  *
     278             :  * @param[in,out] tif Non-NULL live handle with matching current geometry
     279             :  * and codec methods; serialise access externally.
     280             :  * @param[in] strip_or_tile Valid logical strile index for this operation.
     281             :  * @return One after adequate capacity/no growth, zero on invalid
     282             :  * metadata/index or allocation failure.
     283             :  */
     284             : 
     285             : /* Make sure that at the first attempt of rewriting a tile/strip, we will have
     286             :  */
     287             : /* more bytes available in the output buffer than the previous byte count, */
     288             : /* so that TIFFAppendToStrip() will detect the overflow when it is called the
     289             :  * first */
     290             : /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
     291      209621 : static int _TIFFReserveLargeEnoughWriteBuffer(TIFF *tif, uint32_t strip_or_tile)
     292             : {
     293             :     static const char module[] = "_TIFFReserveLargeEnoughWriteBuffer";
     294      209621 :     TIFFDirectory *td = &tif->tif_dir;
     295             : 
     296      209621 :     if (td->td_stripbytecount_p == NULL)
     297             :     {
     298           0 :         TIFFErrorExtR(tif, module, "Strip bytecount array pointer is NULL");
     299           0 :         return 0;
     300             :     }
     301             : 
     302      209621 :     if (strip_or_tile == NOSTRIP || strip_or_tile >= td->td_nstrips)
     303             :     {
     304           0 :         TIFFErrorExtR(tif, module, "Strip/tile number not valid");
     305           0 :         return 0;
     306             :     }
     307             : 
     308      209621 :     if (td->td_stripbytecount_p[strip_or_tile] > 0)
     309             :     {
     310             :         /* The +1 is to ensure at least one extra bytes */
     311             :         /* The +4 is because the LZW encoder flushes 4 bytes before the limit */
     312       40857 :         uint64_t safe_buffer_size =
     313       40857 :             (uint64_t)(td->td_stripbytecount_p[strip_or_tile] + 1 + 4);
     314       40857 :         if (tif->tif_rawdatasize <= (tmsize_t)safe_buffer_size)
     315             :         {
     316           0 :             if (!(TIFFWriteBufferSetup(
     317             :                     tif, NULL,
     318           0 :                     (tmsize_t)TIFFroundup_64(safe_buffer_size, 1024))))
     319           0 :                 return 0;
     320             :         }
     321             :     }
     322      209621 :     return 1;
     323             : }
     324             : 
     325             : /*
     326             :  * Encode the supplied data and write it to the
     327             :  * specified strip.
     328             :  *
     329             :  * NB: Image length must be setup before writing.
     330             :  */
     331      180314 : tmsize_t TIFFWriteEncodedStrip(TIFF *tif, uint32_t strip, void *data,
     332             :                                tmsize_t cc)
     333             : {
     334             :     static const char module[] = "TIFFWriteEncodedStrip";
     335      180314 :     TIFFDirectory *td = &tif->tif_dir;
     336             :     uint16_t sample;
     337             : 
     338      180314 :     if (!WRITECHECKSTRIPS(tif, module))
     339           0 :         return ((tmsize_t)-1);
     340             :     /*
     341             :      * Check strip array to make sure there's space.
     342             :      * We don't support dynamically growing files that
     343             :      * have data organized in separate bitplanes because
     344             :      * it's too painful.  In that case we require that
     345             :      * the imagelength be set properly before the first
     346             :      * write (so that the strips array will be fully
     347             :      * allocated above).
     348             :      */
     349      180314 :     if (strip >= td->td_nstrips)
     350             :     {
     351           0 :         if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
     352             :         {
     353           0 :             TIFFErrorExtR(
     354             :                 tif, module,
     355             :                 "Can not grow image by strips when using separate planes");
     356           0 :             return ((tmsize_t)-1);
     357             :         }
     358             :         /* TIFFGrowStrips() below extends the strip arrays by exactly one
     359             :          * entry, so only the index immediately past the end can be served. */
     360           0 :         if (strip > td->td_nstrips)
     361             :         {
     362           0 :             TIFFErrorExtR(tif, module, "%lu: Strip out of range, max %lu",
     363           0 :                           (unsigned long)strip, (unsigned long)td->td_nstrips);
     364           0 :             return ((tmsize_t)-1);
     365             :         }
     366           0 :         if (!TIFFGrowStrips(tif, 1, module))
     367           0 :             return ((tmsize_t)-1);
     368           0 :         td->td_stripsperimage =
     369           0 :             TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
     370             :     }
     371             :     /*
     372             :      * Handle delayed allocation of data buffer.  This
     373             :      * permits it to be sized according to the directory
     374             :      * info.
     375             :      */
     376      180314 :     if (!BUFFERCHECK(tif))
     377           0 :         return ((tmsize_t)-1);
     378             : 
     379      180313 :     tif->tif_flags |= TIFF_BUF4WRITE;
     380             : 
     381      180313 :     tif->tif_dir.td_curstrip = strip;
     382             : 
     383             :     /* this informs TIFFAppendToStrip() we have changed or reset strip */
     384      180313 :     tif->tif_curoff = 0;
     385             : 
     386      180313 :     if (!_TIFFReserveLargeEnoughWriteBuffer(tif, strip))
     387             :     {
     388           0 :         return ((tmsize_t)(-1));
     389             :     }
     390             : 
     391      180308 :     tif->tif_rawcc = 0;
     392      180308 :     tif->tif_rawcp = tif->tif_rawdata;
     393             : 
     394      180308 :     if (td->td_stripsperimage == 0)
     395             :     {
     396           0 :         TIFFErrorExtR(tif, module, "Zero strips per image");
     397           0 :         return ((tmsize_t)-1);
     398             :     }
     399             : 
     400      180308 :     if (TIFFSafeModMul32(tif, module, strip, td->td_stripsperimage,
     401             :                          td->td_rowsperstrip, tif->tif_dir.td_row))
     402           0 :         return ((tmsize_t)-1);
     403      180303 :     if ((tif->tif_flags & TIFF_CODERSETUP) == 0)
     404             :     {
     405       37185 :         if (!(*tif->tif_setupencode)(tif))
     406           0 :             return ((tmsize_t)-1);
     407       37186 :         tif->tif_flags |= TIFF_CODERSETUP;
     408             :     }
     409             : 
     410      180304 :     tif->tif_flags &= ~TIFF_POSTENCODE;
     411             : 
     412             :     /* shortcut to avoid an extra memcpy() */
     413      180304 :     if (td->td_compression == COMPRESSION_NONE)
     414             :     {
     415             :         /* swab if needed - note that source buffer will be altered */
     416      149544 :         if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, cc, module))
     417           0 :             return ((tmsize_t)(-1));
     418      149544 :         tif->tif_postdecode(tif, (uint8_t *)data, cc);
     419             : 
     420      149542 :         if (!isFillOrder(tif, td->td_fillorder) &&
     421           0 :             (tif->tif_flags & TIFF_NOBITREV) == 0)
     422           0 :             TIFFReverseBits((uint8_t *)data, cc);
     423             : 
     424      149540 :         if (cc > 0 && !TIFFAppendToStrip(tif, strip, (uint8_t *)data, cc))
     425           4 :             return ((tmsize_t)-1);
     426      149503 :         return (cc);
     427             :     }
     428             : 
     429       30760 :     sample = (uint16_t)(strip / td->td_stripsperimage);
     430       30760 :     if (!(*tif->tif_preencode)(tif, sample))
     431           2 :         return ((tmsize_t)-1);
     432             : 
     433             :     /* swab if needed - note that source buffer will be altered */
     434       30757 :     if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, cc, module))
     435           0 :         return ((tmsize_t)(-1));
     436       30757 :     tif->tif_postdecode(tif, (uint8_t *)data, cc);
     437             : 
     438       30757 :     if (!(*tif->tif_encodestrip)(tif, (uint8_t *)data, cc, sample))
     439           0 :         return ((tmsize_t)-1);
     440       30757 :     if (!(*tif->tif_postencode)(tif))
     441           1 :         return ((tmsize_t)-1);
     442       30755 :     if (!isFillOrder(tif, td->td_fillorder) &&
     443           0 :         (tif->tif_flags & TIFF_NOBITREV) == 0)
     444           0 :         TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc);
     445       47221 :     if (tif->tif_rawcc > 0 &&
     446       16466 :         !TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc))
     447           0 :         return ((tmsize_t)-1);
     448       30755 :     tif->tif_rawcc = 0;
     449       30755 :     tif->tif_rawcp = tif->tif_rawdata;
     450       30755 :     return (cc);
     451             : }
     452             : 
     453             : /*
     454             :  * Write the supplied data to the specified strip.
     455             :  *
     456             :  * NB: Image length must be setup before writing.
     457             :  */
     458        7711 : tmsize_t TIFFWriteRawStrip(TIFF *tif, uint32_t strip, void *data, tmsize_t cc)
     459             : {
     460             :     static const char module[] = "TIFFWriteRawStrip";
     461        7711 :     TIFFDirectory *td = &tif->tif_dir;
     462             : 
     463        7711 :     if (cc < 0)
     464             :     {
     465           0 :         TIFFErrorExtR(tif, module, "Invalid data size %" TIFF_SSIZE_FORMAT, cc);
     466           0 :         return ((tmsize_t)-1);
     467             :     }
     468        7711 :     if (!WRITECHECKSTRIPS(tif, module))
     469           0 :         return ((tmsize_t)-1);
     470             :     /*
     471             :      * Check strip array to make sure there's space.
     472             :      * We don't support dynamically growing files that
     473             :      * have data organized in separate bitplanes because
     474             :      * it's too painful.  In that case we require that
     475             :      * the imagelength be set properly before the first
     476             :      * write (so that the strips array will be fully
     477             :      * allocated above).
     478             :      */
     479        7711 :     if (strip >= td->td_nstrips)
     480             :     {
     481           0 :         if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
     482             :         {
     483           0 :             TIFFErrorExtR(
     484             :                 tif, module,
     485             :                 "Can not grow image by strips when using separate planes");
     486           0 :             return ((tmsize_t)-1);
     487             :         }
     488             :         /*
     489             :          * Watch out for a growing image.  The value of
     490             :          * strips/image will initially be 1 (since it
     491             :          * can't be deduced until the imagelength is known).
     492             :          */
     493             :         /* TIFFGrowStrips() below extends the strip arrays by exactly one
     494             :          * entry, so only the index immediately past the end can be served. */
     495           0 :         if (strip > td->td_nstrips)
     496             :         {
     497           0 :             TIFFErrorExtR(tif, module, "%lu: Strip out of range, max %lu",
     498           0 :                           (unsigned long)strip, (unsigned long)td->td_nstrips);
     499           0 :             return ((tmsize_t)-1);
     500             :         }
     501           0 :         if (strip >= td->td_stripsperimage)
     502           0 :             td->td_stripsperimage =
     503           0 :                 TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip);
     504           0 :         if (!TIFFGrowStrips(tif, 1, module))
     505           0 :             return ((tmsize_t)-1);
     506             :     }
     507             : 
     508        7711 :     if (tif->tif_dir.td_curstrip != strip)
     509             :     {
     510        7711 :         tif->tif_dir.td_curstrip = strip;
     511             : 
     512             :         /* this informs TIFFAppendToStrip() we have changed or reset strip */
     513        7711 :         tif->tif_curoff = 0;
     514             :     }
     515             : 
     516        7711 :     if (td->td_stripsperimage == 0)
     517             :     {
     518           0 :         TIFFErrorExtR(tif, module, "Zero strips per image");
     519           0 :         return ((tmsize_t)-1);
     520             :     }
     521        7711 :     if (TIFFSafeModMul32(tif, module, strip, td->td_stripsperimage,
     522             :                          td->td_rowsperstrip, tif->tif_dir.td_row))
     523           0 :         return ((tmsize_t)-1);
     524        7711 :     return (TIFFAppendToStrip(tif, strip, (uint8_t *)data, cc) ? cc
     525        7711 :                                                                : (tmsize_t)-1);
     526             : }
     527             : 
     528             : /*
     529             :  * Write and compress a tile of data.  The
     530             :  * tile is selected by the (x,y,z,s) coordinates.
     531             :  */
     532           0 : tmsize_t TIFFWriteTile(TIFF *tif, void *buf, uint32_t x, uint32_t y, uint32_t z,
     533             :                        uint16_t s)
     534             : {
     535           0 :     bool overflow = false;
     536             :     uint32_t tile;
     537             : 
     538           0 :     if (!TIFFCheckTile(tif, x, y, z, s))
     539           0 :         return ((tmsize_t)(-1));
     540             :     /* An overflow returns 0, which is also a valid tile. */
     541           0 :     tile = _TIFFComputeTileExt(tif, x, y, z, s, &overflow);
     542           0 :     if (overflow)
     543           0 :         return ((tmsize_t)(-1));
     544             :     /*
     545             :      * NB: A tile size of -1 is used instead of tif_tilesize knowing
     546             :      *     that TIFFWriteEncodedTile will clamp this to the tile size.
     547             :      *     This is done because the tile size may not be defined until
     548             :      *     after the output buffer is setup in TIFFWriteBufferSetup.
     549             :      */
     550           0 :     return (TIFFWriteEncodedTile(tif, tile, buf, (tmsize_t)(-1)));
     551             : }
     552             : 
     553             : /*
     554             :  * Encode the supplied data and write it to the
     555             :  * specified tile.  There must be space for the
     556             :  * data.  The function clamps individual writes
     557             :  * to a tile to the tile size, but does not (and
     558             :  * can not) check that multiple writes to the same
     559             :  * tile do not write more than tile size data.
     560             :  *
     561             :  * NB: Image length must be setup before writing; this
     562             :  *     interface does not support automatically growing
     563             :  *     the image on each write (as TIFFWriteScanline does).
     564             :  */
     565       29309 : tmsize_t TIFFWriteEncodedTile(TIFF *tif, uint32_t tile, void *data, tmsize_t cc)
     566             : {
     567             :     static const char module[] = "TIFFWriteEncodedTile";
     568             :     TIFFDirectory *td;
     569             :     uint16_t sample;
     570             :     uint32_t howmany32;
     571             : 
     572       29309 :     if (!WRITECHECKTILES(tif, module))
     573           0 :         return ((tmsize_t)(-1));
     574       29309 :     td = &tif->tif_dir;
     575       29309 :     if (tile >= td->td_nstrips)
     576             :     {
     577           0 :         TIFFErrorExtR(tif, module, "Tile %lu out of range, max %lu",
     578           0 :                       (unsigned long)tile, (unsigned long)td->td_nstrips);
     579           0 :         return ((tmsize_t)(-1));
     580             :     }
     581             :     /*
     582             :      * Handle delayed allocation of data buffer.  This
     583             :      * permits it to be sized more intelligently (using
     584             :      * directory information).
     585             :      */
     586       29309 :     if (!BUFFERCHECK(tif))
     587           0 :         return ((tmsize_t)(-1));
     588             : 
     589       29310 :     tif->tif_flags |= TIFF_BUF4WRITE;
     590             : 
     591       29310 :     tif->tif_dir.td_curtile = tile;
     592             : 
     593             :     /* this informs TIFFAppendToStrip() we have changed or reset tile */
     594       29310 :     tif->tif_curoff = 0;
     595             : 
     596       29310 :     if (!_TIFFReserveLargeEnoughWriteBuffer(tif, tile))
     597             :     {
     598           0 :         return ((tmsize_t)(-1));
     599             :     }
     600             : 
     601       29309 :     tif->tif_rawcc = 0;
     602       29309 :     tif->tif_rawcp = tif->tif_rawdata;
     603             : 
     604             :     /*
     605             :      * Compute tiles per row & per column to compute
     606             :      * current row and column
     607             :      */
     608       29309 :     howmany32 = TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
     609       29309 :     if (howmany32 == 0)
     610             :     {
     611           0 :         TIFFErrorExtR(tif, module, "Zero tiles");
     612           0 :         return ((tmsize_t)(-1));
     613             :     }
     614       29309 :     if (TIFFSafeModMul32(tif, module, tile, howmany32, td->td_tilelength,
     615             :                          tif->tif_dir.td_row))
     616           0 :         return ((tmsize_t)(-1));
     617       29307 :     howmany32 = TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
     618       29307 :     if (howmany32 == 0)
     619             :     {
     620           0 :         TIFFErrorExtR(tif, module, "Zero tiles");
     621           0 :         return ((tmsize_t)(-1));
     622             :     }
     623       29307 :     if (TIFFSafeModMul32(tif, module, tile, howmany32, td->td_tilewidth,
     624             :                          tif->tif_dir.td_col))
     625           0 :         return ((tmsize_t)(-1));
     626             : 
     627       29306 :     if ((tif->tif_flags & TIFF_CODERSETUP) == 0)
     628             :     {
     629        1331 :         if (!(*tif->tif_setupencode)(tif))
     630           0 :             return ((tmsize_t)(-1));
     631        1331 :         tif->tif_flags |= TIFF_CODERSETUP;
     632             :     }
     633       29306 :     tif->tif_flags &= ~TIFF_POSTENCODE;
     634             : 
     635             :     /*
     636             :      * Clamp write amount to the tile size.  This is mostly
     637             :      * done so that callers can pass in some large number
     638             :      * (e.g. -1) and have the tile size used instead.
     639             :      */
     640       29306 :     if (cc < 1 || cc > tif->tif_dir.td_tilesize)
     641           0 :         cc = tif->tif_dir.td_tilesize;
     642             : 
     643             :     /* shortcut to avoid an extra memcpy() */
     644       29306 :     if (td->td_compression == COMPRESSION_NONE)
     645             :     {
     646             :         /* swab if needed - note that source buffer will be altered */
     647       20317 :         if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, cc, module))
     648           0 :             return ((tmsize_t)(-1));
     649       20317 :         tif->tif_postdecode(tif, (uint8_t *)data, cc);
     650             : 
     651       20317 :         if (!isFillOrder(tif, td->td_fillorder) &&
     652           0 :             (tif->tif_flags & TIFF_NOBITREV) == 0)
     653           0 :             TIFFReverseBits((uint8_t *)data, cc);
     654             : 
     655       20317 :         if (cc > 0 && !TIFFAppendToStrip(tif, tile, (uint8_t *)data, cc))
     656           0 :             return ((tmsize_t)-1);
     657       20317 :         return (cc);
     658             :     }
     659             : 
     660        8989 :     sample = (uint16_t)(tile / td->td_stripsperimage);
     661        8989 :     if (!(*tif->tif_preencode)(tif, sample))
     662           0 :         return ((tmsize_t)(-1));
     663             :     /* swab if needed - note that source buffer will be altered */
     664        8991 :     if (!_TIFFCheckPostDecodeLength(tif, tif->tif_postdecode, cc, module))
     665           0 :         return ((tmsize_t)(-1));
     666        8992 :     tif->tif_postdecode(tif, (uint8_t *)data, cc);
     667             : 
     668        8993 :     if (!(*tif->tif_encodetile)(tif, (uint8_t *)data, cc, sample))
     669           0 :         return ((tmsize_t)-1);
     670        8992 :     if (!(*tif->tif_postencode)(tif))
     671           1 :         return ((tmsize_t)(-1));
     672        8992 :     if (!isFillOrder(tif, td->td_fillorder) &&
     673           0 :         (tif->tif_flags & TIFF_NOBITREV) == 0)
     674           0 :         TIFFReverseBits((uint8_t *)tif->tif_rawdata, tif->tif_rawcc);
     675       10985 :     if (tif->tif_rawcc > 0 &&
     676        1993 :         !TIFFAppendToStrip(tif, tile, tif->tif_rawdata, tif->tif_rawcc))
     677          12 :         return ((tmsize_t)(-1));
     678        8980 :     tif->tif_rawcc = 0;
     679        8980 :     tif->tif_rawcp = tif->tif_rawdata;
     680        8980 :     return (cc);
     681             : }
     682             : 
     683             : /*
     684             :  * Write the supplied data to the specified strip.
     685             :  * There must be space for the data; we don't check
     686             :  * if strips overlap!
     687             :  *
     688             :  * NB: Image length must be setup before writing; this
     689             :  *     interface does not support automatically growing
     690             :  *     the image on each write (as TIFFWriteScanline does).
     691             :  */
     692       27371 : tmsize_t TIFFWriteRawTile(TIFF *tif, uint32_t tile, void *data, tmsize_t cc)
     693             : {
     694             :     static const char module[] = "TIFFWriteRawTile";
     695             : 
     696       27371 :     if (cc < 0)
     697             :     {
     698           0 :         TIFFErrorExtR(tif, module, "Invalid data size %" TIFF_SSIZE_FORMAT, cc);
     699           0 :         return ((tmsize_t)(-1));
     700             :     }
     701       27371 :     if (!WRITECHECKTILES(tif, module))
     702           0 :         return ((tmsize_t)(-1));
     703       27371 :     if (tile >= tif->tif_dir.td_nstrips)
     704             :     {
     705           0 :         TIFFErrorExtR(tif, module, "Tile %lu out of range, max %lu",
     706             :                       (unsigned long)tile,
     707           0 :                       (unsigned long)tif->tif_dir.td_nstrips);
     708           0 :         return ((tmsize_t)(-1));
     709             :     }
     710       27371 :     return (TIFFAppendToStrip(tif, tile, (uint8_t *)data, cc) ? cc
     711       27371 :                                                               : (tmsize_t)(-1));
     712             : }
     713             : 
     714             : /**
     715             :  * @brief Test the zero-image-length provisional strile case.
     716             :  * @ingroup libtiff_private_image_transfers
     717             :  *
     718             :  * Pure test with no side effects; it reads the presence bitmap and
     719             :  * ImageLength only.
     720             :  *
     721             :  * @param[in] tif Live handle expression, evaluated twice.
     722             :  * @param[in] f Valid presence-bit index, evaluated twice (by
     723             :  * TIFFFieldSet()).
     724             :  * @return Nonzero if the bit is set and ImageLength is zero.
     725             :  */
     726             : #define isUnspecified(tif, f)                                                  \
     727             :     (TIFFFieldSet(tif, f) && (tif)->tif_dir.td_imagelength == 0)
     728             : 
     729       43055 : int TIFFSetupStrips(TIFF *tif)
     730             : {
     731       43055 :     TIFFDirectory *td = &tif->tif_dir;
     732             : 
     733       43055 :     if (isTiled(tif))
     734        6266 :         td->td_stripsperimage = isUnspecified(tif, FIELD_TILEDIMENSIONS)
     735           0 :                                     ? td->td_samplesperpixel
     736        6266 :                                     : TIFFNumberOfTiles(tif);
     737             :     else
     738       79844 :         td->td_stripsperimage = isUnspecified(tif, FIELD_ROWSPERSTRIP)
     739           0 :                                     ? td->td_samplesperpixel
     740       79844 :                                     : TIFFNumberOfStrips(tif);
     741       43055 :     td->td_nstrips = td->td_stripsperimage;
     742             :     /* TIFFWriteDirectoryTagData has a limitation to 0x80000000U bytes */
     743       86110 :     if (td->td_nstrips >=
     744       43055 :         0x80000000U / ((tif->tif_flags & TIFF_BIGTIFF) ? 0x8U : 0x4U))
     745             :     {
     746           0 :         TIFFErrorExtR(tif, "TIFFSetupStrips",
     747             :                       "Too large Strip/Tile Offsets/ByteCounts arrays");
     748           0 :         return 0;
     749             :     }
     750       43055 :     if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
     751        4007 :         td->td_stripsperimage /= td->td_samplesperpixel;
     752             : 
     753       43055 :     if (td->td_stripoffset_p != NULL)
     754           0 :         _TIFFfreeExt(tif, td->td_stripoffset_p);
     755       86110 :     td->td_stripoffset_p = (uint64_t *)_TIFFCheckMalloc(
     756       43055 :         tif, td->td_nstrips, sizeof(uint64_t), "for \"StripOffsets\" array");
     757       43055 :     if (td->td_stripbytecount_p != NULL)
     758           0 :         _TIFFfreeExt(tif, td->td_stripbytecount_p);
     759       86110 :     td->td_stripbytecount_p = (uint64_t *)_TIFFCheckMalloc(
     760       43055 :         tif, td->td_nstrips, sizeof(uint64_t), "for \"StripByteCounts\" array");
     761       43055 :     if (td->td_stripoffset_p == NULL || td->td_stripbytecount_p == NULL)
     762           0 :         return (0);
     763             :     /*
     764             :      * Place data at the end-of-file
     765             :      * (by setting offsets to zero).
     766             :      */
     767       43055 :     _TIFFmemset(td->td_stripoffset_p, 0,
     768       43055 :                 (tmsize_t)((size_t)td->td_nstrips * sizeof(uint64_t)));
     769       43055 :     _TIFFmemset(td->td_stripbytecount_p, 0,
     770       43055 :                 (tmsize_t)((size_t)td->td_nstrips * sizeof(uint64_t)));
     771       43055 :     TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
     772       43055 :     TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
     773       43055 :     return (1);
     774             : }
     775             : #undef isUnspecified
     776             : 
     777             : /*
     778             :  * Verify file is writable and that the directory
     779             :  * information is setup properly.  In doing the latter
     780             :  * we also "freeze" the state of the directory so
     781             :  * that important information is not changed.
     782             :  */
     783       54103 : int TIFFWriteCheck(TIFF *tif, int tiles, const char *module)
     784             : {
     785       54103 :     if (tif->tif_mode == O_RDONLY)
     786             :     {
     787           0 :         TIFFErrorExtR(tif, module, "File not open for writing");
     788           0 :         return (0);
     789             :     }
     790       54103 :     if (tiles ^ isTiled(tif))
     791             :     {
     792           0 :         TIFFErrorExtR(tif, module,
     793             :                       tiles ? "Can not write tiles to a striped image"
     794             :                             : "Can not write scanlines to a tiled image");
     795           0 :         return (0);
     796             :     }
     797             : 
     798       54103 :     _TIFFFillStriles(tif);
     799             : 
     800             :     /*
     801             :      * On the first write verify all the required information
     802             :      * has been setup and initialize any data structures that
     803             :      * had to wait until directory information was set.
     804             :      * Note that a lot of our work is assumed to remain valid
     805             :      * because we disallow any of the important parameters
     806             :      * from changing after we start writing (i.e. once
     807             :      * TIFF_BEENWRITING is set, TIFFSetField will only allow
     808             :      * the image's length to be changed).
     809             :      */
     810       54103 :     if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS))
     811             :     {
     812           0 :         TIFFErrorExtR(tif, module,
     813             :                       "Must set \"ImageWidth\" before writing data");
     814           0 :         return (0);
     815             :     }
     816       54103 :     if (tif->tif_dir.td_stripoffset_p == NULL && !TIFFSetupStrips(tif))
     817             :     {
     818           0 :         tif->tif_dir.td_nstrips = 0;
     819           0 :         TIFFErrorExtR(tif, module, "No space for %s arrays",
     820           0 :                       isTiled(tif) ? "tile" : "strip");
     821           0 :         return (0);
     822             :     }
     823       54103 :     if (isTiled(tif))
     824             :     {
     825        3589 :         tif->tif_dir.td_tilesize = TIFFTileSize(tif);
     826        3589 :         if (tif->tif_dir.td_tilesize == 0)
     827           0 :             return (0);
     828             :     }
     829             :     else
     830       50514 :         tif->tif_dir.td_tilesize = (tmsize_t)(-1);
     831       54103 :     tif->tif_dir.td_scanlinesize = TIFFScanlineSize(tif);
     832       54103 :     if (tif->tif_dir.td_scanlinesize == 0)
     833           0 :         return (0);
     834       54103 :     tif->tif_flags |= TIFF_BEENWRITING;
     835             : 
     836       54103 :     if (tif->tif_dir.td_stripoffset_entry.tdir_tag != 0 &&
     837       11639 :         tif->tif_dir.td_stripoffset_entry.tdir_count == 0 &&
     838           0 :         tif->tif_dir.td_stripoffset_entry.tdir_type == 0 &&
     839           0 :         tif->tif_dir.td_stripoffset_entry.tdir_offset.toff_long8 == 0 &&
     840           0 :         tif->tif_dir.td_stripbytecount_entry.tdir_tag != 0 &&
     841           0 :         tif->tif_dir.td_stripbytecount_entry.tdir_count == 0 &&
     842           0 :         tif->tif_dir.td_stripbytecount_entry.tdir_type == 0 &&
     843           0 :         tif->tif_dir.td_stripbytecount_entry.tdir_offset.toff_long8 == 0 &&
     844           0 :         !(tif->tif_flags & TIFF_DIRTYDIRECT))
     845             :     {
     846           0 :         if (!TIFFForceStrileArrayWriting(tif))
     847             :         {
     848             :             /* Write macros skip TIFFWriteCheck() while this flag is set */
     849           0 :             tif->tif_flags &= ~TIFF_BEENWRITING;
     850           0 :             return (0);
     851             :         }
     852             :     }
     853             : 
     854       54103 :     return (1);
     855             : }
     856             : 
     857             : /*
     858             :  * Setup the raw data buffer used for encoding.
     859             :  */
     860       38617 : int TIFFWriteBufferSetup(TIFF *tif, void *bp, tmsize_t size)
     861             : {
     862             :     static const char module[] = "TIFFWriteBufferSetup";
     863             : 
     864             :     /* Size -1 selects the library default; any other size must be positive. */
     865       38617 :     if (size != (tmsize_t)(-1) && size <= 0)
     866             :     {
     867           0 :         TIFFErrorExtR(tif, module,
     868             :                       "Invalid raw data buffer size %" TIFF_SSIZE_FORMAT, size);
     869           0 :         return (0);
     870             :     }
     871             : 
     872       38617 :     if (tif->tif_rawdata)
     873             :     {
     874          26 :         if (tif->tif_flags & TIFF_MYBUFFER)
     875             :         {
     876          26 :             _TIFFfreeExt(tif, tif->tif_rawdata);
     877          26 :             tif->tif_flags &= ~TIFF_MYBUFFER;
     878             :         }
     879          26 :         tif->tif_rawdata = NULL;
     880          26 :         tif->tif_rawdatasize = 0;
     881             :     }
     882       38617 :     if (size == (tmsize_t)(-1))
     883             :     {
     884       38617 :         size = (isTiled(tif) ? tif->tif_dir.td_tilesize : TIFFStripSize(tif));
     885             : 
     886             :         /* Adds 10% margin for cases where compression would expand a bit */
     887       38617 :         if (size < TIFF_TMSIZE_T_MAX - size / 10)
     888       38617 :             size += size / 10;
     889             :         /*
     890             :          * Make raw data buffer at least 8K
     891             :          */
     892       38617 :         if (size < 8 * 1024)
     893       27245 :             size = 8 * 1024;
     894       38617 :         bp = NULL; /* NB: force malloc */
     895             :     }
     896       38617 :     if (bp == NULL)
     897             :     {
     898       38617 :         bp = _TIFFmallocExt(tif, size);
     899       38616 :         if (bp == NULL)
     900             :         {
     901           0 :             TIFFErrorExtR(tif, module, "No space for output buffer");
     902           0 :             return (0);
     903             :         }
     904       38616 :         tif->tif_flags |= TIFF_MYBUFFER;
     905             :     }
     906             :     else
     907           0 :         tif->tif_flags &= ~TIFF_MYBUFFER;
     908       38616 :     tif->tif_rawdata = (uint8_t *)bp;
     909       38616 :     tif->tif_rawdatasize = size;
     910       38616 :     tif->tif_rawcc = 0;
     911       38616 :     tif->tif_rawcp = tif->tif_rawdata;
     912       38616 :     tif->tif_flags |= TIFF_BUFFERSETUP;
     913       38616 :     return (1);
     914             : }
     915             : /**
     916             :  * @brief Grow contiguous strip offset/count arrays by a requested delta.
     917             :  * @ingroup libtiff_private_image_transfers
     918             :  *
     919             :  * Requires contiguous layout and representable nonnegative allocation
     920             :  * products. Reallocates arrays separately, updates each pointer
     921             :  * immediately, zeroes new slots and marks directory dirty on success. If
     922             :  * either realloc fails, sets td_nstrips zero but retains the latest
     923             :  * allocated pointers; old views can already be invalidated. Does not grow
     924             :  * image height itself. No client I/O; diagnoses allocation failure. See
     925             :  * @ref image_transfers.
     926             :  *
     927             :  * @param[in,out] tif Non-NULL live handle with matching current geometry
     928             :  * and codec methods; serialise access externally.
     929             :  * @param[in] delta Number of slots to add; allocation products and new
     930             :  * uint32_t count must be representable.
     931             :  * @param[in] module Borrowed diagnostic context string.
     932             :  * @return One on both reallocations, zero on failure with changed
     933             :  * pointer/count state.
     934             :  */
     935             : 
     936             : /*
     937             :  * Grow the strip data structures by delta strips.
     938             :  */
     939           0 : static int TIFFGrowStrips(TIFF *tif, uint32_t delta, const char *module)
     940             : {
     941           0 :     TIFFDirectory *td = &tif->tif_dir;
     942             :     uint64_t *new_stripoffset;
     943             :     uint64_t *new_stripbytecount;
     944             : 
     945           0 :     assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
     946             :     /*
     947             :      * Keep the grown arrays within the same 0x80000000U bytes limitation of
     948             :      * TIFFWriteDirectoryTagData() that TIFFSetupStrips() enforces for the
     949             :      * serialised tag, and compute the in-memory size of the arrays with an
     950             :      * overflow check so that it cannot wrap on 32-bit platforms.
     951             :      */
     952           0 :     const uint64_t new_nstrips = (uint64_t)td->td_nstrips + delta;
     953           0 :     if (new_nstrips >=
     954           0 :         0x80000000U / ((tif->tif_flags & TIFF_BIGTIFF) ? 0x8U : 0x4U))
     955             :     {
     956           0 :         TIFFErrorExtR(tif, module,
     957             :                       "Too large Strip/Tile Offsets/ByteCounts arrays");
     958           0 :         return (0);
     959             :     }
     960           0 :     const tmsize_t arrays_size = _TIFFMultiplySSize(
     961             :         tif, (tmsize_t)new_nstrips, (tmsize_t)sizeof(uint64_t), module);
     962           0 :     if (arrays_size == 0)
     963           0 :         return (0);
     964             :     new_stripoffset =
     965           0 :         (uint64_t *)_TIFFreallocExt(tif, td->td_stripoffset_p, arrays_size);
     966             :     /*
     967             :      * Update td_stripoffset_p immediately so the old pointer is not left
     968             :      * dangling if the second realloc fails.
     969             :      */
     970           0 :     if (new_stripoffset)
     971           0 :         td->td_stripoffset_p = new_stripoffset;
     972             :     new_stripbytecount =
     973           0 :         (uint64_t *)_TIFFreallocExt(tif, td->td_stripbytecount_p, arrays_size);
     974           0 :     if (new_stripbytecount)
     975           0 :         td->td_stripbytecount_p = new_stripbytecount;
     976           0 :     if (new_stripoffset == NULL || new_stripbytecount == NULL)
     977             :     {
     978           0 :         td->td_nstrips = 0;
     979           0 :         TIFFErrorExtR(tif, module, "No space to expand strip arrays");
     980           0 :         return (0);
     981             :     }
     982           0 :     _TIFFmemset(td->td_stripoffset_p + td->td_nstrips, 0,
     983           0 :                 (tmsize_t)((size_t)delta * sizeof(uint64_t)));
     984           0 :     _TIFFmemset(td->td_stripbytecount_p + td->td_nstrips, 0,
     985           0 :                 (tmsize_t)((size_t)delta * sizeof(uint64_t)));
     986           0 :     td->td_nstrips += delta;
     987           0 :     tif->tif_flags |= TIFF_DIRTYDIRECT;
     988             : 
     989           0 :     return (1);
     990             : }
     991             : /**
     992             :  * @brief Append stored bytes or relocate a growing overwritten strile.
     993             :  * @ingroup libtiff_private_image_transfers
     994             :  *
     995             :  * Validates current arrays/index, chooses existing reusable extent or EOF,
     996             :  * resets counts when starting a write, and moves previously appended bytes
     997             :  * to EOF if they outgrow a reused extent. Temporary copying storage is
     998             :  * freed on ordinary exits. Checks classic-file wrap and reports
     999             :  * I/O/allocation failures, but EOF seeks/metadata additions are not all
    1000             :  * checked. May modify earlier bytes and array offsets/counts before
    1001             :  * failure; no overlap proof, rollback, IFD persistence, or durability
    1002             :  * guarantee. Seeks, reads and writes through the client procedures and
    1003             :  * dispatches diagnostics; does not touch the raw buffer. No handle or
    1004             :  * caller-buffer ownership transfers. See @ref image_transfers.
    1005             :  *
    1006             :  * @param[in,out] tif Non-NULL live handle with matching current geometry
    1007             :  * and codec methods; serialise access externally.
    1008             :  * @param[in] strip Zero-based strip or tile index; NOSTRIP and values not
    1009             :  * below td_nstrips are diagnosed and rejected.
    1010             :  * @param[in] data Borrowed readable stored bytes; no alias with buffers
    1011             :  * that append/copy may replace.
    1012             :  * @param[in] cc Nonnegative byte extent with representable
    1013             :  * file-offset/count additions.
    1014             :  * @return One after append, zero on detected metadata/extent/allocation/I/O
    1015             :  * failure; previous bytes and counts may have changed.
    1016             :  */
    1017             : 
    1018             : /*
    1019             :  * Append the data to the specified strip.
    1020             :  */
    1021      244710 : static int TIFFAppendToStrip(TIFF *tif, uint32_t strip, uint8_t *data,
    1022             :                              tmsize_t cc)
    1023             : {
    1024             :     static const char module[] = "TIFFAppendToStrip";
    1025      244710 :     TIFFDirectory *td = &tif->tif_dir;
    1026             :     uint64_t m;
    1027      244710 :     int64_t old_byte_count = -1;
    1028             : 
    1029             :     /* Some security checks */
    1030      244710 :     if (td->td_stripoffset_p == NULL)
    1031             :     {
    1032           0 :         TIFFErrorExtR(tif, module, "Strip offset array pointer is NULL");
    1033           0 :         return (0);
    1034             :     }
    1035      244710 :     if (td->td_stripbytecount_p == NULL)
    1036             :     {
    1037           0 :         TIFFErrorExtR(tif, module, "Strip bytecount array pointer is NULL");
    1038           0 :         return (0);
    1039             :     }
    1040      244710 :     if (strip == NOSTRIP)
    1041             :     {
    1042           0 :         TIFFErrorExtR(tif, module, "Strip number not valid (NOSTRIP)");
    1043           0 :         return (0);
    1044             :     }
    1045      244710 :     if (strip >= td->td_nstrips)
    1046             :     {
    1047           0 :         TIFFErrorExtR(tif, module, "%lu: Strip out of range, max %lu",
    1048           0 :                       (unsigned long)strip, (unsigned long)td->td_nstrips);
    1049           0 :         return (0);
    1050             :     }
    1051             : 
    1052      244710 :     if (tif->tif_curoff == 0)
    1053      218052 :         tif->tif_lastvalidoff = 0;
    1054             : 
    1055      244710 :     if (td->td_stripoffset_p[strip] == 0 || tif->tif_curoff == 0)
    1056             :     {
    1057      244699 :         assert(td->td_nstrips > 0);
    1058             : 
    1059      244699 :         if (td->td_stripbytecount_p[strip] != 0 &&
    1060       41198 :             td->td_stripoffset_p[strip] != 0 &&
    1061       41198 :             td->td_stripbytecount_p[strip] >= (uint64_t)cc)
    1062             :         {
    1063             :             /*
    1064             :              * There is already tile data on disk, and the new tile
    1065             :              * data we have will fit in the same space.  The only
    1066             :              * aspect of this that is risky is that there could be
    1067             :              * more data to append to this strip before we are done
    1068             :              * depending on how we are getting called.
    1069             :              */
    1070       41172 :             if (!SeekOK(tif, td->td_stripoffset_p[strip]))
    1071             :             {
    1072           0 :                 TIFFErrorExtR(tif, module, "Seek error at scanline %lu",
    1073           0 :                               (unsigned long)tif->tif_dir.td_row);
    1074           0 :                 return (0);
    1075             :             }
    1076             : 
    1077       41169 :             tif->tif_lastvalidoff =
    1078       41169 :                 td->td_stripoffset_p[strip] + td->td_stripbytecount_p[strip];
    1079             :         }
    1080             :         else
    1081             :         {
    1082             :             /*
    1083             :              * Seek to end of file, and set that as our location to
    1084             :              * write this strip.
    1085             :              */
    1086      203527 :             td->td_stripoffset_p[strip] = TIFFSeekFile(tif, 0, SEEK_END);
    1087      203527 :             tif->tif_flags |= TIFF_DIRTYSTRIP;
    1088             :         }
    1089             : 
    1090      244696 :         tif->tif_curoff = td->td_stripoffset_p[strip];
    1091             : 
    1092             :         /*
    1093             :          * We are starting a fresh strip/tile, so set the size to zero.
    1094             :          */
    1095      244696 :         old_byte_count = (int64_t)td->td_stripbytecount_p[strip];
    1096      244696 :         td->td_stripbytecount_p[strip] = 0;
    1097             :     }
    1098             : 
    1099      244707 :     m = tif->tif_curoff + (uint64_t)cc;
    1100      244707 :     if (!(tif->tif_flags & TIFF_BIGTIFF))
    1101      229481 :         m = (uint32_t)m;
    1102      244707 :     if ((m < tif->tif_curoff) || (m < (uint64_t)cc))
    1103             :     {
    1104           0 :         TIFFErrorExtR(tif, module, "Maximum TIFF file size exceeded");
    1105           0 :         return (0);
    1106             :     }
    1107             : 
    1108      244707 :     if (tif->tif_lastvalidoff != 0 && m > tif->tif_lastvalidoff &&
    1109           0 :         td->td_stripbytecount_p[strip] > 0)
    1110             :     {
    1111             :         /* Ouch: we have detected that we are rewriting in place a strip/tile */
    1112             :         /* with several calls to TIFFAppendToStrip(). The first call was with */
    1113             :         /* a size smaller than the previous size of the strip/tile, so we */
    1114             :         /* opted to rewrite in place, but a following call causes us to go */
    1115             :         /* outsize of the strip/tile area, so we have to finally go for a */
    1116             :         /* append-at-end-of-file strategy, and start by moving what we already
    1117             :          */
    1118             :         /* wrote. */
    1119             :         tmsize_t tempSize;
    1120             :         void *temp;
    1121             :         uint64_t offsetRead;
    1122             :         uint64_t offsetWrite;
    1123           0 :         uint64_t toCopy = td->td_stripbytecount_p[strip];
    1124             : 
    1125           0 :         if (toCopy < 1024 * 1024)
    1126           0 :             tempSize = (tmsize_t)toCopy;
    1127             :         else
    1128           0 :             tempSize = 1024 * 1024;
    1129             : 
    1130           0 :         offsetRead = td->td_stripoffset_p[strip];
    1131           0 :         offsetWrite = TIFFSeekFile(tif, 0, SEEK_END);
    1132             : 
    1133           0 :         m = offsetWrite + (uint64_t)toCopy + (uint64_t)cc;
    1134           0 :         if (!(tif->tif_flags & TIFF_BIGTIFF) && m != (uint32_t)m)
    1135             :         {
    1136           0 :             TIFFErrorExtR(tif, module, "Maximum TIFF file size exceeded");
    1137           0 :             return (0);
    1138             :         }
    1139             : 
    1140           0 :         temp = _TIFFmallocExt(tif, tempSize);
    1141           0 :         if (temp == NULL)
    1142             :         {
    1143           0 :             TIFFErrorExtR(tif, module, "No space for output buffer");
    1144           0 :             return (0);
    1145             :         }
    1146             : 
    1147           0 :         tif->tif_flags |= TIFF_DIRTYSTRIP;
    1148             : 
    1149           0 :         td->td_stripoffset_p[strip] = offsetWrite;
    1150           0 :         td->td_stripbytecount_p[strip] = 0;
    1151             : 
    1152             :         /* Move data written by previous calls to us at end of file */
    1153           0 :         while (toCopy > 0)
    1154             :         {
    1155           0 :             tmsize_t chunkSize =
    1156           0 :                 toCopy < (uint64_t)tempSize ? (tmsize_t)toCopy : tempSize;
    1157           0 :             if (!SeekOK(tif, offsetRead))
    1158             :             {
    1159           0 :                 TIFFErrorExtR(tif, module, "Seek error");
    1160           0 :                 _TIFFfreeExt(tif, temp);
    1161           0 :                 return (0);
    1162             :             }
    1163           0 :             if (!ReadOK(tif, temp, chunkSize))
    1164             :             {
    1165           0 :                 TIFFErrorExtR(tif, module, "Cannot read");
    1166           0 :                 _TIFFfreeExt(tif, temp);
    1167           0 :                 return (0);
    1168             :             }
    1169           0 :             if (!SeekOK(tif, offsetWrite))
    1170             :             {
    1171           0 :                 TIFFErrorExtR(tif, module, "Seek error");
    1172           0 :                 _TIFFfreeExt(tif, temp);
    1173           0 :                 return (0);
    1174             :             }
    1175           0 :             if (!WriteOK(tif, temp, chunkSize))
    1176             :             {
    1177           0 :                 TIFFErrorExtR(tif, module, "Cannot write");
    1178           0 :                 _TIFFfreeExt(tif, temp);
    1179           0 :                 return (0);
    1180             :             }
    1181           0 :             offsetRead += (uint64_t)chunkSize;
    1182           0 :             offsetWrite += (uint64_t)chunkSize;
    1183           0 :             td->td_stripbytecount_p[strip] += (uint64_t)chunkSize;
    1184           0 :             toCopy -= (uint64_t)chunkSize;
    1185             :         }
    1186           0 :         _TIFFfreeExt(tif, temp);
    1187             : 
    1188             :         /* Append the data of this call */
    1189           0 :         offsetWrite += (uint64_t)cc;
    1190           0 :         m = offsetWrite;
    1191             :     }
    1192             : 
    1193      244707 :     if (!WriteOK(tif, data, cc))
    1194             :     {
    1195          38 :         TIFFErrorExtR(tif, module, "Write error at scanline %lu",
    1196          38 :                       (unsigned long)tif->tif_dir.td_row);
    1197          40 :         return (0);
    1198             :     }
    1199      244645 :     tif->tif_curoff = m;
    1200      244645 :     td->td_stripbytecount_p[strip] += (uint64_t)cc;
    1201             : 
    1202      244645 :     if ((int64_t)td->td_stripbytecount_p[strip] != old_byte_count)
    1203      203511 :         tif->tif_flags |= TIFF_DIRTYSTRIP;
    1204             : 
    1205      244645 :     return (1);
    1206             : }
    1207             : 
    1208             : /*
    1209             :  * Internal version of TIFFFlushData that can be
    1210             :  * called by ``encodestrip routines'' w/o concern
    1211             :  * for infinite recursion.
    1212             :  */
    1213       61681 : int TIFFFlushData1(TIFF *tif)
    1214             : {
    1215       61681 :     if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE)
    1216             :     {
    1217       21313 :         if (!isFillOrder(tif, tif->tif_dir.td_fillorder) &&
    1218           0 :             (tif->tif_flags & TIFF_NOBITREV) == 0)
    1219           0 :             TIFFReverseBits((uint8_t *)tif->tif_rawdata, tif->tif_rawcc);
    1220       21313 :         if (!TIFFAppendToStrip(tif,
    1221       21313 :                                isTiled(tif) ? tif->tif_dir.td_curtile
    1222             :                                             : tif->tif_dir.td_curstrip,
    1223             :                                tif->tif_rawdata, tif->tif_rawcc))
    1224             :         {
    1225             :             /* We update those variables even in case of error since there's */
    1226             :             /* code that doesn't really check the return code of this */
    1227             :             /* function */
    1228          12 :             tif->tif_rawcc = 0;
    1229          12 :             tif->tif_rawcp = tif->tif_rawdata;
    1230          12 :             return (0);
    1231             :         }
    1232       21301 :         tif->tif_rawcc = 0;
    1233       21301 :         tif->tif_rawcp = tif->tif_rawdata;
    1234             :     }
    1235       61669 :     return (1);
    1236             : }
    1237             : 
    1238             : /*
    1239             :  * Set the current write offset.  This should only be
    1240             :  * used to set the offset to a known previous location
    1241             :  * (very carefully), or to 0 so that the next write gets
    1242             :  * appended to the end of the file.
    1243             :  */
    1244         360 : void TIFFSetWriteOffset(TIFF *tif, toff_t off)
    1245             : {
    1246         360 :     tif->tif_curoff = off;
    1247         360 :     tif->tif_lastvalidoff = 0;
    1248         360 : }

Generated by: LCOV version 1.14