[LIBTIFF]
authortfaber <tfaber@97493ccd-5924-5043-b1f5-66cb403b36ce>
Fri, 17 Feb 2017 13:43:05 +0000 (13:43 +0000)
committertfaber <tfaber@97493ccd-5924-5043-b1f5-66cb403b36ce>
Fri, 17 Feb 2017 13:43:05 +0000 (13:43 +0000)
- Update to version 4.0.7
CORE-12775 #resolve

git-svn-id: file:///srv/svn/reactos/trunk@73813 97493ccd-5924-5043-b1f5-66cb403b36ce

49 files changed:
reactos/dll/3rdparty/libtiff/CMakeLists.txt
reactos/dll/3rdparty/libtiff/libtiff.def
reactos/dll/3rdparty/libtiff/mkg3states.c
reactos/dll/3rdparty/libtiff/tif_aux.c
reactos/dll/3rdparty/libtiff/tif_close.c
reactos/dll/3rdparty/libtiff/tif_codec.c
reactos/dll/3rdparty/libtiff/tif_color.c
reactos/dll/3rdparty/libtiff/tif_compress.c
reactos/dll/3rdparty/libtiff/tif_dir.c
reactos/dll/3rdparty/libtiff/tif_dirinfo.c
reactos/dll/3rdparty/libtiff/tif_dirread.c
reactos/dll/3rdparty/libtiff/tif_dirwrite.c
reactos/dll/3rdparty/libtiff/tif_dumpmode.c
reactos/dll/3rdparty/libtiff/tif_extension.c
reactos/dll/3rdparty/libtiff/tif_fax3.c
reactos/dll/3rdparty/libtiff/tif_getimage.c
reactos/dll/3rdparty/libtiff/tif_jpeg.c
reactos/dll/3rdparty/libtiff/tif_jpeg_12.c
reactos/dll/3rdparty/libtiff/tif_luv.c
reactos/dll/3rdparty/libtiff/tif_lzma.c
reactos/dll/3rdparty/libtiff/tif_lzw.c
reactos/dll/3rdparty/libtiff/tif_next.c
reactos/dll/3rdparty/libtiff/tif_ojpeg.c
reactos/dll/3rdparty/libtiff/tif_open.c
reactos/dll/3rdparty/libtiff/tif_packbits.c
reactos/dll/3rdparty/libtiff/tif_pixarlog.c
reactos/dll/3rdparty/libtiff/tif_predict.c
reactos/dll/3rdparty/libtiff/tif_print.c
reactos/dll/3rdparty/libtiff/tif_read.c
reactos/dll/3rdparty/libtiff/tif_stream.cxx [new file with mode: 0644]
reactos/dll/3rdparty/libtiff/tif_strip.c
reactos/dll/3rdparty/libtiff/tif_swab.c
reactos/dll/3rdparty/libtiff/tif_thunder.c
reactos/dll/3rdparty/libtiff/tif_tile.c
reactos/dll/3rdparty/libtiff/tif_unix.c
reactos/dll/3rdparty/libtiff/tif_win32.c
reactos/dll/3rdparty/libtiff/tif_write.c
reactos/dll/3rdparty/libtiff/tif_zip.c
reactos/sdk/include/reactos/libs/libtiff/tif_config.h
reactos/sdk/include/reactos/libs/libtiff/tif_config.vc.h
reactos/sdk/include/reactos/libs/libtiff/tif_fax3.h
reactos/sdk/include/reactos/libs/libtiff/tif_predict.h
reactos/sdk/include/reactos/libs/libtiff/tiff.h
reactos/sdk/include/reactos/libs/libtiff/tiffconf.h
reactos/sdk/include/reactos/libs/libtiff/tiffconf.vc.h
reactos/sdk/include/reactos/libs/libtiff/tiffio.h
reactos/sdk/include/reactos/libs/libtiff/tiffiop.h
reactos/sdk/include/reactos/libs/libtiff/tiffvers.h
reactos/sdk/include/reactos/libs/libtiff/uvcode.h

