Commit 18dea4bc9 for imagemagick.org

commit 18dea4bc91396883ef1bfc6be0f441001ee95bbe
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Wed Dec 2 16:19:56 2026 -0500

    reject images over 65535 pixels or a row stride that overflows 16 bits

diff --git a/coders/palm.c b/coders/palm.c
index ef65ac83f..478f39d00 100644
--- a/coders/palm.c
+++ b/coders/palm.c
@@ -180,27 +180,45 @@ static MagickBooleanType
 %
 %  The format of the FindColor method is:
 %
-%      int FindColor(PixelInfo *pixel)
+%      ssize_t FindColor(const PixelInfo *pixel)
 %
 %  A description of each parameter follows:
 %
-%    o int: the index of the matching color or -1 if not found/
+%    o ssize_t: the index of the matching color or -1 if not found.
 %
 %    o pixel: a pointer to the PixelInfo to be matched.
 %
 */
-static ssize_t FindColor(PixelInfo *packet)
+static ssize_t FindColor(const PixelInfo *packet)
 {
   ssize_t
     i;

+  unsigned char
+    blue,
+    green,
+    red;
+
+  red=ScaleQuantumToChar(ClampToQuantum(packet->red));
+  green=ScaleQuantumToChar(ClampToQuantum(packet->green));
+  blue=ScaleQuantumToChar(ClampToQuantum(packet->blue));
   for (i=0; i < 256; i++)
-    if (ScaleQuantumToChar(ClampToQuantum(packet->red)) == PalmPalette[i][0] &&
-        ScaleQuantumToChar(ClampToQuantum(packet->green)) == PalmPalette[i][1] &&
-        ScaleQuantumToChar(ClampToQuantum(packet->blue)) == PalmPalette[i][2])
+    if ((red == PalmPalette[i][0]) && (green == PalmPalette[i][1]) &&
+        (blue == PalmPalette[i][2]))
       return(i);
   return(-1);
 }
+
+/*
+  Scale a quantum to the range [0..maximum] with rounding (the 5-6-5 direct
+  color channels of a 16-bit Palm pixmap).
+*/
+static inline unsigned int PalmScaleQuantum(const Quantum quantum,
+  const unsigned int maximum)
+{
+  return((unsigned int) (((double) maximum*(double) ClampToQuantum(
+    (MagickRealType) quantum))/(double) QuantumRange+0.5));
+}

 /*
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -213,7 +231,7 @@ static ssize_t FindColor(PixelInfo *packet)
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  ReadPALMImage() reads an image of raw bites in LSB order and returns it.  It
+%  ReadPALMImage() reads an image of raw bits in LSB order and returns it.  It
 %  allocates the memory necessary for the new Image structure and returns a
 %  pointer to the new image.
 %
@@ -310,10 +328,6 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
     image->rows=ReadBlobMSBShort(image);
     if (EOFBlob(image) != MagickFalse)
       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
-    status=SetImageExtent(image,image->columns,image->rows,exception);
-    if (status == MagickFalse)
-      return(DestroyImageList(image));
-    (void) SetImageBackgroundColor(image,exception);
     bytes_per_row=ReadBlobMSBShort(image);
     flags=ReadBlobMSBShort(image);
     bits_per_pixel=(size_t) ReadBlobByte(image);
@@ -333,6 +347,25 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
       ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
     pad=ReadBlobMSBShort(image);
     (void) pad;
+    if (EOFBlob(image) != MagickFalse)
+      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+    if ((image->columns == 0) || (image->rows == 0))
+      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+    if (((flags & PALM_IS_COMPRESSED_FLAG) != 0) &&
+        (compressionType == PALM_COMPRESSION_NONE))
+      ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
+    if (bits_per_pixel == 16)
+      {
+        if (bytes_per_row < (2*image->columns))
+          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+      }
+    else
+      if ((bytes_per_row*8) < (image->columns*bits_per_pixel))
+        ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+    status=SetImageExtent(image,image->columns,image->rows,exception);
+    if (status == MagickFalse)
+      return(DestroyImageList(image));
+    (void) SetImageBackgroundColor(image,exception);
     /*
       Initialize image colormap.
     */
