Commit f57f41d93 for imagemagick.org

commit f57f41d9354db3da6301c11e6f6268388772e5d1
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Fri Dec 4 20:51:20 2026 -0500

    if a thread id was out of range it now fails with UnableToGetCacheNexus

diff --git a/MagickCore/cache-view.c b/MagickCore/cache-view.c
index c436ce2bd..ac5229d09 100644
--- a/MagickCore/cache-view.c
+++ b/MagickCore/cache-view.c
@@ -82,6 +82,61 @@ struct _CacheView
   size_t
     signature;
 };
+
+/*
+  Static helpers.
+*/
+static inline NexusInfo *GetCacheViewNexus(const CacheView *cache_view)
+{
+  const int
+    id = GetOpenMPThreadId();
+
+  /*
+    Each OpenMP thread owns exactly one nexus.  An out-of-range id must fail
+    rather than fall back to nexus 0: sharing another thread's nexus is a
+    silent data race on its staging buffer.
+  */
+  if ((id < 0) || (id >= (int) cache_view->number_threads))
+    return((NexusInfo *) NULL);
+  return(cache_view->nexus_info[id]);
+}
+
+static inline void ThrowCacheViewNexusException(const CacheView *cache_view,
+  ExceptionInfo *exception)
+{
+  (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
+    "UnableToGetCacheNexus","`%s'",cache_view->image->filename);
+}
+
+static inline MagickBooleanType CopyCacheViewPixel(const Image *image,
+  const Quantum *source,Quantum *destination)
+{
+  ssize_t
+    i;
+
+  if (source == (const Quantum *) NULL)
+    {
+      /*
+        Return the image background color on error.
+      */
+      destination[RedPixelChannel]=ClampToQuantum(image->background_color.red);
+      destination[GreenPixelChannel]=ClampToQuantum(
+        image->background_color.green);
+      destination[BluePixelChannel]=ClampToQuantum(
+        image->background_color.blue);
+      destination[BlackPixelChannel]=ClampToQuantum(
+        image->background_color.black);
+      destination[AlphaPixelChannel]=ClampToQuantum(
+        image->background_color.alpha);
+      return(MagickFalse);
+    }
+  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+  {
+    PixelChannel channel = GetPixelChannelChannel(image,i);
+    destination[channel]=source[i];
+  }
+  return(MagickTrue);
+}

 /*
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -299,18 +354,22 @@ MagickExport Quantum *GetCacheViewAuthenticPixels(CacheView *cache_view,
   const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
   ExceptionInfo *exception)
 {
-  int
-    id = GetOpenMPThreadId();
+  NexusInfo
+    *nexus_info;

   Quantum
     *magick_restrict pixels;

   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    {
+      ThrowCacheViewNexusException(cache_view,exception);
+      return((Quantum *) NULL);
+    }
   pixels=GetAuthenticPixelCacheNexus(cache_view->image,x,y,columns,rows,
-    cache_view->nexus_info[id],exception);
+    nexus_info,exception);
   return(pixels);
 }

@@ -341,15 +400,16 @@ MagickExport Quantum *GetCacheViewAuthenticPixels(CacheView *cache_view,
 */
 MagickExport void *GetCacheViewAuthenticMetacontent(CacheView *cache_view)
 {
-  int
-    id = GetOpenMPThreadId();
+  NexusInfo
+    *nexus_info;

   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
   assert(cache_view->image->cache != (Cache) NULL);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
-  return(cache_view->nexus_info[id]->metacontent);
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    return((void *) NULL);
+  return(nexus_info->metacontent);
 }

 /*
@@ -379,15 +439,16 @@ MagickExport void *GetCacheViewAuthenticMetacontent(CacheView *cache_view)
 */
 MagickExport Quantum *GetCacheViewAuthenticPixelQueue(CacheView *cache_view)
 {
-  int
-    id = GetOpenMPThreadId();
+  NexusInfo
+    *nexus_info;

   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
   assert(cache_view->image->cache != (Cache) NULL);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
-  return(cache_view->nexus_info[id]->pixels);
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    return((Quantum *) NULL);
+  return(nexus_info->pixels);
 }

 /*
@@ -449,22 +510,22 @@ MagickExport ColorspaceType GetCacheViewColorspace(const CacheView *cache_view)
 */
 MagickExport MagickSizeType GetCacheViewExtent(const CacheView *cache_view)
 {
-  int
-    id = GetOpenMPThreadId();
-
   MagickSizeType
     extent;

+  NexusInfo
+    *nexus_info;
+
   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
       cache_view->image->filename);
   assert(cache_view->image->cache != (Cache) NULL);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