index 6ecbaa3..5673ed9 100644 (file)
@@ -2,8 +2,6 @@
 add_definitions(
     -DWIN32
     -DNDEBUG
-    -DBUILD_LIBTIFF_DLL
-    -DDLL_EXPORT
     -DUSE_WIN32_FILEIO)
 
 include_directories(
@@ -11,7 +9,7 @@ include_directories(
     ${REACTOS_SOURCE_DIR}/sdk/include/reactos/libs/zlib)
 
 list(APPEND SOURCE
-    mkg3states.c
+    #mkg3states.c
     tif_aux.c
     tif_close.c
     tif_codec.c
@@ -28,18 +26,20 @@ list(APPEND SOURCE
     tif_fax3sm.c
     tif_flush.c
     tif_getimage.c
-    tif_jbig.c
-    tif_jpeg.c
+    #tif_jbig.c
+    #tif_jpeg.c
     tif_luv.c
+    #tif_lzma.c
     tif_lzw.c
     tif_next.c
-    tif_ojpeg.c
+    #tif_ojpeg.c
     tif_open.c
     tif_packbits.c
     tif_pixarlog.c
     tif_predict.c
     tif_print.c
     tif_read.c
+    #tif_stream.cxx
     tif_strip.c
     tif_swab.c
     tif_thunder.c
index 892ad23..acf8609 100644 (file)
-EXPORTS TIFFOpen
-       TIFFOpenW
-       TIFFGetVersion
+EXPORTS        TIFFAccessTagMethods
+       TIFFCIELabToRGBInit
+       TIFFCIELabToXYZ
+       TIFFCheckTile
+       TIFFCheckpointDirectory
        TIFFCleanup
+       TIFFClientOpen
+       TIFFClientdata
        TIFFClose
+       TIFFComputeStrip
+       TIFFComputeTile
+       TIFFCreateCustomDirectory
+       TIFFCreateDirectory
+       TIFFCreateEXIFDirectory
+       TIFFCurrentDirOffset
+       TIFFCurrentDirectory
+       TIFFCurrentRow
+       TIFFCurrentStrip
+       TIFFCurrentTile
+       TIFFDataWidth
+       TIFFDefaultStripSize
+       TIFFDefaultTileSize
+       TIFFError
+       TIFFErrorExt
+       TIFFFdOpen
+       TIFFFieldDataType
+       TIFFFieldName
+       TIFFFieldPassCount
+       TIFFFieldReadCount
+       TIFFFieldTag
+       TIFFFieldWithName
+       TIFFFieldWithTag
+       TIFFFieldWriteCount
+       TIFFFileName
+       TIFFFileno
+       TIFFFindCODEC
+       TIFFFindField
        TIFFFlush
        TIFFFlushData
+       TIFFFreeDirectory
+       TIFFGetBitRevTable
+       TIFFGetClientInfo
+       TIFFGetCloseProc
+       TIFFGetConfiguredCODECs
        TIFFGetField
-       TIFFVGetField
        TIFFGetFieldDefaulted
-       TIFFVGetFieldDefaulted
-       TIFFGetTagListEntry
-       TIFFGetTagListCount
-       TIFFReadDirectory
-       TIFFScanlineSize64
-       TIFFScanlineSize
-       TIFFStripSize64
-       TIFFStripSize
-       TIFFVStripSize64
-       TIFFVStripSize
-       TIFFRawStripSize64
-       TIFFRawStripSize
-       TIFFTileRowSize64
-       TIFFTileRowSize
-       TIFFTileSize64
-       TIFFTileSize
-       TIFFVTileSize64
-       TIFFVTileSize
-       TIFFFileno
-       TIFFSetFileno
+       TIFFGetMapFileProc
        TIFFGetMode
-       TIFFIsTiled
-       TIFFIsByteSwapped
+       TIFFGetReadProc
+       TIFFGetSeekProc
+       TIFFGetSizeProc
+       TIFFGetTagListCount
+       TIFFGetTagListEntry
+       TIFFGetUnmapFileProc
+       TIFFGetVersion
+       TIFFGetWriteProc
        TIFFIsBigEndian
+       TIFFIsByteSwapped
+       TIFFIsCODECConfigured
        TIFFIsMSB2LSB
+       TIFFIsTiled
        TIFFIsUpSampled
-       TIFFCIELabToRGBInit
-       TIFFCIELabToXYZ
-       TIFFXYZToRGB
-       TIFFYCbCrToRGBInit
-       TIFFYCbCrtoRGB
-       TIFFCurrentRow
-       TIFFCurrentDirectory
-       TIFFCurrentStrip
-       TIFFCurrentTile
-       TIFFDataWidth
-       TIFFReadBufferSetup
-       TIFFWriteBufferSetup
-       TIFFSetupStrips
        TIFFLastDirectory
-       TIFFSetDirectory
-       TIFFSetSubDirectory
-       TIFFUnlinkDirectory
-       TIFFSetField
-       TIFFVSetField
-       TIFFCheckpointDirectory
-       TIFFWriteDirectory
-       TIFFRewriteDirectory
+       TIFFMergeFieldInfo
+       TIFFNumberOfDirectories
+       TIFFNumberOfStrips
+       TIFFNumberOfTiles
+       TIFFOpen
+       TIFFOpenW
        TIFFPrintDirectory
-       TIFFReadScanline
-       TIFFWriteScanline
+       TIFFRGBAImageBegin
+       TIFFRGBAImageEnd
+       TIFFRGBAImageGet
+       TIFFRGBAImageOK
+       TIFFRasterScanlineSize
+       TIFFRasterScanlineSize64
+       TIFFRawStripSize
+       TIFFRawStripSize64
+       TIFFReadBufferSetup
+       TIFFReadCustomDirectory
+       TIFFReadDirectory
+       TIFFReadEXIFDirectory
+       TIFFReadEncodedStrip
+       TIFFReadEncodedTile
        TIFFReadRGBAImage
        TIFFReadRGBAImageOriented
-       TIFFFdOpen
-       TIFFClientOpen
-       TIFFFileName
-       TIFFError
-       TIFFErrorExt
-       TIFFWarning
-       TIFFWarningExt
+       TIFFReadRGBAStrip
+       TIFFReadRGBATile
+       TIFFReadRawStrip
+       TIFFReadRawTile
+       TIFFReadScanline
+       TIFFReadTile
+       TIFFRegisterCODEC
+       TIFFReverseBits
+       TIFFRewriteDirectory
+       TIFFScanlineSize
+       TIFFScanlineSize64
+       TIFFSetClientInfo
+       TIFFSetClientdata
+       TIFFSetCompressionScheme
+       TIFFSetDirectory
        TIFFSetErrorHandler
        TIFFSetErrorHandlerExt
+       TIFFSetField
+       TIFFSetFileName
+       TIFFSetFileno
+       TIFFSetMode
+       TIFFSetSubDirectory
+       TIFFSetTagExtender
        TIFFSetWarningHandler
        TIFFSetWarningHandlerExt
-       TIFFComputeTile
-       TIFFCheckTile
-       TIFFNumberOfTiles
-       TIFFReadTile
-       TIFFWriteTile
-       TIFFComputeStrip
-       TIFFNumberOfStrips
-       TIFFRGBAImageBegin
-       TIFFRGBAImageGet
-       TIFFRGBAImageEnd
-       TIFFReadEncodedStrip
-       TIFFReadRawStrip
-       TIFFReadEncodedTile
-       TIFFReadRawTile
-       TIFFReadRGBATile
-       TIFFReadRGBAStrip
-       TIFFWriteEncodedStrip
-       TIFFWriteRawStrip
-       TIFFWriteEncodedTile
-       TIFFWriteRawTile
        TIFFSetWriteOffset
-       TIFFSwabFloat
-       TIFFSwabDouble
-       TIFFSwabShort
-       TIFFSwabLong
-       TIFFSwabArrayOfShort
-       TIFFSwabArrayOfLong
-       TIFFSwabArrayOfFloat
+       TIFFSetupStrips
+       TIFFStripSize
+       TIFFStripSize64
        TIFFSwabArrayOfDouble
+       TIFFSwabArrayOfFloat
+       TIFFSwabArrayOfLong
+       TIFFSwabArrayOfLong8
+       TIFFSwabArrayOfShort
        TIFFSwabArrayOfTriples
-       TIFFReverseBits
-       TIFFGetBitRevTable
-       TIFFDefaultStripSize
-       TIFFDefaultTileSize
-       TIFFRasterScanlineSize64
-       TIFFRasterScanlineSize
-       _TIFFmalloc
-       _TIFFrealloc
-       _TIFFfree
-       _TIFFmemset
-       _TIFFmemcpy
-       _TIFFmemcmp
-       _TIFFCheckMalloc
-       TIFFCreateDirectory
-       TIFFSetTagExtender
-       TIFFFieldWithName
-       TIFFFieldWithTag
-       TIFFFieldTag
-       TIFFFieldName
-       TIFFFieldDataType
-       TIFFFieldPassCount
-       TIFFFieldReadCount
-       TIFFFieldWriteCount
-       TIFFCurrentDirOffset
-       TIFFWriteCheck
-       TIFFRGBAImageOK
-       TIFFNumberOfDirectories
-       TIFFSetFileName
-       TIFFSetClientdata
-       TIFFSetMode
-       TIFFClientdata
-       TIFFGetReadProc
-       TIFFGetWriteProc
-       TIFFGetSeekProc
-       TIFFGetCloseProc
-       TIFFGetSizeProc
-       TIFFGetMapFileProc
-       TIFFGetUnmapFileProc
-       TIFFIsCODECConfigured
-       TIFFGetConfiguredCODECs
-       TIFFFindCODEC
-       TIFFRegisterCODEC
-       TIFFUnRegisterCODEC
-       TIFFFreeDirectory
-       TIFFReadCustomDirectory
-       TIFFReadEXIFDirectory
-       TIFFAccessTagMethods
-       TIFFGetClientInfo
-       TIFFSetClientInfo
+       TIFFSwabDouble
+       TIFFSwabFloat
+       TIFFSwabLong
        TIFFSwabLong8
-       TIFFSwabArrayOfLong8
-       TIFFFindField
+       TIFFSwabShort
+       TIFFTileRowSize
+       TIFFTileRowSize64
+       TIFFTileSize
+       TIFFTileSize64
+       TIFFUnRegisterCODEC
+       TIFFUnlinkDirectory
        TIFFUnsetField
-       TIFFMergeFieldInfo
+       TIFFVGetField
+       TIFFVGetFieldDefaulted
+       TIFFVSetField
+       TIFFVStripSize
+       TIFFVStripSize64
+       TIFFVTileSize
+       TIFFVTileSize64
+       TIFFWarning
+       TIFFWarningExt
+       TIFFWriteBufferSetup
+       TIFFWriteCheck
+       TIFFWriteCustomDirectory
+       TIFFWriteDirectory
+       TIFFWriteEncodedStrip
+       TIFFWriteEncodedTile
+       TIFFWriteRawStrip
+       TIFFWriteRawTile
+       TIFFWriteScanline
+       TIFFWriteTile
+       TIFFXYZToRGB
+       TIFFYCbCrToRGBInit
+       TIFFYCbCrtoRGB
+       _TIFFCheckMalloc
+       _TIFFCheckRealloc
+       _TIFFRewriteField
+       _TIFFfree
+       _TIFFmalloc
+       _TIFFmemcmp
+       _TIFFmemcpy
+       _TIFFmemset
+       _TIFFrealloc
+        _TIFFMultiply32
+        _TIFFMultiply64
index 1df9ccc..16ad3c2 100644 (file)
@@ -1,4 +1,4 @@
-/* "$Id: mkg3states.c,v 1.11 2010-03-10 18:56:48 bfriesen Exp $ */
+/* "$Id: mkg3states.c,v 1.12 2015-06-21 01:09:09 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1991-1997 Sam Leffler
@@ -383,8 +383,11 @@ main(int argc, char* argv[])
     FILE* fd;
     char* outputfile;
     int c;
+
+#if !HAVE_DECL_OPTARG
     extern int optind;
     extern char* optarg;
+#endif
 
     while ((c = getopt(argc, argv, "c:s:bp")) != -1)
        switch (c) {
index 64fd93b..74602c2 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_aux.c,v 1.26 2010-07-01 15:33:28 dron Exp $ */
+/* $Id: tif_aux.c,v 1.29 2016-11-11 20:45:53 erouault Exp $ */
 
 /*
  * Copyright (c) 1991-1997 Sam Leffler
@@ -101,7 +101,8 @@ TIFFDefaultTransferFunction(TIFFDirectory* td)
 
        n = ((tmsize_t)1)<<td->td_bitspersample;
        nbytes = n * sizeof (uint16);
-       if (!(tf[0] = (uint16 *)_TIFFmalloc(nbytes)))
+        tf[0] = (uint16 *)_TIFFmalloc(nbytes);
+       if (tf[0] == NULL)
                return 0;
        tf[0][0] = 0;
        for (i = 1; i < n; i++) {
@@ -110,10 +111,12 @@ TIFFDefaultTransferFunction(TIFFDirectory* td)
        }
 
        if (td->td_samplesperpixel - td->td_extrasamples > 1) {
-               if (!(tf[1] = (uint16 *)_TIFFmalloc(nbytes)))
+                tf[1] = (uint16 *)_TIFFmalloc(nbytes);
+               if(tf[1] == NULL)
                        goto bad;
                _TIFFmemcpy(tf[1], tf[0], nbytes);
-               if (!(tf[2] = (uint16 *)_TIFFmalloc(nbytes)))
+                tf[2] = (uint16 *)_TIFFmalloc(nbytes);
+               if (tf[2] == NULL)
                        goto bad;
                _TIFFmemcpy(tf[2], tf[0], nbytes);
        }
@@ -135,7 +138,8 @@ TIFFDefaultRefBlackWhite(TIFFDirectory* td)
 {
        int i;
 
-       if (!(td->td_refblackwhite = (float *)_TIFFmalloc(6*sizeof (float))))
+        td->td_refblackwhite = (float *)_TIFFmalloc(6*sizeof (float));
+       if (td->td_refblackwhite == NULL)
                return 0;
         if (td->td_photometric == PHOTOMETRIC_YCBCR) {
                /*
@@ -164,7 +168,7 @@ TIFFDefaultRefBlackWhite(TIFFDirectory* td)
  * value if the tag is not present in the directory.
  *
  * NB: We use the value in the directory, rather than
- *     explcit values so that defaults exist only one
+ *     explicit values so that defaults exist only one
  *     place in the library -- in TIFFDefaultDirectory.
  */
 int
@@ -209,11 +213,18 @@ TIFFVGetFieldDefaulted(TIFF* tif, uint32 tag, va_list ap)
                *va_arg(ap, uint16 *) = td->td_resolutionunit;
                return (1);
        case TIFFTAG_PREDICTOR:
-                {
-                       TIFFPredictorState* sp = (TIFFPredictorState*) tif->tif_data;
-                       *va_arg(ap, uint16*) = (uint16) sp->predictor;
-                       return 1;
-                }
+    {
+        TIFFPredictorState* sp = (TIFFPredictorState*) tif->tif_data;
+        if( sp == NULL )
+        {
+            TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
+                         "Cannot get \"Predictor\" tag as plugin is not configured");
+            *va_arg(ap, uint16*) = 0;
+            return 0;
+        }
+        *va_arg(ap, uint16*) = (uint16) sp->predictor;
+        return 1;
+    }
        case TIFFTAG_DOTRANGE:
                *va_arg(ap, uint16 *) = 0;
                *va_arg(ap, uint16 *) = (1<<td->td_bitspersample)-1;
index c3ff0ff..fffae4a 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_close.c,v 1.19 2010-03-10 18:56:48 bfriesen Exp $ */
+/* $Id: tif_close.c,v 1.21 2016-01-23 21:20:34 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -29,6 +29,7 @@
  */
 
 #include <precomp.h>
+//#include <string.h>
 
 /************************************************************************/
 /*                            TIFFCleanup()                             */
@@ -36,7 +37,7 @@
 
 /**
  * Auxiliary function to free the TIFF structure. Given structure will be
- * completetly freed, so you should save opened file handle and pointer
+ * completely freed, so you should save opened file handle and pointer
  * to the close procedure in external variables before calling
  * _TIFFCleanup(), if you will need these ones to close the file.
  * 
@@ -62,11 +63,11 @@ TIFFCleanup(TIFF* tif)
          */
        while( tif->tif_clientinfo )
        {
-               TIFFClientInfoLink *link = tif->tif_clientinfo;
+               TIFFClientInfoLink *psLink = tif->tif_clientinfo;
 
-               tif->tif_clientinfo = link->next;
-               _TIFFfree( link->name );
-               _TIFFfree( link );
+               tif->tif_clientinfo = psLink->next;
+               _TIFFfree( psLink->name );
+               _TIFFfree( psLink );
        }
 
        if (tif->tif_rawdata && (tif->tif_flags&TIFF_MYBUFFER))
index 037d47a..136a483 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_codec.c,v 1.15 2010-12-14 12:53:00 dron Exp $ */
+/* $Id: tif_codec.c,v 1.17 2015-08-19 02:31:04 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -109,7 +109,7 @@ _notConfigured(TIFF* tif)
        const TIFFCodec* c = TIFFFindCODEC(tif->tif_dir.td_compression);
         char compression_code[20];
         
-        sprintf( compression_code, "%d", tif->tif_dir.td_compression );
+        sprintf(compression_code, "%d",tif->tif_dir.td_compression );
        TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
                      "%s compression support is not configured", 
                      c ? c->name : compression_code );
index 6790907..819f120 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_color.c,v 1.19 2010-12-14 02:22:42 faxguy Exp $ */
+/* $Id: tif_color.c,v 1.22 2016-09-04 21:32:56 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -126,37 +126,37 @@ TIFFCIELabToRGBInit(TIFFCIELabToRGB* cielab,
                    const TIFFDisplay *display, float *refWhite)
 {
        int i;
-       double gamma;
+       double dfGamma;
 
        cielab->range = CIELABTORGB_TABLE_RANGE;
 
        _TIFFmemcpy(&cielab->display, display, sizeof(TIFFDisplay));
 
        /* Red */
-       gamma = 1.0 / cielab->display.d_gammaR ;
+       dfGamma = 1.0 / cielab->display.d_gammaR ;
        cielab->rstep =
                (cielab->display.d_YCR - cielab->display.d_Y0R) / cielab->range;
        for(i = 0; i <= cielab->range; i++) {
                cielab->Yr2r[i] = cielab->display.d_Vrwr
-                   * ((float)pow((double)i / cielab->range, gamma));
+                   * ((float)pow((double)i / cielab->range, dfGamma));
        }
 
        /* Green */
-       gamma = 1.0 / cielab->display.d_gammaG ;
+       dfGamma = 1.0 / cielab->display.d_gammaG ;
        cielab->gstep =
            (cielab->display.d_YCR - cielab->display.d_Y0R) / cielab->range;
        for(i = 0; i <= cielab->range; i++) {
                cielab->Yg2g[i] = cielab->display.d_Vrwg
-                   * ((float)pow((double)i / cielab->range, gamma));
+                   * ((float)pow((double)i / cielab->range, dfGamma));
        }
 
        /* Blue */
-       gamma = 1.0 / cielab->display.d_gammaB ;
+       dfGamma = 1.0 / cielab->display.d_gammaB ;
        cielab->bstep =
            (cielab->display.d_YCR - cielab->display.d_Y0R) / cielab->range;
        for(i = 0; i <= cielab->range; i++) {
                cielab->Yb2b[i] = cielab->display.d_Vrwb
-                   * ((float)pow((double)i / cielab->range, gamma));
+                   * ((float)pow((double)i / cielab->range, dfGamma));
        }
 
        /* Init reference white point */
@@ -175,7 +175,7 @@ TIFFCIELabToRGBInit(TIFFCIELabToRGB* cielab,
 #define        SHIFT                   16
 #define        FIX(x)                  ((int32)((x) * (1L<<SHIFT) + 0.5))
 #define        ONE_HALF                ((int32)(1<<(SHIFT-1)))
-#define        Code2V(c, RB, RW, CR)   ((((c)-(int32)(RB))*(float)(CR))/(float)(((RW)-(RB)) ? ((RW)-(RB)) : 1))
+#define        Code2V(c, RB, RW, CR)   ((((c)-(int32)(RB))*(float)(CR))/(float)(((RW)-(RB)!=0) ? ((RW)-(RB)) : 1))
 #define        CLAMP(f,min,max)        ((f)<(min)?(min):(f)>(max)?(max):(f))
 #define HICLAMP(f,max)         ((f)>(max)?(max):(f))
 
@@ -186,7 +186,9 @@ TIFFYCbCrtoRGB(TIFFYCbCrToRGB *ycbcr, uint32 Y, int32 Cb, int32 Cr,
        int32 i;
 
        /* XXX: Only 8-bit YCbCr input supported for now */
-       Y = HICLAMP(Y, 255), Cb = CLAMP(Cb, 0, 255), Cr = CLAMP(Cr, 0, 255);
+       Y = HICLAMP(Y, 255);
+       Cb = CLAMP(Cb, 0, 255);
+       Cr = CLAMP(Cr, 0, 255);
 
        i = ycbcr->Y_tab[Y] + ycbcr->Cr_r_tab[Cr];
        *r = CLAMP(i, 0, 255);
index 5b1b470..ce3a73f 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_compress.c,v 1.22 2010-03-10 18:56:48 bfriesen Exp $ */
+/* $Id: tif_compress.c,v 1.25 2016-10-25 20:04:22 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -83,10 +83,10 @@ TIFFNoDecode(TIFF* tif, const char* method)
                TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
                             "Compression scheme %u %s decoding is not implemented",
                             tif->tif_dir.td_compression, method);
-       return (-1);
+       return (0);
 }
 
-int
+static int
 _TIFFNoFixupTags(TIFF* tif)
 {
        (void) tif;
@@ -228,7 +228,7 @@ TIFFUnRegisterCODEC(TIFFCodec* c)
        codec_t* cd;
        codec_t** pcd;
 
-       for (pcd = &registeredCODECS; (cd = *pcd); pcd = &cd->next)
+       for (pcd = &registeredCODECS; (cd = *pcd) != NULL; pcd = &cd->next)
                if (cd->info == c) {
                        *pcd = cd->next;
                        _TIFFfree(cd);
index 6565e7c..702b512 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_dir.c,v 1.113 2012-06-14 20:32:53 fwarmerdam Exp $ */
+/* $Id: tif_dir.c,v 1.127 2016-10-25 21:35:15 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
 static void
 setByteArray(void** vpp, void* vp, size_t nmemb, size_t elem_size)
 {
-       if (*vpp)
-               _TIFFfree(*vpp), *vpp = 0;
+       if (*vpp) {
+               _TIFFfree(*vpp);
+               *vpp = 0;
+       }
        if (vp) {
                tmsize_t bytes = (tmsize_t)(nmemb * elem_size);
                if (elem_size && bytes / elem_size == nmemb)
@@ -58,13 +60,13 @@ void _TIFFsetByteArray(void** vpp, void* vp, uint32 n)
     { setByteArray(vpp, vp, n, 1); }
 void _TIFFsetString(char** cpp, char* cp)
     { setByteArray((void**) cpp, (void*) cp, strlen(cp)+1, 1); }
-void _TIFFsetNString(char** cpp, char* cp, uint32 n)
+static void _TIFFsetNString(char** cpp, char* cp, uint32 n)
     { setByteArray((void**) cpp, (void*) cp, n, 1); }
 void _TIFFsetShortArray(uint16** wpp, uint16* wp, uint32 n)
     { setByteArray((void**) wpp, (void*) wp, n, sizeof (uint16)); }
 void _TIFFsetLongArray(uint32** lpp, uint32* lp, uint32 n)
     { setByteArray((void**) lpp, (void*) lp, n, sizeof (uint32)); }
-void _TIFFsetLong8Array(uint64** lpp, uint64* lp, uint32 n)
+static void _TIFFsetLong8Array(uint64** lpp, uint64* lp, uint32 n)
     { setByteArray((void**) lpp, (void*) lp, n, sizeof (uint64)); }
 void _TIFFsetFloatArray(float** fpp, float* fp, uint32 n)
     { setByteArray((void**) fpp, (void*) fp, n, sizeof (float)); }
@@ -161,15 +163,17 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
        TIFFDirectory* td = &tif->tif_dir;
        int status = 1;
        uint32 v32, i, v;
+    double dblval;
        char* s;
        const TIFFField *fip = TIFFFindField(tif, tag, TIFF_ANY);
        uint32 standard_tag = tag;
-
+       if( fip == NULL ) /* cannot happen since OkToChangeTag() already checks it */
+           return 0;
        /*
         * We want to force the custom code to be used for custom
         * fields even if the tag happens to match a well known 
         * one - important for reinterpreted handling of standard
-        * tag values in custom directories (ie. EXIF) 
+        * tag values in custom directories (i.e. EXIF) 
         */
        if (fip->field_bit == FIELD_CUSTOM) {
                standard_tag = 0;
@@ -253,6 +257,28 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
                v = (uint16) va_arg(ap, uint16_vap);
                if (v == 0)
                        goto badvalue;
+        if( v != td->td_samplesperpixel )
+        {
+            /* See http://bugzilla.maptools.org/show_bug.cgi?id=2500 */
+            if( td->td_sminsamplevalue != NULL )
+            {
+                TIFFWarningExt(tif->tif_clientdata,module,
+                    "SamplesPerPixel tag value is changing, "
+                    "but SMinSampleValue tag was read with a different value. Cancelling it");
+                TIFFClrFieldBit(tif,FIELD_SMINSAMPLEVALUE);
+                _TIFFfree(td->td_sminsamplevalue);
+                td->td_sminsamplevalue = NULL;
+            }
+            if( td->td_smaxsamplevalue != NULL )
+            {
+                TIFFWarningExt(tif->tif_clientdata,module,
+                    "SamplesPerPixel tag value is changing, "
+                    "but SMaxSampleValue tag was read with a different value. Cancelling it");
+                TIFFClrFieldBit(tif,FIELD_SMAXSAMPLEVALUE);
+                _TIFFfree(td->td_smaxsamplevalue);
+                td->td_smaxsamplevalue = NULL;
+            }
+        }
                td->td_samplesperpixel = (uint16) v;
                break;
        case TIFFTAG_ROWSPERSTRIP:
@@ -284,10 +310,16 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
                        setDoubleArrayOneValue(&td->td_smaxsamplevalue, va_arg(ap, double), td->td_samplesperpixel);
                break;
        case TIFFTAG_XRESOLUTION:
-               td->td_xresolution = (float) va_arg(ap, double);
+        dblval = va_arg(ap, double);
+        if( dblval < 0 )
+            goto badvaluedouble;
+               td->td_xresolution = (float) dblval;
                break;
        case TIFFTAG_YRESOLUTION:
-               td->td_yresolution = (float) va_arg(ap, double);
+        dblval = va_arg(ap, double);
+        if( dblval < 0 )
+            goto badvaluedouble;
+               td->td_yresolution = (float) dblval;
                break;
        case TIFFTAG_PLANARCONFIG:
                v = (uint16) va_arg(ap, uint16_vap);
@@ -395,7 +427,7 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
                if ((tif->tif_flags & TIFF_INSUBIFD) == 0) {
                        td->td_nsubifd = (uint16) va_arg(ap, uint16_vap);
                        _TIFFsetLong8Array(&td->td_subifd, (uint64*) va_arg(ap, uint64*),
-                           (long) td->td_nsubifd);
+                           (uint32) td->td_nsubifd);
                } else {
                        TIFFErrorExt(tif->tif_clientdata, module,
                                     "%s: Sorry, cannot nest SubIFDs",
@@ -414,7 +446,7 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
                v = (td->td_samplesperpixel - td->td_extrasamples) > 1 ? 3 : 1;
                for (i = 0; i < v; i++)
                        _TIFFsetShortArray(&td->td_transferfunction[i],
-                           va_arg(ap, uint16*), 1L<<td->td_bitspersample);
+                           va_arg(ap, uint16*), 1U<<td->td_bitspersample);
                break;
        case TIFFTAG_REFERENCEBLACKWHITE:
                /* XXX should check for null range */
@@ -450,11 +482,11 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
                 * happens, for example, when tiffcp is used to convert between
                 * compression schemes and codec-specific tags are blindly copied.
                 */
-               if(fip == NULL || fip->field_bit != FIELD_CUSTOM) {
+               if(fip->field_bit != FIELD_CUSTOM) {
                        TIFFErrorExt(tif->tif_clientdata, module,
                            "%s: Invalid %stag \"%s\" (not supported by codec)",
                            tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "",
-                           fip ? fip->field_name : "Unknown");
+                           fip->field_name);
                        status = 0;
                        break;
                }
@@ -572,10 +604,10 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
                                   handled this way ... likely best if we move it into
                                   the directory structure with an explicit field in 
                                   libtiff 4.1 and assign it a FIELD_ value */
-                               uint16 v[2];
-                               v[0] = (uint16)va_arg(ap, int);
-                               v[1] = (uint16)va_arg(ap, int);
-                               _TIFFmemcpy(tv->value, &v, 4);
+                               uint16 v2[2];
+                               v2[0] = (uint16)va_arg(ap, int);
+                               v2[1] = (uint16)va_arg(ap, int);
+                               _TIFFmemcpy(tv->value, &v2, 4);
                        }
 
                        else if (fip->field_passcount
@@ -593,66 +625,66 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
                                case TIFF_BYTE:
                                case TIFF_UNDEFINED:
                                        {
-                                               uint8 v = (uint8)va_arg(ap, int);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               uint8 v2 = (uint8)va_arg(ap, int);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_SBYTE:
                                        {
-                                               int8 v = (int8)va_arg(ap, int);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               int8 v2 = (int8)va_arg(ap, int);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_SHORT:
                                        {
-                                               uint16 v = (uint16)va_arg(ap, int);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               uint16 v2 = (uint16)va_arg(ap, int);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_SSHORT:
                                        {
-                                               int16 v = (int16)va_arg(ap, int);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               int16 v2 = (int16)va_arg(ap, int);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_LONG:
                                case TIFF_IFD:
                                        {
-                                               uint32 v = va_arg(ap, uint32);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               uint32 v2 = va_arg(ap, uint32);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_SLONG:
                                        {
-                                               int32 v = va_arg(ap, int32);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               int32 v2 = va_arg(ap, int32);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_LONG8:
                                case TIFF_IFD8:
                                        {
-                                               uint64 v = va_arg(ap, uint64);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               uint64 v2 = va_arg(ap, uint64);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_SLONG8:
                                        {
-                                               int64 v = va_arg(ap, int64);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               int64 v2 = va_arg(ap, int64);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_RATIONAL:
                                case TIFF_SRATIONAL:
                                case TIFF_FLOAT:
                                        {
-                                               float v = (float)va_arg(ap, double);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               float v2 = (float)va_arg(ap, double);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                case TIFF_DOUBLE:
                                        {
-                                               double v = va_arg(ap, double);
-                                               _TIFFmemcpy(val, &v, tv_size);
+                                               double v2 = va_arg(ap, double);
+                                               _TIFFmemcpy(val, &v2, tv_size);
                                        }
                                        break;
                                default:
@@ -665,9 +697,9 @@ _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
        }
        }
        if (status) {
-               const TIFFField* fip=TIFFFieldWithTag(tif,tag);
-               if (fip)                
-                       TIFFSetFieldBit(tif, fip->field_bit);
+               const TIFFField* fip2=TIFFFieldWithTag(tif,tag);
+               if (fip2)                
+                       TIFFSetFieldBit(tif, fip2->field_bit);
                tif->tif_flags |= TIFF_DIRTYDIRECT;
        }
 
@@ -676,24 +708,34 @@ end:
        return (status);
 badvalue:
         {
-               const TIFFField* fip=TIFFFieldWithTag(tif,tag);
+               const TIFFField* fip2=TIFFFieldWithTag(tif,tag);
                TIFFErrorExt(tif->tif_clientdata, module,
                     "%s: Bad value %u for \"%s\" tag",
                     tif->tif_name, v,
-                    fip ? fip->field_name : "Unknown");
+                    fip2 ? fip2->field_name : "Unknown");
                va_end(ap);
         }
        return (0);
 badvalue32:
         {
-               const TIFFField* fip=TIFFFieldWithTag(tif,tag);
+               const TIFFField* fip2=TIFFFieldWithTag(tif,tag);
                TIFFErrorExt(tif->tif_clientdata, module,
                     "%s: Bad value %u for \"%s\" tag",
                     tif->tif_name, v32,
-                    fip ? fip->field_name : "Unknown");
+                    fip2 ? fip2->field_name : "Unknown");
                va_end(ap);
         }
        return (0);
+badvaluedouble:
+        {
+        const TIFFField* fip2=TIFFFieldWithTag(tif,tag);
+        TIFFErrorExt(tif->tif_clientdata, module,
+             "%s: Bad value %f for \"%s\" tag",
+             tif->tif_name, dblval,
+             fip2 ? fip2->field_name : "Unknown");
+        va_end(ap);
+        }
+    return (0);
 }
 
 /*
@@ -810,12 +852,14 @@ _TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
        int ret_val = 1;
        uint32 standard_tag = tag;
        const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
+       if( fip == NULL ) /* cannot happen since TIFFGetField() already checks it */
+           return 0;
        
        /*
         * We want to force the custom code to be used for custom
         * fields even if the tag happens to match a well known 
         * one - important for reinterpreted handling of standard
-        * tag values in custom directories (ie. EXIF) 
+        * tag values in custom directories (i.e. EXIF) 
         */
        if (fip->field_bit == FIELD_CUSTOM) {
                standard_tag = 0;
@@ -866,7 +910,7 @@ _TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
                                *va_arg(ap, double**) = td->td_sminsamplevalue;
                        else
                        {
-                               /* libtiff historially treats this as a single value. */
+                               /* libtiff historically treats this as a single value. */
                                uint16 i;
                                double v = td->td_sminsamplevalue[0];
                                for (i=1; i < td->td_samplesperpixel; ++i)
@@ -880,7 +924,7 @@ _TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
                                *va_arg(ap, double**) = td->td_smaxsamplevalue;
                        else
                        {
-                               /* libtiff historially treats this as a single value. */
+                               /* libtiff historically treats this as a single value. */
                                uint16 i;
                                double v = td->td_smaxsamplevalue[0];
                                for (i=1; i < td->td_samplesperpixel; ++i)
@@ -1007,14 +1051,14 @@ _TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
                                 * get a tag that is not valid for the image's
                                 * codec then we'll arrive here.
                                 */
-                               if( fip == NULL || fip->field_bit != FIELD_CUSTOM )
+                               if( fip->field_bit != FIELD_CUSTOM )
                                {
                                        TIFFErrorExt(tif->tif_clientdata, "_TIFFVGetField",
                                            "%s: Invalid %stag \"%s\" "
                                            "(not supported by codec)",
                                            tif->tif_name,
                                            isPseudoTag(tag) ? "pseudo-" : "",
-                                           fip ? fip->field_name : "Unknown");
+                                           fip->field_name);
                                        ret_val = 0;
                                        break;
                                }
@@ -1303,8 +1347,20 @@ TIFFDefaultDirectory(TIFF* tif)
        tif->tif_tagmethods.printdir = NULL;
        /*
         *  Give client code a chance to install their own
-        *  tag extensions & methods, prior to compression overloads.
+        *  tag extensions & methods, prior to compression overloads,
+        *  but do some prior cleanup first. (http://trac.osgeo.org/gdal/ticket/5054)
         */
+       if (tif->tif_nfieldscompat > 0) {
+               uint32 i;
+
+               for (i = 0; i < tif->tif_nfieldscompat; i++) {
+                               if (tif->tif_fieldscompat[i].allocated_size)
+                                               _TIFFfree(tif->tif_fieldscompat[i].fields);
+               }
+               _TIFFfree(tif->tif_fieldscompat);
+               tif->tif_nfieldscompat = 0;
+               tif->tif_fieldscompat = NULL;
+       }
        if (_TIFFextender)
                (*_TIFFextender)(tif);
        (void) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
@@ -1345,6 +1401,7 @@ TIFFAdvanceDirectory(TIFF* tif, uint64* nextdir, uint64* off)
                        if (((uint64)poffa!=poff)||(poffb<poffa)||(poffb<(tmsize_t)sizeof(uint16))||(poffb>tif->tif_size))
                        {
                                TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory count");
+                                  *nextdir=0;
                                return(0);
                        }
                        _TIFFmemcpy(&dircount,tif->tif_base+poffa,sizeof(uint16));
@@ -1454,7 +1511,8 @@ TIFFAdvanceDirectory(TIFF* tif, uint64* nextdir, uint64* off)
                                (void) TIFFSeekFile(tif,
                                    dircount16*20, SEEK_CUR);
                        if (!ReadOK(tif, nextdir, sizeof (uint64))) {
-                               TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory link",
+                               TIFFErrorExt(tif->tif_clientdata, module,
+                                             "%s: Error fetching directory link",
                                    tif->tif_name);
                                return (0);
                        }
@@ -1471,6 +1529,7 @@ TIFFAdvanceDirectory(TIFF* tif, uint64* nextdir, uint64* off)
 uint16
 TIFFNumberOfDirectories(TIFF* tif)
 {
+       static const char module[] = "TIFFNumberOfDirectories";
        uint64 nextdir;
        uint16 n;
        if (!(tif->tif_flags&TIFF_BIGTIFF))
@@ -1479,7 +1538,18 @@ TIFFNumberOfDirectories(TIFF* tif)
                nextdir = tif->tif_header.big.tiff_diroff;
        n = 0;
        while (nextdir != 0 && TIFFAdvanceDirectory(tif, &nextdir, NULL))
-               n++;
+        {
+                if (n != 65535) {
+                        ++n;
+                }
+               else
+                {
+                        TIFFErrorExt(tif->tif_clientdata, module,
+                                     "Directory count exceeded 65535 limit,"
+                                     " giving up on counting.");
+                        return (65535);
+                }
+        }
        return (n);
 }
 
index 0e7d340..c703551 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_dirinfo.c,v 1.117 2012-08-19 16:56:34 bfriesen Exp $ */
+/* $Id: tif_dirinfo.c,v 1.126 2016-11-18 02:52:13 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -31,6 +31,7 @@
  */
 
 #include <precomp.h>
+//#include <stdlib.h>
 
 /*
  * NOTE: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG.
  * NOTE: The second field (field_readcount) and third field (field_writecount)
  *       sometimes use the values TIFF_VARIABLE (-1), TIFF_VARIABLE2 (-3)
  *       and TIFF_SPP (-2). The macros should be used but would throw off
- *       the formatting of the code, so please interprete the -1, -2 and -3
+ *       the formatting of the code, so please interpret the -1, -2 and -3
  *       values accordingly.
  */
 
-static TIFFFieldArray tiffFieldArray;
-static TIFFFieldArray exifFieldArray;
-
-static TIFFField
+/* const object should be initialized */
+#ifdef _MSC_VER
+#pragma warning( push )
+#pragma warning( disable : 4132 )
+#endif
+static const TIFFFieldArray tiffFieldArray;
+static const TIFFFieldArray exifFieldArray;
+#ifdef _MSC_VER
+#pragma warning( pop )
+#endif
+
+static const TIFFField
 tiffFields[] = {
        { TIFFTAG_SUBFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "SubfileType", NULL },
        { TIFFTAG_OSUBFILETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "OldSubfileType", NULL },
@@ -95,7 +104,7 @@ tiffFields[] = {
        { TIFFTAG_TILELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileLength", NULL },
        { TIFFTAG_TILEOFFSETS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "TileOffsets", NULL },
        { TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "TileByteCounts", NULL },
-       { TIFFTAG_SUBIFD, -1, -1, TIFF_IFD8, 0, TIFF_SETGET_C16_IFD8, TIFF_SETGET_UNDEFINED, FIELD_SUBIFD, 1, 1, "SubIFD", &tiffFieldArray },
+       { TIFFTAG_SUBIFD, -1, -1, TIFF_IFD8, 0, TIFF_SETGET_C16_IFD8, TIFF_SETGET_UNDEFINED, FIELD_SUBIFD, 1, 1, "SubIFD", (TIFFFieldArray*) &tiffFieldArray },
        { TIFFTAG_INKSET, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InkSet", NULL },
        { TIFFTAG_INKNAMES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_C16_ASCII, TIFF_SETGET_UNDEFINED, FIELD_INKNAMES, 1, 1, "InkNames", NULL },
        { TIFFTAG_NUMBEROFINKS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "NumberOfInks", NULL },
@@ -128,11 +137,13 @@ tiffFields[] = {
        { TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, 0, TIFF_SETGET_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FieldOfViewCotangent", NULL },
        { TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToScreen", NULL },
        { TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToCamera", NULL },
+       { TIFFTAG_CFAREPEATPATTERNDIM, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED,       FIELD_CUSTOM, 0,        0,      "CFARepeatPatternDim", NULL },
+       { TIFFTAG_CFAPATTERN,   4, 4,   TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0,     0,      "CFAPattern" , NULL},
        { TIFFTAG_COPYRIGHT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Copyright", NULL },
        /* end Pixar tags */
        { TIFFTAG_RICHTIFFIPTC, -3, -3, TIFF_LONG, 0, TIFF_SETGET_C32_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "RichTIFFIPTC", NULL },
        { TIFFTAG_PHOTOSHOP, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Photoshop", NULL },
-       { TIFFTAG_EXIFIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "EXIFIFDOffset", &exifFieldArray },
+       { TIFFTAG_EXIFIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "EXIFIFDOffset", (TIFFFieldArray*) &exifFieldArray },
        { TIFFTAG_ICCPROFILE, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ICC Profile", NULL },
        { TIFFTAG_GPSIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GPSIFDOffset", NULL },
        { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvParams", NULL },
@@ -193,23 +204,23 @@ tiffFields[] = {
        { TIFFTAG_PERSAMPLE, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "PerSample", NULL},
        /* end DNG tags */
        /* begin TIFF/FX tags */
-    { TIFFTAG_INDEXED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "Indexed" },
-    { TIFFTAG_GLOBALPARAMETERSIFD, 1, 1, TIFF_IFD, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GlobalParametersIFD", NULL },
-    { TIFFTAG_PROFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ProfileType", NULL },
-    { TIFFTAG_FAXPROFILE, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "FaxProfile", NULL },
-    { TIFFTAG_CODINGMETHODS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CodingMethods", NULL },
-    { TIFFTAG_VERSIONYEAR, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "VersionYear", NULL },
-    { TIFFTAG_MODENUMBER, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ModeNumber", NULL },
-    { TIFFTAG_DECODE, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Decode", NULL },
-    { TIFFTAG_IMAGEBASECOLOR, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ImageBaseColor", NULL },
-    { TIFFTAG_T82OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "T82Options", NULL },
-    { TIFFTAG_STRIPROWCOUNTS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "StripRowCounts", NULL },
-    { TIFFTAG_IMAGELAYER, 2, 2, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ImageLayer", NULL },
-       /* end DNG tags */
+        { TIFFTAG_INDEXED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "Indexed", NULL },
+        { TIFFTAG_GLOBALPARAMETERSIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GlobalParametersIFD", NULL },
+        { TIFFTAG_PROFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ProfileType", NULL },
+        { TIFFTAG_FAXPROFILE, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "FaxProfile", NULL },
+        { TIFFTAG_CODINGMETHODS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CodingMethods", NULL },
+        { TIFFTAG_VERSIONYEAR, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "VersionYear", NULL },
+        { TIFFTAG_MODENUMBER, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ModeNumber", NULL },
+        { TIFFTAG_DECODE, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Decode", NULL },
+        { TIFFTAG_IMAGEBASECOLOR, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ImageBaseColor", NULL },
+        { TIFFTAG_T82OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "T82Options", NULL },
+        { TIFFTAG_STRIPROWCOUNTS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "StripRowCounts", NULL },
+        { TIFFTAG_IMAGELAYER, 2, 2, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ImageLayer", NULL },
+       /* end TIFF/FX tags */
        /* begin pseudo tags */
 };
 
-static TIFFField
+static const TIFFField
 exifFields[] = {
        { EXIFTAG_EXPOSURETIME, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureTime", NULL },
        { EXIFTAG_FNUMBER, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FNumber", NULL },
@@ -269,13 +280,13 @@ exifFields[] = {
        { EXIFTAG_IMAGEUNIQUEID, 33, 33, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageUniqueID", NULL }
 };
 
-static TIFFFieldArray
-tiffFieldArray = { tfiatImage, 0, TIFFArrayCount(tiffFields), tiffFields };
-static TIFFFieldArray
-exifFieldArray = { tfiatExif, 0, TIFFArrayCount(exifFields), exifFields };
+static const TIFFFieldArray
+tiffFieldArray = { tfiatImage, 0, TIFFArrayCount(tiffFields), (TIFFField*) tiffFields };
+static const TIFFFieldArray
+exifFieldArray = { tfiatExif, 0, TIFFArrayCount(exifFields), (TIFFField*) exifFields };
 
 /*
- *  We have our own local lfind() equivelent to avoid subtle differences
+ *  We have our own local lfind() equivalent to avoid subtle differences
  *  in types passed to lfind() on different systems. 
  */
 
@@ -519,7 +530,7 @@ TIFFFindField(TIFF* tif, uint32 tag, TIFFDataType dt)
        return tif->tif_foundfield = (ret ? *ret : NULL);
 }
 
-const TIFFField*
+static const TIFFField*
 _TIFFFindFieldByName(TIFF* tif, const char *field_name, TIFFDataType dt)
 {
        TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL};
@@ -711,7 +722,7 @@ _TIFFCreateAnonField(TIFF *tif, uint32 tag, TIFFDataType field_type)
         * note that this name is a special sign to TIFFClose() and
         * _TIFFSetupFields() to free the field
         */
-       sprintf(fld->field_name, "Tag %d", (int) tag);
+       (void) snprintf(fld->field_name, 32, "Tag %d", (int) tag);
 
        return fld;    
 }
index e7ae094..9c26852 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_dirread.c,v 1.178 2012-08-19 16:56:34 bfriesen Exp $ */
+/* $Id: tif_dirread.c,v 1.204 2016-11-16 15:14:15 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -166,6 +166,8 @@ static int TIFFFetchSubjectDistance(TIFF*, TIFFDirEntry*);
 static void ChopUpSingleUncompressedStrip(TIFF*);
 static uint64 TIFFReadUInt64(const uint8 *value);
 
+static int _TIFFFillStrilesInternal( TIFF *tif, int loadStripByteCount );
+
 typedef union _UInt64Aligned_t
 {
         double d;
@@ -2172,11 +2174,6 @@ static enum TIFFReadDirEntryErr TIFFReadDirEntrySlong8Array(TIFF* tif, TIFFDirEn
                        break;
        }
        _TIFFfree(origdata);
-       if (err!=TIFFReadDirEntryErrOk)
-       {
-               _TIFFfree(data);
-               return(err);
-       }
        *value=data;
        return(TIFFReadDirEntryErrOk);
 }
@@ -2414,11 +2411,6 @@ static enum TIFFReadDirEntryErr TIFFReadDirEntryFloatArray(TIFF* tif, TIFFDirEnt
                        break;
        }
        _TIFFfree(origdata);
-       if (err!=TIFFReadDirEntryErrOk)
-       {
-               _TIFFfree(data);
-               return(err);
-       }
        *value=data;
        return(TIFFReadDirEntryErrOk);
 }
@@ -2657,11 +2649,6 @@ TIFFReadDirEntryDoubleArray(TIFF* tif, TIFFDirEntry* direntry, double** value)
                        break;
        }
        _TIFFfree(origdata);
-       if (err!=TIFFReadDirEntryErrOk)
-       {
-               _TIFFfree(data);
-               return(err);
-       }
        *value=data;
        return(TIFFReadDirEntryErrOk);
 }
@@ -2723,11 +2710,6 @@ static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8Array(TIFF* tif, TIFFDirEntr
                        break;
        }
        _TIFFfree(origdata);
-       if (err!=TIFFReadDirEntryErrOk)
-       {
-               _TIFFfree(data);
-               return(err);
-       }
        *value=data;
        return(TIFFReadDirEntryErrOk);
 }
@@ -3194,11 +3176,7 @@ static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong(int32 value)
 /*
  * Largest 32-bit unsigned integer value.
  */
-#if defined(__WIN32__) && defined(_MSC_VER)
-# define TIFF_UINT32_MAX 0xFFFFFFFFI64
-#else
-# define TIFF_UINT32_MAX 0xFFFFFFFFLL
-#endif
+#define TIFF_UINT32_MAX 0xFFFFFFFFU
 
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeLongLong8(uint64 value)
@@ -3212,7 +3190,7 @@ TIFFReadDirEntryCheckRangeLongLong8(uint64 value)
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeLongSlong8(int64 value)
 {
-       if ((value<0) || (value > TIFF_UINT32_MAX))
+       if ((value < 0) || (value > (int64) TIFF_UINT32_MAX))
                return(TIFFReadDirEntryErrRange);
        else
                return(TIFFReadDirEntryErrOk);
@@ -3229,19 +3207,21 @@ TIFFReadDirEntryCheckRangeSlongLong(uint32 value)
                return(TIFFReadDirEntryErrOk);
 }
 
+/* Check that the 8-byte unsigned value can fit in a 4-byte unsigned range */
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeSlongLong8(uint64 value)
 {
-       if (value > 0x7FFFFFFFUL)
+       if (value > 0x7FFFFFFF)
                return(TIFFReadDirEntryErrRange);
        else
                return(TIFFReadDirEntryErrOk);
 }
 
+/* Check that the 8-byte signed value can fit in a 4-byte signed range */
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeSlongSlong8(int64 value)
 {
-       if ((value < 0L-0x80000000L) || (value > 0x7FFFFFFFL))
+        if ((value < 0-((int64) 0x7FFFFFFF+1)) || (value > 0x7FFFFFFF))
                return(TIFFReadDirEntryErrRange);
        else
                return(TIFFReadDirEntryErrOk);
@@ -3286,11 +3266,7 @@ TIFFReadDirEntryCheckRangeLong8Slong8(int64 value)
 /*
  * Largest 64-bit signed integer value.
  */
-#if defined(__WIN32__) && defined(_MSC_VER)
-# define TIFF_INT64_MAX 0x7FFFFFFFFFFFFFFFI64
-#else
-# define TIFF_INT64_MAX 0x7FFFFFFFFFFFFFFFLL
-#endif
+#define TIFF_INT64_MAX ((int64)(((uint64) ~0) >> 1))
 
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeSlong8Long8(uint64 value)
@@ -3374,7 +3350,7 @@ static void TIFFReadDirEntryOutputErr(TIFF* tif, enum TIFFReadDirEntryErr err, c
        } else {
                switch (err) {
                        case TIFFReadDirEntryErrCount:
-                               TIFFErrorExt(tif->tif_clientdata, module,
+                               TIFFWarningExt(tif->tif_clientdata, module,
                                "Incorrect count for \"%s\"; tag ignored",
                                             tagname);
                                break;
@@ -3430,6 +3406,8 @@ TIFFReadDirectory(TIFF* tif)
        const TIFFField* fip;
        uint32 fii=FAILED_FII;
         toff_t nextdiroff;
+    int bitspersample_read = FALSE;
+
        tif->tif_diroff=tif->tif_nextdiroff;
        if (!TIFFCheckDirOffset(tif,tif->tif_nextdiroff))
                return 0;           /* last offset or bad offset (IFD looping) */
@@ -3481,12 +3459,12 @@ TIFFReadDirectory(TIFF* tif)
         * the fields to check type and tag information,
         * and to extract info required to size data
         * structures.  A second pass is made afterwards
-        * to read in everthing not taken in the first pass.
+        * to read in everything not taken in the first pass.
         * But we must process the Compression tag first
         * in order to merge in codec-private tag definitions (otherwise
         * we may get complaints about unknown tags).  However, the
         * Compression tag may be dependent on the SamplesPerPixel
-        * tag value because older TIFF specs permited Compression
+        * tag value because older TIFF specs permitted Compression
         * to be written as a SamplesPerPixel-count tag entry.
         * Thus if we don't first figure out the correct SamplesPerPixel
         * tag value then we may end up ignoring the Compression tag
@@ -3650,6 +3628,7 @@ TIFFReadDirectory(TIFF* tif)
        if (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE)
                tif->tif_dir.td_stripsperimage /= tif->tif_dir.td_samplesperpixel;
        if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
+#ifdef OJPEG_SUPPORT
                if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG) &&
                    (isTiled(tif)==0) &&
                    (tif->tif_dir.td_nstrips==1)) {
@@ -3662,7 +3641,9 @@ TIFFReadDirectory(TIFF* tif)
                         * JpegInterchangeFormat stream.
                         */
                        TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
-               } else {
+               } else
+#endif
+        {
                        MissingRequired(tif,
                                isTiled(tif) ? "TileOffsets" : "StripOffsets");
                        goto bad;
@@ -3687,7 +3668,7 @@ TIFFReadDirectory(TIFF* tif)
                                 * DataType and SampleFormat tags are supposed to be
                                 * written as one value/sample, but some vendors
                                 * incorrectly write one value only -- so we accept
-                                * that as well (yech). Other vendors write correct
+                                * that as well (yuck). Other vendors write correct
                                 * value for NumberOfSamples, but incorrect one for
                                 * BitsPerSample and friends, and we will read this
                                 * too.
@@ -3706,13 +3687,15 @@ TIFFReadDirectory(TIFF* tif)
                                        }
                                        if (!TIFFSetField(tif,dp->tdir_tag,value))
                                                goto bad;
+                    if( dp->tdir_tag == TIFFTAG_BITSPERSAMPLE )
+                        bitspersample_read = TRUE;
                                }
                                break;
                        case TIFFTAG_SMINSAMPLEVALUE:
                        case TIFFTAG_SMAXSAMPLEVALUE:
                                {
 
-                                       double *data;
+                                       double *data = NULL;
                                        enum TIFFReadDirEntryErr err;
                                        uint32 saved_flags;
                                        int m;
@@ -3763,7 +3746,32 @@ TIFFReadDirectory(TIFF* tif)
                                        uint32 countrequired;
                                        uint32 incrementpersample;
                                        uint16* value=NULL;
-                                       countpersample=(1L<<tif->tif_dir.td_bitspersample);
+                    /* It would be dangerous to instantiate those tag values */
+                    /* since if td_bitspersample has not yet been read (due to */
+                    /* unordered tags), it could be read afterwards with a */
+                    /* values greater than the default one (1), which may cause */
+                    /* crashes in user code */
+                    if( !bitspersample_read )
+                    {
+                        fip = TIFFFieldWithTag(tif,dp->tdir_tag);
+                        TIFFWarningExt(tif->tif_clientdata,module,
+                                       "Ignoring %s since BitsPerSample tag not found",
+                                       fip ? fip->field_name : "unknown tagname");
+                        continue;
+                    }
+                                       /* ColorMap or TransferFunction for high bit */
+                                       /* depths do not make much sense and could be */
+                                       /* used as a denial of service vector */
+                                       if (tif->tif_dir.td_bitspersample > 24)
+                                       {
+                                           fip = TIFFFieldWithTag(tif,dp->tdir_tag);
+                                           TIFFWarningExt(tif->tif_clientdata,module,
+                                               "Ignoring %s because BitsPerSample=%d>24",
+                                               fip ? fip->field_name : "unknown tagname",
+                                               tif->tif_dir.td_bitspersample);
+                                           continue;
+                                       }
+                                       countpersample=(1U<<tif->tif_dir.td_bitspersample);
                                        if ((dp->tdir_tag==TIFFTAG_TRANSFERFUNCTION)&&(dp->tdir_count==(uint64)countpersample))
                                        {
                                                countrequired=countpersample;
@@ -4151,7 +4159,7 @@ TIFFReadDirectoryFindFieldInfo(TIFF* tif, uint16 tagid, uint32* fii)
 }
 
 /*
- * Read custom directory from the arbitarry offset.
+ * Read custom directory from the arbitrary offset.
  * The code is very similar to TIFFReadDirectory().
  */
 int
@@ -4278,7 +4286,9 @@ EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount)
        TIFFDirectory *td = &tif->tif_dir;
        uint32 strip;
 
-    _TIFFFillStriles( tif );
+    /* Do not try to load stripbytecount as we will compute it */
+        if( !_TIFFFillStrilesInternal( tif, 0 ) )
+            return -1;
 
        if (td->td_stripbytecount)
                _TIFFfree(td->td_stripbytecount);
@@ -4300,7 +4310,7 @@ EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount)
                /* calculate amount of space used by indirect values */
                for (dp = dir, n = dircount; n > 0; n--, dp++)
                {
-                       uint32 typewidth = TIFFDataWidth((TIFFDataType) dp->tdir_type);
+                       uint32 typewidth;
                        uint64 datasize;
                        typewidth = TIFFDataWidth((TIFFDataType) dp->tdir_type);
                        if (typewidth == 0) {
@@ -4377,6 +4387,11 @@ TIFFCheckDirOffset(TIFF* tif, uint64 diroff)
 
        if (diroff == 0)                        /* no more directories */
                return 0;
+       if (tif->tif_dirnumber == 65535) {
+           TIFFErrorExt(tif->tif_clientdata, "TIFFCheckDirOffset",
+                        "Cannot handle more than 65535 TIFF directories");
+           return 0;
+       }
 
        for (n = 0; n < tif->tif_dirnumber && tif->tif_dirlist; n++) {
                if (tif->tif_dirlist[n] == diroff)
@@ -4385,7 +4400,7 @@ TIFFCheckDirOffset(TIFF* tif, uint64 diroff)
 
        tif->tif_dirnumber++;
 
-       if (tif->tif_dirnumber > tif->tif_dirlistsize) {
+       if (tif->tif_dirlist == NULL || tif->tif_dirnumber > tif->tif_dirlistsize) {
                uint64* new_dirlist;
 
                /*
@@ -4396,7 +4411,10 @@ TIFFCheckDirOffset(TIFF* tif, uint64 diroff)
                    tif->tif_dirnumber, 2 * sizeof(uint64), "for IFD list");
                if (!new_dirlist)
                        return 0;
-               tif->tif_dirlistsize = 2 * tif->tif_dirnumber;
+               if( tif->tif_dirnumber >= 32768 )
+                   tif->tif_dirlistsize = 65535;
+               else
+                   tif->tif_dirlistsize = 2 * tif->tif_dirnumber;
                tif->tif_dirlist = new_dirlist;
        }
 
@@ -4572,7 +4590,6 @@ TIFFFetchDirectory(TIFF* tif, uint64 diroff, TIFFDirEntry** pdir,
                }
                else
                {
-                       tmsize_t m;
                        uint64 dircount64;
                        m=off+sizeof(uint64);
                        if ((m<off)||(m<(tmsize_t)sizeof(uint64))||(m>tif->tif_size)) {
@@ -4708,6 +4725,7 @@ TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover)
             return 0;
         }
        fip=tif->tif_fields[fii];
+       assert(fip != NULL); /* should not happen */
        assert(fip->set_field_type!=TIFF_SETGET_OTHER);  /* if so, we shouldn't arrive here but deal with this in specialized code */
        assert(fip->set_field_type!=TIFF_SETGET_INT);    /* if so, we shouldn't arrive here as this is only the case for pseudo-tags */
        err=TIFFReadDirEntryErrOk;
@@ -4982,6 +5000,11 @@ TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover)
                                        if (err==TIFFReadDirEntryErrOk)
                                        {
                                                int m;
+                        if( dp->tdir_count > 0 && data[dp->tdir_count-1] != '\0' )
+                        {
+                            TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte. Forcing it to be null",fip->field_name);
+                            data[dp->tdir_count-1] = '\0';
+                        }
                                                m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data);
                                                if (data!=0)
                                                        _TIFFfree(data);
@@ -5154,6 +5177,11 @@ TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover)
                                if (err==TIFFReadDirEntryErrOk)
                                {
                                        int m;
+                    if( dp->tdir_count > 0 && data[dp->tdir_count-1] != '\0' )
+                    {
+                        TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte. Forcing it to be null",fip->field_name);
+                        data[dp->tdir_count-1] = '\0';
+                    }
                                        m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data);
                                        if (data!=0)
                                                _TIFFfree(data);
@@ -5355,7 +5383,7 @@ TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover)
        }
        if (err!=TIFFReadDirEntryErrOk)
        {
-               TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",recover);
+               TIFFReadDirEntryOutputErr(tif,err,module,fip->field_name,recover);
                return(0);
        }
        return(1);
@@ -5557,6 +5585,11 @@ ChopUpSingleUncompressedStrip(TIFF* tif)
 
 int _TIFFFillStriles( TIFF *tif )
 {
+    return _TIFFFillStrilesInternal( tif, 1 );
+}
+
+static int _TIFFFillStrilesInternal( TIFF *tif, int loadStripByteCount )
+{
 #if defined(DEFER_STRILE_LOAD)
         register TIFFDirectory *td = &tif->tif_dir;
         int return_value = 1;
@@ -5573,7 +5606,8 @@ int _TIFFFillStriles( TIFF *tif )
                 return_value = 0;
         }
 
-        if (!TIFFFetchStripThing(tif,&(td->td_stripbytecount_entry),
+        if (loadStripByteCount &&
+            !TIFFFetchStripThing(tif,&(td->td_stripbytecount_entry),
                                  td->td_nstrips,&td->td_stripbytecount))
         {
                 return_value = 0;
@@ -5598,6 +5632,7 @@ int _TIFFFillStriles( TIFF *tif )
         return return_value;
 #else /* !defined(DEFER_STRILE_LOAD) */
         (void) tif;
+        (void) loadStripByteCount;
         return 1;
 #endif 
 }
index 5adadef..ecdab6d 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_dirwrite.c,v 1.77 2012-07-06 19:18:31 bfriesen Exp $ */
+/* $Id: tif_dirwrite.c,v 1.83 2016-10-25 21:35:15 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -543,8 +543,20 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                        {
                                if (!isTiled(tif))
                                {
-                                       if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset))
-                                               goto bad;
+                    /* td_stripoffset might be NULL in an odd OJPEG case. See
+                     *  tif_dirread.c around line 3634.
+                     * XXX: OJPEG hack.
+                     * If a) compression is OJPEG, b) it's not a tiled TIFF,
+                     * and c) the number of strips is 1,
+                     * then we tolerate the absence of stripoffsets tag,
+                     * because, presumably, all required data is in the
+                     * JpegInterchangeFormat stream.
+                     * We can get here when using tiffset on such a file.
+                     * See http://bugzilla.maptools.org/show_bug.cgi?id=2500
+                    */
+                    if (tif->tif_dir.td_stripoffset != NULL &&
+                        !TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset))
+                        goto bad;
                                }
                                else
                                {
@@ -646,7 +658,7 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                                                                        assert(o->field_passcount==0);
                                                                        TIFFGetField(tif,o->field_tag,&pb);
                                                                        pa=(uint32)(strlen(pb));
-                                                                       if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,o->field_tag,pa,pb))
+                                                                       if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,(uint16)o->field_tag,pa,pb))
                                                                                goto bad;
                                                                }
                                                                break;
@@ -657,7 +669,7 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                                                                        assert(o->field_readcount==1);
                                                                        assert(o->field_passcount==0);
                                                                        TIFFGetField(tif,o->field_tag,&p);
-                                                                       if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,o->field_tag,p))
+                                                                       if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,(uint16)o->field_tag,p))
                                                                                goto bad;
                                                                }
                                                                break;
@@ -668,7 +680,7 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                                                                        assert(o->field_readcount==1);
                                                                        assert(o->field_passcount==0);
                                                                        TIFFGetField(tif,o->field_tag,&p);
-                                                                       if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,o->field_tag,p))
+                                                                       if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,(uint16)o->field_tag,p))
                                                                                goto bad;
                                                                }
                                                                break;
@@ -680,7 +692,7 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                                                                        assert(o->field_readcount==TIFF_VARIABLE2);
                                                                        assert(o->field_passcount==1);
                                                                        TIFFGetField(tif,o->field_tag,&pa,&pb);
-                                                                       if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,o->field_tag,pa,pb))
+                                                                       if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,(uint16)o->field_tag,pa,pb))
                                                                                goto bad;
                                                                }
                                                                break;
@@ -694,70 +706,72 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                }
                for (m=0; m<(uint32)(tif->tif_dir.td_customValueCount); m++)
                {
+                        uint16 tag = (uint16)tif->tif_dir.td_customValues[m].info->field_tag;
+                        uint32 count = tif->tif_dir.td_customValues[m].count;
                        switch (tif->tif_dir.td_customValues[m].info->field_type)
                        {
                                case TIFF_ASCII:
-                                       if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_UNDEFINED:
-                                       if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_BYTE:
-                                       if (!TIFFWriteDirectoryTagByteArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagByteArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_SBYTE:
-                                       if (!TIFFWriteDirectoryTagSbyteArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagSbyteArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_SHORT:
-                                       if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_SSHORT:
-                                       if (!TIFFWriteDirectoryTagSshortArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagSshortArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_LONG:
-                                       if (!TIFFWriteDirectoryTagLongArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagLongArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_SLONG:
-                                       if (!TIFFWriteDirectoryTagSlongArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagSlongArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_LONG8:
-                                       if (!TIFFWriteDirectoryTagLong8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagLong8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_SLONG8:
-                                       if (!TIFFWriteDirectoryTagSlong8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagSlong8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_RATIONAL:
-                                       if (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_SRATIONAL:
-                                       if (!TIFFWriteDirectoryTagSrationalArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagSrationalArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_FLOAT:
-                                       if (!TIFFWriteDirectoryTagFloatArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagFloatArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_DOUBLE:
-                                       if (!TIFFWriteDirectoryTagDoubleArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagDoubleArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_IFD:
-                                       if (!TIFFWriteDirectoryTagIfdArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagIfdArray(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                case TIFF_IFD8:
-                                       if (!TIFFWriteDirectoryTagIfdIfd8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value))
+                                       if (!TIFFWriteDirectoryTagIfdIfd8Array(tif,&ndir,dir,tag,count,tif->tif_dir.td_customValues[m].value))
                                                goto bad;
                                        break;
                                default:
@@ -779,7 +793,7 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                                goto bad;
                }
                else
-                       tif->tif_diroff=(TIFFSeekFile(tif,0,SEEK_END)+1)&(~1);
+                       tif->tif_diroff=(TIFFSeekFile(tif,0,SEEK_END)+1)&(~((toff_t)1));
                if (pdiroff!=NULL)
                        *pdiroff=tif->tif_diroff;
                if (!(tif->tif_flags&TIFF_BIGTIFF))
@@ -829,7 +843,7 @@ TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff)
                uint32 nTmp;
                TIFFDirEntry* o;
                n=dirmem;
-               *(uint16*)n=ndir;
+               *(uint16*)n=(uint16)ndir;
                if (tif->tif_flags&TIFF_SWAB)
                        TIFFSwabShort((uint16*)n);
                n+=2;
@@ -2142,13 +2156,13 @@ TIFFWriteDirectoryTagCheckedRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry*
                }
                else if (*na<1.0)
                {
-                       nb[0]=(uint32)((*na)*0xFFFFFFFF);
+                       nb[0]=(uint32)((double)(*na)*0xFFFFFFFF);
                        nb[1]=0xFFFFFFFF;
                }
                else
                {
                        nb[0]=0xFFFFFFFF;
-                       nb[1]=(uint32)(0xFFFFFFFF/(*na));
+                       nb[1]=(uint32)((double)0xFFFFFFFF/(*na));
                }
        }
        if (tif->tif_flags&TIFF_SWAB)
@@ -2185,13 +2199,13 @@ TIFFWriteDirectoryTagCheckedSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry
                        }
                        else if (*na>-1.0)
                        {
-                               nb[0]=-(int32)((-*na)*0x7FFFFFFF);
+                               nb[0]=-(int32)((double)(-*na)*0x7FFFFFFF);
                                nb[1]=0x7FFFFFFF;
                        }
                        else
                        {
                                nb[0]=-0x7FFFFFFF;
-                               nb[1]=(int32)(0x7FFFFFFF/(-*na));
+                               nb[1]=(int32)((double)0x7FFFFFFF/(-*na));
                        }
                }
                else
@@ -2203,13 +2217,13 @@ TIFFWriteDirectoryTagCheckedSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry
                        }
                        else if (*na<1.0)
                        {
-                               nb[0]=(int32)((*na)*0x7FFFFFFF);
+                               nb[0]=(int32)((double)(*na)*0x7FFFFFFF);
                                nb[1]=0x7FFFFFFF;
                        }
                        else
                        {
                                nb[0]=0x7FFFFFFF;
-                               nb[1]=(int32)(0x7FFFFFFF/(*na));
+                               nb[1]=(int32)((double)0x7FFFFFFF/(*na));
                        }
                }
        }
@@ -2369,7 +2383,7 @@ TIFFLinkDirectory(TIFF* tif)
 {
        static const char module[] = "TIFFLinkDirectory";
 
-       tif->tif_diroff = (TIFFSeekFile(tif,0,SEEK_END)+1) &~ 1;
+       tif->tif_diroff = (TIFFSeekFile(tif,0,SEEK_END)+1) & (~((toff_t)1));
 
        /*
         * Handle SubIFDs
@@ -2840,14 +2854,15 @@ _TIFFRewriteField(TIFF* tif, uint16 tag, TIFFDataType in_datatype,
                          "Error writing directory link");
             return (0);
         }
-        
-        _TIFFfree( buf_to_write );
     }
     else
     {
         memcpy( &entry_offset, buf_to_write, count*TIFFDataWidth(datatype));
     }
 
+    _TIFFfree( buf_to_write );
+    buf_to_write = 0;
+
 /* -------------------------------------------------------------------- */
 /*      Adjust the directory entry.                                     */
 /* -------------------------------------------------------------------- */
index 6398758..1e1425a 100644 (file)
@@ -1,4 +1,4 @@
-/* $Header: /cvs/maptools/cvsroot/libtiff/libtiff/tif_dumpmode.c,v 1.14 2011-04-02 20:54:09 bfriesen Exp $ */
+/* $Header: /cvs/maptools/cvsroot/libtiff/libtiff/tif_dumpmode.c,v 1.15 2015-12-12 18:04:26 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -67,7 +67,7 @@ DumpModeEncode(TIFF* tif, uint8* pp, tmsize_t cc, uint16 s)
                cc -= n;
                if (tif->tif_rawcc >= tif->tif_rawdatasize &&
                    !TIFFFlushData1(tif))
-                       return (-1);
+                       return (0);
        }
        return (1);
 }
index c756616..c10fa34 100644 (file)
@@ -1,4 +1,4 @@
-/* $Header: /cvs/maptools/cvsroot/libtiff/libtiff/tif_extension.c,v 1.7 2010-03-10 18:56:48 bfriesen Exp $ */
+/* $Header: /cvs/maptools/cvsroot/libtiff/libtiff/tif_extension.c,v 1.8 2015-12-06 11:13:43 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -66,13 +66,13 @@ TIFFTagMethods *TIFFAccessTagMethods( TIFF *tif )
 void *TIFFGetClientInfo( TIFF *tif, const char *name )
 
 {
-    TIFFClientInfoLink *link = tif->tif_clientinfo;
+    TIFFClientInfoLink *psLink = tif->tif_clientinfo;
 
-    while( link != NULL && strcmp(link->name,name) != 0 )
-        link = link->next;
+    while( psLink != NULL && strcmp(psLink->name,name) != 0 )
+        psLink = psLink->next;
 
-    if( link != NULL )
-        return link->data;
+    if( psLink != NULL )
+        return psLink->data;
     else
         return NULL;
 }
@@ -80,18 +80,18 @@ void *TIFFGetClientInfo( TIFF *tif, const char *name )
 void TIFFSetClientInfo( TIFF *tif, void *data, const char *name )
 
 {
-    TIFFClientInfoLink *link = tif->tif_clientinfo;
+    TIFFClientInfoLink *psLink = tif->tif_clientinfo;
 
     /*
     ** Do we have an existing link with this name?  If so, just
     ** set it.
     */
-    while( link != NULL && strcmp(link->name,name) != 0 )
-        link = link->next;
+    while( psLink != NULL && strcmp(psLink->name,name) != 0 )
+        psLink = psLink->next;
 
-    if( link != NULL )
+    if( psLink != NULL )
     {
-        link->data = data;
+        psLink->data = data;
         return;
     }
 
@@ -99,15 +99,15 @@ void TIFFSetClientInfo( TIFF *tif, void *data, const char *name )
     ** Create a new link.
     */
 
-    link = (TIFFClientInfoLink *) _TIFFmalloc(sizeof(TIFFClientInfoLink));
-    assert (link != NULL);
-    link->next = tif->tif_clientinfo;
-    link->name = (char *) _TIFFmalloc((tmsize_t)(strlen(name)+1));
-    assert (link->name != NULL);
-    strcpy(link->name, name);
-    link->data = data;
+    psLink = (TIFFClientInfoLink *) _TIFFmalloc(sizeof(TIFFClientInfoLink));
+    assert (psLink != NULL);
+    psLink->next = tif->tif_clientinfo;
+    psLink->name = (char *) _TIFFmalloc((tmsize_t)(strlen(name)+1));
+    assert (psLink->name != NULL);
+    strcpy(psLink->name, name);
+    psLink->data = data;
 
-    tif->tif_clientinfo = link;
+    tif->tif_clientinfo = psLink;
 }
 /*
  * Local Variables:
index df62740..cee03ce 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_fax3.c,v 1.74 2012-06-21 02:01:31 fwarmerdam Exp $ */
+/* $Id: tif_fax3.c,v 1.78 2016-09-04 21:32:56 erouault Exp $ */
 
 /*
  * Copyright (c) 1990-1997 Sam Leffler
@@ -443,8 +443,9 @@ _TIFFFax3fillruns(unsigned char* buf, uint32* runs, uint32* erun, uint32 lastx)
                        FILL(n, cp);
                        run &= 7;
                    }
+                    /* Explicit 0xff masking to make icc -check=conversions happy */
                    if (run)
-                       cp[0] |= 0xff00 >> run;
+                       cp[0] = (unsigned char)((cp[0] | (0xff00 >> run))&0xff);
                } else
                    cp[0] |= _fillmasks[run]>>bx;
                x += runs[1];
@@ -644,7 +645,8 @@ putspan(TIFF* tif, int32 span, const tableentry* tab)
 
        while (span >= 2624) {
                const tableentry* te = &tab[63 + (2560>>6)];
-               code = te->code, length = te->length;
+               code = te->code;
+               length = te->length;
 #ifdef FAX3_DEBUG
                DEBUG_PRINT("MakeUp", te->runlen);
 #endif
@@ -654,14 +656,16 @@ putspan(TIFF* tif, int32 span, const tableentry* tab)
        if (span >= 64) {
                const tableentry* te = &tab[63 + (span>>6)];
                assert(te->runlen == 64*(span>>6));
-               code = te->code, length = te->length;
+               code = te->code;
+               length = te->length;
 #ifdef FAX3_DEBUG
                DEBUG_PRINT("MakeUp", te->runlen);
 #endif
                _PutBits(tif, code, length);
                span -= te->runlen;
        }
-       code = tab[span].code, length = tab[span].length;
+       code = tab[span].code;
+       length = tab[span].length;
 #ifdef FAX3_DEBUG
        DEBUG_PRINT("  Term", tab[span].runlen);
 #endif
@@ -697,14 +701,16 @@ Fax3PutEOL(TIFF* tif)
                                align = sp->bit + (8 - align);
                        else
                                align = sp->bit - align;
-                       code = 0;
                        tparm=align; 
                        _PutBits(tif, 0, tparm);
                }
        }
-       code = EOL, length = 12;
-       if (is2DEncoding(sp))
-               code = (code<<1) | (sp->tag == G3_1D), length++;
+       code = EOL;
+       length = 12;
+       if (is2DEncoding(sp)) {
+               code = (code<<1) | (sp->tag == G3_1D);
+               length++;
+       }
        _PutBits(tif, code, length);
 
        sp->data = data;
@@ -815,7 +821,7 @@ find0span(unsigned char* bp, int32 bs, int32 be)
        /*
         * Check partial byte on lhs.
         */
-       if (bits > 0 && (n = (bs & 7))) {
+       if (bits > 0 && (n = (bs & 7)) != 0) {
                span = zeroruns[(*bp << n) & 0xff];
                if (span > 8-n)         /* table value too generous */
                        span = 8-n;
@@ -835,12 +841,14 @@ find0span(unsigned char* bp, int32 bs, int32 be)
                while (!isAligned(bp, long)) {
                        if (*bp != 0x00)
                                return (span + zeroruns[*bp]);
-                       span += 8, bits -= 8;
+                       span += 8;
+                       bits -= 8;
                        bp++;
                }
                lp = (long*) bp;
                while ((bits >= (int32)(8 * sizeof(long))) && (0 == *lp)) {
-                       span += 8*sizeof (long), bits -= 8*sizeof (long);
+                       span += 8*sizeof (long);
+                       bits -= 8*sizeof (long);
                        lp++;
                }
                bp = (unsigned char*) lp;
@@ -851,7 +859,8 @@ find0span(unsigned char* bp, int32 bs, int32 be)
        while (bits >= 8) {
                if (*bp != 0x00)        /* end of run */
                        return (span + zeroruns[*bp]);
-               span += 8, bits -= 8;
+               span += 8;
+               bits -= 8;
                bp++;
        }
        /*
@@ -874,7 +883,7 @@ find1span(unsigned char* bp, int32 bs, int32 be)
        /*
         * Check partial byte on lhs.
         */
-       if (bits > 0 && (n = (bs & 7))) {
+       if (bits > 0 && (n = (bs & 7)) != 0) {
                span = oneruns[(*bp << n) & 0xff];
                if (span > 8-n)         /* table value too generous */
                        span = 8-n;
@@ -894,12 +903,14 @@ find1span(unsigned char* bp, int32 bs, int32 be)
                while (!isAligned(bp, long)) {
                        if (*bp != 0xff)
                                return (span + oneruns[*bp]);
-                       span += 8, bits -= 8;
+                       span += 8;
+                       bits -= 8;
                        bp++;
                }
                lp = (long*) bp;
                while ((bits >= (int32)(8 * sizeof(long))) && (~0 == *lp)) {
-                       span += 8*sizeof (long), bits -= 8*sizeof (long);
+                       span += 8*sizeof (long);
+                       bits -= 8*sizeof (long);
                        lp++;
                }
                bp = (unsigned char*) lp;
@@ -910,7 +921,8 @@ find1span(unsigned char* bp, int32 bs, int32 be)
        while (bits >= 8) {
                if (*bp != 0xff)        /* end of run */
                        return (span + oneruns[*bp]);
-               span += 8, bits -= 8;
+               span += 8;
+               bits -= 8;
                bp++;
        }
        /*
@@ -1094,8 +1106,10 @@ Fax3Close(TIFF* tif)
                unsigned int length = 12;
                int i;
 
-               if (is2DEncoding(sp))
-                       code = (code<<1) | (sp->tag == G3_1D), length++;
+               if (is2DEncoding(sp)) {
+                       code = (code<<1) | (sp->tag == G3_1D);
+                       length++;
+               }
                for (i = 0; i < 6; i++)
                        Fax3PutBits(tif, code, length);
                Fax3FlushBits(tif, sp);
@@ -1182,7 +1196,7 @@ Fax3VSetField(TIFF* tif, uint32 tag, va_list ap)
                return (*sp->vsetparent)(tif, tag, ap);
        }
        
-       if ((fip = TIFFFieldWithTag(tif, tag)))
+       if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
                TIFFSetFieldBit(tif, fip->field_bit);
        else
                return 0;
@@ -1241,10 +1255,14 @@ Fax3PrintDir(TIFF* tif, FILE* fd, long flags)
                } else {
 
                        fprintf(fd, "  Group 3 Options:");
-                       if (sp->groupoptions & GROUP3OPT_2DENCODING)
-                               fprintf(fd, "%s2-d encoding", sep), sep = "+";
-                       if (sp->groupoptions & GROUP3OPT_FILLBITS)
-                               fprintf(fd, "%sEOL padding", sep), sep = "+";
+                       if (sp->groupoptions & GROUP3OPT_2DENCODING) {
+                               fprintf(fd, "%s2-d encoding", sep);
+                               sep = "+";
+                       }
+                       if (sp->groupoptions & GROUP3OPT_FILLBITS) {
+                               fprintf(fd, "%sEOL padding", sep);
+                               sep = "+";
+                       }
                        if (sp->groupoptions & GROUP3OPT_UNCOMPRESSED)
                                fprintf(fd, "%suncompressed data", sep);
                }
index 1a3089c..2c600d0 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_getimage.c,v 1.82 2012-06-06 00:17:49 fwarmerdam Exp $ */
+/* $Id: tif_getimage.c,v 1.98 2016-11-18 02:47:45 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1991-1997 Sam Leffler
@@ -31,6 +31,7 @@
  */
 
 #include <precomp.h>
+//#include <stdio.h>
 
 static int gtTileContig(TIFFRGBAImage*, uint32*, uint32, uint32);
 static int gtTileSeparate(TIFFRGBAImage*, uint32*, uint32, uint32);
@@ -95,6 +96,10 @@ TIFFRGBAImageOK(TIFF* tif, char emsg[1024])
                            td->td_bitspersample);
                        return (0);
        }
+        if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP) {
+                sprintf(emsg, "Sorry, can not handle images with IEEE floating-point samples");
+                return (0);
+        }
        colorchannels = td->td_samplesperpixel - td->td_extrasamples;
        if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) {
                switch (colorchannels) {
@@ -182,10 +187,25 @@ TIFFRGBAImageOK(TIFF* tif, char emsg[1024])
                                    "Planarconfiguration", td->td_planarconfig);
                                return (0);
                        }
+                       if ( td->td_samplesperpixel != 3 || colorchannels != 3 ) {
+                                sprintf(emsg,
+                                        "Sorry, can not handle image with %s=%d, %s=%d",
+                                        "Samples/pixel", td->td_samplesperpixel,
+                                        "colorchannels", colorchannels);
+                                return 0;
+                        }
                        break;
                case PHOTOMETRIC_CIELAB:
+                        if ( td->td_samplesperpixel != 3 || colorchannels != 3 || td->td_bitspersample != 8 ) {
+                                sprintf(emsg,
+                                        "Sorry, can not handle image with %s=%d, %s=%d and %s=%d",
+                                        "Samples/pixel", td->td_samplesperpixel,
+                                        "colorchannels", colorchannels,
+                                        "Bits/sample", td->td_bitspersample);
+                                return 0;
+                        }
                        break;
-               default:
+                default:
                        sprintf(emsg, "Sorry, can not handle image with %s=%d",
                            photoTag, photometric);
                        return (0);
@@ -196,20 +216,34 @@ TIFFRGBAImageOK(TIFF* tif, char emsg[1024])
 void
 TIFFRGBAImageEnd(TIFFRGBAImage* img)
 {
-       if (img->Map)
-               _TIFFfree(img->Map), img->Map = NULL;
-       if (img->BWmap)
-               _TIFFfree(img->BWmap), img->BWmap = NULL;
-       if (img->PALmap)
-               _TIFFfree(img->PALmap), img->PALmap = NULL;
-       if (img->ycbcr)
-               _TIFFfree(img->ycbcr), img->ycbcr = NULL;
-       if (img->cielab)
-               _TIFFfree(img->cielab), img->cielab = NULL;
-       if (img->UaToAa)
-               _TIFFfree(img->UaToAa), img->UaToAa = NULL;
-       if (img->Bitdepth16To8)
-               _TIFFfree(img->Bitdepth16To8), img->Bitdepth16To8 = NULL;
+       if (img->Map) {
+               _TIFFfree(img->Map);
+               img->Map = NULL;
+       }
+       if (img->BWmap) {
+               _TIFFfree(img->BWmap);
+               img->BWmap = NULL;
+       }
+       if (img->PALmap) {
+               _TIFFfree(img->PALmap);
+               img->PALmap = NULL;
+       }
+       if (img->ycbcr) {
+               _TIFFfree(img->ycbcr);
+               img->ycbcr = NULL;
+       }
+       if (img->cielab) {
+               _TIFFfree(img->cielab);
+               img->cielab = NULL;
+       }
+       if (img->UaToAa) {
+               _TIFFfree(img->UaToAa);
+               img->UaToAa = NULL;
+       }
+       if (img->Bitdepth16To8) {
+               _TIFFfree(img->Bitdepth16To8);
+               img->Bitdepth16To8 = NULL;
+       }
 
        if( img->redcmap ) {
                _TIFFfree( img->redcmap );
@@ -240,6 +274,9 @@ TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024])
        int colorchannels;
        uint16 *red_orig, *green_orig, *blue_orig;
        int n_color;
+       
+       if( !TIFFRGBAImageOK(tif, emsg) )
+               return 0;
 
        /* Initialize to normal values */
        img->row_offset = 0;
@@ -323,7 +360,7 @@ TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024])
                        }
 
                        /* copy the colormaps so we can modify them */
-                       n_color = (1L << img->bitspersample);
+                       n_color = (1U << img->bitspersample);
                        img->redcmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color);
                        img->greencmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color);
                        img->bluecmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color);
@@ -336,7 +373,7 @@ TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024])
                        _TIFFmemcpy( img->greencmap, green_orig, n_color * 2 );
                        _TIFFmemcpy( img->bluecmap, blue_orig, n_color * 2 );
 
-                       /* fall thru... */
+                       /* fall through... */
                case PHOTOMETRIC_MINISWHITE:
                case PHOTOMETRIC_MINISBLACK:
                        if (planarconfig == PLANARCONFIG_CONTIG
@@ -494,7 +531,7 @@ TIFFReadRGBAImageOriented(TIFF* tif,
     int ok;
 
        if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop, emsg)) {
-               img.req_orientation = orientation;
+               img.req_orientation = (uint16)orientation;
                /* XXX verify rwidth and rheight against width and height */
                ok = TIFFRGBAImageGet(&img, raster+(rheight-img.height)*rwidth,
                        rwidth, img.height);
@@ -597,6 +634,10 @@ gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
     int32 fromskew, toskew;
     uint32 nrow;
     int ret = 1, flip;
+    uint32 this_tw, tocol;
+    int32 this_toskew, leftmost_toskew;
+    int32 leftmost_fromskew;
+    uint32 leftmost_tw;
 
     buf = (unsigned char*) _TIFFmalloc(TIFFTileSize(tif));
     if (buf == 0) {
@@ -617,37 +658,50 @@ gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
            toskew = -(int32)(tw - w);
     }
      
+    /*
+     * Leftmost tile is clipped on left side if col_offset > 0.
+     */
+    leftmost_fromskew = img->col_offset % tw;
+    leftmost_tw = tw - leftmost_fromskew;
+    leftmost_toskew = toskew + leftmost_fromskew;
     for (row = 0; row < h; row += nrow)
     {
         rowstoread = th - (row + img->row_offset) % th;
        nrow = (row + rowstoread > h ? h - row : rowstoread);
-       for (col = 0; col < w; col += tw) 
+       fromskew = leftmost_fromskew;
+       this_tw = leftmost_tw;
+       this_toskew = leftmost_toskew;
+       tocol = 0;
+       col = img->col_offset;
+       while (tocol < w)
         {
-           if (TIFFReadTile(tif, buf, col+img->col_offset,  
+           if (TIFFReadTile(tif, buf, col,  
                             row+img->row_offset, 0, 0)==(tmsize_t)(-1) && img->stoponerr)
             {
                 ret = 0;
                 break;
             }
-           
-           pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif);  
-
-           if (col + tw > w) 
-            {
-                /*
-                 * Tile is clipped horizontally.  Calculate
-                 * visible portion and skewing factors.
-                 */
-                uint32 npix = w - col;
-                fromskew = tw - npix;
-                (*put)(img, raster+y*w+col, col, y,
-                       npix, nrow, fromskew, toskew + fromskew, buf + pos);
-            }
-            else 
-            {
-                (*put)(img, raster+y*w+col, col, y, tw, nrow, 0, toskew, buf + pos);
-            }
-        }
+            pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \
+                  ((tmsize_t) fromskew * img->samplesperpixel);
+           if (tocol + this_tw > w) 
+           {
+               /*
+                * Rightmost tile is clipped on right side.
+                */
+               fromskew = tw - (w - tocol);
+               this_tw = tw - fromskew;
+               this_toskew = toskew + fromskew;
+           }
+           (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos);
+           tocol += this_tw;
+           col += this_tw;
+           /*
+            * After the leftmost tile, tiles are no longer clipped on left side.
+            */
+           fromskew = 0;
+           this_tw = tw;
+           this_toskew = toskew;
+       }
 
         y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
     }
@@ -664,7 +718,8 @@ gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                            uint32 temp = *left;
                            *left = *right;
                            *right = temp;
-                           left++, right--;
+                           left++;
+                               right--;
                    }
            }
     }
@@ -697,7 +752,11 @@ gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
        int alpha = img->alpha;
        uint32 nrow;
        int ret = 1, flip;
-        int colorchannels;
+        uint16 colorchannels;
+       uint32 this_tw, tocol;
+       int32 this_toskew, leftmost_toskew;
+       int32 leftmost_fromskew;
+       uint32 leftmost_tw;
 
        tilesize = TIFFTileSize(tif);  
        bufsize = TIFFSafeMultiply(tmsize_t,alpha?4:3,tilesize);
@@ -742,20 +801,31 @@ gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
             break;
         }
 
+       /*
+        *      Leftmost tile is clipped on left side if col_offset > 0.
+        */
+       leftmost_fromskew = img->col_offset % tw;
+       leftmost_tw = tw - leftmost_fromskew;
+       leftmost_toskew = toskew + leftmost_fromskew;
        for (row = 0; row < h; row += nrow)
        {
                rowstoread = th - (row + img->row_offset) % th;
                nrow = (row + rowstoread > h ? h - row : rowstoread);
-               for (col = 0; col < w; col += tw)
+               fromskew = leftmost_fromskew;
+               this_tw = leftmost_tw;
+               this_toskew = leftmost_toskew;
+               tocol = 0;
+               col = img->col_offset;
+               while (tocol < w)
                {
-                       if (TIFFReadTile(tif, p0, col+img->col_offset,  
+                       if (TIFFReadTile(tif, p0, col,  
                            row+img->row_offset,0,0)==(tmsize_t)(-1) && img->stoponerr)
                        {
                                ret = 0;
                                break;
                        }
                        if (colorchannels > 1 
-                            && TIFFReadTile(tif, p1, col+img->col_offset,  
+                            && TIFFReadTile(tif, p1, col,  
                                             row+img->row_offset,0,1) == (tmsize_t)(-1) 
                             && img->stoponerr)
                        {
@@ -763,7 +833,7 @@ gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                                break;
                        }
                        if (colorchannels > 1 
-                            && TIFFReadTile(tif, p2, col+img->col_offset,  
+                            && TIFFReadTile(tif, p2, col,  
                                             row+img->row_offset,0,2) == (tmsize_t)(-1) 
                             && img->stoponerr)
                        {
@@ -771,7 +841,7 @@ gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                                break;
                        }
                        if (alpha
-                            && TIFFReadTile(tif,pa,col+img->col_offset,  
+                            && TIFFReadTile(tif,pa,col,  
                                             row+img->row_offset,0,colorchannels) == (tmsize_t)(-1) 
                             && img->stoponerr)
                         {
@@ -779,23 +849,27 @@ gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                             break;
                        }
 
-                       pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif);  
-
-                       if (col + tw > w)
+                       pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \
+                          ((tmsize_t) fromskew * img->samplesperpixel);
+                       if (tocol + this_tw > w) 
                        {
                                /*
-                                * Tile is clipped horizontally.  Calculate
-                                * visible portion and skewing factors.
+                                * Rightmost tile is clipped on right side.
                                 */
-                               uint32 npix = w - col;
-                               fromskew = tw - npix;
-                               (*put)(img, raster+y*w+col, col, y,
-                                   npix, nrow, fromskew, toskew + fromskew,
-                                   p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
-                       } else {
-                               (*put)(img, raster+y*w+col, col, y,
-                                   tw, nrow, 0, toskew, p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
+                               fromskew = tw - (w - tocol);
+                               this_tw = tw - fromskew;
+                               this_toskew = toskew + fromskew;
                        }
+                       (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, \
+                               p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
+                       tocol += this_tw;
+                       col += this_tw;
+                       /*
+                       * After the leftmost tile, tiles are no longer clipped on left side.
+                       */
+                       fromskew = 0;
+                       this_tw = tw;
+                       this_toskew = toskew;
                }
 
                y += (flip & FLIP_VERTICALLY ?-(int32) nrow : (int32) nrow);
@@ -812,7 +886,8 @@ gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                                uint32 temp = *left;
                                *left = *right;
                                *right = temp;
-                               left++, right--;
+                               left++;
+                               right--;
                        }
                }
        }
@@ -842,6 +917,12 @@ gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
        int32 fromskew, toskew;
        int ret = 1, flip;
 
+       TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver);
+       if( subsamplingver == 0 ) {
+               TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Invalid vertical YCbCr subsampling");
+               return (0);
+       }
+
        buf = (unsigned char*) _TIFFmalloc(TIFFStripSize(tif));
        if (buf == 0) {
                TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "No space for strip buffer");
@@ -859,7 +940,7 @@ gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
        }
 
        TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
-       TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver);
+
        scanline = TIFFScanlineSize(tif);
        fromskew = (w < imagewidth ? imagewidth - w : 0);
        for (row = 0; row < h; row += nrow)
@@ -879,7 +960,8 @@ gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                        break;
                }
 
-               pos = ((row + img->row_offset) % rowsperstrip) * scanline;
+               pos = ((row + img->row_offset) % rowsperstrip) * scanline + \
+                       ((tmsize_t) img->col_offset * img->samplesperpixel);
                (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos);
                y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
        }
@@ -895,7 +977,8 @@ gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                                uint32 temp = *left;
                                *left = *right;
                                *right = temp;
-                               left++, right--;
+                               left++;
+                               right--;
                        }
                }
        }
@@ -926,7 +1009,8 @@ gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
        tmsize_t bufsize;
        int32 fromskew, toskew;
        int alpha = img->alpha;
-       int ret = 1, flip, colorchannels;
+       int ret = 1, flip;
+        uint16 colorchannels;
 
        stripsize = TIFFStripSize(tif);  
        bufsize = TIFFSafeMultiply(tmsize_t,alpha?4:3,stripsize);
@@ -1010,7 +1094,8 @@ gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                        }
                }
 
-               pos = ((row + img->row_offset) % rowsperstrip) * scanline;
+               pos = ((row + img->row_offset) % rowsperstrip) * scanline + \
+                       ((tmsize_t) img->col_offset * img->samplesperpixel);
                (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos,
                    p2 + pos, (alpha?(pa+pos):NULL));
                y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
@@ -1027,7 +1112,8 @@ gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h)
                                uint32 temp = *left;
                                *left = *right;
                                *right = temp;
-                               left++, right--;
+                               left++;
+                               right--;
                        }
                }
        }
@@ -1355,7 +1441,7 @@ DECLAREContigPutFunc(putRGBUAcontig8bittile)
                uint8* m;
                for (x = w; x-- > 0;) {
                        a = pp[3];
-                       m = img->UaToAa+(a<<8);
+                       m = img->UaToAa+((size_t) a<<8);
                        r = m[pp[0]];
                        g = m[pp[1]];
                        b = m[pp[2]];
@@ -1426,7 +1512,7 @@ DECLAREContigPutFunc(putRGBUAcontig16bittile)
                uint8* m;
                for (x = w; x-- > 0;) {
                        a = img->Bitdepth16To8[wp[3]];
-                       m = img->UaToAa+(a<<8);
+                       m = img->UaToAa+((size_t) a<<8);
                        r = m[img->Bitdepth16To8[wp[0]]];
                        g = m[img->Bitdepth16To8[wp[1]]];
                        b = m[img->Bitdepth16To8[wp[2]]];
@@ -1557,7 +1643,7 @@ DECLARESepPutFunc(putRGBUAseparate8bittile)
                uint8* m;
                for (x = w; x-- > 0;) {
                        av = *a++;
-                       m = img->UaToAa+(av<<8);
+                       m = img->UaToAa+((size_t) av<<8);
                        rv = m[*r++];
                        gv = m[*g++];
                        bv = m[*b++];
@@ -1619,15 +1705,15 @@ DECLARESepPutFunc(putRGBUAseparate16bittile)
        uint16 *wa = (uint16*) a;
        (void) img; (void) y;
        while (h-- > 0) {
-               uint32 r,g,b,a;
+               uint32 r2,g2,b2,a2;
                uint8* m;
                for (x = w; x-- > 0;) {
-                       a = img->Bitdepth16To8[*wa++];
-                       m = img->UaToAa+(a<<8);
-                       r = m[img->Bitdepth16To8[*wr++]];
-                       g = m[img->Bitdepth16To8[*wg++]];
-                       b = m[img->Bitdepth16To8[*wb++]];
-                       *cp++ = PACK4(r,g,b,a);
+                       a2 = img->Bitdepth16To8[*wa++];
+                       m = img->UaToAa+((size_t) a2<<8);
+                       r2 = m[img->Bitdepth16To8[*wr++]];
+                       g2 = m[img->Bitdepth16To8[*wg++]];
+                       b2 = m[img->Bitdepth16To8[*wb++]];
+                       *cp++ = PACK4(r2,g2,b2,a2);
                }
                SKEW4(wr, wg, wb, wa, fromskew);
                cp += toskew;
@@ -1782,10 +1868,16 @@ DECLAREContigPutFunc(putcontig8bitYCbCr44tile)
                 YCbCrtoRGB(cp3[2], pp[14]);
                 YCbCrtoRGB(cp3[3], pp[15]);
 
-                cp += 4, cp1 += 4, cp2 += 4, cp3 += 4;
+                cp += 4;
+                cp1 += 4;
+                cp2 += 4;
+                cp3 += 4;
                 pp += 18;
             } while (--x);
-            cp += incr, cp1 += incr, cp2 += incr, cp3 += incr;
+            cp += incr;
+            cp1 += incr;
+            cp2 += incr;
+            cp3 += incr;
             pp += fromskew;
         }
     } else {
@@ -1836,7 +1928,10 @@ DECLAREContigPutFunc(putcontig8bitYCbCr44tile)
             if (h <= 4)
                 break;
             h -= 4;
-            cp += incr, cp1 += incr, cp2 += incr, cp3 += incr;
+            cp += incr;
+            cp1 += incr;
+            cp2 += incr;
+            cp3 += incr;
             pp += fromskew;
         }
     }
@@ -1852,7 +1947,7 @@ DECLAREContigPutFunc(putcontig8bitYCbCr42tile)
 
     (void) y;
     fromskew = (fromskew * 10) / 4;
-    if ((h & 3) == 0 && (w & 1) == 0) {
+    if ((w & 3) == 0 && (h & 1) == 0) {
         for (; h >= 2; h -= 2) {
             x = w>>2;
             do {
@@ -1868,10 +1963,12 @@ DECLAREContigPutFunc(putcontig8bitYCbCr42tile)
                 YCbCrtoRGB(cp1[2], pp[6]);
                 YCbCrtoRGB(cp1[3], pp[7]);
                 
-                cp += 4, cp1 += 4;
+                cp += 4;
+                cp1 += 4;
                 pp += 10;
             } while (--x);
-            cp += incr, cp1 += incr;
+            cp += incr;
+            cp1 += incr;
             pp += fromskew;
         }
     } else {
@@ -1914,7 +2011,8 @@ DECLAREContigPutFunc(putcontig8bitYCbCr42tile)
             if (h <= 2)
                 break;
             h -= 2;
-            cp += incr, cp1 += incr;
+            cp += incr;
+            cp1 += incr;
             pp += fromskew;
         }
     }
@@ -1929,7 +2027,7 @@ DECLAREContigPutFunc(putcontig8bitYCbCr41tile)
     /* XXX adjust fromskew */
     do {
        x = w>>2;
-       do {
+       while(x>0) {
            int32 Cb = pp[4];
            int32 Cr = pp[5];
 
@@ -1940,7 +2038,8 @@ DECLAREContigPutFunc(putcontig8bitYCbCr41tile)
 
            cp += 4;
            pp += 6;
-       } while (--x);
+               x--;
+       }
 
         if( (w&3) != 0 )
         {
@@ -2031,7 +2130,7 @@ DECLAREContigPutFunc(putcontig8bitYCbCr21tile)
        fromskew = (fromskew * 4) / 2;
        do {
                x = w>>1;
-               do {
+               while(x>0) {
                        int32 Cb = pp[2];
                        int32 Cr = pp[3];
 
@@ -2040,7 +2139,8 @@ DECLAREContigPutFunc(putcontig8bitYCbCr21tile)
 
                        cp += 2;
                        pp += 4;
-               } while (--x);
+                       x --;
+               }
 
                if( (w&1) != 0 )
                {
@@ -2301,7 +2401,8 @@ setupMap(TIFFRGBAImage* img)
        if (!makebwmap(img))
            return (0);
        /* no longer need Map, free it */
-       _TIFFfree(img->Map), img->Map = NULL;
+       _TIFFfree(img->Map);
+       img->Map = NULL;
     }
     return (1);
 }
@@ -2409,7 +2510,7 @@ buildMap(TIFFRGBAImage* img)
     case PHOTOMETRIC_SEPARATED:
        if (img->bitspersample == 8)
            break;
-       /* fall thru... */
+       /* fall through... */
     case PHOTOMETRIC_MINISBLACK:
     case PHOTOMETRIC_MINISWHITE:
        if (!setupMap(img))
@@ -2447,29 +2548,33 @@ PickContigCase(TIFFRGBAImage* img)
                case PHOTOMETRIC_RGB:
                        switch (img->bitspersample) {
                                case 8:
-                                       if (img->alpha == EXTRASAMPLE_ASSOCALPHA)
+                                       if (img->alpha == EXTRASAMPLE_ASSOCALPHA &&
+                                               img->samplesperpixel >= 4)
                                                img->put.contig = putRGBAAcontig8bittile;
-                                       else if (img->alpha == EXTRASAMPLE_UNASSALPHA)
+                                       else if (img->alpha == EXTRASAMPLE_UNASSALPHA &&
+                                                        img->samplesperpixel >= 4)
                                        {
                                                if (BuildMapUaToAa(img))
                                                        img->put.contig = putRGBUAcontig8bittile;
                                        }
-                                       else
+                                       else if( img->samplesperpixel >= 3 )
                                                img->put.contig = putRGBcontig8bittile;
                                        break;
                                case 16:
-                                       if (img->alpha == EXTRASAMPLE_ASSOCALPHA)
+                                       if (img->alpha == EXTRASAMPLE_ASSOCALPHA &&
+                                               img->samplesperpixel >=4 )
                                        {
                                                if (BuildMapBitdepth16To8(img))
                                                        img->put.contig = putRGBAAcontig16bittile;
                                        }
-                                       else if (img->alpha == EXTRASAMPLE_UNASSALPHA)
+                                       else if (img->alpha == EXTRASAMPLE_UNASSALPHA &&
+                                                        img->samplesperpixel >=4 )
                                        {
                                                if (BuildMapBitdepth16To8(img) &&
                                                    BuildMapUaToAa(img))
                                                        img->put.contig = putRGBUAcontig16bittile;
                                        }
-                                       else
+                                       else if( img->samplesperpixel >=3 )
                                        {
                                                if (BuildMapBitdepth16To8(img))
                                                        img->put.contig = putRGBcontig16bittile;
@@ -2478,7 +2583,7 @@ PickContigCase(TIFFRGBAImage* img)
                        }
                        break;
                case PHOTOMETRIC_SEPARATED:
-                       if (buildMap(img)) {
+                       if (img->samplesperpixel >=4 && buildMap(img)) {
                                if (img->bitspersample == 8) {
                                        if (!img->Map)
                                                img->put.contig = putRGBcontig8bitCMYKtile;
@@ -2541,7 +2646,7 @@ PickContigCase(TIFFRGBAImage* img)
                                         * must always be <= horizontal subsampling; so
                                         * there are only a few possibilities and we just
                                         * enumerate the cases.
-                                        * Joris: added support for the [1,2] case, nonetheless, to accomodate
+                                        * Joris: added support for the [1,2] case, nonetheless, to accommodate
                                         * some OJPEG files
                                         */
                                        uint16 SubsamplingHor;
@@ -2574,7 +2679,7 @@ PickContigCase(TIFFRGBAImage* img)
                        }
                        break;
                case PHOTOMETRIC_CIELAB:
-                       if (buildMap(img)) {
+                       if (img->samplesperpixel == 3 && buildMap(img)) {
                                if (img->bitspersample == 8)
                                        img->put.contig = initCIELabConversion(img);
                                break;
@@ -2675,7 +2780,7 @@ BuildMapUaToAa(TIFFRGBAImage* img)
        for (na=0; na<256; na++)
        {
                for (nv=0; nv<256; nv++)
-                       *m++=(nv*na+127)/255;
+                       *m++=(uint8)((nv*na+127)/255);
        }
        return(1);
 }
@@ -2695,7 +2800,7 @@ BuildMapBitdepth16To8(TIFFRGBAImage* img)
        }
        m=img->Bitdepth16To8;
        for (n=0; n<65536; n++)
-               *m++=(n+128)/257;
+               *m++=(uint8)((n+128)/257);
        return(1);
 }
 
index 5a4ede4..02944f8 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_jpeg.c,v 1.111 2012-07-06 18:48:04 bfriesen Exp $ */
+/* $Id: tif_jpeg.c,v 1.123 2016-01-23 21:20:34 erouault Exp $ */
 
 /*
  * Copyright (c) 1994-1997 Sam Leffler
@@ -59,7 +59,7 @@ int TIFFReInitJPEG_12( TIFF *tif, int scheme, int is_encode );
   Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
   not defined.  Unfortunately, the MinGW and Borland compilers include
   a typedef for INT32, which causes a conflict.  MSVC does not include
-  a conficting typedef given the headers which are included.
+  a conflicting typedef given the headers which are included.
 */
 #if defined(__BORLANDC__) || defined(__MINGW32__)
 # define XMD_H 1
@@ -253,6 +253,9 @@ TIFFjpeg_create_compress(JPEGState* sp)
        sp->err.error_exit = TIFFjpeg_error_exit;
        sp->err.output_message = TIFFjpeg_output_message;
 
+       /* set client_data to avoid UMR warning from tools like Purify */
+       sp->cinfo.c.client_data = NULL;
+
        return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
 }
 
@@ -264,6 +267,9 @@ TIFFjpeg_create_decompress(JPEGState* sp)
        sp->err.error_exit = TIFFjpeg_error_exit;
        sp->err.output_message = TIFFjpeg_output_message;
 
+       /* set client_data to avoid UMR warning from tools like Purify */
+       sp->cinfo.d.client_data = NULL;
+
        return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
 }
 
@@ -659,7 +665,9 @@ alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
 
 #define JPEG_MARKER_SOF0 0xC0
 #define JPEG_MARKER_SOF1 0xC1
-#define JPEG_MARKER_SOF3 0xC3
+#define JPEG_MARKER_SOF2 0xC2
+#define JPEG_MARKER_SOF9 0xC9
+#define JPEG_MARKER_SOF10 0xCA
 #define JPEG_MARKER_DHT 0xC4
 #define JPEG_MARKER_SOI 0xD8
 #define JPEG_MARKER_SOS 0xDA
@@ -730,6 +738,7 @@ JPEGFixupTagsSubsampling(TIFF* tif)
         _TIFFFillStriles( tif );
         
         if( tif->tif_dir.td_stripbytecount == NULL
+            || tif->tif_dir.td_stripoffset == NULL
             || tif->tif_dir.td_stripbytecount[0] == 0 )
         {
             /* Do not even try to check if the first strip/tile does not
@@ -817,8 +826,11 @@ JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
                                                JPEGFixupTagsSubsamplingSkip(data,n);
                                }
                                break;
-                       case JPEG_MARKER_SOF0:
-                       case JPEG_MARKER_SOF1:
+                       case JPEG_MARKER_SOF0: /* Baseline sequential Huffman */
+                       case JPEG_MARKER_SOF1: /* Extended sequential Huffman */
+                       case JPEG_MARKER_SOF2: /* Progressive Huffman: normally not allowed by TechNote, but that doesn't hurt supporting it */
+                       case JPEG_MARKER_SOF9: /* Extended sequential arithmetic */
+                       case JPEG_MARKER_SOF10: /* Progressive arithmetic: normally not allowed by TechNote, but that doesn't hurt supporting it */
                                /* this marker contains the subsampling factors we're scanning for */
                                {
                                        uint16 n;
@@ -926,7 +938,7 @@ JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 s
        else
        {
                uint16 m;
-               m=skiplength-data->bufferbytesleft;
+               m=(uint16)(skiplength-data->bufferbytesleft);
                if (m<=data->filebytesleft)
                {
                        data->bufferbytesleft=0;
@@ -993,7 +1005,7 @@ JPEGSetupDecode(TIFF* tif)
 /*
  * Set up for decoding a strip or tile.
  */
-static int
+/*ARGSUSED*/ static int
 JPEGPreDecode(TIFF* tif, uint16 s)
 {
        JPEGState *sp = JState(tif);
@@ -1169,7 +1181,8 @@ JPEGPreDecode(TIFF* tif, uint16 s)
  * Decode a chunk of pixels.
  * "Standard" case: returned data is not downsampled.
  */
-/*ARGSUSED*/ static int
+#if !JPEG_LIB_MK1_OR_12BIT
+static int
 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
 {
        JPEGState *sp = JState(tif);
@@ -1188,91 +1201,137 @@ JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
         
        nrows = cc / sp->bytesperline;
        if (cc % sp->bytesperline)
-               TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
+               TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
+                               "fractional scanline not read");
 
        if( nrows > (tmsize_t) sp->cinfo.d.image_height )
                nrows = sp->cinfo.d.image_height;
 
        /* data is expected to be read in multiples of a scanline */
        if (nrows)
-       {
-               JSAMPROW line_work_buf = NULL;
+        {
+                do
+                {
+                        /*
+                         * In the libjpeg6b-9a 8bit case.  We read directly into
+                         * the TIFF buffer.
+                         */
+                        JSAMPROW bufptr = (JSAMPROW)buf;
 
-               /*
-                * For 6B, only use temporary buffer for 12 bit imagery.
-                * For Mk1 always use it.
-                */
-#if !defined(JPEG_LIB_MK1)
-               if( sp->cinfo.d.data_precision == 12 )
-#endif
-               {
-                       line_work_buf = (JSAMPROW)
-                           _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
-                           * sp->cinfo.d.num_components );
-               }
+                        if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
+                                return (0);
 
-               do {
-                       if( line_work_buf != NULL )
-                       {
-                               /*
-                                * In the MK1 case, we aways read into a 16bit buffer, and then
-                                * pack down to 12bit or 8bit.  In 6B case we only read into 16
-                                * bit buffer for 12bit data, which we need to repack.
-                               */
-                               if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
-                                       return (0);
+                        ++tif->tif_row;
+                        buf += sp->bytesperline;
+                        cc -= sp->bytesperline;
+                } while (--nrows > 0);
+        }
 
-                               if( sp->cinfo.d.data_precision == 12 )
-                               {
-                                       int value_pairs = (sp->cinfo.d.output_width
-                                           * sp->cinfo.d.num_components) / 2;
-                                       int iPair;
+        /* Update information on consumed data */
+        tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
+        tif->tif_rawcc = sp->src.bytes_in_buffer;
+                
+       /* Close down the decompressor if we've finished the strip or tile. */
+       return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
+                || TIFFjpeg_finish_decompress(sp);
+}
+#endif /* !JPEG_LIB_MK1_OR_12BIT */
 
-                                       for( iPair = 0; iPair < value_pairs; iPair++ )
-                                       {
-                                               unsigned char *out_ptr =
-                                                   ((unsigned char *) buf) + iPair * 3;
-                                               JSAMPLE *in_ptr = line_work_buf + iPair * 2;
-
-                                               out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
-                                               out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
-                                                   | ((in_ptr[1] & 0xf00) >> 8);
-                                               out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
-                                       }
-                               }
-                               else if( sp->cinfo.d.data_precision == 8 )
-                               {
-                                       int value_count = (sp->cinfo.d.output_width
-                                           * sp->cinfo.d.num_components);
-                                       int iValue;
+#if JPEG_LIB_MK1_OR_12BIT
+/*ARGSUSED*/ static int
+JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
+{
+       JPEGState *sp = JState(tif);
+       tmsize_t nrows;
+       (void) s;
 
-                                       for( iValue = 0; iValue < value_count; iValue++ )
-                                       {
-                                               ((unsigned char *) buf)[iValue] =
-                                                   line_work_buf[iValue] & 0xff;
-                                       }
-                               }
-                       }
-                       else
-                       {
-                               /*
-                                * In the libjpeg6b 8bit case.  We read directly into the
-                                * TIFF buffer.
-                               */
-                               JSAMPROW bufptr = (JSAMPROW)buf;
+        /*
+        ** Update available information, buffer may have been refilled
+        ** between decode requests
+        */
+       sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
+       sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
 
-                               if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
-                                       return (0);
-                       }
+        if( sp->bytesperline == 0 )
+                return 0;
+        
+       nrows = cc / sp->bytesperline;
+       if (cc % sp->bytesperline)
+               TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
+                               "fractional scanline not read");
 
-                       ++tif->tif_row;
-                       buf += sp->bytesperline;
-                       cc -= sp->bytesperline;
-               } while (--nrows > 0);
+       if( nrows > (tmsize_t) sp->cinfo.d.image_height )
+               nrows = sp->cinfo.d.image_height;
 
-               if( line_work_buf != NULL )
-                       _TIFFfree( line_work_buf );
-       }
+       /* data is expected to be read in multiples of a scanline */
+       if (nrows)
+        {
+                JSAMPROW line_work_buf = NULL;
+
+                /*
+                 * For 6B, only use temporary buffer for 12 bit imagery.
+                 * For Mk1 always use it.
+                 */
+                if( sp->cinfo.d.data_precision == 12 )
+                {
+                        line_work_buf = (JSAMPROW)
+                                _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
+                                            * sp->cinfo.d.num_components );
+                }
+
+               do
+               {
+                       if( line_work_buf != NULL )
+                       {
+                               /*
+                                * In the MK1 case, we always read into a 16bit
+                                * buffer, and then pack down to 12bit or 8bit.
+                                * In 6B case we only read into 16 bit buffer
+                                * for 12bit data, which we need to repack.
+                                */
+                               if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
+                                       return (0);
+
+                               if( sp->cinfo.d.data_precision == 12 )
+                               {
+                                       int value_pairs = (sp->cinfo.d.output_width
+                                                          * sp->cinfo.d.num_components) / 2;
+                                       int iPair;
+
+                                       for( iPair = 0; iPair < value_pairs; iPair++ )
+                                       {
+                                               unsigned char *out_ptr =
+                                                       ((unsigned char *) buf) + iPair * 3;
+                                               JSAMPLE *in_ptr = line_work_buf + iPair * 2;
+
+                                               out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
+                                               out_ptr[1] = (unsigned char)(((in_ptr[0] & 0xf) << 4)
+                                                       | ((in_ptr[1] & 0xf00) >> 8));
+                                               out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
+                                       }
+                               }
+                               else if( sp->cinfo.d.data_precision == 8 )
+                               {
+                                       int value_count = (sp->cinfo.d.output_width
+                                                          * sp->cinfo.d.num_components);
+                                       int iValue;
+
+                                       for( iValue = 0; iValue < value_count; iValue++ )
+                                       {
+                                               ((unsigned char *) buf)[iValue] =
+                                                       line_work_buf[iValue] & 0xff;
+                                       }
+                               }
+                       }
+
+                       ++tif->tif_row;
+                       buf += sp->bytesperline;
+                       cc -= sp->bytesperline;
+               } while (--nrows > 0);
+
+               if( line_work_buf != NULL )
+                       _TIFFfree( line_work_buf );
+        }
 
         /* Update information on consumed data */
         tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
@@ -1280,8 +1339,9 @@ JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
                 
        /* Close down the decompressor if we've finished the strip or tile. */
        return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
-           || TIFFjpeg_finish_decompress(sp);
+                || TIFFjpeg_finish_decompress(sp);
 }
+#endif /* JPEG_LIB_MK1_OR_12BIT */
 
 /*ARGSUSED*/ static int
 DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
@@ -1308,7 +1368,7 @@ JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
        (void) s;
 
        /* data is expected to be read in multiples of a scanline */
-       if ( (nrows = sp->cinfo.d.image_height) ) {
+       if ( (nrows = sp->cinfo.d.image_height) != 0 ) {
 
                /* Cb,Cr both have sampling factors 1, so this is correct */
                JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;            
@@ -1408,10 +1468,10 @@ JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
                                        {
                                                unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
                                                JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
-                                               out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
-                                               out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
-                                                       | ((in_ptr[1] & 0xf00) >> 8);
-                                               out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
+                                               out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
+                                               out_ptr[1] = (unsigned char)(((in_ptr[0] & 0xf) << 4)
+                                                       | ((in_ptr[1] & 0xf00) >> 8));
+                                               out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
                                        }
                                }
                        }
@@ -1452,6 +1512,15 @@ unsuppress_quant_table (JPEGState* sp, int tblno)
 }
 
 static void
+suppress_quant_table (JPEGState* sp, int tblno)
+{
+       JQUANT_TBL* qtbl;
+
+       if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
+               qtbl->sent_table = TRUE;
+}
+
+static void
 unsuppress_huff_table (JPEGState* sp, int tblno)
 {
        JHUFF_TBL* htbl;
@@ -1462,6 +1531,17 @@ unsuppress_huff_table (JPEGState* sp, int tblno)
                htbl->sent_table = FALSE;
 }
 
+static void
+suppress_huff_table (JPEGState* sp, int tblno)
+{
+       JHUFF_TBL* htbl;
+
+       if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
+               htbl->sent_table = TRUE;
+       if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
+               htbl->sent_table = TRUE;
+}
+
 static int
 prepare_JPEGTables(TIFF* tif)
 {
@@ -1511,17 +1591,38 @@ JPEGSetupEncode(TIFF* tif)
        assert(sp != NULL);
        assert(!sp->cinfo.comm.is_decompressor);
 
+       sp->photometric = td->td_photometric;
+
        /*
         * Initialize all JPEG parameters to default values.
         * Note that jpeg_set_defaults needs legal values for
         * in_color_space and input_components.
         */
-       sp->cinfo.c.in_color_space = JCS_UNKNOWN;
-       sp->cinfo.c.input_components = 1;
+       if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
+               sp->cinfo.c.input_components = td->td_samplesperpixel;
+               if (sp->photometric == PHOTOMETRIC_YCBCR) {
+                       if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
+                               sp->cinfo.c.in_color_space = JCS_RGB;
+                       } else {
+                               sp->cinfo.c.in_color_space = JCS_YCbCr;
+                       }
+               } else {
+                       if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
+                               sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
+                       else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
+                               sp->cinfo.c.in_color_space = JCS_RGB;
+                       else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
+                               sp->cinfo.c.in_color_space = JCS_CMYK;
+                       else
+                               sp->cinfo.c.in_color_space = JCS_UNKNOWN;
+               }
+       } else {
+               sp->cinfo.c.input_components = 1;
+               sp->cinfo.c.in_color_space = JCS_UNKNOWN;
+       }
        if (!TIFFjpeg_set_defaults(sp))
                return (0);
        /* Set per-file parameters */
-       sp->photometric = td->td_photometric;
        switch (sp->photometric) {
        case PHOTOMETRIC_YCBCR:
                sp->h_sampling = td->td_ycbcrsubsampling[0];
@@ -1681,10 +1782,7 @@ JPEGPreEncode(TIFF* tif, uint16 s)
        if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
                sp->cinfo.c.input_components = td->td_samplesperpixel;
                if (sp->photometric == PHOTOMETRIC_YCBCR) {
-                       if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
-                               sp->cinfo.c.in_color_space = JCS_RGB;
-                       } else {
-                               sp->cinfo.c.in_color_space = JCS_YCbCr;
+                       if (sp->jpegcolormode != JPEGCOLORMODE_RGB) {
                                if (sp->h_sampling != 1 || sp->v_sampling != 1)
                                        downsampled_input = TRUE;
                        }
@@ -1697,21 +1795,11 @@ JPEGPreEncode(TIFF* tif, uint16 s)
                        sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
                        sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
                } else {
-                       if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
-                               sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
-                       else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
-                               sp->cinfo.c.in_color_space = JCS_RGB;
-                       else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
-                               sp->cinfo.c.in_color_space = JCS_CMYK;
-                       else
-                               sp->cinfo.c.in_color_space = JCS_UNKNOWN;
                        if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
                                return (0);
                        /* jpeg_set_colorspace set all sampling factors to 1 */
                }
        } else {
-               sp->cinfo.c.input_components = 1;
-               sp->cinfo.c.in_color_space = JCS_UNKNOWN;
                if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
                        return (0);
                sp->cinfo.c.comp_info[0].component_id = s;
@@ -1726,14 +1814,30 @@ JPEGPreEncode(TIFF* tif, uint16 s)
        sp->cinfo.c.write_JFIF_header = FALSE;
        sp->cinfo.c.write_Adobe_marker = FALSE;
        /* set up table handling correctly */
-        if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
+       /* calling TIFFjpeg_set_quality() causes quantization tables to be flagged */
+       /* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT */
+       /* mode, so we must manually suppress them. However TIFFjpeg_set_quality() */
+       /* should really be called when dealing with files with directories with */
+       /* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
+       if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
                return (0);
-       if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
+       if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
+               suppress_quant_table(sp, 0);
+               suppress_quant_table(sp, 1);
+       }
+       else {
                unsuppress_quant_table(sp, 0);
                unsuppress_quant_table(sp, 1);
        }
        if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
+       {
+               /* Explicit suppression is only needed if we did not go through the */
+               /* prepare_JPEGTables() code path, which may be the case if updating */
+               /* an existing file */
+               suppress_huff_table(sp, 0);
+               suppress_huff_table(sp, 1);
                sp->cinfo.c.optimize_coding = FALSE;
+       }
        else
                sp->cinfo.c.optimize_coding = TRUE;
        if (downsampled_input) {
@@ -1790,9 +1894,16 @@ JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
 
         if( sp->cinfo.c.data_precision == 12 )
         {
-            line16_count = (sp->bytesperline * 2) / 3;
+            line16_count = (int)((sp->bytesperline * 2) / 3);
             line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
-           // FIXME: undiagnosed malloc failure
+            if (!line16)
+            {
+                TIFFErrorExt(tif->tif_clientdata,
+                            "JPEGEncode",
+                             "Failed to allocate memory");
+
+                return 0;
+            }
         }
             
        while (nrows-- > 0) {
@@ -1967,13 +2078,10 @@ JPEGCleanup(TIFF* tif)
        tif->tif_tagmethods.vgetfield = sp->vgetparent;
        tif->tif_tagmethods.vsetfield = sp->vsetparent;
        tif->tif_tagmethods.printdir = sp->printdir;
-
-       if( sp != NULL ) {
-               if( sp->cinfo_initialized )
-                   TIFFjpeg_destroy(sp);       /* release libjpeg resources */
-               if (sp->jpegtables)             /* tag value */
-                       _TIFFfree(sp->jpegtables);
-       }
+        if( sp->cinfo_initialized )
+                TIFFjpeg_destroy(sp);  /* release libjpeg resources */
+        if (sp->jpegtables)            /* tag value */
+                _TIFFfree(sp->jpegtables);
        _TIFFfree(tif->tif_data);       /* release local state */
        tif->tif_data = NULL;
 
@@ -2031,8 +2139,7 @@ JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
                        /* XXX */
                        return (0);
                }
-               _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
-                   (long) v32);
+               _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*), v32);
                sp->jpegtables_length = v32;
                TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
                break;
@@ -2061,7 +2168,7 @@ JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
                return (*sp->vsetparent)(tif, tag, ap);
        }
 
-       if ((fip = TIFFFieldWithTag(tif, tag))) {
+       if ((fip = TIFFFieldWithTag(tif, tag)) != NULL) {
                TIFFSetFieldBit(tif, fip->field_bit);
        } else {
                return (0);
@@ -2285,8 +2392,17 @@ here hopefully is harmless.
 */
             sp->jpegtables_length = SIZE_OF_JPEGTABLES;
             sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
-           // FIXME: NULL-deref after malloc failure
-           _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
+            if (sp->jpegtables)
+            {
+                _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
+            }
+            else
+            {
+                TIFFErrorExt(tif->tif_clientdata,
+                            "TIFFInitJPEG",
+                             "Failed to allocate memory for JPEG tables");
+                return 0;
+            }
 #undef SIZE_OF_JPEGTABLES
         }
 
index 87b8b17..afb5acd 100644 (file)
@@ -5,6 +5,9 @@
 
 #  define TIFFInitJPEG TIFFInitJPEG_12
 
+int
+TIFFInitJPEG_12(TIFF* tif, int scheme);
+
 #  include LIBJPEG_12_PATH
 
 #  include "tif_jpeg.c"
index df483ad..d90e03e 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_luv.c,v 1.35 2011-04-02 20:54:09 bfriesen Exp $ */
+/* $Id: tif_luv.c,v 1.43 2016-09-04 21:32:56 erouault Exp $ */
 
 /*
  * Copyright (c) 1997 Greg Ward Larson
@@ -203,7 +203,11 @@ LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
        if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
                tp = (int16*) op;
        else {
-               assert(sp->tbuflen >= npixels);
+               if(sp->tbuflen < npixels) {
+                       TIFFErrorExt(tif->tif_clientdata, module,
+                                                "Translation buffer too short");
+                       return (0);
+               }
                tp = (int16*) sp->tbuf;
        }
        _TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));
@@ -212,9 +216,11 @@ LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
        cc = tif->tif_rawcc;
        /* get each byte string */
        for (shft = 2*8; (shft -= 8) >= 0; ) {
-               for (i = 0; i < npixels && cc > 0; )
+               for (i = 0; i < npixels && cc > 0; ) {
                        if (*bp >= 128) {               /* run */
-                               rc = *bp++ + (2-128);   /* TODO: potential input buffer overrun when decoding corrupt or truncated data */
+                               if( cc < 2 )
+                                       break;
+                               rc = *bp++ + (2-128);
                                b = (int16)(*bp++ << shft);
                                cc -= 2;
                                while (rc-- && i < npixels)
@@ -224,6 +230,7 @@ LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
                                while (--cc && rc-- && i < npixels)
                                        tp[i++] |= (int16)*bp++ << shft;
                        }
+               }
                if (i != npixels) {
 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
                        TIFFErrorExt(tif->tif_clientdata, module,
@@ -269,13 +276,17 @@ LogLuvDecode24(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
        if (sp->user_datafmt == SGILOGDATAFMT_RAW)
                tp = (uint32 *)op;
        else {
-               assert(sp->tbuflen >= npixels);
+               if(sp->tbuflen < npixels) {
+                       TIFFErrorExt(tif->tif_clientdata, module,
+                                                "Translation buffer too short");
+                       return (0);
+               }
                tp = (uint32 *) sp->tbuf;
        }
        /* copy to array of uint32 */
        bp = (unsigned char*) tif->tif_rawcp;
        cc = tif->tif_rawcc;
-       for (i = 0; i < npixels && cc > 0; i++) {
+       for (i = 0; i < npixels && cc >= 3; i++) {
                tp[i] = bp[0] << 16 | bp[1] << 8 | bp[2];
                bp += 3;
                cc -= 3;
@@ -326,7 +337,11 @@ LogLuvDecode32(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
        if (sp->user_datafmt == SGILOGDATAFMT_RAW)
                tp = (uint32*) op;
        else {
-               assert(sp->tbuflen >= npixels);
+               if(sp->tbuflen < npixels) {
+                       TIFFErrorExt(tif->tif_clientdata, module,
+                                                "Translation buffer too short");
+                       return (0);
+               }
                tp = (uint32*) sp->tbuf;
        }
        _TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));
@@ -335,11 +350,13 @@ LogLuvDecode32(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
        cc = tif->tif_rawcc;
        /* get each byte string */
        for (shft = 4*8; (shft -= 8) >= 0; ) {
-               for (i = 0; i < npixels && cc > 0; )
+               for (i = 0; i < npixels && cc > 0; ) {
                        if (*bp >= 128) {               /* run */
+                               if( cc < 2 )
+                                       break;
                                rc = *bp++ + (2-128);
                                b = (uint32)*bp++ << shft;
-                               cc -= 2;                /* TODO: potential input buffer overrun when decoding corrupt or truncated data */
+                               cc -= 2;
                                while (rc-- && i < npixels)
                                        tp[i++] |= b;
                        } else {                        /* non-run */
@@ -347,6 +364,7 @@ LogLuvDecode32(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
                                while (--cc && rc-- && i < npixels)
                                        tp[i++] |= (uint32)*bp++ << shft;
                        }
+               }
                if (i != npixels) {
 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
                        TIFFErrorExt(tif->tif_clientdata, module,
@@ -380,9 +398,14 @@ LogLuvDecodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 {
        tmsize_t rowlen = TIFFScanlineSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
        assert(cc%rowlen == 0);
-       while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
-               bp += rowlen, cc -= rowlen;
+       while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s)) {
+               bp += rowlen;
+               cc -= rowlen;
+       }
        return (cc == 0);
 }
 
@@ -396,9 +419,14 @@ LogLuvDecodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 {
        tmsize_t rowlen = TIFFTileRowSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
        assert(cc%rowlen == 0);
-       while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
-               bp += rowlen, cc -= rowlen;
+       while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s)) {
+               bp += rowlen;
+               cc -= rowlen;
+       }
        return (cc == 0);
 }
 
@@ -408,6 +436,7 @@ LogLuvDecodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 static int
 LogL16Encode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 {
+       static const char module[] = "LogL16Encode";
        LogLuvState* sp = EncoderState(tif);
        int shft;
        tmsize_t i;
@@ -428,7 +457,11 @@ LogL16Encode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
                tp = (int16*) bp;
        else {
                tp = (int16*) sp->tbuf;
-               assert(sp->tbuflen >= npixels);
+               if(sp->tbuflen < npixels) {
+                       TIFFErrorExt(tif->tif_clientdata, module,
+                                                "Translation buffer too short");
+                       return (0);
+               }
                (*sp->tfunc)(sp, bp, npixels);
        }
        /* compress each byte string */
@@ -501,6 +534,7 @@ LogL16Encode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 static int
 LogLuvEncode24(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 {
+       static const char module[] = "LogLuvEncode24";
        LogLuvState* sp = EncoderState(tif);
        tmsize_t i;
        tmsize_t npixels;
@@ -516,7 +550,11 @@ LogLuvEncode24(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
                tp = (uint32*) bp;
        else {
                tp = (uint32*) sp->tbuf;
-               assert(sp->tbuflen >= npixels);
+               if(sp->tbuflen < npixels) {
+                       TIFFErrorExt(tif->tif_clientdata, module,
+                                                "Translation buffer too short");
+                       return (0);
+               }
                (*sp->tfunc)(sp, bp, npixels);
        }
        /* write out encoded pixels */
@@ -548,6 +586,7 @@ LogLuvEncode24(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 static int
 LogLuvEncode32(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 {
+       static const char module[] = "LogLuvEncode32";
        LogLuvState* sp = EncoderState(tif);
        int shft;
        tmsize_t i;
@@ -569,7 +608,11 @@ LogLuvEncode32(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
                tp = (uint32*) bp;
        else {
                tp = (uint32*) sp->tbuf;
-               assert(sp->tbuflen >= npixels);
+               if(sp->tbuflen < npixels) {
+                       TIFFErrorExt(tif->tif_clientdata, module,
+                                                "Translation buffer too short");
+                       return (0);
+               }
                (*sp->tfunc)(sp, bp, npixels);
        }
        /* compress each byte string */
@@ -645,9 +688,14 @@ LogLuvEncodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 {
        tmsize_t rowlen = TIFFScanlineSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
        assert(cc%rowlen == 0);
-       while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
-               bp += rowlen, cc -= rowlen;
+       while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1) {
+               bp += rowlen;
+               cc -= rowlen;
+       }
        return (cc == 0);
 }
 
@@ -660,9 +708,14 @@ LogLuvEncodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 {
        tmsize_t rowlen = TIFFTileRowSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
        assert(cc%rowlen == 0);
-       while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
-               bp += rowlen, cc -= rowlen;
+       while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1) {
+               bp += rowlen;
+               cc -= rowlen;
+       }
        return (cc == 0);
 }
 
@@ -684,7 +737,9 @@ LogLuvEncodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
 #ifndef M_PI
 #define M_PI           3.14159265358979323846
 #endif
+#undef log2 /* Conflict with C'99 function */
 #define log2(x)                ((1./M_LN2)*log(x))
+#undef exp2  /* Conflict with C'99 function */
 #define exp2(x)                exp(M_LN2*(x))
 
 #define itrunc(x,m)    ((m)==SGILOGENCODE_NODITHER ? \
@@ -1230,6 +1285,14 @@ LogL16InitState(TIFF* tif)
        assert(sp != NULL);
        assert(td->td_photometric == PHOTOMETRIC_LOGL);
 
+       if( td->td_samplesperpixel != 1 )
+       {
+               TIFFErrorExt(tif->tif_clientdata, module,
+                            "Sorry, can not handle LogL image with %s=%d",
+                            "Samples/pixel", td->td_samplesperpixel);
+               return 0;
+       }
+
        /* for some reason, we can't do this in TIFFInitLogL16 */
        if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN)
                sp->user_datafmt = LogL16GuessDataFmt(td);
@@ -1552,17 +1615,21 @@ LogLuvVSetField(TIFF* tif, uint32 tag, va_list ap)
                 */
                switch (sp->user_datafmt) {
                case SGILOGDATAFMT_FLOAT:
-                       bps = 32, fmt = SAMPLEFORMAT_IEEEFP;
+                       bps = 32;
+                       fmt = SAMPLEFORMAT_IEEEFP;
                        break;
                case SGILOGDATAFMT_16BIT:
-                       bps = 16, fmt = SAMPLEFORMAT_INT;
+                       bps = 16;
+                       fmt = SAMPLEFORMAT_INT;
                        break;
                case SGILOGDATAFMT_RAW:
-                       bps = 32, fmt = SAMPLEFORMAT_UINT;
+                       bps = 32;
+                       fmt = SAMPLEFORMAT_UINT;
                        TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1);
                        break;
                case SGILOGDATAFMT_8BIT:
-                       bps = 8, fmt = SAMPLEFORMAT_UINT;
+                       bps = 8;
+                       fmt = SAMPLEFORMAT_UINT;
                        break;
                default:
                        TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
index 620c2d1..b95fe46 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_lzma.c,v 1.4 2011-12-22 00:29:29 bfriesen Exp $ */
+/* $Id: tif_lzma.c,v 1.6 2016-09-17 09:18:59 erouault Exp $ */
 
 /*
  * Copyright (c) 2010, Andrey Kiselev <dron@ak4719.spb.edu>
@@ -96,7 +96,7 @@ LZMAStrerror(lzma_ret ret)
                case LZMA_PROG_ERROR:
                    return "programming error";
                default:
-                   return "unindentified liblzma error";
+                   return "unidentified liblzma error";
        }
 }
 
@@ -491,6 +491,6 @@ bad:
                     "No space for LZMA2 state block");
        return 0;
 }
-#endif /* LZMA_SUPORT */
+#endif /* LZMA_SUPPORT */
 
 /* vim: set ts=8 sts=8 sw=8 noet: */
index 3a3558e..3cf8495 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_lzw.c,v 1.45 2011-04-02 20:54:09 bfriesen Exp $ */
+/* $Id: tif_lzw.c,v 1.52 2016-09-04 21:32:56 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -95,7 +95,7 @@ typedef struct {
        unsigned short  nbits;          /* # of bits/code */
        unsigned short  maxcode;        /* maximum code for lzw_nbits */
        unsigned short  free_ent;       /* next free entry in hash table */
-       long            nextdata;       /* next bits of i/o */
+       unsigned long   nextdata;       /* next bits of i/o */
        long            nextbits;       /* # of valid bits in lzw_nextdata */
 
        int             rw_mode;        /* preserve rw_mode from init */
@@ -241,8 +241,8 @@ LZWSetupDecode(TIFF* tif)
                 */
                code = 255;
                do {
-                       sp->dec_codetab[code].value = code;
-                       sp->dec_codetab[code].firstchar = code;
+                       sp->dec_codetab[code].value = (unsigned char)code;
+                       sp->dec_codetab[code].firstchar = (unsigned char)code;
                        sp->dec_codetab[code].length = 1;
                        sp->dec_codetab[code].next = NULL;
                } while (code--);
@@ -269,6 +269,8 @@ LZWPreDecode(TIFF* tif, uint16 s)
        if( sp->dec_codetab == NULL )
         {
             tif->tif_setupdecode( tif );
+           if( sp->dec_codetab == NULL )
+               return (0);
         }
 
        /*
@@ -366,7 +368,8 @@ LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
        unsigned char *bp;
        hcode_t code;
        int len;
-       long nbits, nextbits, nextdata, nbitsmask;
+       long nbits, nextbits, nbitsmask;
+        unsigned long nextdata;
        code_t *codep, *free_entp, *maxcodep, *oldcodep;
 
        (void) s;
@@ -409,14 +412,15 @@ LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
                /*
                 * Residue satisfies only part of the decode request.
                 */
-               op += residue, occ -= residue;
+               op += residue;
+               occ -= residue;
                tp = op;
                do {
                        int t;
                        --tp;
                        t = codep->value;
                        codep = codep->next;
-                       *tp = t;
+                       *tp = (char)t;
                } while (--residue && codep);
                sp->dec_restart = 0;
        }
@@ -435,22 +439,25 @@ LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
                if (code == CODE_EOI)
                        break;
                if (code == CODE_CLEAR) {
-                       free_entp = sp->dec_codetab + CODE_FIRST;
-                       _TIFFmemset(free_entp, 0,
-                                   (CSIZE - CODE_FIRST) * sizeof (code_t));
-                       nbits = BITS_MIN;
-                       nbitsmask = MAXCODE(BITS_MIN);
-                       maxcodep = sp->dec_codetab + nbitsmask-1;
-                       NextCode(tif, sp, bp, code, GetNextCode);
+                       do {
+                               free_entp = sp->dec_codetab + CODE_FIRST;
+                               _TIFFmemset(free_entp, 0,
+                                           (CSIZE - CODE_FIRST) * sizeof (code_t));
+                               nbits = BITS_MIN;
+                               nbitsmask = MAXCODE(BITS_MIN);
+                               maxcodep = sp->dec_codetab + nbitsmask-1;
+                               NextCode(tif, sp, bp, code, GetNextCode);
+                       } while (code == CODE_CLEAR);   /* consecutive CODE_CLEAR codes */
                        if (code == CODE_EOI)
                                break;
-                       if (code >= CODE_CLEAR) {
+                       if (code > CODE_CLEAR) {
                                TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
                                "LZWDecode: Corrupted LZW table at scanline %d",
                                             tif->tif_row);
                                return (0);
                        }
-                       *op++ = (char)code, occ--;
+                       *op++ = (char)code;
+                       occ--;
                        oldcodep = sp->dec_codetab + code;
                        continue;
                }
@@ -528,16 +535,19 @@ LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
                                --tp;
                                t = codep->value;
                                codep = codep->next;
-                               *tp = t;
+                               *tp = (char)t;
                        } while (codep && tp > op);
                        if (codep) {
                            codeLoop(tif, module);
                            break;
                        }
                        assert(occ >= len);
-                       op += len, occ -= len;
-               } else
-                       *op++ = (char)code, occ--;
+                       op += len;
+                       occ -= len;
+               } else {
+                       *op++ = (char)code;
+                       occ--;
+               }
        }
 
        tif->tif_rawcp = (uint8*) bp;
@@ -631,7 +641,8 @@ LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
                /*
                 * Residue satisfies only part of the decode request.
                 */
-               op += residue, occ -= residue;
+               op += residue;
+               occ -= residue;
                tp = op;
                do {
                        *--tp = codep->value;
@@ -654,22 +665,25 @@ LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
                if (code == CODE_EOI)
                        break;
                if (code == CODE_CLEAR) {
-                       free_entp = sp->dec_codetab + CODE_FIRST;
-                       _TIFFmemset(free_entp, 0,
-                                   (CSIZE - CODE_FIRST) * sizeof (code_t));
-                       nbits = BITS_MIN;
-                       nbitsmask = MAXCODE(BITS_MIN);
-                       maxcodep = sp->dec_codetab + nbitsmask;
-                       NextCode(tif, sp, bp, code, GetNextCodeCompat);
+                       do {
+                               free_entp = sp->dec_codetab + CODE_FIRST;
+                               _TIFFmemset(free_entp, 0,
+                                           (CSIZE - CODE_FIRST) * sizeof (code_t));
+                               nbits = BITS_MIN;
+                               nbitsmask = MAXCODE(BITS_MIN);
+                               maxcodep = sp->dec_codetab + nbitsmask;
+                               NextCode(tif, sp, bp, code, GetNextCodeCompat);
+                       } while (code == CODE_CLEAR);   /* consecutive CODE_CLEAR codes */
                        if (code == CODE_EOI)
                                break;
-                       if (code >= CODE_CLEAR) {
+                       if (code > CODE_CLEAR) {
                                TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
                                "LZWDecode: Corrupted LZW table at scanline %d",
                                             tif->tif_row);
                                return (0);
                        }
-                       *op++ = code, occ--;
+                       *op++ = (char)code;
+                       occ--;
                        oldcodep = sp->dec_codetab + code;
                        continue;
                }
@@ -735,17 +749,20 @@ LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
                                break;
                        }
                        assert(occ >= codep->length);
-                       op += codep->length, occ -= codep->length;
+                       op += codep->length;
+                       occ -= codep->length;
                        tp = op;
                        do {
                                *--tp = codep->value;
                        } while( (codep = codep->next) != NULL );
-               } else
-                       *op++ = code, occ--;
+               } else {
+                       *op++ = (char)code;
+                       occ--;
+               }
        }
 
        tif->tif_rawcp = (uint8*) bp;
-       sp->lzw_nbits = nbits;
+       sp->lzw_nbits = (unsigned short)nbits;
        sp->lzw_nextdata = nextdata;
        sp->lzw_nextbits = nextbits;
        sp->dec_nbitsmask = nbitsmask;
@@ -831,13 +848,15 @@ LZWPreEncode(TIFF* tif, uint16 s)
        } else                                                  \
                rat = (incount<<8) / outcount;                  \
 }
+
+/* Explicit 0xff masking to make icc -check=conversions happy */
 #define        PutNextCode(op, c) {                                    \
        nextdata = (nextdata << nbits) | c;                     \
        nextbits += nbits;                                      \
-       *op++ = (unsigned char)(nextdata >> (nextbits-8));              \
+       *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff);               \
        nextbits -= 8;                                          \
        if (nextbits >= 8) {                                    \
-               *op++ = (unsigned char)(nextdata >> (nextbits-8));      \
+               *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff);       \
                nextbits -= 8;                                  \
        }                                                       \
        outcount += nbits;                                      \
@@ -867,7 +886,8 @@ LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
        hcode_t ent;
        long disp;
        long incount, outcount, checkpoint;
-       long nextdata, nextbits;
+       unsigned long nextdata;
+        long nextbits;
        int free_ent, maxcode, nbits;
        uint8* op;
        uint8* limit;
@@ -891,7 +911,7 @@ LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
        nbits = sp->lzw_nbits;
        op = tif->tif_rawcp;
        limit = sp->enc_rawlimit;
-       ent = sp->enc_oldcode;
+       ent = (hcode_t)sp->enc_oldcode;
 
        if (ent == (hcode_t) -1 && cc > 0) {
                /*
@@ -927,7 +947,7 @@ LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
                                disp = 1;
                        do {
                                /*
-                                * Avoid pointer arithmetic 'cuz of
+                                * Avoid pointer arithmetic because of
                                 * wraparound problems with segments.
                                 */
                                if ((h -= disp) < 0)
@@ -954,8 +974,8 @@ LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
                        op = tif->tif_rawdata;
                }
                PutNextCode(op, ent);
-               ent = c;
-               hp->code = free_ent++;
+               ent = (hcode_t)c;
+               hp->code = (hcode_t)(free_ent++);
                hp->hash = fcode;
                if (free_ent == CODE_MAX-1) {
                        /* table is full, emit clear code and reset */
@@ -1012,9 +1032,9 @@ LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
        sp->enc_oldcode = ent;
        sp->lzw_nextdata = nextdata;
        sp->lzw_nextbits = nextbits;
-       sp->lzw_free_ent = free_ent;
-       sp->lzw_maxcode = maxcode;
-       sp->lzw_nbits = nbits;
+       sp->lzw_free_ent = (unsigned short)free_ent;
+       sp->lzw_maxcode = (unsigned short)maxcode;
+       sp->lzw_nbits = (unsigned short)nbits;
        tif->tif_rawcp = op;
        return (1);
 }
@@ -1029,7 +1049,7 @@ LZWPostEncode(TIFF* tif)
        register LZWCodecState *sp = EncoderState(tif);
        uint8* op = tif->tif_rawcp;
        long nextbits = sp->lzw_nextbits;
-       long nextdata = sp->lzw_nextdata;
+       unsigned long nextdata = sp->lzw_nextdata;
        long outcount = sp->enc_outcount;
        int nbits = sp->lzw_nbits;
 
@@ -1043,8 +1063,9 @@ LZWPostEncode(TIFF* tif)
                sp->enc_oldcode = (hcode_t) -1;
        }
        PutNextCode(op, CODE_EOI);
+        /* Explicit 0xff masking to make icc -check=conversions happy */
        if (nextbits > 0) 
-               *op++ = (unsigned char)(nextdata << (8-nextbits));
+               *op++ = (unsigned char)((nextdata << (8-nextbits))&0xff);
        tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
        return (1);
 }
