Commit 7b8247419 for imagemagick.org

commit 7b82474199e1f96a03e5f2fca7c27052c811d394
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Sun Nov 29 09:17:06 2026 -0500

    add a bounds check to prevent reads out of bounds

diff --git a/coders/hdr.c b/coders/hdr.c
index 1c91bbbc7..737c1547e 100644
--- a/coders/hdr.c
+++ b/coders/hdr.c
@@ -62,10 +62,24 @@
 #include "MagickCore/string-private.h"
 #include "MagickCore/module.h"

+/*
+  Define declarations.
+
+  Radiance only run-length encodes scanlines that are 8 to 32767 pixels wide
+  (the encoded scanline header stores the width in 15 bits).
+*/
+#define HDRMinimumScanlineLength  8
+#define HDRMaximumScanlineLength  0x7fff
+#define HDRIsRunlengthEncoded(columns) \
+  (((columns) >= HDRMinimumScanlineLength) && \
+   ((columns) <= HDRMaximumScanlineLength))
+
 /*
   Forward declarations.
 */
 static MagickBooleanType
+  HDRReadRunlengthPixels(Image *,unsigned char *),
+  HDRWriteRunlengthPixels(Image *,const unsigned char *),
   WriteHDRImage(const ImageInfo *,Image *,ExceptionInfo *);

 /*
@@ -97,11 +111,11 @@ static MagickBooleanType
 static MagickBooleanType IsHDR(const unsigned char *magick,
   const size_t length)
 {
-  if (length < 10)
-    return(MagickFalse);
-  if (LocaleNCompare((const char *) magick,"#?RADIANCE",10) == 0)
+  if ((length >= 10) &&
+      (LocaleNCompare((const char *) magick,"#?RADIANCE",10) == 0))
     return(MagickTrue);
-  if (LocaleNCompare((const char *) magick,"#?RGBE",6) == 0)
+  if ((length >= 6) &&
+      (LocaleNCompare((const char *) magick,"#?RGBE",6) == 0))
     return(MagickTrue);
   return(MagickFalse);
 }
@@ -141,11 +155,11 @@ static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
     value[MagickPathExtent];

   double
-    gamma;
+    scale;

   float
-    chromaticity[6],
-    white_point[2];
+    chromaticity[6] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
+    white_point[2] = { 0.0f, 0.0f };

   Image
     *image;
@@ -169,7 +183,6 @@ static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
     y;

   unsigned char
-    *end,
     pixel[4],
     *pixels;

@@ -198,11 +211,9 @@ static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
   *format='\0';
   c=ReadBlobByte(image);
   if (c == EOF)
-    {
-      image=DestroyImage(image);
-      return((Image *) NULL);
-    }
-  while (isgraph((int) ((unsigned char) c)) && (image->columns == 0) && (image->rows == 0))
+    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+  while ((c != EOF) && (isgraph((int) ((unsigned char) c)) != 0) &&
+         (image->columns == 0) && (image->rows == 0))
   {
     if (c == (int) '#')
       {
@@ -381,8 +392,8 @@ static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
       image->chromaticity.white_point.x=white_point[0];
       image->chromaticity.white_point.y=white_point[1];
     }
-  image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?
-    NoCompression : RLECompression;
+  image->compression=HDRIsRunlengthEncoded(image->columns) ?
+    RLECompression : NoCompression;
   if (image_info->ping != MagickFalse)
     {
       (void) CloseBlob(image);
@@ -413,57 +424,35 @@ static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
     else
       {
         count=ReadBlob(image,4*sizeof(*pixel),pixel);
-        if (count != 4)
+        if (count != (ssize_t) (4*sizeof(*pixel)))
           break;
-        if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)
+        if ((pixel[0] != 2) || (pixel[1] != 2) ||
+            ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) !=
+             image->columns))
           {
+            /*
+              Not a new-style RLE scanline header: the data is stored flat.
+            */
             (void) memcpy(pixels,pixel,4*sizeof(*pixel));
-            count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);
+            count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),
+              pixels+4);
+            if (count != (ssize_t) (4*(image->columns-1)*sizeof(*pixels)))
+              break;
             image->compression=NoCompression;
           }
         else