-  extent=GetPixelCacheNexusExtent(cache_view->image->cache,
-    cache_view->nexus_info[id]);
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    return(0);
+  extent=GetPixelCacheNexusExtent(cache_view->image->cache,nexus_info);
   return(extent);
 }

@@ -561,19 +622,20 @@ MagickExport ClassType GetCacheViewStorageClass(const CacheView *cache_view)
 MagickExport const void *GetCacheViewVirtualMetacontent(
   const CacheView *cache_view)
 {
-  int
-    id = GetOpenMPThreadId();
-
   const void
     *magick_restrict metacontent;

+  NexusInfo
+    *nexus_info;
+
   assert(cache_view != (const CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
   assert(cache_view->image->cache != (Cache) NULL);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    return((const void *) NULL);
   metacontent=GetVirtualMetacontentFromNexus(cache_view->image->cache,
-    cache_view->nexus_info[id]);
+    nexus_info);
   return(metacontent);
 }

@@ -608,16 +670,16 @@ MagickExport const Quantum *GetCacheViewVirtualPixelQueue(
   const Quantum
     *magick_restrict pixels;

-  int
-    id = GetOpenMPThreadId();
+  NexusInfo
+    *nexus_info;

   assert(cache_view != (const CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
   assert(cache_view->image->cache != (Cache) NULL);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
-  pixels=GetVirtualPixelsNexus(cache_view->image->cache,
-    cache_view->nexus_info[id]);
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    return((const Quantum *) NULL);
+  pixels=GetVirtualPixelsNexus(cache_view->image->cache,nexus_info);
   return(pixels);
 }

@@ -657,19 +719,22 @@ MagickExport const Quantum *GetCacheViewVirtualPixels(
   const CacheView *cache_view,const ssize_t x,const ssize_t y,
   const size_t columns,const size_t rows,ExceptionInfo *exception)
 {
-  int
-    id = GetOpenMPThreadId();
-
   const Quantum
     *magick_restrict pixels;

+  NexusInfo
+    *nexus_info;
+
   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    {
+      ThrowCacheViewNexusException(cache_view,exception);
+      return((const Quantum *) NULL);
+    }
   pixels=GetVirtualPixelCacheNexus(cache_view->image,
-    cache_view->virtual_pixel_method,x,y,columns,rows,
-    cache_view->nexus_info[id],exception);
+    cache_view->virtual_pixel_method,x,y,columns,rows,nexus_info,exception);
   return(pixels);
 }

@@ -708,41 +773,23 @@ MagickExport MagickBooleanType GetOneCacheViewAuthenticPixel(
   const CacheView *cache_view,const ssize_t x,const ssize_t y,Quantum *pixel,
   ExceptionInfo *exception)
 {
-  int
-    id = GetOpenMPThreadId();
+  NexusInfo
+    *nexus_info;

   Quantum
     *magick_restrict q;

-  ssize_t
-    i;
-
   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
   (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel));
-  q=GetAuthenticPixelCacheNexus(cache_view->image,x,y,1,1,
-    cache_view->nexus_info[id],exception);
-  if (q == (const Quantum *) NULL)
-    {
-      PixelInfo
-        background_color;
-
-      background_color=cache_view->image->background_color;
-      pixel[RedPixelChannel]=ClampToQuantum(background_color.red);
-      pixel[GreenPixelChannel]=ClampToQuantum(background_color.green);
-      pixel[BluePixelChannel]=ClampToQuantum(background_color.blue);
-      pixel[BlackPixelChannel]=ClampToQuantum(background_color.black);
-      pixel[AlphaPixelChannel]=ClampToQuantum(background_color.alpha);
-      return(MagickFalse);
-    }
-  for (i=0; i < (ssize_t) GetPixelChannels(cache_view->image); i++)
-  {
-    PixelChannel channel = GetPixelChannelChannel(cache_view->image,i);
-    pixel[channel]=q[i];
-  }
-  return(MagickTrue);
+  q=(Quantum *) NULL;
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    ThrowCacheViewNexusException(cache_view,exception);
+  else
+    q=GetAuthenticPixelCacheNexus(cache_view->image,x,y,1,1,nexus_info,
+      exception);
+  return(CopyCacheViewPixel(cache_view->image,q,pixel));
 }

 /*
@@ -784,39 +831,20 @@ MagickExport MagickBooleanType GetOneCacheViewVirtualPixel(
   const Quantum
     *magick_restrict p;

-  int
-    id = GetOpenMPThreadId();
-
-  ssize_t
-    i;
+  NexusInfo
+    *nexus_info;

   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
   (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel));
-  p=GetVirtualPixelCacheNexus(cache_view->image,
-    cache_view->virtual_pixel_method,x,y,1,1,cache_view->nexus_info[id],
-    exception);
-  if (p == (const Quantum *) NULL)
-    {
-      PixelInfo
-        background_color;
-
-      background_color=cache_view->image->background_color;
-      pixel[RedPixelChannel]=ClampToQuantum(background_color.red);
-      pixel[GreenPixelChannel]=ClampToQuantum(background_color.green);
-      pixel[BluePixelChannel]=ClampToQuantum(background_color.blue);
-      pixel[BlackPixelChannel]=ClampToQuantum(background_color.black);
-      pixel[AlphaPixelChannel]=ClampToQuantum(background_color.alpha);
-      return(MagickFalse);
-    }
-  for (i=0; i < (ssize_t) GetPixelChannels(cache_view->image); i++)
-  {
-    PixelChannel channel = GetPixelChannelChannel(cache_view->image,i);
-    pixel[channel]=p[i];
-  }
-  return(MagickTrue);
+  p=(const Quantum *) NULL;
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    ThrowCacheViewNexusException(cache_view,exception);
+  else
+    p=GetVirtualPixelCacheNexus(cache_view->image,
+      cache_view->virtual_pixel_method,x,y,1,1,nexus_info,exception);
+  return(CopyCacheViewPixel(cache_view->image,p,pixel));
 }

 /*
@@ -858,17 +886,20 @@ MagickExport MagickBooleanType GetOneCacheViewVirtualPixelInfo(
   const Quantum
     *magick_restrict p;

-  int
-    id = GetOpenMPThreadId();
+  NexusInfo
+    *nexus_info;

   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
   GetPixelInfo(cache_view->image,pixel);
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    {
+      ThrowCacheViewNexusException(cache_view,exception);
+      return(MagickFalse);
+    }
   p=GetVirtualPixelCacheNexus(cache_view->image,
-    cache_view->virtual_pixel_method,x,y,1,1,cache_view->nexus_info[id],
-    exception);
+    cache_view->virtual_pixel_method,x,y,1,1,nexus_info,exception);
   if (p == (const Quantum *) NULL)
     return(MagickFalse);
   GetPixelInfoPixel(cache_view->image,p,pixel);
@@ -918,38 +949,20 @@ MagickExport MagickBooleanType GetOneCacheViewVirtualMethodPixel(
   const Quantum
     *magick_restrict p;

-  int
-    id = GetOpenMPThreadId();
-
-  ssize_t
-    i;
+  NexusInfo
+    *nexus_info;

   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
   (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel));
-  p=GetVirtualPixelCacheNexus(cache_view->image,virtual_pixel_method,x,y,1,1,
-    cache_view->nexus_info[id],exception);
-  if (p == (const Quantum *) NULL)
-    {
-      PixelInfo
-        background_color;
-
-      background_color=cache_view->image->background_color;
-      pixel[RedPixelChannel]=ClampToQuantum(background_color.red);
-      pixel[GreenPixelChannel]=ClampToQuantum(background_color.green);
-      pixel[BluePixelChannel]=ClampToQuantum(background_color.blue);
-      pixel[BlackPixelChannel]=ClampToQuantum(background_color.black);
-      pixel[AlphaPixelChannel]=ClampToQuantum(background_color.alpha);
-      return(MagickFalse);
-    }
-  for (i=0; i < (ssize_t) GetPixelChannels(cache_view->image); i++)
-  {
-    PixelChannel channel = GetPixelChannelChannel(cache_view->image,i);
-    pixel[channel]=p[i];
-  }
-  return(MagickTrue);
+  p=(const Quantum *) NULL;
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    ThrowCacheViewNexusException(cache_view,exception);
+  else
+    p=GetVirtualPixelCacheNexus(cache_view->image,virtual_pixel_method,x,y,
+      1,1,nexus_info,exception);
+  return(CopyCacheViewPixel(cache_view->image,p,pixel));
 }

 /*
@@ -988,18 +1001,22 @@ MagickExport Quantum *QueueCacheViewAuthenticPixels(CacheView *cache_view,
   const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
   ExceptionInfo *exception)
 {
-  int
-    id = GetOpenMPThreadId();
+  NexusInfo
+    *nexus_info;

   Quantum
     *magick_restrict pixels;

   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    {
+      ThrowCacheViewNexusException(cache_view,exception);
+      return((Quantum *) NULL);
+    }
   pixels=QueueAuthenticPixelCacheNexus(cache_view->image,x,y,columns,rows,
-    MagickFalse,cache_view->nexus_info[id],exception);
+    MagickFalse,nexus_info,exception);
   return(pixels);
 }

@@ -1111,17 +1128,20 @@ MagickExport MagickBooleanType SetCacheViewVirtualPixelMethod(
 MagickExport MagickBooleanType SyncCacheViewAuthenticPixels(
   CacheView *magick_restrict cache_view,ExceptionInfo *exception)
 {
-  int
-    id = GetOpenMPThreadId();
-
   MagickBooleanType
     status;

+  NexusInfo
+    *nexus_info;
+
   assert(cache_view != (CacheView *) NULL);
   assert(cache_view->signature == MagickCoreSignature);
-  if ((id < 0) || (id >= (int) cache_view->number_threads))
-    id=0;
-  status=SyncAuthenticPixelCacheNexus(cache_view->image,
-    cache_view->nexus_info[id],exception);
+  nexus_info=GetCacheViewNexus(cache_view);
+  if (nexus_info == (NexusInfo *) NULL)
+    {
+      ThrowCacheViewNexusException(cache_view,exception);
+      return(MagickFalse);
+    }
+  status=SyncAuthenticPixelCacheNexus(cache_view->image,nexus_info,exception);
   return(status);
 }
diff --git a/MagickCore/cache.c b/MagickCore/cache.c
index 57154be0b..90063a4a8 100644
--- a/MagickCore/cache.c
+++ b/MagickCore/cache.c
@@ -2810,6 +2810,14 @@ static inline ssize_t DitherX(const ssize_t x,const size_t columns)
   ssize_t
     index;

+  /*
+    The dither offset lies in [-32,31]; saturate first so x+offset can never
+    overflow (signed overflow is undefined behavior).
+  */
+  if (x <= (MAGICK_SSIZE_MIN+32L))
+    return(0L);
+  if (x >= (MAGICK_SSIZE_MAX-31L))
+    return((ssize_t) columns-1L);
   index=x+DitherMatrix[x & 0x07]-32L;
   if (index < 0L)
     return(0L);
@@ -2823,6 +2831,10 @@ static inline ssize_t DitherY(const ssize_t y,const size_t rows)
   ssize_t
     index;

+  if (y <= (MAGICK_SSIZE_MIN+32L))
+    return(0L);
+  if (y >= (MAGICK_SSIZE_MAX-31L))
+    return((ssize_t) rows-1L);
   index=y+DitherMatrix[y & 0x07]-32L;
   if (index < 0L)
     return(0L);
@@ -2849,6 +2861,10 @@ static inline ssize_t EdgeY(const ssize_t y,const size_t rows)
   return(y);
 }