@@ -348,8 +381,8 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
         (void) greenbits;
         bluebits=(size_t) ReadBlobByte(image);  /* # of bits of blue */
         (void) bluebits;
-        ReadBlobByte(image);  /* reserved by Palm */
-        ReadBlobByte(image);  /* reserved by Palm */
+        (void) ReadBlobByte(image);  /* reserved by Palm */
+        (void) ReadBlobByte(image);  /* reserved by Palm */
         transpix.red=(double) (QuantumRange*ReadBlobByte(image)/31);
         transpix.green=(double) (QuantumRange*ReadBlobByte(image)/63);
         transpix.blue=(double) (QuantumRange*ReadBlobByte(image)/31);
@@ -362,9 +395,11 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
         if (flags & PALM_HAS_COLORMAP_FLAG)
           {
             count=(ssize_t) ReadBlobMSBShort(image);
-            for (i=0; i < (ssize_t) count; i++)
+            if (count > 256)
+              ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+            for (i=0; i < count; i++)
             {
-              ReadBlobByte(image);
+              (void) ReadBlobByte(image);
               idx=ConstrainColormapIndex(image,255-i,exception);
               image->colormap[idx].red=(MagickRealType)
                 ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
@@ -372,20 +407,23 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
                 ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
               image->colormap[idx].blue=(MagickRealType)
                 ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
+            }
+            if (EOFBlob(image) != MagickFalse)
+              ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+          }
+        else
+          for (i=0; i < ((ssize_t) 1L << bits_per_pixel); i++)
+          {
+            idx=ConstrainColormapIndex(image,255-i,exception);
+            image->colormap[idx].red=(MagickRealType)
+              ScaleCharToQuantum(PalmPalette[i][0]);
+            image->colormap[idx].green=(MagickRealType)
+              ScaleCharToQuantum(PalmPalette[i][1]);
+            image->colormap[idx].blue=(MagickRealType)
+              ScaleCharToQuantum(PalmPalette[i][2]);
           }
-        }
-      else
-        for (i=0; i < ((ssize_t) 1L << bits_per_pixel); i++)
-        {
-          idx=ConstrainColormapIndex(image,255-i,exception);
-          image->colormap[idx].red=(MagickRealType)
-            ScaleCharToQuantum(PalmPalette[i][0]);
-          image->colormap[idx].green=(MagickRealType)
-            ScaleCharToQuantum(PalmPalette[i][1]);
-          image->colormap[idx].blue=(MagickRealType)
-            ScaleCharToQuantum(PalmPalette[i][2]);
-        }
       }
+    size=0;
     if (flags & PALM_IS_COMPRESSED_FLAG)
       size=ReadBlobMSBShort(image);
     (void) size;
@@ -422,38 +460,40 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
            sizeof(*last_row));
       }
     mask=((size_t) 1U << bits_per_pixel)-1;