index 0636d83..c75f7f1 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_next.c,v 1.13 2010-03-10 18:56:48 bfriesen Exp $ */
+/* $Id: tif_next.c,v 1.19 2016-09-04 21:32:56 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -38,7 +38,7 @@
        case 0: op[0]  = (unsigned char) ((v) << 6); break;     \
        case 1: op[0] |= (v) << 4; break;       \
        case 2: op[0] |= (v) << 2; break;       \
-       case 3: *op++ |= (v);      break;       \
+       case 3: *op++ |= (v);      op_offset++; break;  \
        }                                       \
 }
 
@@ -72,8 +72,9 @@ NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
                TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read");
                return (0);
        }
-       for (row = buf; occ > 0; occ -= scanline, row += scanline) {
-               n = *bp++, cc--;
+       for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) {
+               n = *bp++;
+               cc--;
                switch (n) {
                case LITERALROW:
                        /*
@@ -91,6 +92,8 @@ NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
                         * The scanline has a literal span that begins at some
                         * offset.
                         */
+                       if( cc < 4 )
+                               goto bad;
                        off = (bp[0] * 256) + bp[1];
                        n = (bp[2] * 256) + bp[3];
                        if (cc < 4+n || off+n > scanline)
@@ -102,7 +105,10 @@ NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
                }
                default: {
                        uint32 npixels = 0, grey;
+                       tmsize_t op_offset = 0;
                        uint32 imagewidth = tif->tif_dir.td_imagewidth;
+            if( isTiled(tif) )
+                imagewidth = tif->tif_dir.td_tilewidth;
 
                        /*
                         * The scanline is composed of a sequence of constant
@@ -119,13 +125,19 @@ NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
                                 * bounds, potentially resulting in a security
                                 * issue.
                                 */
-                               while (n-- > 0 && npixels < imagewidth)
+                               while (n-- > 0 && npixels < imagewidth && op_offset < scanline)
                                        SETPIXEL(op, grey);
                                if (npixels >= imagewidth)
                                        break;
+                if (op_offset >= scanline ) {
+                    TIFFErrorExt(tif->tif_clientdata, module, "Invalid data for scanline %ld",
+                        (long) tif->tif_row);
+                    return (0);
+                }
                                if (cc == 0)
                                        goto bad;
-                               n = *bp++, cc--;
+                               n = *bp++;
+                               cc--;
                        }
                        break;
                }