+/*
+  Note: despite its name, IsOffsetOverflow() returns MagickTrue when x+y is
+  SAFE and MagickFalse when the addition would overflow.
+*/
 static inline MagickBooleanType IsOffsetOverflow(const MagickOffsetType x,
   const MagickOffsetType y)
 {
@@ -2863,8 +2879,21 @@ static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns)
   double
     x;

+  ssize_t
+    index;
+
+  /*
+    Clamp into [0,columns-1]: a random value of exactly 1.0 (or rounding)
+    must never produce an out-of-range coordinate, which would recurse into
+    the outside-extent path on the virtual nexus.
+  */
   x=(double) columns*GetPseudoRandomValue(random_info);
-  return(CastDoubleToSsizeT(x));
+  index=CastDoubleToSsizeT(x);
+  if (index < 0)
+    return(0);
+  if (index >= (ssize_t) columns)
+    return((ssize_t) columns-1);
+  return(index);
 }

 static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows)
@@ -2872,8 +2901,16 @@ static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows)
   double
     y;

+  ssize_t
+    index;
+
   y=(double) rows*GetPseudoRandomValue(random_info);
-  return(CastDoubleToSsizeT(y));
+  index=CastDoubleToSsizeT(y);
+  if (index < 0)
+    return(0);
+  if (index >= (ssize_t) rows)
+    return((ssize_t) rows-1);
+  return(index);
 }

 static inline MagickModulo VirtualPixelModulo(const ssize_t offset,
@@ -2992,6 +3029,16 @@ MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image,
     Pixel request is outside cache extents.
   */
   virtual_nexus=nexus_info->virtual_nexus;
+  if (virtual_nexus == (NexusInfo *) NULL)
+    {
+      /*
+        Only primary nexuses own a virtual nexus; a request that lands here
+        through a virtual nexus would otherwise dereference NULL.
+      */
+      (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
+        "UnableToGetCacheNexus","`%s'",image->filename);
+      return((const Quantum *) NULL);
+    }
   q=pixels;
   s=(unsigned char *) nexus_info->metacontent;
   (void) memset(virtual_pixel,0,cache_info->number_channels*
@@ -3092,11 +3139,8 @@ MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image,
         x_offset;

       x_offset=x+u;
-      length=(MagickSizeType) MagickMin((ssize_t) cache_info->columns-
-        x_offset,(ssize_t) columns-u);
       if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) ||
-          ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) ||
-          (length == 0))
+          ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)))
         {
           MagickModulo
             x_modulo,
@@ -3252,16 +3296,26 @@ MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image,
           (void) memcpy(q,p,(size_t) (cache_info->number_channels*length*
             sizeof(*p)));
           q+=(ptrdiff_t) cache_info->number_channels;
-          if ((s != (void *) NULL) && (r != (const void *) NULL))
+          if (s != (unsigned char *) NULL)
             {
-              (void) memcpy(s,r,(size_t) cache_info->metacontent_extent);
+              /*
+                Always advance the metacontent cursor so it stays aligned
+                with the pixel cursor.
+              */
+              if (r != (const void *) NULL)
+                (void) memcpy(s,r,(size_t) cache_info->metacontent_extent);
+              else
+                (void) memset(s,0,(size_t) cache_info->metacontent_extent);
               s+=(ptrdiff_t) cache_info->metacontent_extent;
             }
           continue;
         }
       /*
-        Transfer a run of pixels.
+        Transfer a run of pixels.  x_offset is known to be in range here, so
+        the subtraction below cannot overflow.
       */