+    image->compression=NoCompression;
+    if ((flags & PALM_IS_COMPRESSED_FLAG) != 0)
+      {
+        if (compressionType == PALM_COMPRESSION_RLE)
+          image->compression=RLECompression;
+        else
+          if (compressionType == PALM_COMPRESSION_SCANLINE)
+            image->compression=FaxCompression;
+      }
     for (y=0; y < (ssize_t) image->rows; y++)
     {
       if ((flags & PALM_IS_COMPRESSED_FLAG) == 0)
         {
-          /* TODO move out of loop! */
-          image->compression=NoCompression;
           count=ReadBlob(image,bytes_per_row,one_row);
           if (count != (ssize_t) bytes_per_row)
             break;
         }
       else
-        {
-          if (compressionType == PALM_COMPRESSION_RLE)
-            {
-              /* TODO move out of loop! */
-              image->compression=RLECompression;
-              for (i=0; i < (ssize_t) bytes_per_row; )
-              {
-                count=(ssize_t) ReadBlobByte(image);
-                if (count < 0)
-                  break;
-                count=MagickMin(count,(ssize_t) bytes_per_row-i);
-                byte=(size_t) ReadBlobByte(image);
-                (void) memset(one_row+i,(int) byte,(size_t) count);
-                i+=count;
-              }
+        if (compressionType == PALM_COMPRESSION_RLE)
+          {
+            for (i=0; i < (ssize_t) bytes_per_row; )
+            {
+              count=(ssize_t) ReadBlobByte(image);
+              byte=(size_t) ReadBlobByte(image);
+              if ((count < 0) || (byte > 255))
+                break;
+              count=MagickMin(count,(ssize_t) bytes_per_row-i);
+              (void) memset(one_row+i,(int) byte,(size_t) count);
+              i+=count;
+            }
           }
         else
           if (compressionType == PALM_COMPRESSION_SCANLINE)
             {
-              /* TODO move out of loop! */
-              image->compression=FaxCompression;
               for (i=0; i < (ssize_t) bytes_per_row; i+=8)
               {
                 count=(ssize_t) ReadBlobByte(image);
@@ -469,26 +509,18 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
                     one_row[i+bit]=last_row[i+bit];
                 }
               }
-              (void) memcpy(last_row, one_row, bytes_per_row);
+              (void) memcpy(last_row,one_row,bytes_per_row);
             }
-        }
       ptr=one_row;
       q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
       if (q == (Quantum *) NULL)
         break;
       if (bits_per_pixel == 16)
         {
-          if (image->columns > (2*bytes_per_row))
-            {
-              one_row=(unsigned char *) RelinquishMagickMemory(one_row);
-              if (compressionType == PALM_COMPRESSION_SCANLINE)
-                last_row=(unsigned char *) RelinquishMagickMemory(last_row);
-              ThrowReaderException(CorruptImageError,"CorruptImage");
-            }
           for (x=0; x < (ssize_t) image->columns; x++)
           {
-            color16=(*ptr++ << 8);
-            color16|=(*ptr++);
+            color16=(unsigned short) (*ptr++ << 8);
+            color16|=(unsigned short) (*ptr++);
             SetPixelRed(image,(Quantum) ((QuantumRange*((color16 >> 11) &
               0x1f))/0x1f),q);
             SetPixelGreen(image,(Quantum) ((QuantumRange*((color16 >> 5) &
@@ -504,13 +536,6 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
           bit=(int) (8-bits_per_pixel);
           for (x=0; x < (ssize_t) image->columns; x++)
           {
-            if ((size_t) (ptr-one_row) >= bytes_per_row)
-              {
-                one_row=(unsigned char *) RelinquishMagickMemory(one_row);
-                if (compressionType == PALM_COMPRESSION_SCANLINE)
-                  last_row=(unsigned char *) RelinquishMagickMemory(last_row);
-                ThrowReaderException(CorruptImageError,"CorruptImage");
-              }
             index=(Quantum) (mask-(((*ptr) & (mask << bit)) >> bit));
             SetPixelIndex(image,index,q);
             SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
@@ -523,27 +548,30 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
               }
             q+=(ptrdiff_t) GetPixelChannels(image);
           }
-          if (SyncAuthenticPixels(image,exception) == MagickFalse)
+        }
+      if (SyncAuthenticPixels(image,exception) == MagickFalse)
+        break;
+      if (image->previous == (Image *) NULL)
+        {
+          status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+            image->rows);
+          if (status == MagickFalse)
             break;
         }
-        if (image->previous == (Image *) NULL)
-          {
-            status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
-              image->rows);
-            if (status == MagickFalse)
-              break;
-          }
-        if (EOFBlob(image) != MagickFalse)
-          break;
-      }
+      if (EOFBlob(image) != MagickFalse)
+        break;
+    }
     if (flags & PALM_HAS_TRANSPARENCY_FLAG)
       {
-        ssize_t
-           idx;
-        idx=ConstrainColormapIndex(image,(ssize_t) (mask-
-          transparentIndex),exception);
         if (bits_per_pixel != 16)
-          transpix=image->colormap[idx];
+          {
+            ssize_t
+              idx;
+
+            idx=ConstrainColormapIndex(image,(ssize_t) (mask-
+              transparentIndex),exception);
+            transpix=image->colormap[idx];
+          }
         (void) TransparentPaintImage(image,&transpix,(Quantum) TransparentAlpha,
           MagickFalse,exception);
       }
@@ -569,9 +597,8 @@ static Image *ReadPALMImage(const ImageInfo *image_info,
         */
         totalOffset+=(MagickOffsetType) (nextDepthOffset*4);
         if (totalOffset >= (MagickOffsetType) GetBlobSize(image))
-          ThrowReaderException(CorruptImageError,"ImproperImageHeader")
-        else
-          seekNextDepth=SeekBlob(image,totalOffset,SEEK_SET);
+          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+        seekNextDepth=SeekBlob(image,totalOffset,SEEK_SET);
         if (seekNextDepth != totalOffset)
           ThrowReaderException(CorruptImageError,"ImproperImageHeader");
         /*
@@ -698,11 +725,11 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,

   MagickOffsetType
     currentOffset,
+    endOffset,
     offset,
-    scene;
-
-  PixelInfo
-    transpix;
+    padding,
+    scene,
+    sizeOffset;

   QuantizeInfo
     *quantize_info;
@@ -719,6 +746,7 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
     one;

   ssize_t
+    i,
     x,
     y;

@@ -735,7 +763,8 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,

   unsigned short
     color16,
-    flags;
+    flags,
+    transparentColor;

   /*
     Open output image file.
@@ -752,28 +781,34 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
   if (status == MagickFalse)
     return(status);
   quantize_info=AcquireQuantizeInfo(image_info);
-  flags=0;
   currentOffset=0;
   transparentIndex=0;
-  transpix.red=0.0;
-  transpix.green=0.0;
-  transpix.blue=0.0;
-  transpix.alpha=0.0;
   one=1;
-  version=0;
   scene=0;
   number_scenes=GetImageListLength(image);
   do
   {
+    /*
+      Per-image state: nothing may leak from one image of the list into the
+      next one.
+    */
+    flags=0;
+    transparentColor=0;
+    version=0;
     if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
       (void) TransformImageColorspace(image,sRGBColorspace,exception);
     count=GetNumberColors(image,NULL,exception);
     for (bits_per_pixel=1; (bits_per_pixel < 64) && (one << bits_per_pixel) < count; bits_per_pixel*=2) ;
     if (bits_per_pixel > 16)
       bits_per_pixel=16;
-    else
-      if (bits_per_pixel < 16)
-        (void) TransformImageColorspace(image,image->colorspace,exception);
+    bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/
+      bits_per_pixel))*2;
+    if ((image->columns > 65535UL) || (image->rows > 65535UL) ||
+        (bytes_per_row > 65535UL))
+      {
+        quantize_info=DestroyQuantizeInfo(quantize_info);
+        ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
+      }
     if (bits_per_pixel < 8)
       {
         (void) TransformImageColorspace(image,GRAYColorspace,exception);
@@ -782,18 +817,22 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
       }
     if ((image->storage_class == PseudoClass) && (image->colors > 256))
       (void) SetImageStorageClass(image,DirectClass,exception);