-          {
-            unsigned char
-              *p;
-
-            p=pixels;
-            for (i=0; i < 4; i++)
+          if (HDRReadRunlengthPixels(image,pixels) == MagickFalse)
             {
-              end=&pixels[(i+1)*(ssize_t) image->columns];
-              while (p < end)
-              {
-                count=ReadBlob(image,2*sizeof(*pixel),pixel);
-                if (count < 1)
-                  break;
-                if (pixel[0] > 128)
-                  {
-                    count=(ssize_t) pixel[0]-128;
-                    if ((count == 0) || (count > (ssize_t) (end-p)))
-                      break;
-                    while (count-- > 0)
-                      *p++=pixel[1];
-                  }
-                else
-                  {
-                    count=(ssize_t) pixel[0];
-                    if ((count == 0) || (count > (ssize_t) (end-p)))
-                      break;
-                    *p++=pixel[1];
-                    if (--count > 0)
-                      {
-                        count=ReadBlob(image,(size_t) count*sizeof(*p),p);
-                        if (count < 1)
-                          break;
-                        p+=(ptrdiff_t) count;
-                      }
-                  }
-              }
+              pixels=(unsigned char *) RelinquishMagickMemory(pixels);
+              ThrowReaderException(CorruptImageError,"UnableToReadImageData");
             }
-          }
       }
     q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
     if (q == (Quantum *) NULL)
