draft_MemoryContextContains_fixes.patch

text/plain

Filename: draft_MemoryContextContains_fixes.patch
Type: text/plain
Part: 0
Message: Re: Reducing the chunk header sizes on all memory context types

Patch

Format: unified
File+
src/backend/utils/mmgr/mcxt.c 7 10
diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c
index 64bcc7ef32..a6b2d02b75 100644
--- a/src/backend/utils/mmgr/mcxt.c
+++ b/src/backend/utils/mmgr/mcxt.c
@@ -809,11 +809,10 @@ MemoryContextCheck(MemoryContext context)
  *		Detect whether an allocated chunk of memory belongs to a given
  *		context or not.
  *
- * Caution: this test is reliable as long as 'pointer' does point to
- * a chunk of memory allocated from *some* context.  If 'pointer' points
- * at memory obtained in some other way, there is a small chance of a
- * false-positive result, since the bits right before it might look like
- * a valid chunk header by chance.
+ * Caution: 'pointer' must point to a pointer which was allocated by a
+ * MemoryContext.  It's not safe or valid to use this function on arbitrary
+ * pointers as obtaining the MemoryContext which 'pointer' belongs to requires
+ * possibly several pointer dereferences.
  */
 bool
 MemoryContextContains(MemoryContext context, void *pointer)
@@ -821,10 +820,6 @@ MemoryContextContains(MemoryContext context, void *pointer)
 	MemoryContext ptr_context;
 
 	/*
-	 * NB: Can't use GetMemoryChunkContext() here - that performs assertions
-	 * that aren't acceptable here since we might be passed memory not
-	 * allocated by any memory context.
-	 *
 	 * Try to detect bogus pointers handed to us, poorly though we can.
 	 * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
 	 * allocated chunk.
@@ -835,7 +830,7 @@ MemoryContextContains(MemoryContext context, void *pointer)
 	/*
 	 * OK, it's probably safe to look at the context.
 	 */
-	ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *));
+	ptr_context = GetMemoryChunkContext(pointer);
 
 	return ptr_context == context;
 }
@@ -1151,6 +1146,8 @@ palloc(Size size)
 						   size, context->name)));
 	}
 
+	Assert(MemoryContextContains(context, ret));
+
 	VALGRIND_MEMPOOL_ALLOC(context, ret, size);
 
 	return ret;