+      length=(MagickSizeType) MagickMin((ssize_t) cache_info->columns-
+        x_offset,(ssize_t) columns-u);
       p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x_offset,y_offset,
         (size_t) length,1UL,virtual_nexus,exception);
       if (p == (const Quantum *) NULL)
@@ -3270,9 +3324,13 @@ MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image,
       (void) memcpy(q,p,(size_t) (cache_info->number_channels*length*
         sizeof(*p)));
       q+=(ptrdiff_t) (cache_info->number_channels*length);
-      if ((r != (void *) NULL) && (s != (const void *) NULL))
+      if (s != (unsigned char *) NULL)
         {
-          (void) memcpy(s,r,(size_t) (length*cache_info->metacontent_extent));
+          if (r != (const void *) NULL)
+            (void) memcpy(s,r,(size_t) (length*cache_info->metacontent_extent));
+          else
+            (void) memset(s,0,(size_t) (length*
+              cache_info->metacontent_extent));
           s+=(ptrdiff_t) (length*cache_info->metacontent_extent);
         }
     }
@@ -4053,10 +4111,13 @@ static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
               cache_info->storage_class=image->storage_class;
               if (status == 0)
                 {
-                  if ((source_info.storage_class != UndefinedClass) &&
-                      (mode != ReadMode))
-                    RelinquishPixelCachePixels(&source_info);
-                  cache_info->type=UndefinedCache;
+                  /*
+                    The clone failed: release the storage just acquired for
+                    this cache (memory, mapping, temp file, resources);
+                    resetting the type alone would leak it.  The source was
+                    already relinquished above.
+                  */
+                  RelinquishPixelCachePixels(cache_info);
                   return(MagickFalse);
                 }
               return(MagickTrue);
