Commit 7b6e7bad8 for imagemagick.org

commit 7b6e7bad8f989b7c0564f50f6df1886544f2ea20
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Sat Dec 5 11:10:37 2026 -0500

    GetChannelBit() macro shifts in 64-bit + ChannelFxImage() creates the alpha channel properly

diff --git a/MagickCore/channel.c b/MagickCore/channel.c
index 4cace01c2..b66a95697 100644
--- a/MagickCore/channel.c
+++ b/MagickCore/channel.c
@@ -362,8 +362,6 @@ MagickExport Image *ChannelFxImage(const Image *image,const char *expression,
         else
           {
             i=ParsePixelChannelOption(token);
-            if (LocaleCompare(token,"alpha") == 0)
-              destination_image->alpha_trait=BlendPixelTrait;
             if ((i < 0) || (i >= (ssize_t) MaxPixelChannels))
               {
                 (void) ThrowMagickException(exception,GetMagickModule(),
@@ -371,6 +369,22 @@ MagickExport Image *ChannelFxImage(const Image *image,const char *expression,
                 destination_image=DestroyImageList(destination_image);
                 return(destination_image);
               }
+            if (((PixelChannel) i == AlphaPixelChannel) &&
+                ((destination_image->alpha_trait & BlendPixelTrait) == 0))
+              {
+                /*
+                  Setting alpha_trait alone leaves the channel map stale, so
+                  ChannelImage() would see no alpha channel and silently do
+                  nothing; activate it (opaque) and resync the pixel cache.
+                */
+                status=SetImageAlphaChannel(destination_image,OnAlphaChannel,
+                  exception);
+                if (status == MagickFalse)
+                  {
+                    destination_image=DestroyImageList(destination_image);
+                    return(destination_image);
+                  }
+              }
           }
         destination_channel=(PixelChannel) i;
         if (image->colorspace != UndefinedColorspace)
@@ -569,15 +583,6 @@ MagickExport Image *CombineImages(const Image *image,
   number_channels=GetImageListLength(image);
   switch (combine_image->colorspace)
   {
-    case UndefinedColorspace:
-    case sRGBColorspace:
-    {
-      if (number_channels > 3)
-        combine_image->alpha_trait=BlendPixelTrait;
-      if (number_channels > 4)
-        status=SetPixelMetaChannels(combine_image,number_channels-4,exception);
-      break;
-    }
     case LinearGRAYColorspace:
     case GRAYColorspace:
     {
@@ -595,9 +600,23 @@ MagickExport Image *CombineImages(const Image *image,
         status=SetPixelMetaChannels(combine_image,number_channels-5,exception);
       break;
     }
+    case UndefinedColorspace:
+    case sRGBColorspace:
     default:
+    {
+      /*
+        Three-channel colorspaces (sRGB, linear RGB, Lab, HSL, YCbCr, ...):
+        a 4th image is alpha, any further images become meta channels.
+      */
+      if (number_channels > 3)
+        combine_image->alpha_trait=BlendPixelTrait;
+      if (number_channels > 4)
+        status=SetPixelMetaChannels(combine_image,number_channels-4,exception);
       break;
+    }
   }
+  if (status != MagickFalse)
+    status=SyncImagePixelCache(combine_image,exception);  /* map before loop */
   if (status == MagickFalse)
     {
       combine_image=DestroyImage(combine_image);
diff --git a/MagickCore/channel.h b/MagickCore/channel.h
index bea29da18..cb0c483f1 100644
--- a/MagickCore/channel.h
+++ b/MagickCore/channel.h
@@ -18,7 +18,7 @@
 #ifndef MAGICKCORE_CHANNEL_H
 #define MAGICKCORE_CHANNEL_H

-#include <MagickCore/image.h>
+#include "MagickCore/image.h"

 #if defined(__cplusplus) || defined(c_plusplus)
 extern "C" {
diff --git a/MagickCore/pixel-accessor.h b/MagickCore/pixel-accessor.h
index 974dbdbe6..e8bf69721 100644
--- a/MagickCore/pixel-accessor.h
+++ b/MagickCore/pixel-accessor.h
@@ -937,9 +937,14 @@ static inline void SetPixelMagentaTraits(Image *image,const PixelTrait traits)
 }

 static inline void SetPixelMeta(const Image *magick_restrict image,
-  const Quantum red,Quantum *magick_restrict pixel)
-{
-  pixel[image->channel_map[MetaPixelChannels].offset]=red;
+  const Quantum meta,Quantum *magick_restrict pixel)
+{
+  /*
+    Without a meta channel its map offset is 0, so an unguarded write would
+    silently overwrite the red/gray channel.
+  */
+  if (image->channel_map[MetaPixelChannels].traits != UndefinedPixelTrait)
+    pixel[image->channel_map[MetaPixelChannels].offset]=meta;
 }

 static inline void SetPixelMetaTraits(Image *image,const PixelTrait traits)
diff --git a/MagickCore/pixel-private.h b/MagickCore/pixel-private.h
index 202c0bdce..d8348bb19 100644
--- a/MagickCore/pixel-private.h
+++ b/MagickCore/pixel-private.h
@@ -18,6 +18,9 @@
 #ifndef MAGICKCORE_PIXEL_PRIVATE_H
 #define MAGICKCORE_PIXEL_PRIVATE_H

+#include "MagickCore/exception.h"
+#include "MagickCore/image.h"
+
 #if defined(__cplusplus) || defined(c_plusplus)
 extern "C" {
 #endif
diff --git a/MagickCore/pixel.c b/MagickCore/pixel.c
index 82d837277..12c4bc235 100644
--- a/MagickCore/pixel.c
+++ b/MagickCore/pixel.c
@@ -1987,6 +1987,13 @@ MagickExport MagickBooleanType ExportImagePixels(const Image *image,
   assert(image->signature == MagickCoreSignature);
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+  if ((map == (const char *) NULL) || (*map == '\0') ||
+      (pixels == (void *) NULL))
+    {
+      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
+        "UnrecognizedPixelMap","`%s'",map == (const char *) NULL ? "" : map);
+      return(MagickFalse);
+    }
   length=strlen(map);
   quantum_map=(QuantumType *) AcquireQuantumMemory(length,sizeof(*quantum_map));
   if (quantum_map == (QuantumType *) NULL)
@@ -2138,7 +2145,7 @@ MagickExport MagickBooleanType ExportImagePixels(const Image *image,
     default:
     {
       (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
-        "UnrecognizedPixelMap","`%s'",map);
+        "UnrecognizedStorageType","`%d'",type);
       status=MagickFalse;
     }
   }
@@ -4192,6 +4199,13 @@ MagickExport MagickBooleanType ImportImagePixels(Image *image,const ssize_t x,
   assert(image->signature == MagickCoreSignature);
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+  if ((map == (const char *) NULL) || (*map == '\0') ||
+      (pixels == (const void *) NULL))
+    {
+      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
+        "UnrecognizedPixelMap","`%s'",map == (const char *) NULL ? "" : map);
+      return(MagickFalse);
+    }
   length=strlen(map);
   quantum_map=(QuantumType *) AcquireQuantumMemory(length,sizeof(*quantum_map));
   if (quantum_map == (QuantumType *) NULL)
@@ -4472,6 +4486,16 @@ MagickExport MagickBooleanType InterpolatePixelChannel(
   if ((channel < 0) || (channel >= MaxPixelChannels))
     ThrowBinaryException(OptionError,"NoSuchImageChannel",image->filename);
   traits=GetPixelChannelTraits(image,channel);
+  if (traits == UndefinedPixelTrait)
+    {
+      /*
+        Channel absent: its map offset is 0, so reading it would return the
+        red/gray value; report the same defaults the pixel accessors use.
+      */
+      if (channel == AlphaPixelChannel)
+        *pixel=(double) OpaqueAlpha;
+      return(MagickTrue);
+    }
   x_offset=CastDoubleToSsizeT(floor(x));
   y_offset=CastDoubleToSsizeT(floor(y));
   interpolate=method;
@@ -5961,7 +5985,7 @@ MagickExport MagickBooleanType IsFuzzyEquivalencePixel(const Image *image,
     MSE metric for comparing two pixels.
   */
   for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
-  {
+  {
     double
       error;

@@ -6337,7 +6361,12 @@ static void LogPixelChannels(const Image *image)
 MagickExport ChannelType SetPixelChannelMask(Image *image,
   const ChannelType channel_mask)
 {
-#define GetChannelBit(mask,bit)  (((size_t) (mask) >> (size_t) (bit)) & 0x01)
+/*
+  Shift in 64 bits: channels run up to MaxPixelChannels-1 (63), and shifting a
+  32-bit size_t by 32 or more is undefined behavior.
+*/
+#define GetChannelBit(mask,bit)  \
+  (((MagickSizeType) (mask) >> (MagickSizeType) (bit)) & 0x01)

   ChannelType
     mask;
@@ -6459,6 +6488,34 @@ MagickExport MagickBooleanType SetPixelMetaChannels(Image *image,
 %    o exception: return any errors or warnings in this structure.
 %
 */
+typedef struct _PixelSortInfo
+{
+  MagickRealType
+    intensity;
+
+  ssize_t
+    index;
+} PixelSortInfo;
+
+static int PixelSortCompare(const void *x,const void *y)
+{
+  const PixelSortInfo
+    *p = (const PixelSortInfo *) x,
+    *q = (const PixelSortInfo *) y;
+
+  if (p->intensity < q->intensity)
+    return(-1);
+  if (p->intensity > q->intensity)
+    return(1);
+  /*
+    Tie-break on the original column so the sort is stable, matching the
+    order the former in-place bubble sort produced.
+  */
+  if (p->index < q->index)
+    return(-1);
+  return(p->index > q->index ? 1 : 0);
+}
+
 MagickExport MagickBooleanType SortImagePixels(Image *image,
   ExceptionInfo *exception)
 {
@@ -6492,8 +6549,15 @@ MagickExport MagickBooleanType SortImagePixels(Image *image,
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
+    PixelSortInfo
+      *sort_info;
+
     Quantum
-      *magick_restrict q;
+      *magick_restrict q,
+      *row;
+
+    size_t
+      channels;

     ssize_t
       x;
@@ -6506,40 +6570,42 @@ MagickExport MagickBooleanType SortImagePixels(Image *image,
         status=MagickFalse;
         continue;
       }
-    for (x=0; x < (ssize_t) image->columns-1; x++)
+    /*
+      Sort the row by intensity in O(n log n) (was an O(n^2) bubble sort).
+    */
+    channels=GetPixelChannels(image);
+    sort_info=(PixelSortInfo *) AcquireQuantumMemory(image->columns,
+      sizeof(*sort_info));
+    row=(Quantum *) AcquireQuantumMemory(image->columns,channels*sizeof(*row));
+    if ((sort_info == (PixelSortInfo *) NULL) || (row == (Quantum *) NULL))
+      {
+        if (row != (Quantum *) NULL)
+          row=(Quantum *) RelinquishMagickMemory(row);
+        if (sort_info != (PixelSortInfo *) NULL)
+          sort_info=(PixelSortInfo *) RelinquishMagickMemory(sort_info);
+        (void) ThrowMagickException(exception,GetMagickModule(),
+          ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
+        status=MagickFalse;
+        continue;
+      }
+    for (x=0; x < (ssize_t) image->columns; x++)
     {
       MagickRealType
-        current,
-        previous;
-
-      ssize_t
-        j;
-
-      previous=GetPixelIntensity(image,q);
-      for (j=0; j < ((ssize_t) image->columns-x-1); j++)
-      {
-        current=GetPixelIntensity(image,q+(j+1)*(ssize_t)
-          GetPixelChannels(image));
-        if (previous > current)
-          {
-            Quantum
-              pixel[MaxPixelChannels];
-
-            /*
-              Swap adjacent pixels.
-            */
-            (void) memcpy(pixel,q+j*(ssize_t) GetPixelChannels(image),
-              GetPixelChannels(image)*sizeof(Quantum));
-            (void) memcpy(q+j*(ssize_t) GetPixelChannels(image),q+(j+1)*
-              (ssize_t) GetPixelChannels(image),GetPixelChannels(image)*
-              sizeof(Quantum));
-            (void) memcpy(q+(j+1)*(ssize_t) GetPixelChannels(image),pixel,
-              GetPixelChannels(image)*sizeof(Quantum));
-          }
-        else
-          previous=current;
-      }
-    }
+        intensity;
+
+      intensity=GetPixelIntensity(image,q+x*(ssize_t) channels);
+      if (IsNaN(intensity) != 0)
+        intensity=(MagickRealType) -MagickMaximumValue;  /* total order */
+      sort_info[x].intensity=intensity;
+      sort_info[x].index=x;
+    }
+    qsort(sort_info,image->columns,sizeof(*sort_info),PixelSortCompare);
+    (void) memcpy(row,q,image->columns*channels*sizeof(*row));
+    for (x=0; x < (ssize_t) image->columns; x++)
+      (void) memcpy(q+x*(ssize_t) channels,row+sort_info[x].index*
+        (ssize_t) channels,channels*sizeof(*row));
+    row=(Quantum *) RelinquishMagickMemory(row);
+    sort_info=(PixelSortInfo *) RelinquishMagickMemory(sort_info);
     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
       status=MagickFalse;
     if (image->progress_monitor != (MagickProgressMonitor) NULL)
diff --git a/MagickCore/pixel.h b/MagickCore/pixel.h
index 2b02680b8..ffb28b007 100644
--- a/MagickCore/pixel.h
+++ b/MagickCore/pixel.h
@@ -45,7 +45,7 @@ typedef enum
   MagentaChannel = 0x0002,
   aChannel = 0x0002,
   BlueChannel = 0x0004,
-  bChannel = 0x0002,
+  bChannel = 0x0004,                 /* Lab b* is the 3rd channel (was 0x0002) */
   YellowChannel = 0x0004,
   BlackChannel = 0x0008,
   AlphaChannel = 0x0010,