-    if (image->storage_class == PseudoClass)
-      flags|=PALM_HAS_COLORMAP_FLAG;
-    else
+    /*
+      The colormap flag promises a color table in the file and the direct
+      color flag promises 5-6-5 pixels, so only set them for the depths that
+      actually carry that data.
+    */
+    if (bits_per_pixel == 16)
       flags|=PALM_IS_DIRECT_COLOR;
-    (void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */
-    (void) WriteBlobMSBShort(image,(unsigned short) image->rows);  /* height */
-    bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/
-      bits_per_pixel))*2;
-    (void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row);
+    else
+      if ((bits_per_pixel == 8) && (image->storage_class == PseudoClass))
+        flags|=PALM_HAS_COLORMAP_FLAG;
     if ((image_info->compression == RLECompression) ||
         (image_info->compression == FaxCompression))
       flags|=PALM_IS_COMPRESSED_FLAG;
+    (void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */
+    (void) WriteBlobMSBShort(image,(unsigned short) image->rows);  /* height */
+    (void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row);
     (void) WriteBlobMSBShort(image, flags);
     (void) WriteBlobByte(image,(unsigned char) bits_per_pixel);
     if (bits_per_pixel > 1)
@@ -843,31 +882,60 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
             }
             offset+=2+(MagickOffsetType) count*4;
           }