@@ -4122,10 +4183,13 @@ static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
                 }
               if (status == 0)
                 {
-                  if ((source_info.storage_class != UndefinedClass) &&
-                      (mode != ReadMode))
-                    RelinquishPixelCachePixels(&source_info);
-                  cache_info->type=UndefinedCache;
+                  /*
+                    The clone failed: release the storage just acquired for
+                    this cache (memory, mapping, temp file, resources);
+                    resetting the type alone would leak it.  The source was
+                    already relinquished above.
+                  */
+                  RelinquishPixelCachePixels(cache_info);
                   return(MagickFalse);
                 }
               return(MagickTrue);
@@ -4164,6 +4228,7 @@ static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
     {
       if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
         RelinquishPixelCachePixels(&source_info);
+      RelinquishMagickResource(DiskResource,cache_info->length);
       cache_info->type=UndefinedCache;
       ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
         image->filename);
@@ -4175,7 +4240,8 @@ static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
     {
       if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
         RelinquishPixelCachePixels(&source_info);
-      cache_info->type=UndefinedCache;
+      cache_info->type=DiskCache;
+      RelinquishPixelCachePixels(cache_info);  /* close fd, drop temp file */
       ThrowFileException(exception,CacheError,"UnableToExtendCache",
         image->filename);
       return(MagickFalse);
@@ -4232,10 +4298,13 @@ static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
                 }
               if (status == 0)
                 {
-                  if ((source_info.storage_class != UndefinedClass) &&
-                      (mode != ReadMode))
-                    RelinquishPixelCachePixels(&source_info);
-                  cache_info->type=UndefinedCache;
+                  /*
+                    The clone failed: release the storage just acquired for
+                    this cache (memory, mapping, temp file, resources);
+                    resetting the type alone would leak it.  The source was
+                    already relinquished above.
+                  */
+                  RelinquishPixelCachePixels(cache_info);
                   return(MagickFalse);
                 }
               return(MagickTrue);