@@ -140,10 +152,27 @@ bad:
        return (0);
 }
 
+static int
+NeXTPreDecode(TIFF* tif, uint16 s)
+{
+       static const char module[] = "NeXTPreDecode";
+       TIFFDirectory *td = &tif->tif_dir;
+       (void)s;
+
+       if( td->td_bitspersample != 2 )
+       {
+               TIFFErrorExt(tif->tif_clientdata, module, "Unsupported BitsPerSample = %d",
+                                        td->td_bitspersample);
+               return (0);
+       }
+       return (1);
+}
+       
 int
 TIFFInitNeXT(TIFF* tif, int scheme)
 {
        (void) scheme;
+       tif->tif_predecode = NeXTPreDecode;  
        tif->tif_decoderow = NeXTDecode;  
        tif->tif_decodestrip = NeXTDecode;  
        tif->tif_decodetile = NeXTDecode;
index 520d464..c120b04 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_ojpeg.c,v 1.56 2012-05-24 03:15:18 fwarmerdam Exp $ */
+/* $Id: tif_ojpeg.c,v 1.65 2016-09-04 21:32:56 erouault Exp $ */
 
 /* WARNING: The type of JPEG encapsulation defined by the TIFF Version 6.0
    specification is now totally obsolete and deprecated for new applications and
@@ -39,7 +39,7 @@
    OF THIS SOFTWARE.
 
    Joris Van Damme and/or AWare Systems may be available for custom
-   developement. If you like what you see, and need anything similar or related,
+   development. If you like what you see, and need anything similar or related,
    contact <info@awaresystems.be>.
 */
 
@@ -75,7 +75,7 @@
    OJPEGSubsamplingCorrect, making no note of any other data, reporting no warnings
    or errors, up to the point where either these values are read, or it's clear they
    aren't there. This means that some of the data is read twice, but we feel speed
-   in correcting these values is important enough to warrant this sacrifice. Allthough
+   in correcting these values is important enough to warrant this sacrifice. Although
    there is currently no define or other configuration mechanism to disable this behaviour,
    the actual header scanning is build to robustly respond with error report if it
    should encounter an uncorrected mismatch of subsampling values. See
@@ -84,7 +84,7 @@
    The restart interval and restart markers are the most tricky part... The restart
    interval can be specified in a tag. It can also be set inside the input JPEG stream.
    It can be used inside the input JPEG stream. If reading from strile data, we've
-   consistenly discovered the need to insert restart markers in between the different
+   consistently discovered the need to insert restart markers in between the different
    striles, as is also probably the most likely interpretation of the original TIFF 6.0
    specification. With all this setting of interval, and actual use of markers that is not
    predictable at the time of valid JPEG header assembly, the restart thing may turn
    planarconfig is not separate (vast majority). We may one day use that to build
    converters to JPEG, and/or to new-style JPEG compression inside TIFF.
 
-   A dissadvantage is the lack of random access to the individual striles. This is the
+   A disadvantage is the lack of random access to the individual striles. This is the
    reason for much of the complicated restart-and-position stuff inside OJPEGPreDecode.
    Applications would do well accessing all striles in order, as this will result in
    a single sequential scan of the input stream, and no restarting of LibJpeg decoding
  *     The default mode, without JPEG_ENCAP_EXTERNAL, implements the call encapsulators
  *     here, internally, with normal longjump.
  * SETJMP, LONGJMP, JMP_BUF: On some machines/environments a longjump equivalent is
- *     conviniently available, but still it may be worthwhile to use _setjmp or sigsetjmp
+ *     conveniently available, but still it may be worthwhile to use _setjmp or sigsetjmp
  *     in place of plain setjmp. These macros will make it easier. It is useless
  *     to fiddle with these if you define JPEG_ENCAP_EXTERNAL.
  * OJPEG_BUFFER: Define the size of the desired buffer here. Should be small enough so as to guarantee
  *     instant processing, optimal streaming and optimal use of processor cache, but also big
  *     enough so as to not result in significant call overhead. It should be at least a few
- *     bytes to accomodate some structures (this is verified in asserts), but it would not be
+ *     bytes to accommodate some structures (this is verified in asserts), but it would not be
  *     sensible to make it this small anyway, and it should be at most 64K since it is indexed
  *     with uint16. We recommend 2K.
  * EGYPTIANWALK: You could also define EGYPTIANWALK here, but it is not used anywhere and has
@@ -201,7 +201,7 @@ static const TIFFField ojpegFields[] = {
   Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
   not defined.  Unfortunately, the MinGW and Borland compilers include
   a typedef for INT32, which causes a conflict.  MSVC does not include
-  a conficting typedef given the headers which are included.
+  a conflicting typedef given the headers which are included.
 */
 #if defined(__BORLANDC__) || defined(__MINGW32__)
 # define XMD_H 1
@@ -529,6 +529,8 @@ OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
        uint32 ma;
        uint64* mb;
        uint32 n;
+       const TIFFField* fip;
+
        switch(tag)
        {
                case TIFFTAG_JPEGIFOFFSET:
@@ -598,7 +600,10 @@ OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
                default:
                        return (*sp->vsetparent)(tif,tag,ap);
        }
-       TIFFSetFieldBit(tif,TIFFFieldWithTag(tif,tag)->field_bit);
+       fip = TIFFFieldWithTag(tif,tag);
+       if( fip == NULL ) /* shouldn't happen */
+           return(0);
+       TIFFSetFieldBit(tif,fip->field_bit);
        tif->tif_flags|=TIFF_DIRTYDIRECT;
        return(1);
 }
@@ -1077,7 +1082,7 @@ OJPEGReadHeaderInfo(TIFF* tif)
                        TIFFErrorExt(tif->tif_clientdata,module,"Incompatible vertical subsampling and image strip/tile length");
                        return(0);
                }