-      else  /* Map colors to Palm standard colormap */
-        {
-          Image
-            *affinity_image;
-
-          affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette,
-            exception);
-          (void) TransformImageColorspace(affinity_image,
-            affinity_image->colorspace,exception);
-          (void) RemapImage(quantize_info,image,affinity_image,exception);
-          for (y=0; y < (ssize_t) image->rows; y++)
+        else  /* Map colors to Palm standard colormap */
           {
-            q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
-            if (q == (Quantum *) NULL)
-              break;
-            for (x=0; x < (ssize_t) image->columns; x++)
+            Image
+              *affinity_image;
+
+            ssize_t
+              *palm_index;
+
+            affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette,
+              exception);
+            if (affinity_image == (Image *) NULL)
+              {
+                quantize_info=DestroyQuantizeInfo(quantize_info);
+                ThrowWriterException(ResourceLimitError,
+                  "MemoryAllocationFailed");
+              }
+            (void) RemapImage(quantize_info,image,affinity_image,exception);
+            affinity_image=DestroyImage(affinity_image);
+            /*
+              Translate each colormap entry to its Palm palette index once,
+              rather than searching the palette for every pixel.
+            */
+            palm_index=(ssize_t *) AcquireQuantumMemory(image->colors,
+              sizeof(*palm_index));
+            if (palm_index == (ssize_t *) NULL)
+              {
+                quantize_info=DestroyQuantizeInfo(quantize_info);
+                ThrowWriterException(ResourceLimitError,
+                  "MemoryAllocationFailed");
+              }
+            for (i=0; i < (ssize_t) image->colors; i++)
             {
-              SetPixelIndex(image,(Quantum) FindColor(&image->colormap[(ssize_t)
-                GetPixelIndex(image,q)]),q);
-              q+=(ptrdiff_t) GetPixelChannels(image);
+              palm_index[i]=FindColor(image->colormap+i);
+              if (palm_index[i] < 0)
+                palm_index[i]=0;
+            }
+            for (y=0; y < (ssize_t) image->rows; y++)
+            {
+              q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
+              if (q == (Quantum *) NULL)
+                break;
+              for (x=0; x < (ssize_t) image->columns; x++)
+              {
+                i=(ssize_t) GetPixelIndex(image,q);
+                SetPixelIndex(image,(Quantum) palm_index[i],q);
+                q+=(ptrdiff_t) GetPixelChannels(image);
+              }
+              if (SyncAuthenticPixels(image,exception) == MagickFalse)
+                break;
             }
+            palm_index=(ssize_t *) RelinquishMagickMemory(palm_index);
           }
-          affinity_image=DestroyImage(affinity_image);
-        }
       }
+    sizeOffset=offset;  /* where the compressed size field lives */
     if (flags & PALM_IS_COMPRESSED_FLAG)
       (void) WriteBlobMSBShort(image,0);  /* fill in size later */
     last_row=(unsigned char *) NULL;
