From 11fec0c183fecdd8d40c3dd09e9115beaa646255 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Mon, 29 Dec 2025 17:12:48 +0800
Subject: [PATCH v1] lsyscache: free IndexAmRoutine objects returned by
 GetIndexAmRoutineByAmId()

Several callers in lsyscache.c obtain an IndexAmRoutine via
GetIndexAmRoutineByAmId() but did not release the returned object,
unlike get_opmethod_canorder(), which already frees it after use.

Capture the needed fields from IndexAmRoutine into local variables and
pfree() the struct before continuing. This makes ownership handling
consistent across callers and avoids leaking memory on these code paths.

No functional change intended.

Author: Chao Li <lic@highgo.com>
---
 src/backend/utils/cache/lsyscache.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/backend/utils/cache/lsyscache.c b/src/backend/utils/cache/lsyscache.c
index 5aa7a26d95c..2b91a0204db 100644
--- a/src/backend/utils/cache/lsyscache.c
+++ b/src/backend/utils/cache/lsyscache.c
@@ -730,10 +730,13 @@ get_op_index_interpretation(Oid opno)
 				HeapTuple	op_tuple = &catlist->members[i]->tuple;
 				Form_pg_amop op_form = (Form_pg_amop) GETSTRUCT(op_tuple);
 				IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(op_form->amopmethod, false);
+				bool		amcanorder = amroutine->amcanorder;
 				CompareType cmptype;
 
+				pfree(amroutine);
+
 				/* must be ordering index */
-				if (!amroutine->amcanorder)
+				if (!amcanorder)
 					continue;
 
 				/* Get the operator's comparision type */
@@ -803,8 +806,11 @@ equality_ops_are_compatible(Oid opno1, Oid opno2)
 		if (op_in_opfamily(opno2, op_form->amopfamily))
 		{
 			IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(op_form->amopmethod, false);
+			bool		amconsistentequality = amroutine->amconsistentequality;
 
-			if (amroutine->amconsistentequality)
+			pfree(amroutine);
+
+			if (amconsistentequality)
 			{
 				result = true;
 				break;
@@ -859,8 +865,11 @@ comparison_ops_are_compatible(Oid opno1, Oid opno2)
 		if (op_in_opfamily(opno2, op_form->amopfamily))
 		{
 			IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(op_form->amopmethod, false);
+			bool		amconsistentordering = amroutine->amconsistentordering;
+
+			pfree(amroutine);
 
-			if (amroutine->amconsistentordering)
+			if (amconsistentordering)
 			{
 				result = true;
 				break;
-- 
2.39.5 (Apple Git-154)