-               sp->restart_interval=((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8))*(sp->strile_length/(sp->subsampling_ver*8));
+               sp->restart_interval=(uint16)(((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8))*(sp->strile_length/(sp->subsampling_ver*8)));
        }
        if (OJPEGReadHeaderInfoSec(tif)==0)
                return(0);
@@ -1099,7 +1104,7 @@ OJPEGReadSecondarySos(TIFF* tif, uint16 s)
        assert(s<3);
        assert(sp->sos_end[0].log!=0);
        assert(sp->sos_end[s].log==0);
-       sp->plane_sample_offset=s-1;
+       sp->plane_sample_offset=(uint8)(s-1);
        while(sp->sos_end[sp->plane_sample_offset].log==0)
                sp->plane_sample_offset--;
        sp->in_buffer_source=sp->sos_end[sp->plane_sample_offset].in_buffer_source;
@@ -1377,7 +1382,8 @@ OJPEGReadHeaderInfoSec(TIFF* tif)
 static int
 OJPEGReadHeaderInfoSecStreamDri(TIFF* tif)
 {
-       /* this could easilly cause trouble in some cases... but no such cases have occured sofar */
+       /* This could easily cause trouble in some cases... but no such cases have
+           occurred so far */
        static const char module[]="OJPEGReadHeaderInfoSecStreamDri";
        OJPEGState* sp=(OJPEGState*)tif->tif_data;
        uint16 m;
@@ -1493,14 +1499,17 @@ OJPEGReadHeaderInfoSecStreamDht(TIFF* tif)
                nb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
                nb[sizeof(uint32)+2]=(m>>8);
                nb[sizeof(uint32)+3]=(m&255);
-               if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0)
+               if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0) {
+                        _TIFFfree(nb);
                        return(0);
+                }
                o=nb[sizeof(uint32)+4];
                if ((o&240)==0)
                {
                        if (3<o)
                        {
                                TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
+                                _TIFFfree(nb);
                                return(0);
                        }
                        if (sp->dctable[o]!=0)
@@ -1512,12 +1521,14 @@ OJPEGReadHeaderInfoSecStreamDht(TIFF* tif)
                        if ((o&240)!=16)
                        {
                                TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
+                                _TIFFfree(nb);
                                return(0);
                        }
                        o&=15;
                        if (3<o)
                        {
                                TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
+                                _TIFFfree(nb);
                                return(0);
                        }
                        if (sp->actable[o]!=0)
@@ -1770,7 +1781,7 @@ OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif)
                        ob[sizeof(uint32)+3]=67;
                        ob[sizeof(uint32)+4]=m;
                        TIFFSeekFile(tif,sp->qtable_offset[m],SEEK_SET); 
