memory context mismatch in LockMethodLocalHash entries.

From: Ashutosh Bapat <ashutosh(dot)bapat(dot)oss(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Cc: Ashutosh Bapat <ashutosh(dot)bapat(at)enterprisedb(dot)com>
Subject: memory context mismatch in LockMethodLocalHash entries.
Date: 2023-04-20 13:31:49
Message-ID: CAExHW5v5gFOp+tdWe1md9owqaau00mmbE++TzrR7D1_F7A7-Ug@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi All,
LockMethodLocalHash hash table is allocated in memory context ""LOCALLOCK hash".
LockAcquireExtended() fetches an entry from this hash table and
allocates memory for locallock->lockOwners in TopMemoryContext. Thus
the entry locallock and an array pointed from this entry are allocated
in two different memory contexts.

Theoretically if LockMethodLocalHash was destroyed with some entries
in it, it would leave some dangling pointers in TopMemoryContext. It
looks to me that the array lockOwners should be allocated in same
context as LOCALLOCK hash or its child. Something like below

diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index 42595b38b2..32804b1c2c 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -843,7 +843,7 @@ LockAcquireExtended(const LOCKTAG *locktag,
locallock->maxLockOwners = 8;
locallock->lockOwners = NULL; /* in case next line fails */
locallock->lockOwners = (LOCALLOCKOWNER *)
- MemoryContextAlloc(TopMemoryContext,
+ MemoryContextAlloc(GetMemoryChunkContext(locallock),

locallock->maxLockOwners * sizeof(LOCALLOCKOWNER));
}
else

LockMethodLocalHash is hash_destroyed() in InitLocks(). The comment
there mentions that possibly there are no entries in that hash table
at that time. So the problem described above is rare or non-existent
as of now. But it's possibly worth fixing while it's not too serious.

There were some untraceable bugs related to locks reported earlier
[1]. Those may be linked to this. But we couldn't establish the
connection.

[1] https://www.postgresql.org/message-id/flat/5227.1315428924%40sss.pgh.pa.us#00116525613b7ddb82669d2ba358b31e

--
Best Wishes,
Ashutosh Bapat

Browse pgsql-hackers by date

  From Date Subject
Next Message Miroslav Bendik 2023-04-20 13:36:52 Re: Incremental sort for access method with ordered scan support (amcanorderbyop)
Previous Message Daniel Gustafsson 2023-04-20 12:57:46 Re: Should we put command options in alphabetical order in the doc?