-      break;
+      {
+        status=MagickFalse;
+        break;
+      }
     i=0;
     for (x=0; x < (ssize_t) image->columns; x++)
     {
@@ -486,18 +475,21 @@ static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
       SetPixelBlue(image,0,q);
       if (pixel[3] != 0)
         {
-          gamma=pow(2.0,pixel[3]-(128.0+8.0));
-          SetPixelRed(image,ClampToQuantum((double) QuantumRange*gamma*
+          scale=pow(2.0,pixel[3]-(128.0+8.0));
+          SetPixelRed(image,ClampToQuantum((double) QuantumRange*scale*
             (double) pixel[0]),q);
-          SetPixelGreen(image,ClampToQuantum((double) QuantumRange*gamma*
+          SetPixelGreen(image,ClampToQuantum((double) QuantumRange*scale*
             (double) pixel[1]),q);
-          SetPixelBlue(image,ClampToQuantum((double) QuantumRange*gamma*
+          SetPixelBlue(image,ClampToQuantum((double) QuantumRange*scale*
             (double) pixel[2]),q);
         }
       q+=(ptrdiff_t) GetPixelChannels(image);
     }
     if (SyncAuthenticPixels(image,exception) == MagickFalse)
-      break;
+      {
+        status=MagickFalse;
+        break;
+      }
     status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
       image->rows);
     if (status == MagickFalse)
@@ -599,68 +591,140 @@ ModuleExport void UnregisterHDRImage(void)
 %
 */

-static size_t HDRWriteRunlengthPixels(Image *image,unsigned char *pixels)
+static MagickBooleanType HDRReadRunlengthPixels(Image *image,
+  unsigned char *pixels)
 {
-#define MinimumRunlength 4
+  ssize_t
+    count,
+    i;

-  size_t
-    p,
-    q;
+  unsigned char
+    *end,
+    *p,
+    pixel[2];

-  size_t
-    runlength;
+  /*
+    Decode one new-style RLE scanline: four planes (R,G,B,E), each exactly
+    image->columns bytes long.  Any malformed run is an error rather than
+    silently misaligning the remaining planes.
+  */
+  p=pixels;
+  for (i=0; i < 4; i++)
+  {
+    end=pixels+(i+1)*(ssize_t) image->columns;
+    while (p < end)
+    {
+      if (ReadBlob(image,2*sizeof(*pixel),pixel) != (ssize_t) (2*sizeof(*pixel)))
+        return(MagickFalse);
+      if (pixel[0] > 128)
+        {
+          count=(ssize_t) pixel[0]-128;
+          if (count > (ssize_t) (end-p))
+            return(MagickFalse);
+          while (count-- > 0)
+            *p++=pixel[1];
+        }
+      else
+        {
+          count=(ssize_t) pixel[0];
+          if ((count == 0) || (count > (ssize_t) (end-p)))
+            return(MagickFalse);
+          *p++=pixel[1];
+          if (--count > 0)
+            {
+              if (ReadBlob(image,(size_t) count*sizeof(*p),p) != count)
+                return(MagickFalse);
+              p+=count;
+            }
+        }
+    }
+  }
+  return(MagickTrue);
+}

-  ssize_t
+static MagickBooleanType HDRWriteRunlengthPixels(Image *image,
+  const unsigned char *pixels)
+{
+#define MinimumRunlength 4
+#define MaximumRunlength 127
+#define MaximumLiteral 128
+
+  size_t
+    beg,
     count,
-    previous_count;
+    i,
+    p,
+    run;

   unsigned char
     pixel[2];

-  for (p=0; p < image->columns; )
+  /*
+    Encode one plane of a scanline.  Runs of MinimumRunlength or more equal
+    bytes are written as (128+length,value); everything else is written as
+    literals (length,bytes...).
+  */
+  p=0;
+  while (p < image->columns)
   {
-    q=p;
-    runlength=0;
-    previous_count=0;
-    while ((runlength < MinimumRunlength) && (q < image->columns))
+    /*
+      Find the next run that is long enough to be worth encoding.
+    */
+    run=1;
+    for (beg=p; beg < image->columns; beg+=run)
     {
-      q+=(ptrdiff_t) runlength;
-      previous_count=(ssize_t) runlength;
-      runlength=1;
-      while ((pixels[q] == pixels[q+runlength]) &&
-             ((q+runlength) < image->columns) && (runlength < 127))
-       runlength++;
+      for (run=1; ((beg+run) < image->columns) && (run < MaximumRunlength) &&
+           (pixels[beg+run] == pixels[beg]); run++) ;
+      if (run >= MinimumRunlength)
+        break;
     }
-    if ((previous_count > 1) && (previous_count == (ssize_t) (q-p)))
+    if (run < MinimumRunlength)
+      run=0;
+    /*
+      A short run (2 or 3 bytes) filling the gap before the long run is
+      cheaper as a run than as a literal.
+    */
+    if (((beg-p) > 1) && ((beg-p) < MinimumRunlength))
       {
-        pixel[0]=(unsigned char) (128+previous_count);
-        pixel[1]=pixels[p];
-        if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
-          break;
-        p=q;
+        for (i=p+1; i < beg; i++)
+          if (pixels[i] != pixels[p])
+            break;
+        if (i == beg)
+          {
+            pixel[0]=(unsigned char) (128+(beg-p));
+            pixel[1]=pixels[p];
+            if (WriteBlob(image,2*sizeof(*pixel),pixel) !=
+                (ssize_t) (2*sizeof(*pixel)))
+              return(MagickFalse);
+            p=beg;
+          }
       }
-    while (p < q)
+    /*
+      Literal bytes up to the start of the long run.
+    */
+    while (p < beg)
     {
-      count=(ssize_t) (q-p);
-      if (count > 128)
-        count=128;
+      count=beg-p;
+      if (count > MaximumLiteral)
+        count=MaximumLiteral;
       pixel[0]=(unsigned char) count;
-      if (WriteBlob(image,sizeof(*pixel),pixel) < 1)
-        break;
-      if (WriteBlob(image,(size_t) count*sizeof(*pixel),&pixels[p]) < 1)
-        break;
-      p+=(ptrdiff_t) count;
+      if (WriteBlob(image,sizeof(*pixel),pixel) != (ssize_t) sizeof(*pixel))
+        return(MagickFalse);
+      if (WriteBlob(image,count*sizeof(*pixel),pixels+p) != (ssize_t) count)
+        return(MagickFalse);
+      p+=count;
     }
-    if (runlength >= MinimumRunlength)
+    if (run >= MinimumRunlength)
       {
-        pixel[0]=(unsigned char) (128+runlength);
-        pixel[1]=pixels[q];
-        if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
-          break;
-        p+=(ptrdiff_t) runlength;
+        pixel[0]=(unsigned char) (128+run);
+        pixel[1]=pixels[beg];
+        if (WriteBlob(image,2*sizeof(*pixel),pixel) !=
+            (ssize_t) (2*sizeof(*pixel)))
+          return(MagickFalse);
+        p=beg+run;
       }
   }
-  return(p);
+  return(MagickTrue);
 }

 static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
@@ -707,8 +771,12 @@ static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
   if (status == MagickFalse)
     return(status);
-  if (IsRGBColorspace(image->colorspace) == MagickFalse)
-    (void) TransformImageColorspace(image,RGBColorspace,exception);
+  if ((IsRGBColorspace(image->colorspace) == MagickFalse) &&
+      (TransformImageColorspace(image,RGBColorspace,exception) == MagickFalse))
+    {
+      (void) CloseBlob(image);
+      return(MagickFalse);
+    }
   /*
     Write header.
   */
@@ -727,7 +795,7 @@ static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
   if (property != (const char *) NULL)
     {
       count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n",
-        strtod(property,(char **) NULL));
+        StringToDouble(property,(char **) NULL));
       (void) WriteBlob(image,(size_t) count,(unsigned char *) header);
     }
   if (image->gamma != 0.0)
@@ -760,8 +828,11 @@ static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
   {
     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
     if (p == (const Quantum *) NULL)
-      break;
-    if ((image->columns >= 8) && (image->columns <= 0x7ffff))
+      {
+        status=MagickFalse;
+        break;
+      }
+    if (HDRIsRunlengthEncoded(image->columns))
       {
         pixel[0]=2;
         pixel[1]=2;
@@ -778,35 +849,38 @@ static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
     for (x=0; x < (ssize_t) image->columns; x++)
     {
       double
-        gamma;
+        maximum;

       pixel[0]=0;
       pixel[1]=0;
       pixel[2]=0;
       pixel[3]=0;
-      gamma=QuantumScale*(double) GetPixelRed(image,p);
-      if ((QuantumScale*(double) GetPixelGreen(image,p)) > gamma)
-        gamma=QuantumScale*(double) GetPixelGreen(image,p);
-      if ((QuantumScale*(double) GetPixelBlue(image,p)) > gamma)
-        gamma=QuantumScale*(double) GetPixelBlue(image,p);
-      if (gamma > MagickEpsilon)
+      maximum=QuantumScale*(double) GetPixelRed(image,p);
+      if ((QuantumScale*(double) GetPixelGreen(image,p)) > maximum)
+        maximum=QuantumScale*(double) GetPixelGreen(image,p);
+      if ((QuantumScale*(double) GetPixelBlue(image,p)) > maximum)
+        maximum=QuantumScale*(double) GetPixelBlue(image,p);
+      if (maximum > MagickEpsilon)
         {
+          double
+            scale;
+
           int
             exponent;

-          gamma=frexp(gamma,&exponent)*256.0/gamma;
+          scale=frexp(maximum,&exponent)*256.0/maximum;
           if (GetPixelRed(image,p) > 0)
-            pixel[0]=(unsigned char) (gamma*QuantumScale*(double)
+            pixel[0]=(unsigned char) (scale*QuantumScale*(double)
               GetPixelRed(image,p));
           if (GetPixelGreen(image,p) > 0)
-            pixel[1]=(unsigned char) (gamma*QuantumScale*
+            pixel[1]=(unsigned char) (scale*QuantumScale*
               (double) GetPixelGreen(image,p));
           if (GetPixelBlue(image,p) > 0)
-            pixel[2]=(unsigned char) (gamma*QuantumScale*(double)
+            pixel[2]=(unsigned char) (scale*QuantumScale*(double)
               GetPixelBlue(image,p));
           pixel[3]=(unsigned char) (exponent+128);
         }
-      if ((image->columns >= 8) && (image->columns <= 0x7ffff))
+      if (HDRIsRunlengthEncoded(image->columns))
         {
           pixels[x]=pixel[0];
           pixels[x+(ssize_t) image->columns]=pixel[1];
@@ -822,11 +896,15 @@ static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
         }
       p+=(ptrdiff_t) GetPixelChannels(image);
     }
-    if ((image->columns >= 8) && (image->columns <= 0x7ffff))
+    if (HDRIsRunlengthEncoded(image->columns))
       {
         for (i=0; i < 4; i++)
-          length=HDRWriteRunlengthPixels(image,
+        {
+          status=HDRWriteRunlengthPixels(image,
             &pixels[i*(ssize_t) image->columns]);
+          if (status == MagickFalse)
+            break;
+        }
       }
     else
       {