@@ -4263,7 +4332,7 @@ static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
     }
   if (status == 0)
     {
-      cache_info->type=UndefinedCache;
+      RelinquishPixelCachePixels(cache_info);  /* close + remove temp file */
       return(MagickFalse);
     }
   return(MagickTrue);
@@ -4357,9 +4426,11 @@ MagickExport MagickBooleanType PersistPixelCache(Image *image,
   status=AcquireMagickResource(DiskResource,cache_info->length);
   if (status == MagickFalse)
     {
-      cache_info->type=UndefinedCache;
-      (void) memset(image->channel_map,0,MaxPixelChannels*
-        sizeof(*image->channel_map));
+      /*
+        Failing to persist must not destroy the live image: leave the source
+        cache and channel map untouched (previously its type was reset, which
+        leaked its pixels and left the image unusable).
+      */
       (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
         "CacheResourcesExhausted","`%s'",image->filename);
       return(MagickFalse);
@@ -5247,10 +5318,18 @@ MagickExport MagickBooleanType ReshapePixelCache(Image *image,
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   assert(image->cache != (void *) NULL);
+  if ((columns == 0) || (rows == 0))
+    ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename);
   extent=(MagickSizeType) columns*rows;
   if (extent > ((MagickSizeType) image->columns*image->rows))
     ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit",
       image->filename);
+  /*
+    Take exclusive ownership first: the cache may be shared with other
+    images, which must not see their geometry change underneath them.
+  */
+  if (SyncImagePixelCache(image,exception) == MagickFalse)
+    return(MagickFalse);
   image->columns=columns;
   image->rows=rows;
   cache_info=(CacheInfo *) image->cache;
@@ -5479,10 +5558,15 @@ static Quantum *SetPixelCacheNexusPixels(
   if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) &&
       (buffered == MagickFalse))
     {
+      /*
+        Bounds are compared by subtraction (rows, columns, width and height
+        are all bounded by the width/height limits) so a large x or y cannot
+        overflow the addition.
+      */
       if (((x >= 0) && (y >= 0) &&
-          (((ssize_t) height+y-1) < (ssize_t) cache_info->rows)) &&
+          (y <= ((ssize_t) cache_info->rows-(ssize_t) height))) &&
           (((x == 0) && (width == cache_info->columns)) || ((height == 1) &&
-          (((ssize_t) width+x-1) < (ssize_t) cache_info->columns))))
+          (x <= ((ssize_t) cache_info->columns-(ssize_t) width)))))
         {
           MagickOffsetType
             offset;
@@ -5813,9 +5897,8 @@ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image,
     }
   assert(cache_info->signature == MagickCoreSignature);
   status=WritePixelCachePixels(cache_info,nexus_info,exception);
-  if ((cache_info->metacontent_extent != 0) &&
-      (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse))
-    return(MagickFalse);
+  if ((status != MagickFalse) && (cache_info->metacontent_extent != 0))
+    status=WritePixelCacheMetacontent(cache_info,nexus_info,exception);
   if ((status != MagickFalse) && (image->taint == MagickFalse))
     image->taint=MagickTrue;
   return(status);