@@ -885,7 +953,7 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
       sizeof(*one_row));
     if (one_row == (unsigned char *) NULL)
       {
-        if (last_row != (unsigned char *) NULL)
+        if (last_row != (unsigned char *) NULL)
           last_row=(unsigned char *) RelinquishMagickMemory(last_row);
         quantize_info=DestroyQuantizeInfo(quantize_info);
         ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
@@ -896,21 +964,20 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
       (void) memset(ptr,0,bytes_per_row);
       p=GetVirtualPixels(image,0,y,image->columns,1,exception);
       if (p == (const Quantum *) NULL)
-        break;
+        {
+          status=MagickFalse;
+          break;
+        }
       if (bits_per_pixel == 16)
         {
           for (x=0; x < (ssize_t) image->columns; x++)
           {
-            color16=(unsigned short) ((((31*(ssize_t) GetPixelRed(image,p))/
-              (ssize_t) QuantumRange) << 11) | (((63*(ssize_t)
-              GetPixelGreen(image,p))/(ssize_t) QuantumRange) << 5) |
-              ((31*(ssize_t) GetPixelBlue(image,p))/(ssize_t) QuantumRange));
+            color16=(unsigned short) ((PalmScaleQuantum(GetPixelRed(image,p),
+              31) << 11) | (PalmScaleQuantum(GetPixelGreen(image,p),63) << 5) |
+              PalmScaleQuantum(GetPixelBlue(image,p),31));
             if (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)
               {
-                transpix.red=(MagickRealType) GetPixelRed(image,p);
-                transpix.green=(MagickRealType) GetPixelGreen(image,p);
-                transpix.blue=(MagickRealType) GetPixelBlue(image,p);
-                transpix.alpha=(MagickRealType) GetPixelAlpha(image,p);
+                transparentColor=color16;
                 flags|=PALM_HAS_TRANSPARENCY_FLAG;
               }
             *ptr++=(unsigned char) ((color16 >> 8) & 0xff);
@@ -921,7 +988,7 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
       else
         {
           byte=0x00;
-          bit=(unsigned char) (8-bits_per_pixel);
+          bit=(int) (8-bits_per_pixel);
           for (x=0; x < (ssize_t) image->columns; x++)
           {
             if (bits_per_pixel >= 8)
@@ -929,14 +996,14 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
             else
               color=(unsigned char) (GetPixelIndex(image,p)*
                 ((one << bits_per_pixel)-1)/MagickMax(1*image->colors-1,1));
-            byte|=color << bit;
+            byte|=(unsigned char) (color << bit);
             if (bit != 0)
-              bit-=(unsigned char) bits_per_pixel;
+              bit-=(int) bits_per_pixel;
             else
               {
                 *ptr++=byte;
                 byte=0x00;
-                bit=(unsigned char) (8-bits_per_pixel);
+                bit=(int) (8-bits_per_pixel);
               }
             p+=(ptrdiff_t) GetPixelChannels(image);
           }
@@ -948,13 +1015,16 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
           x=0;
           while (x < (ssize_t) bytes_per_row)
           {
-            byte=one_row[x];
+            byte=one_row[x++];
             count=1;
-            while ((one_row[++x] == byte) && (count < 255) &&
-                   (x < (ssize_t) bytes_per_row))
+            while ((x < (ssize_t) bytes_per_row) && (one_row[x] == byte) &&
+                   (count < 255))
+            {
               count++;
+              x++;
+            }
             (void) WriteBlobByte(image,(unsigned char) count);
-            (void) WriteBlobByte(image,(unsigned char) byte);
+            (void) WriteBlobByte(image,byte);
           }
         }
       else
@@ -963,7 +1033,7 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
             char
               tmpbuf[8],
               *tptr;
-
+
             for (x=0;  x < (ssize_t) bytes_per_row; x+=8)
             {
               tptr = tmpbuf;
@@ -971,7 +1041,7 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
               {
                 if ((y == 0) || (last_row[x + bit] != one_row[x + bit]))
                   {
-                    byte |= (1 << (7 - bit));
+                    byte |= (unsigned char) (1 << (7 - bit));
                     *tptr++ = (char) one_row[x + bit];
                   }
               }
@@ -983,46 +1053,63 @@ static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
           }
         else
           (void) WriteBlob(image,bytes_per_row,one_row);
-      }
+    }
+    one_row=(unsigned char *) RelinquishMagickMemory(one_row);
+    if (last_row != (unsigned char *) NULL)
+      last_row=(unsigned char *) RelinquishMagickMemory(last_row);
+    if (status == MagickFalse)
+      break;
+    /*
+      Go back and patch the header fields that were only known after the pixel
+      data was written, then return to the end of this image.  The end of the
+      image is remembered up front: the seeks below move the write position
+      and `offset` must not be reused as the compressed-size location.
+    */
+    endOffset=TellBlob(image);
     if (flags & PALM_HAS_TRANSPARENCY_FLAG)
       {
-        offset=SeekBlob(image,currentOffset+6,SEEK_SET);
+        (void) SeekBlob(image,currentOffset+6,SEEK_SET);
         (void) WriteBlobMSBShort(image,flags);
-        offset=SeekBlob(image,currentOffset+12,SEEK_SET);
+        (void) SeekBlob(image,currentOffset+12,SEEK_SET);
         (void) WriteBlobByte(image,(unsigned char) transparentIndex);  /* trans index */
       }
     if (bits_per_pixel == 16)
       {
-        offset=SeekBlob(image,currentOffset+20,SEEK_SET);
+        (void) SeekBlob(image,currentOffset+20,SEEK_SET);
         (void) WriteBlobByte(image,0);  /* reserved by Palm */
-        (void) WriteBlobByte(image,(unsigned char) ((31*transpix.red)/
-          (double) QuantumRange));
-        (void) WriteBlobByte(image,(unsigned char) ((63*transpix.green)/
-          (double) QuantumRange));
-        (void) WriteBlobByte(image,(unsigned char) ((31*transpix.blue)/
-          (double) QuantumRange));
+        (void) WriteBlobByte(image,(unsigned char) ((transparentColor >> 11) &
+          0x1f));
+        (void) WriteBlobByte(image,(unsigned char) ((transparentColor >> 5) &
+          0x3f));
+        (void) WriteBlobByte(image,(unsigned char) (transparentColor & 0x1f));
       }
     if (flags & PALM_IS_COMPRESSED_FLAG)  /* fill in size now */
       {
-        offset=SeekBlob(image,currentOffset+offset,SEEK_SET);
-        (void) WriteBlobMSBShort(image,(unsigned short) ((MagickOffsetType)
-          GetBlobSize(image)-currentOffset-offset));
+        (void) SeekBlob(image,currentOffset+sizeOffset,SEEK_SET);
+        (void) WriteBlobMSBShort(image,(unsigned short) (endOffset-
+          currentOffset-sizeOffset));
       }
-    if (one_row != (unsigned char *) NULL)
-      one_row=(unsigned char *) RelinquishMagickMemory(one_row);
-    if (last_row != (unsigned char *) NULL)
-      last_row=(unsigned char *) RelinquishMagickMemory(last_row);
-    if (GetNextImageInList(image) == (Image *) NULL)
+    (void) SeekBlob(image,endOffset,SEEK_SET);
+    if ((GetNextImageInList(image) == (Image *) NULL) ||
+        (image_info->adjoin == MagickFalse))
       break;
     /* padding to 4 byte word */
-    (void) WriteBlobPadding(image,(size_t) (GetBlobSize(image) % 4),'\0');
+    for (padding=(4-(endOffset % 4)) % 4; padding > 0; padding--)
+      (void) WriteBlobByte(image,0);
     /* write nextDepthOffset and return to end of image */
-    offset=SeekBlob(image,currentOffset+10,SEEK_SET);
-    nextDepthOffset=(size_t) (((MagickOffsetType) GetBlobSize(image)-
-      currentOffset)/4);
+    endOffset=TellBlob(image);
+    nextDepthOffset=(size_t) ((endOffset-currentOffset)/4);
+    if (nextDepthOffset > 65535UL)
+      {
+        (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
+          "NextDepthOffsetExceedsLimit","`%s'",image->filename);
+        status=MagickFalse;
+        break;
+      }
+    (void) SeekBlob(image,currentOffset+10,SEEK_SET);
     (void) WriteBlobMSBShort(image,(unsigned short) nextDepthOffset);
-    currentOffset=(MagickOffsetType) GetBlobSize(image);
-    offset=SeekBlob(image,currentOffset,SEEK_SET);
+    currentOffset=endOffset;
+    (void) SeekBlob(image,currentOffset,SEEK_SET);
     image=SyncNextImageInList(image);
     status=SetImageProgress(image,SaveImagesTag,scene++,number_scenes);
     if (status == MagickFalse)