-                       p=TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
+                       p=(uint32)TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
                        if (p!=64)
                                return(0);
                        sp->qtable[m]=ob;
@@ -1813,7 +1824,7 @@ OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif)
                                }
                        }
                        TIFFSeekFile(tif,sp->dctable_offset[m],SEEK_SET);
-                       p=TIFFReadFile(tif,o,16);
+                       p=(uint32)TIFFReadFile(tif,o,16);
                        if (p!=16)
                                return(0);
                        q=0;
@@ -1829,12 +1840,12 @@ OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif)
                        *(uint32*)rb=ra;
                        rb[sizeof(uint32)]=255;
                        rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
-                       rb[sizeof(uint32)+2]=((19+q)>>8);
+                       rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
                        rb[sizeof(uint32)+3]=((19+q)&255);
                        rb[sizeof(uint32)+4]=m;
                        for (n=0; n<16; n++)
                                rb[sizeof(uint32)+5+n]=o[n];
-                       p=TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
+                       p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
                        if (p!=q)
                                return(0);
                        sp->dctable[m]=rb;
@@ -1877,7 +1888,7 @@ OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif)
                                }
                        }
                        TIFFSeekFile(tif,sp->actable_offset[m],SEEK_SET);  
-                       p=TIFFReadFile(tif,o,16);
+                       p=(uint32)TIFFReadFile(tif,o,16);
                        if (p!=16)
                                return(0);
                        q=0;
