Commit 7f34ed459 for imagemagick.org

commit 7f34ed459b1735a78085a030aac261705d64516b
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Sat Dec 5 12:51:25 2026 -0500

    use a sentinel to guard against # thread changes + avoid 32-bit truncation of thread limit

diff --git a/MagickCore/resample-private.h b/MagickCore/resample-private.h
index ec7b9dd59..2a8ccd550 100644
--- a/MagickCore/resample-private.h
+++ b/MagickCore/resample-private.h
@@ -57,10 +57,20 @@ static inline ResampleFilter **AcquireResampleFilterTLS(const Image *image,
   ResampleFilter
     **filter;

+  MagickSizeType
+    limit;
+
   size_t
     number_threads;

-  number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
+  /*
+    Clamp before narrowing: an unlimited or oversized thread limit must not
+    truncate on 32-bit builds or wrap number_threads+1 to zero below.
+  */
+  limit=GetMagickResourceLimit(ThreadResource);
+  if (limit > (MagickSizeType) (MAGICK_SSIZE_MAX/sizeof(*filter)-1))
+    limit=(MagickSizeType) (MAGICK_SSIZE_MAX/sizeof(*filter)-1);
+  number_threads=(size_t) limit;
   if (number_threads == 0)
     number_threads=1;
   /*
diff --git a/MagickCore/resample.c b/MagickCore/resample.c
index c5cd1cb6f..cbfb5d299 100644
--- a/MagickCore/resample.c
+++ b/MagickCore/resample.c
@@ -553,8 +553,11 @@ MagickExport MagickBooleanType ResamplePixelColor(
   pixel->red = pixel->green = pixel->blue = 0.0;
   if (pixel->colorspace == CMYKColorspace)
     pixel->black = 0.0;
-  if (pixel->alpha_trait != UndefinedPixelTrait)
-    pixel->alpha = 0.0;
+  /*
+    Always clear alpha: the loop below accumulates into it unconditionally,
+    so leaving it uninitialized for alpha-less pixels summed into garbage.
+  */
+  pixel->alpha = 0.0;

   /*
     Determine the parallelogram bounding box fitted to the ellipse
@@ -679,8 +682,8 @@ MagickExport MagickBooleanType ResamplePixelColor(
     Finalize results of resampling
   */
   divisor_m = 1.0/divisor_m;
-  if (pixel->alpha_trait != UndefinedPixelTrait)
-    pixel->alpha = (double) ClampToQuantum(divisor_m*pixel->alpha);
+  /* alpha-less images sum OpaqueAlpha here, so this yields OpaqueAlpha */
+  pixel->alpha = (double) ClampToQuantum(divisor_m*pixel->alpha);
   divisor_c = 1.0/divisor_c;
   pixel->red   = (double) ClampToQuantum(divisor_c*pixel->red);
   pixel->green = (double) ClampToQuantum(divisor_c*pixel->green);
@@ -1173,8 +1176,13 @@ MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,
      In this case some alternative means of pixel sampling, such as
      the average of the whole image is needed to get a reasonable
      result. Calculate only as needed.
+
+     All limit tests below are written in the negated "!(x <= limit)" form so
+     that a NaN coefficient (e.g. from inf*0 in distortion derivatives near a
+     perspective horizon) also trips the limit, instead of slipping past
+     every comparison and producing NaN ellipse bounds.
   */
-  if ( (4*A*C - B*B) > MagickMaximumValue ) {
+  if ( !((4*A*C - B*B) <= MagickMaximumValue) ) {
     resample_filter->limit_reached = MagickTrue;
     return;
   }
@@ -1188,7 +1196,7 @@ MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,

   /* A degenerate (zero area) ellipse cannot be sampled - treat the area as
      too large, as for the limits above */
-  if ( A <= 0.0 || (A*C-0.25*B*B) <= 0.0 ) {
+  if ( !(A > 0.0) || !((A*C-0.25*B*B) > 0.0) || !(F <= MagickMaximumValue) ) {
     resample_filter->limit_reached = MagickTrue;
     return;
   }
@@ -1211,8 +1219,8 @@ MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,
    * This limit needs more work, as it is too slow for larger images
    * with tiled views of the horizon.
   */
-  if ( (resample_filter->Uwidth * resample_filter->Vlimit)
-         > (4.0*resample_filter->image_area)) {
+  if ( !((resample_filter->Uwidth * resample_filter->Vlimit)
+         <= (4.0*resample_filter->image_area)) ) {
     resample_filter->limit_reached = MagickTrue;
     return;
   }
@@ -1356,8 +1364,14 @@ MagickExport void SetResampleFilter(ResampleFilter *resample_filter,
 #endif

 #if FILTER_LUT
+  /*
+    A critical section, not "omp single": single is a worksharing construct
+    with an implied barrier and is non-conforming (can hang) when reached by
+    only some threads of a team, e.g. a per-thread AcquireResampleFilter().
+    Outside a parallel region both behave identically.
+  */
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp single
+  #pragma omp critical (MagickCore_SetResampleFilter)
 #endif
   {
     if (IsStringTrue(GetImageArtifact(resample_filter->image,
diff --git a/MagickCore/resample.h b/MagickCore/resample.h
index 67e8b05ac..fc08b614d 100644
--- a/MagickCore/resample.h
+++ b/MagickCore/resample.h
@@ -25,9 +25,12 @@ extern "C" {
 #endif

 /*
-  WARNING:  The order of this table must also match the order of a table
-  located in AcquireResizeFilter() in "resize.c" otherwise the users filter
-  will not match the actual filter that is setup.
+  WARNING:  The order of this table must also match the order of the
+  "mapping" and "filters" tables located in AcquireResizeFilter() in
+  "resize.c" otherwise the users filter will not match the actual filter that
+  is setup.  Append new filters immediately before SentinelFilter; resize.c
+  rejects at compile time any table whose entry count differs from
+  SentinelFilter.
 */
 typedef enum
 {
diff --git a/MagickCore/resize-private.h b/MagickCore/resize-private.h
index 638b891ee..1806d1a54 100644
--- a/MagickCore/resize-private.h
+++ b/MagickCore/resize-private.h
@@ -18,6 +18,8 @@
 #ifndef MAGICKCORE_RESIZE_PRIVATE_H
 #define MAGICKCORE_RESIZE_PRIVATE_H

+#include "MagickCore/resize.h"
+
 #if defined(__cplusplus) || defined(c_plusplus)
 extern "C" {
 #endif
@@ -41,6 +43,11 @@ typedef enum
   LagrangeWeightingFunction,
   CosineWeightingFunction,
   MagicKernelSharpWeightingFunction,
+  /*
+    Appended (not inserted) so the values above, which the OpenCL resize
+    kernels depend on, are unchanged.  Not GPU-accelerated: CPU fallback.
+  */
+  CubicSplineWeightingFunction,
   LastWeightingFunction
 } ResizeWeightingFunctionType;

diff --git a/MagickCore/resize.c b/MagickCore/resize.c
index b545f93f2..e7d7f1d73 100644
--- a/MagickCore/resize.c
+++ b/MagickCore/resize.c
@@ -838,7 +838,7 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,
     FilterType
       filter,
       window;
-  } const mapping[SentinelFilter] =
+  } const mapping[] =
   {
     { UndefinedFilter,     BoxFilter      },  /* Undefined (default to Box)   */
     { PointFilter,         BoxFilter      },  /* SPECIAL: Nearest neighbour   */
@@ -895,7 +895,7 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,
                  Typically equal to the location of the first zero crossing. */
       B,C;     /* BC-spline coefficients, ignored if not a CubicBC filter. */
     ResizeWeightingFunctionType weightingFunctionType;
-  } const filters[SentinelFilter] =
+  } const filters[] =
   {
     /*            .---  support window (if used as a Weighting Function)
                   |    .--- first crossing (if used as a Windowing Function)
@@ -937,7 +937,7 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,
     { Cosine,    1.0, 1.0, 0.0, 0.0, CosineWeightingFunction },   /* Low level cosine window     */
     { CubicBC,   2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction },  /* Cubic B-Spline (B=1,C=0)    */
     { SincFast,  3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Integer Radius    */
-    { CubicSpline,2.0, 0.5, 0.0, 0.0, BoxWeightingFunction },  /* Spline Lobes 2-lobed */
+    { CubicSpline,2.0, 0.5, 0.0, 0.0, CubicSplineWeightingFunction },  /* Spline Lobes 2-lobed */
     { MagicKernelSharp2013, 2.5, 1.0, 0.0, 0.0, MagicKernelSharpWeightingFunction }, /* MagicKernelSharp2013 */
     { MagicKernelSharp2021, 4.5, 1.0, 0.0, 0.0, MagicKernelSharpWeightingFunction }, /* MagicKernelSharp2021 */
   };
@@ -973,6 +973,20 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,
       16.247661874700962
    };

+  /*
+    Compile-time guards: each table must have exactly one entry per FilterType
+    (a short table would otherwise be silently zero-filled and mis-map every
+    filter after the gap).  A negative array size fails the build.
+  */
+  typedef char
+    mapping_table_matches_FilterType[
+      (sizeof(mapping)/sizeof(mapping[0]) == (size_t) SentinelFilter) ? 1 : -1],
+    filters_table_matches_FilterType[
+      (sizeof(filters)/sizeof(filters[0]) == (size_t) SentinelFilter) ? 1 : -1];
+
+  ssize_t
+    index;
+
   /*
     Allocate resize filter.
   */
@@ -984,22 +998,32 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   (void) exception;
+  (void) sizeof(mapping_table_matches_FilterType);
+  (void) sizeof(filters_table_matches_FilterType);
   resize_filter=(ResizeFilter *) AcquireCriticalMemory(sizeof(*resize_filter));
   (void) memset(resize_filter,0,sizeof(*resize_filter));
   /*
-    Defaults for the requested filter.
+    Defaults for the requested filter.  The assert above vanishes in release
+    builds, so bound the table index here as well.
   */
-  filter_type=mapping[filter].filter;
-  window_type=mapping[filter].window;
+  index=(ssize_t) filter;
+  if ((index < 0) || (index >= (ssize_t) SentinelFilter))
+    index=(ssize_t) UndefinedFilter;
+  filter_type=mapping[index].filter;
+  window_type=mapping[index].window;
   resize_filter->blur=1.0;
   /* Promote 1D Windowed Sinc Filters to a 2D Windowed Jinc filters */
   if ((cylindrical != MagickFalse) && (filter_type == SincFastFilter) &&
       (filter != SincFastFilter))
     filter_type=JincFilter;  /* 1D Windowed Sinc => 2D Windowed Jinc filters */

-  /* Expert filter setting override */
+  /*
+    Expert filter setting override.  The value is a filter name (e.g. "Sinc"),
+    so test for presence: IsStringTrue() only accepts "true", "on", "yes" or
+    "1", which made this documented override unreachable.
+  */
   artifact=GetImageArtifact(image,"filter:filter");
-  if (IsStringTrue(artifact) != MagickFalse)
+  if (artifact != (const char *) NULL)
     {
       ssize_t
         option;
@@ -1161,14 +1185,21 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,
   artifact=GetImageArtifact(image,"filter:blur");
   if (artifact != (const char *) NULL)
     resize_filter->blur*=StringToDouble(artifact,(char **) NULL);
-  if (resize_filter->blur < MagickEpsilon)
+  /* negated test also rejects a NaN blur ("filter:blur=nan") */
+  if (!(resize_filter->blur >= MagickEpsilon))
     resize_filter->blur=(double) MagickEpsilon;
+  if (resize_filter->blur > MagickMaximumValue)
+    resize_filter->blur=(double) MagickMaximumValue;
   /*
-    Expert override of the support setting.
+    Expert override of the support setting (non-finite values are ignored).
   */
   artifact=GetImageArtifact(image,"filter:support");
   if (artifact != (const char *) NULL)
-    resize_filter->support=fabs(StringToDouble(artifact,(char **) NULL));
+    {
+      value=fabs(StringToDouble(artifact,(char **) NULL));
+      if (value <= MagickMaximumValue)
+        resize_filter->support=value;
+    }
   /*
     Scale windowing function separately to the support 'clipping' window
     that calling operator is planning to actually use. (Expert override)
@@ -1176,7 +1207,11 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,
   resize_filter->window_support=resize_filter->support; /* default */
   artifact=GetImageArtifact(image,"filter:win-support");
   if (artifact != (const char *) NULL)
-    resize_filter->window_support=fabs(StringToDouble(artifact,(char **) NULL));
+    {
+      value=fabs(StringToDouble(artifact,(char **) NULL));
+      if (value <= MagickMaximumValue)
+        resize_filter->window_support=value;
+    }
   /*
     Adjust window function scaling to match windowing support for weighting
     function.  This avoids a division on every filter call.
@@ -1234,11 +1269,15 @@ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image,

   /*
     Expert Option Request for verbose details of the resulting filter.
+
+    The test and the DeleteImageArtifact() below are one critical section:
+    "omp single" (used before) is non-conforming when reached by only some
+    threads of a team, and the unguarded lookup raced with the deletion.
   */
-  if (IsStringTrue(GetImageArtifact(image,"filter:verbose")) != MagickFalse)
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-    #pragma omp single
+  #pragma omp critical (MagickCore_AcquireResizeFilter)
 #endif
+  if (IsStringTrue(GetImageArtifact(image,"filter:verbose")) != MagickFalse)
     {
       double
         support,
@@ -3082,6 +3121,16 @@ MagickExport Image *MagnifyImage(const Image *image,ExceptionInfo *exception)
       source_image=DestroyImage(source_image);
       return((Image *) NULL);
     }
+  /*
+    Scale2X and friends write mixed (new) colors; a PseudoClass clone would
+    later be re-synced from its colormap and lose them.
+  */
+  if (SetImageStorageClass(magnify_image,DirectClass,exception) == MagickFalse)
+    {
+      magnify_image=DestroyImage(magnify_image);
+      source_image=DestroyImage(source_image);
+      return((Image *) NULL);
+    }
   /*
     Magnify the image.
   */
@@ -3128,12 +3177,13 @@ MagickExport Image *MagnifyImage(const Image *image,ExceptionInfo *exception)
         i,
         j;

-      p=GetCacheViewVirtualPixels(image_view,x-width/2,y-width/2,width,width,
-        exception);
-      if (p == (Quantum *) NULL)
+      /* signed offsets: x-width/2 was computed in unsigned (size_t) math */
+      p=GetCacheViewVirtualPixels(image_view,x-(ssize_t) (width/2),
+        y-(ssize_t) (width/2),width,width,exception);
+      if (p == (const Quantum *) NULL)
         {
           status=MagickFalse;
-          continue;
+          break;  /* row has failed; stop instead of retrying every column */
         }
       channels=GetPixelChannels(source_image);
       scaling_method(source_image,p,r,channels);
@@ -3338,6 +3388,13 @@ typedef struct _ContributionInfo
     pixel;
 } ContributionInfo;

+/*
+  The array is allocated with one extra, always-NULL sentinel slot and filled
+  contiguously from index 0 (same scheme as DestroyResampleFilterTLS()).
+  Destroy walks to the sentinel instead of re-reading the thread resource
+  limit, which may have been raised since the array was acquired: that read
+  past the allocation and handed stray pointers to RelinquishAlignedMemory().
+*/
 static ContributionInfo **DestroyContributionTLS(
   ContributionInfo **contribution)
 {
@@ -3345,10 +3402,9 @@ static ContributionInfo **DestroyContributionTLS(
     i;

   assert(contribution != (ContributionInfo **) NULL);
-  for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
-    if (contribution[i] != (ContributionInfo *) NULL)
-      contribution[i]=(ContributionInfo *) RelinquishAlignedMemory(
-        contribution[i]);
+  for (i=0; contribution[i] != (ContributionInfo *) NULL; i++)
+    contribution[i]=(ContributionInfo *) RelinquishAlignedMemory(
+      contribution[i]);
   contribution=(ContributionInfo **) RelinquishMagickMemory(contribution);
   return(contribution);
 }
@@ -3361,15 +3417,23 @@ static ContributionInfo **AcquireContributionTLS(const size_t count)
   ContributionInfo
     **contribution;

+  MagickSizeType
+    limit;
+
   size_t
     number_threads;

-  number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
-  contribution=(ContributionInfo **) AcquireQuantumMemory(number_threads,
+  limit=GetMagickResourceLimit(ThreadResource);
+  if (limit > (MagickSizeType) (MAGICK_SSIZE_MAX/sizeof(*contribution)-1))
+    limit=(MagickSizeType) (MAGICK_SSIZE_MAX/sizeof(*contribution)-1);
+  number_threads=(size_t) limit;
+  if (number_threads == 0)
+    number_threads=1;
+  contribution=(ContributionInfo **) AcquireQuantumMemory(number_threads+1,
     sizeof(*contribution));
   if (contribution == (ContributionInfo **) NULL)
     return((ContributionInfo **) NULL);
-  (void) memset(contribution,0,number_threads*sizeof(*contribution));
+  (void) memset(contribution,0,(number_threads+1)*sizeof(*contribution));
   for (i=0; i < (ssize_t) number_threads; i++)
   {
     contribution[i]=(ContributionInfo *) MagickAssumeAligned(
@@ -3380,6 +3444,21 @@ static ContributionInfo **AcquireContributionTLS(const size_t count)
   return(contribution);
 }

+/*
+  Number of contribution slots needed per output pixel.  A filter pass uses at
+  most min(2*support+1, extent) source pixels (stop <= extent, start >= 0), so
+  cap the allocation at the source extent.  This also keeps a huge, infinite
+  or NaN support (expert "filter:support"/"filter:blur" defines) out of the
+  undefined double-to-size_t conversion.
+*/
+static inline size_t ContributionCount(const double support,
+  const size_t extent)
+{
+  if (!(support < (double) extent))
+    return(extent+1);
+  return((size_t) (2.0*support+3.0));
+}
+
 static MagickBooleanType HorizontalFilter(
   const ResizeFilter *magick_restrict resize_filter,
   const Image *magick_restrict image,Image *magick_restrict resize_image,
@@ -3424,7 +3503,8 @@ static MagickBooleanType HorizontalFilter(
       support=(double) 0.5;
       scale=1.0;
     }
-  contributions=AcquireContributionTLS((size_t) (2.0*support+3.0));
+  contributions=AcquireContributionTLS(ContributionCount(support,
+    image->columns));
   if (contributions == (ContributionInfo **) NULL)
     {
       (void) ThrowMagickException(exception,GetMagickModule(),
@@ -3680,7 +3760,8 @@ static MagickBooleanType VerticalFilter(
       support=(double) 0.5;
       scale=1.0;
     }
-  contributions=AcquireContributionTLS((size_t) (2.0*support+3.0));
+  contributions=AcquireContributionTLS(ContributionCount(support,
+    image->rows));
   if (contributions == (ContributionInfo **) NULL)
     {
       (void) ThrowMagickException(exception,GetMagickModule(),
diff --git a/MagickCore/resize.h b/MagickCore/resize.h
index c19922dae..6beaa0d15 100644
--- a/MagickCore/resize.h
+++ b/MagickCore/resize.h
@@ -18,6 +18,8 @@
 #ifndef MAGICKCORE_RESIZE_H
 #define MAGICKCORE_RESIZE_H

+#include "MagickCore/resample.h"  /* FilterType, PixelInterpolateMethod */
+
 #if defined(__cplusplus) || defined(c_plusplus)
 extern "C" {
 #endif