Subject: Re: bug#22526: 25.0.90; Crash starting gnus

From: Eli Zaretskii <[email-masked]>
Date: Sun, 14 Feb 2016 07:41:18 +0200

> Date: Sun, 14 Feb 2016 00:11:58 +0200
> From: Eli Zaretskii <[email-masked]>
> Cc: [email-masked], [email-masked]
> 
> > From: Fabrice Popineau <[email-masked]>
> > Date: Sat, 13 Feb 2016 22:35:57 +0100
> > Cc: [email-masked], [email-masked]
> > 
> > I think we need the DebPrint() trace of the problem to conclude.
> 
> I think the patch I propose below will help in that.

Fabrice didn't like my goto, so here's a version without that:

diff --git a/src/w32heap.c b/src/w32heap.c
index 00da86a..6047b19 100644
--- a/src/w32heap.c
+++ b/src/w32heap.c
@@ -652,15 +652,19 @@ mmap_alloc (void **var, size_t nbytes)
     {
       /* Now, commit pages for NBYTES.  */
       *var = VirtualAlloc (p, nbytes, MEM_COMMIT, PAGE_READWRITE);
+      if (*var == NULL)
+	p = *var;
     }
 
   if (!p)
     {
-      if (GetLastError () == ERROR_NOT_ENOUGH_MEMORY)
+      DWORD e = GetLastError ();
+
+      if (e == ERROR_NOT_ENOUGH_MEMORY)
 	errno = ENOMEM;
       else
 	{
-	  DebPrint (("mmap_alloc: error %ld\n", GetLastError ()));
+	  DebPrint (("mmap_alloc: error %ld\n", e));
 	  errno = EINVAL;
 	}
     }
@@ -700,6 +704,8 @@ mmap_realloc (void **var, size_t nbytes)
   /* We need to enlarge the block.  */
   if (memInfo.RegionSize < nbytes)
     {
+      void *old_ptr;
+
       if (VirtualQuery (*var + memInfo.RegionSize, &m2, sizeof(m2)) == 0)
         DebPrint (("mmap_realloc: VirtualQuery error = %ld\n",
 		   GetLastError ()));
@@ -715,31 +721,29 @@ mmap_realloc (void **var, size_t nbytes)
 			    MEM_COMMIT, PAGE_READWRITE);
 	  if (!p /* && GetLastError() != ERROR_NOT_ENOUGH_MEMORY */)
 	    {
-	      DebPrint (("realloc enlarge: VirtualAlloc error %ld\n",
+	      DebPrint (("realloc enlarge: VirtualAlloc (%p + %I64x, %I64x) error %ld\n",
+			 *var, (uint64_t)memInfo.RegionSize,
+			 (uint64_t)(nbytes - memInfo.RegionSize),
 			 GetLastError ()));
-	      errno = ENOMEM;
 	    }
+	  else
+	    return *var;
+	}
+      /* Else we must actually enlarge the block by allocating a new
+	 one and copying previous contents from the old to the new one.  */
+      old_ptr = *var;
+
+      if (mmap_alloc (var, nbytes))
+	{
+	  CopyMemory (*var, old_ptr, memInfo.RegionSize);
+	  mmap_free (&old_ptr);
 	  return *var;
 	}
       else
 	{
-	  /* Else we must actually enlarge the block by allocating a
-	     new one and copying previous contents from the old to the
-	     new one.  */
-	  void *old_ptr = *var;
-
-	  if (mmap_alloc (var, nbytes))
-	    {
-	      CopyMemory (*var, old_ptr, memInfo.RegionSize);
-	      mmap_free (&old_ptr);
-	      return *var;
-	    }
-	  else
-	    {
-	      /* We failed to enlarge the buffer.  */
-	      *var = old_ptr;
-	      return NULL;
-	    }
+	  /* We failed to reallocate the buffer.  */
+	  *var = old_ptr;
+	  return NULL;
 	}
     }