@@ -1893,12 +1904,12 @@ OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif)
                        *(uint32*)rb=ra;
                        rb[sizeof(uint32)]=255;
                        rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
-                       rb[sizeof(uint32)+2]=((19+q)>>8);
+                       rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
                        rb[sizeof(uint32)+3]=((19+q)&255);
                        rb[sizeof(uint32)+4]=(16|m);
                        for (n=0; n<16; n++)
                                rb[sizeof(uint32)+5+n]=o[n];
-                       p=TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
+                       p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
                        if (p!=q)
                                return(0);
                        sp->actable[m]=rb;
@@ -1956,6 +1967,7 @@ OJPEGReadBufferFill(OJPEGState* sp)
                                break;
                        case osibsJpegInterchangeFormat:
                                sp->in_buffer_source=osibsStrile;
+                                break;
                        case osibsStrile:
                                if (!_TIFFFillStriles( sp->tif ) 
                                    || sp->tif->tif_dir.td_stripoffset == NULL
@@ -2259,10 +2271,10 @@ OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len)
        /* P */
        sp->out_buffer[4]=8;
        /* Y */
-       sp->out_buffer[5]=(sp->sof_y>>8);
+       sp->out_buffer[5]=(uint8)(sp->sof_y>>8);
        sp->out_buffer[6]=(sp->sof_y&255);
        /* X */
-       sp->out_buffer[7]=(sp->sof_x>>8);
+       sp->out_buffer[7]=(uint8)(sp->sof_x>>8);
        sp->out_buffer[8]=(sp->sof_x&255);
        /* Nf */
        sp->out_buffer[9]=sp->samples_per_pixel_per_plane;
@@ -2375,7 +2387,12 @@ OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len)
 static int
 jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
 {
-       return(SETJMP(sp->exit_jmpbuf)?0:(jpeg_create_decompress(cinfo),1));
+       if( SETJMP(sp->exit_jmpbuf) )
+               return 0;
+       else {
+               jpeg_create_decompress(cinfo);
+               return 1;
+       }
 }
 #endif
 
@@ -2383,7 +2400,12 @@ jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
 static int
 jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image)
 {
-       return(SETJMP(sp->exit_jmpbuf)?0:(jpeg_read_header(cinfo,require_image),1));
+       if( SETJMP(sp->exit_jmpbuf) )
+               return 0;
+       else {
+               jpeg_read_header(cinfo,require_image);
+               return 1;
+       }
 }
 #endif
 
@@ -2391,7 +2413,12 @@ jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 requ
 static int
 jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
 {
-       return(SETJMP(sp->exit_jmpbuf)?0:(jpeg_start_decompress(cinfo),1));
+       if( SETJMP(sp->exit_jmpbuf) )
+               return 0;
+       else {
+               jpeg_start_decompress(cinfo);
+               return 1;
+       }
 }
 #endif
 
@@ -2399,7 +2426,12 @@ jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
 static int
 jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines)
 {
-       return(SETJMP(sp->exit_jmpbuf)?0:(jpeg_read_scanlines(cinfo,scanlines,max_lines),1));
+       if( SETJMP(sp->exit_jmpbuf) )
+               return 0;
+       else {
+               jpeg_read_scanlines(cinfo,scanlines,max_lines);
+               return 1;
+       }
 }
 #endif
 
@@ -2407,7 +2439,12 @@ jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* s
 static int
 jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines)
 {
-       return(SETJMP(sp->exit_jmpbuf)?0:(jpeg_read_raw_data(cinfo,data,max_lines),1));
+       if( SETJMP(sp->exit_jmpbuf) )
+               return 0;
+       else {
+               jpeg_read_raw_data(cinfo,data,max_lines);
+               return 1;
+       }
 }
 #endif
 
@@ -2469,6 +2506,10 @@ OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_b
        jpeg_encap_unwind(tif);
 }
 
+#ifdef _MSC_VER
+#pragma warning( push )
+#pragma warning( disable : 4702 ) /* unreachable code */
+#endif
 static boolean
 OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired)
 {
@@ -2478,6 +2519,9 @@ OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desi
        jpeg_encap_unwind(tif);
        return(0);
 }
+#ifdef _MSC_VER
+#pragma warning( pop ) 
+#endif
 
 static void
 OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo)
index 6168c8f..510d618 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_open.c,v 1.46 2010-12-06 16:54:54 faxguy Exp $ */
+/* $Id: tif_open.c,v 1.47 2016-01-23 21:20:34 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -169,7 +169,7 @@ TIFFClientOpen(
         * The following flags may be used to control intrinsic library
         * behaviour that may or may not be desirable (usually for
         * compatibility with some application that claims to support
-        * TIFF but only supports some braindead idea of what the
+        * TIFF but only supports some brain dead idea of what the
         * vendor thinks TIFF is):
         *
         * 'l' use little-endian byte order for creating a file
@@ -199,8 +199,8 @@ TIFFClientOpen(
         * The 'L', 'B', and 'H' flags are intended for applications
         * that can optimize operations on data by using a particular
         * bit order.  By default the library returns data in MSB2LSB
-        * bit order for compatibiltiy with older versions of this
-        * library.  Returning data in the bit order of the native cpu
+        * bit order for compatibility with older versions of this
+        * library.  Returning data in the bit order of the native CPU
         * makes the most sense but also requires applications to check
         * the value of the FillOrder tag; something they probably do
         * not do right now.
index 0b7d1d4..d7a6ff4 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_packbits.c,v 1.22 2012-06-20 05:25:33 fwarmerdam Exp $ */
+/* $Id: tif_packbits.c,v 1.24 2016-09-04 21:32:56 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
  *
  * PackBits Compression Algorithm Support
  */
+//#include <stdio.h>
 
 static int
 PackBitsPreEncode(TIFF* tif, uint16 s)
 {
        (void) s;
 
-       if (!(tif->tif_data = (uint8*)_TIFFmalloc(sizeof(tmsize_t))))
+        tif->tif_data = (uint8*)_TIFFmalloc(sizeof(tmsize_t));
+       if (tif->tif_data == NULL)
                return (0);
        /*
         * Calculate the scanline/tile-width size in bytes.
@@ -81,7 +83,9 @@ PackBitsEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
                /*
                 * Find the longest string of identical bytes.
                 */
-               b = *bp++, cc--, n = 1;
+               b = *bp++;
+               cc--;
+               n = 1;
                for (; cc > 0 && b == *bp; cc--, bp++)
                        n++;
        again:
@@ -222,7 +226,8 @@ PackBitsDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
        bp = (char*) tif->tif_rawcp;
        cc = tif->tif_rawcc;
        while (cc > 0 && occ > 0) {
-               n = (long) *bp++, cc--;
+               n = (long) *bp++;
+               cc--;
                /*
                 * Watch out for compilers that
                 * don't sign extend chars...
@@ -241,7 +246,8 @@ PackBitsDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
                                n = (long)occ;
                        }
                        occ -= n;
-                       b = *bp++, cc--;
+                       b = *bp++;
+                       cc--;
                        while (n-- > 0)
                                *op++ = (uint8) b;
                } else {                /* copy next n+1 bytes literally */
index d36f1f9..4e61445 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_pixarlog.c,v 1.38 2012-06-21 01:01:53 fwarmerdam Exp $ */
+/* $Id: tif_pixarlog.c,v 1.48 2016-09-23 22:12:18 erouault Exp $ */
 
 /*
  * Copyright (c) 1996-1997 Sam Leffler
  * input is assumed to be unsigned linear color values that represent
  * the range 0-1.  In the case of IEEE values, the 0-1 range is assumed to
  * be the normal linear color range, in addition over 1 values are
- * accepted up to a value of about 25.0 to encode "hot" hightlights and such.
+ * accepted up to a value of about 25.0 to encode "hot" highlights and such.
  * The encoding is lossless for 8-bit values, slightly lossy for the
  * other bit depths.  The actual color precision should be better
  * than the human eye can perceive with extra room to allow for
  * error introduced by further image computation.  As with any quantized
  * color format, it is possible to perform image calculations which
  * expose the quantization error. This format should certainly be less 
- * susceptable to such errors than standard 8-bit encodings, but more
- * susceptable than straight 16-bit or 32-bit encodings.
+ * susceptible to such errors than standard 8-bit encodings, but more
+ * susceptible than straight 16-bit or 32-bit encodings.
  *
  * On reading the internal format is converted to the desired output format.
  * The program can request which format it desires by setting the internal
@@ -93,6 +93,8 @@
 #include "tif_predict.h"
 #include "zlib.h"
 
+//#include <stdio.h>
+//#include <stdlib.h>
 #include <math.h>
 
 /* Tables for converting to/from 11 bit coded values */
@@ -295,33 +297,35 @@ horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op,
 static void
 horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op)
 {
-    register unsigned int  cr, cg, cb, ca, mask;
+    register unsigned int cr, cg, cb, ca, mask;
 
     if (n >= stride) {
        mask = CODE_MASK;
        if (stride == 3) {
-           op[0] = cr = wp[0];  op[1] = cg = wp[1];  op[2] = cb = wp[2];
+           op[0] = wp[0];  op[1] = wp[1];  op[2] = wp[2];
+            cr = wp[0];  cg = wp[1];  cb = wp[2];
            n -= 3;
            while (n > 0) {
                wp += 3;
                op += 3;
                n -= 3;
-               op[0] = (cr += wp[0]) & mask;
-               op[1] = (cg += wp[1]) & mask;
-               op[2] = (cb += wp[2]) & mask;
+               op[0] = (uint16)((cr += wp[0]) & mask);
+               op[1] = (uint16)((cg += wp[1]) & mask);
+               op[2] = (uint16)((cb += wp[2]) & mask);
            }
        } else if (stride == 4) {
-           op[0] = cr = wp[0];  op[1] = cg = wp[1];
-           op[2] = cb = wp[2];  op[3] = ca = wp[3];
+           op[0] = wp[0];  op[1] = wp[1];
+           op[2] = wp[2];  op[3] = wp[3];
+            cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3];
            n -= 4;
            while (n > 0) {
                wp += 4;
                op += 4;
                n -= 4;
-               op[0] = (cr += wp[0]) & mask;
-               op[1] = (cg += wp[1]) & mask;
-               op[2] = (cb += wp[2]) & mask;
-               op[3] = (ca += wp[3]) & mask;
+               op[0] = (uint16)((cr += wp[0]) & mask);
+               op[1] = (uint16)((cg += wp[1]) & mask);
+               op[2] = (uint16)((cb += wp[2]) & mask);
+               op[3] = (uint16)((ca += wp[3]) & mask);
            } 
        } else {
            REPEAT(stride, *op = *wp&mask; wp++; op++)
@@ -456,6 +460,7 @@ horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op,
 typedef        struct {
        TIFFPredictorState      predict;
        z_stream                stream;
+       tmsize_t                tbuf_size; /* only set/used on reading for now */
        uint16                  *tbuf; 
        uint16                  stride;
        int                     state;
@@ -555,7 +560,7 @@ PixarLogMakeTables(PixarLogState *sp)
     for (i = 0; i < lt2size; i++)  {
        if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1])
            j++;
-       FromLT2[i] = j;
+       FromLT2[i] = (uint16)j;
     }
 
     /*
@@ -567,14 +572,14 @@ PixarLogMakeTables(PixarLogState *sp)
     for (i = 0; i < 16384; i++)  {
        while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1])
            j++;
-       From14[i] = j;
+       From14[i] = (uint16)j;
     }
 
     j = 0;
     for (i = 0; i < 256; i++)  {
        while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1])
            j++;
-       From8[i] = j;
+       From8[i] = (uint16)j;
     }
 
     Fltsize = (float)(lt2size/2);
@@ -643,6 +648,20 @@ multiply_ms(tmsize_t m1, tmsize_t m2)
        return bytes;
 }
 
+static tmsize_t
+add_ms(tmsize_t m1, tmsize_t m2)
+{
+       tmsize_t bytes = m1 + m2;
+
+       /* if either input is zero, assume overflow already occurred */
+       if (m1 == 0 || m2 == 0)
+               bytes = 0;
+       else if (bytes <= m1 || bytes <= m2)
+               bytes = 0;
+
+       return bytes;
+}
+
 static int
 PixarLogFixupTags(TIFF* tif)
 {
@@ -670,11 +689,14 @@ PixarLogSetupDecode(TIFF* tif)
            td->td_samplesperpixel : 1);
        tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
                                      td->td_rowsperstrip), sizeof(uint16));
+       /* add one more stride in case input ends mid-stride */
+       tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
        if (tbuf_size == 0)
                return (0);   /* TODO: this is an error return without error report through TIFFErrorExt */
-       sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size+sizeof(uint16)*sp->stride);
+       sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
        if (sp->tbuf == NULL)
                return (0);
+       sp->tbuf_size = tbuf_size;
        if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
                sp->user_datafmt = PixarLogGuessDataFmt(td);
        if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) {
@@ -685,7 +707,7 @@ PixarLogSetupDecode(TIFF* tif)
        }
 
        if (inflateInit(&sp->stream) != Z_OK) {
-               TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg);
+               TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
                return (0);
        } else {
                sp->state |= PLSTATE_INIT;
@@ -708,7 +730,7 @@ PixarLogPreDecode(TIFF* tif, uint16 s)
        assert(sizeof(sp->stream.avail_in)==4);  /* if this assert gets raised,
            we need to simplify this code to reflect a ZLib that is likely updated
            to deal with 8byte memory sizes, though this code will respond
-           apropriately even before we simplify it */
+           appropriately even before we simplify it */
        sp->stream.avail_in = (uInt) tif->tif_rawcc;
        if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc)
        {
@@ -757,13 +779,19 @@ PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
        assert(sizeof(sp->stream.avail_out)==4);  /* if this assert gets raised,
            we need to simplify this code to reflect a ZLib that is likely updated
            to deal with 8byte memory sizes, though this code will respond
-           apropriately even before we simplify it */
+           appropriately even before we simplify it */
        sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
        if (sp->stream.avail_out != nsamples * sizeof(uint16))
        {
                TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
                return (0);
        }
+       /* Check that we will not fill more than what was allocated */
+       if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size)
+       {
+               TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size");
+               return (0);
+       }
        do {
                int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
                if (state == Z_STREAM_END) {
@@ -772,14 +800,14 @@ PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
                if (state == Z_DATA_ERROR) {
                        TIFFErrorExt(tif->tif_clientdata, module,
                            "Decoding error at scanline %lu, %s",
-                           (unsigned long) tif->tif_row, sp->stream.msg);
+                           (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
                        if (inflateSync(&sp->stream) != Z_OK)
                                return (0);
                        continue;
                }
                if (state != Z_OK) {
                        TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
-                           sp->stream.msg);
+                           sp->stream.msg ? sp->stream.msg : "(null)");
                        return (0);
                }
        } while (sp->stream.avail_out > 0);
@@ -881,7 +909,7 @@ PixarLogSetupEncode(TIFF* tif)
        }
 
        if (deflateInit(&sp->stream, sp->quality) != Z_OK) {
-               TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg);
+               TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)");
                return (0);
        } else {
                sp->state |= PLSTATE_INIT;
@@ -904,8 +932,8 @@ PixarLogPreEncode(TIFF* tif, uint16 s)
        assert(sizeof(sp->stream.avail_out)==4);  /* if this assert gets raised,
            we need to simplify this code to reflect a ZLib that is likely updated
            to deal with 8byte memory sizes, though this code will respond
-           apropriately even before we simplify it */
-       sp->stream.avail_out = tif->tif_rawdatasize;
+           appropriately even before we simplify it */
+       sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
        if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
        {
                TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
@@ -936,9 +964,9 @@ horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
                n -= 3;
                wp += 3;
                ip += 3;
-               r1 = (int32) CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
-               g1 = (int32) CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
-               b1 = (int32) CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
+               r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
+               g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
+               b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
            }
        } else if (stride == 4) {
            r2 = wp[0] = (uint16) CLAMP(ip[0]);
@@ -950,23 +978,20 @@ horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
                n -= 4;
                wp += 4;
                ip += 4;
-               r1 = (int32) CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
-               g1 = (int32) CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
-               b1 = (int32) CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
-               a1 = (int32) CLAMP(ip[3]); wp[3] = (a1-a2) & mask; a2 = a1;
+               r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
+               g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
+               b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
+               a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
            }
        } else {
-           ip += n - 1;        /* point to last one */
-           wp += n - 1;        /* point to last one */
-           n -= stride;
-           while (n > 0) {
-               REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);
-                               wp[stride] -= wp[0];
-                               wp[stride] &= mask;
-                               wp--; ip--)
-               n -= stride;
-           }
-           REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)
+        REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp++; ip++)
+        n -= stride;
+        while (n > 0) {
+            REPEAT(stride,
+                wp[0] = (uint16)(((int32)CLAMP(ip[0])-(int32)CLAMP(ip[-stride])) & mask);
+                wp++; ip++)
+            n -= stride;
+        }
        }
     }
 }
@@ -991,9 +1016,9 @@ horizontalDifference16(unsigned short *ip, int n, int stride,
                n -= 3;
                wp += 3;
                ip += 3;
-               r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
-               g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
-               b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
+               r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
+               g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
+               b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
            }
        } else if (stride == 4) {
            r2 = wp[0] = CLAMP(ip[0]);  g2 = wp[1] = CLAMP(ip[1]);
@@ -1003,23 +1028,20 @@ horizontalDifference16(unsigned short *ip, int n, int stride,
                n -= 4;
                wp += 4;
                ip += 4;
-               r1 = CLAMP(ip[0]); wp[0] = (r1-r2) & mask; r2 = r1;
-               g1 = CLAMP(ip[1]); wp[1] = (g1-g2) & mask; g2 = g1;
-               b1 = CLAMP(ip[2]); wp[2] = (b1-b2) & mask; b2 = b1;
-               a1 = CLAMP(ip[3]); wp[3] = (a1-a2) & mask; a2 = a1;
+               r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
+               g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
+               b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
+               a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
            }
        } else {
-           ip += n - 1;        /* point to last one */
-           wp += n - 1;        /* point to last one */
+        REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
            n -= stride;
            while (n > 0) {
-               REPEAT(stride, wp[0] = CLAMP(ip[0]);
-                               wp[stride] -= wp[0];
-                               wp[stride] &= mask;
-                               wp--; ip--)
-               n -= stride;
-           }
-           REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
+            REPEAT(stride,
+                wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
+                wp++; ip++)
+            n -= stride;
+        }
        }
     }
 }
@@ -1042,9 +1064,9 @@ horizontalDifference8(unsigned char *ip, int n, int stride,
            n -= 3;
            while (n > 0) {
                n -= 3;
-               r1 = CLAMP(ip[3]); wp[3] = (r1-r2) & mask; r2 = r1;
-               g1 = CLAMP(ip[4]); wp[4] = (g1-g2) & mask; g2 = g1;
-               b1 = CLAMP(ip[5]); wp[5] = (b1-b2) & mask; b2 = b1;
+               r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
+               g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
+               b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
                wp += 3;
                ip += 3;
            }
@@ -1054,26 +1076,23 @@ horizontalDifference8(unsigned char *ip, int n, int stride,
            n -= 4;
            while (n > 0) {
                n -= 4;
-               r1 = CLAMP(ip[4]); wp[4] = (r1-r2) & mask; r2 = r1;
-               g1 = CLAMP(ip[5]); wp[5] = (g1-g2) & mask; g2 = g1;
-               b1 = CLAMP(ip[6]); wp[6] = (b1-b2) & mask; b2 = b1;
-               a1 = CLAMP(ip[7]); wp[7] = (a1-a2) & mask; a2 = a1;
+               r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
+               g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
+               b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
+               a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
                wp += 4;
                ip += 4;
            }
        } else {
-           wp += n + stride - 1;       /* point to last one */
-           ip += n + stride - 1;       /* point to last one */
-           n -= stride;
-           while (n > 0) {
-               REPEAT(stride, wp[0] = CLAMP(ip[0]);
-                               wp[stride] -= wp[0];
-                               wp[stride] &= mask;
-                               wp--; ip--)
-               n -= stride;
-           }
-           REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
-       }
+        REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
+        n -= stride;
+        while (n > 0) {
+            REPEAT(stride,
+                wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
+                wp++; ip++)
+            n -= stride;
+        }
+    }
     }
 }
 
@@ -1114,6 +1133,13 @@ PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
        }
 
        llen = sp->stride * td->td_imagewidth;
+    /* Check against the number of elements (of size uint16) of sp->tbuf */
+    if( n > (tmsize_t)(td->td_rowsperstrip * llen) )
+    {
+        TIFFErrorExt(tif->tif_clientdata, module,
+                     "Too many input bytes provided");
+        return 0;
+    }
 
        for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) {
                switch (sp->user_datafmt)  {
@@ -1144,7 +1170,7 @@ PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
        assert(sizeof(sp->stream.avail_in)==4);  /* if this assert gets raised,
            we need to simplify this code to reflect a ZLib that is likely updated
            to deal with 8byte memory sizes, though this code will respond
-           apropriately even before we simplify it */
+           appropriately even before we simplify it */
        sp->stream.avail_in = (uInt) (n * sizeof(uint16));
        if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n)
        {
@@ -1156,7 +1182,7 @@ PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
        do {
                if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
                        TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
-                           sp->stream.msg);
+                           sp->stream.msg ? sp->stream.msg : "(null)");
                        return (0);
                }
                if (sp->stream.avail_out == 0) {
@@ -1198,7 +1224,7 @@ PixarLogPostEncode(TIFF* tif)
                    break;
                default:
                        TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
-                       sp->stream.msg);
+                       sp->stream.msg ? sp->stream.msg : "(null)");
                    return (0);
                }
        } while (state != Z_STREAM_END);
@@ -1210,7 +1236,7 @@ PixarLogClose(TIFF* tif)
 {
        TIFFDirectory *td = &tif->tif_dir;
 
-       /* In a really sneaky (and really incorrect, and untruthfull, and
+       /* In a really sneaky (and really incorrect, and untruthful, and
         * troublesome, and error-prone) maneuver that completely goes against
         * the spirit of TIFF, and breaks TIFF, on close, we covertly
         * modify both bitspersample and sampleformat in the directory to
@@ -1268,7 +1294,7 @@ PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap)
                        if (deflateParams(&sp->stream,
                            sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) {
                                TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
-                                       sp->stream.msg);
+                                       sp->stream.msg ? sp->stream.msg : "(null)");
                                return (0);
                        }
                }
index ca4f015..e26bbab 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id: tif_predict.c,v 1.32 2010-03-10 18:56:49 bfriesen Exp $ */
+/* $Id: tif_predict.c,v 1.40 2016-11-04 09:19:13 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
 
 #define        PredictorState(tif)     ((TIFFPredictorState*) (tif)->tif_data)
 
-static void horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc);
-static void fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc);
+static int fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc);
 static int PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
 static int PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
 static int PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s);
@@ -79,6 +81,15 @@ PredictorSetup(TIFF* tif)
                                    td->td_sampleformat);
                                return 0;
                        }
+                        if (td->td_bitspersample != 16
+                            && td->td_bitspersample != 24
+                            && td->td_bitspersample != 32
+                            && td->td_bitspersample != 64) { /* Should 64 be allowed? */
+                                TIFFErrorExt(tif->tif_clientdata, module,
+                                             "Floating point \"Predictor\" not supported with %d-bit samples",
+                                             td->td_bitspersample);
+                               return 0;
+                            }
                        break;
                default:
                        TIFFErrorExt(tif->tif_clientdata, module,
@@ -173,7 +184,7 @@ PredictorSetupDecode(TIFF* tif)
                }
                /*
                 * Allocate buffer to keep the decoded bytes before
-                * rearranging in the ight order
+                * rearranging in the right order
                 */
        }
 
@@ -208,7 +219,24 @@ PredictorSetupEncode(TIFF* tif)
                     sp->encodetile = tif->tif_encodetile;
                     tif->tif_encodetile = PredictorEncodeTile;
                 }
-       }
+
+                /*
+                 * If the data is horizontally differenced 16-bit data that
+                 * requires byte-swapping, then it must be byte swapped after
+                 * the differentiation step.  We do this with a special-purpose
+                 * routine and override the normal post decoding logic that
+                 * the library setup when the directory was read.
+                 */
+                if (tif->tif_flags & TIFF_SWAB) {
+                    if (sp->encodepfunc == horDiff16) {
+                            sp->encodepfunc = swabHorDiff16;
+                            tif->tif_postdecode = _TIFFNoPostDecode;
+                    } else if (sp->encodepfunc == horDiff32) {
+                            sp->encodepfunc = swabHorDiff32;
+                            tif->tif_postdecode = _TIFFNoPostDecode;
+                    }
+                }
+        }
 
        else if (sp->predictor == 3) {
                sp->encodepfunc = fpDiff;
@@ -240,13 +268,25 @@ PredictorSetupEncode(TIFF* tif)
     case 0:  ;                 \
     }
 
-static void
+/* Remarks related to C standard compliance in all below functions : */
+/* - to avoid any undefined behaviour, we only operate on unsigned types */
+/*   since the behaviour of "overflows" is defined (wrap over) */
+/* - when storing into the byte stream, we explicitly mask with 0xff so */
+/*   as to make icc -check=conversions happy (not necessary by the standard) */
+
+static int
 horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
        tmsize_t stride = PredictorState(tif)->stride;
 
-       char* cp = (char*) cp0;
-       assert((cc%stride)==0);
+       unsigned char* cp = (unsigned char*) cp0;
+    if((cc%stride)!=0)
+    {
+        TIFFErrorExt(tif->tif_clientdata, "horAcc8",
+                     "%s", "(cc%stride)!=0");
+        return 0;
+    }
+
        if (cc > stride) {
                /*
                 * Pipeline the most common cases.
@@ -258,9 +298,9 @@ horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
                        cc -= 3;
                        cp += 3;
                        while (cc>0) {
-                               cp[0] = (char) (cr += cp[0]);
-                               cp[1] = (char) (cg += cp[1]);
-                               cp[2] = (char) (cb += cp[2]);
+                               cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
+                               cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
+                               cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
                                cc -= 3;
                                cp += 3;
                        }
@@ -272,10 +312,10 @@ horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
                        cc -= 4;
                        cp += 4;
                        while (cc>0) {
-                               cp[0] = (char) (cr += cp[0]);
-                               cp[1] = (char) (cg += cp[1]);
-                               cp[2] = (char) (cb += cp[2]);
-                               cp[3] = (char) (ca += cp[3]);
+                               cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
+                               cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
+                               cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
+                               cp[3] = (unsigned char) ((ca += cp[3]) & 0xff);
                                cc -= 4;
                                cp += 4;
                        }
@@ -283,77 +323,71 @@ horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
                        cc -= stride;
                        do {
                                REPEAT4(stride, cp[stride] =
-                                       (char) (cp[stride] + *cp); cp++)
+                                       (unsigned char) ((cp[stride] + *cp) & 0xff); cp++)
                                cc -= stride;
                        } while (cc>0);
                }
        }
+       return 1;
 }
 
-static void
+static int
 swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
-       tmsize_t stride = PredictorState(tif)->stride;
        uint16* wp = (uint16*) cp0;
        tmsize_t wc = cc / 2;
 
-       assert((cc%(2*stride))==0);
-
-       if (wc > stride) {
-               TIFFSwabArrayOfShort(wp, wc);
-               wc -= stride;
-               do {
-                       REPEAT4(stride, wp[stride] += wp[0]; wp++)
-                       wc -= stride;
-               } while (wc > 0);
-       }
+        TIFFSwabArrayOfShort(wp, wc);
+        return horAcc16(tif, cp0, cc);
 }
 
-static void
+static int
 horAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
        tmsize_t stride = PredictorState(tif)->stride;
        uint16* wp = (uint16*) cp0;
        tmsize_t wc = cc / 2;
 
-       assert((cc%(2*stride))==0);
+    if((cc%(2*stride))!=0)
+    {
+        TIFFErrorExt(tif->tif_clientdata, "horAcc16",
+                     "%s", "cc%(2*stride))!=0");
+        return 0;
+    }
 
        if (wc > stride) {
                wc -= stride;
                do {
-                       REPEAT4(stride, wp[stride] += wp[0]; wp++)
+                       REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++)
                        wc -= stride;
                } while (wc > 0);
        }
+       return 1;
 }
 
-static void
+static int
 swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
-       tmsize_t stride = PredictorState(tif)->stride;
        uint32* wp = (uint32*) cp0;
        tmsize_t wc = cc / 4;
 
-       assert((cc%(4*stride))==0);
-
-       if (wc > stride) {
-               TIFFSwabArrayOfLong(wp, wc);
-               wc -= stride;
-               do {
-                       REPEAT4(stride, wp[stride] += wp[0]; wp++)
-                       wc -= stride;
-               } while (wc > 0);
-       }
+        TIFFSwabArrayOfLong(wp, wc);
+       return horAcc32(tif, cp0, cc);
 }
 
-static void
+static int
 horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
        tmsize_t stride = PredictorState(tif)->stride;
        uint32* wp = (uint32*) cp0;
        tmsize_t wc = cc / 4;
 
-       assert((cc%(4*stride))==0);
+    if((cc%(4*stride))!=0)
+    {
+        TIFFErrorExt(tif->tif_clientdata, "horAcc32",
+                     "%s", "cc%(4*stride))!=0");
+        return 0;
+    }
 
        if (wc > stride) {
                wc -= stride;
@@ -362,12 +396,13 @@ horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
                        wc -= stride;
                } while (wc > 0);
        }
+       return 1;
 }
 
 /*
  * Floating point predictor accumulation routine.
  */
-static void
+static int
 fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
        tmsize_t stride = PredictorState(tif)->stride;
@@ -375,15 +410,22 @@ fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
        tmsize_t wc = cc / bps;
        tmsize_t count = cc;
        uint8 *cp = (uint8 *) cp0;
-       uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
+       uint8 *tmp;
 
-       assert((cc%(bps*stride))==0);
+    if(cc%(bps*stride)!=0)
+    {
+        TIFFErrorExt(tif->tif_clientdata, "fpAcc",
+                     "%s", "cc%(bps*stride))!=0");
+        return 0;
+    }
 
+    tmp = (uint8 *)_TIFFmalloc(cc);
        if (!tmp)
-               return;
+               return 0;
 
        while (count > stride) {
-               REPEAT4(stride, cp[stride] += cp[0]; cp++)
+               REPEAT4(stride, cp[stride] =
+                        (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
                count -= stride;
        }
 
@@ -401,6 +443,7 @@ fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
                }
        }
        _TIFFfree(tmp);
+    return 1;
 }
 
 /*
@@ -416,8 +459,7 @@ PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
        assert(sp->decodepfunc != NULL);  
 
        if ((*sp->decoderow)(tif, op0, occ0, s)) {
-               (*sp->decodepfunc)(tif, op0, occ0);
-               return 1;
+               return (*sp->decodepfunc)(tif, op0, occ0);
        } else
                return 0;
 }
@@ -440,10 +482,16 @@ PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
        if ((*sp->decodetile)(tif, op0, occ0, s)) {
                tmsize_t rowsize = sp->rowsize;
                assert(rowsize > 0);
-               assert((occ0%rowsize)==0);
+               if((occ0%rowsize) !=0)
+        {
+            TIFFErrorExt(tif->tif_clientdata, "PredictorDecodeTile",
+                         "%s", "occ0%rowsize != 0");
+            return 0;
+        }
                assert(sp->decodepfunc != NULL);
                while (occ0 > 0) {
-                       (*sp->decodepfunc)(tif, op0, rowsize);
+                       if( !(*sp->decodepfunc)(tif, op0, rowsize) )
+                return 0;
                        occ0 -= rowsize;
                        op0 += rowsize;
                }
@@ -452,14 +500,19 @@ PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s)
                return 0;
 }
 
-static void
+static int
 horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
        TIFFPredictorState* sp = PredictorState(tif);
        tmsize_t stride = sp->stride;
-       char* cp = (char*) cp0;
+       unsigned char* cp = (unsigned char*) cp0;
 
-       assert((cc%stride)==0);
+    if((cc%stride)!=0)
+    {
+        TIFFErrorExt(tif->tif_clientdata, "horDiff8",
+                     "%s", "(cc%stride)!=0");
+        return 0;
+    }
 
        if (cc > stride) {
                cc -= stride;
@@ -467,67 +520,92 @@ horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc)
                 * Pipeline the most common cases.
                 */
                if (stride == 3) {
-                       int r1, g1, b1;
-                       int r2 = cp[0];
-                       int g2 = cp[1];
-                       int b2 = cp[2];
+                       unsigned int r1, g1, b1;
+                       unsigned int r2 = cp[0];
+                       unsigned int g2 = cp[1];
+                       unsigned  int b2 = cp[2];
                        do {
-                               r1 = cp[3]; cp[3] = r1-r2; r2 = r1;
-                               g1 = cp[4]; cp[4] = g1-g2; g2 = g1;
-                               b1 = cp[5]; cp[5] = b1-b2; b2 = b1;
+                               r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
+                               g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
+                               b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
                                cp += 3;
                        } while ((cc -= 3) > 0);
                } else if (stride == 4) {
-                       int r1, g1, b1, a1;
-                       int r2 = cp[0];
-                       int g2 = cp[1];
-                       int b2 = cp[2];
-                       int a2 = cp[3];
+                       unsigned int r1, g1, b1, a1;
+                       unsigned int r2 = cp[0];
+                       unsigned int g2 = cp[1];
+                       unsigned int b2 = cp[2];
+                       unsigned int a2 = cp[3];
                        do {
-                               r1 = cp[4]; cp[4] = r1-r2; r2 = r1;
-                               g1 = cp[5]; cp[5] = g1-g2; g2 = g1;
-                               b1 = cp[6]; cp[6] = b1-b2; b2 = b1;
-                               a1 = cp[7]; cp[7] = a1-a2; a2 = a1;
+                               r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
+                               g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
+                               b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
+                               a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
                                cp += 4;
                        } while ((cc -= 4) > 0);
                } else {
                        cp += cc - 1;
                        do {
-                               REPEAT4(stride, cp[stride] -= cp[0]; cp--)
+                               REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
                        } while ((cc -= stride) > 0);
                }
        }
+       return 1;
 }
 
-static void
+static int
 horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
        TIFFPredictorState* sp = PredictorState(tif);
        tmsize_t stride = sp->stride;
-       int16 *wp = (int16*) cp0;
+       uint16 *wp = (uint16*) cp0;
        tmsize_t wc = cc/2;
 
-       assert((cc%(2*stride))==0);
+    if((cc%(2*stride))!=0)
+    {
+        TIFFErrorExt(tif->tif_clientdata, "horDiff8",
+                     "%s", "(cc%(2*stride))!=0");
+        return 0;
+    }
 
        if (wc > stride) {
                wc -= stride;
                wp += wc - 1;
                do {
-                       REPEAT4(stride, wp[stride] -= wp[0]; wp--)
+                       REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
                        wc -= stride;
                } while (wc > 0);
        }
+       return 1;
 }
 
-static void
+static int
+swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
+{
+    uint16* wp = (uint16*) cp0;
+    tmsize_t wc = cc / 2;
+