[PATCH] Fix SIGSEGV in GrantLockLocal when OOM leaves LOCALLOCK.lockOwners NULL

From: Bryan Green <dbryan(dot)green(at)gmail(dot)com>
To: pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: [PATCH] Fix SIGSEGV in GrantLockLocal when OOM leaves LOCALLOCK.lockOwners NULL
Date: 2026-08-09 03:26:40
Message-ID: c9a5eeb1-4d31-46e1-bb9e-33448a23a5d3@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Greetings,

An out-of-memory error during the first LockAcquire for a lock tag leaves a
LOCALLOCK that crashes the next acquire of the same tag.  The initial
lockOwners allocation is done with maxLockOwners already set to 8 and
lockOwners still NULL; if that allocation throws, the entry survives in that
state.  The next acquire takes the existing-entry path, where the only check
is numLockOwners >= maxLockOwners (0 >= 8, false), so it skips the
allocation and GrantLockLocal() dereferences the NULL pointer.

This is not a hypothetical state.  Tom Lane hardened RemoveLocalLock()
against exactly it in ba51774d87 (2015, "per low-memory testing by Andreas
Seltenreich"): "RemoveLocalLock() must consider the possibility that
LockAcquireExtended() failed to palloc the initial space for a locallock's
lockOwners array."  That fix covered the cleanup path; the re-acquire path
still assumes lockOwners is allocated.  This closes that gap, the same way:
if lockOwners is NULL, allocate it before use.

One subtlety worth stating: a plain top-level OOM here aborts the
transaction, and RemoveLocalLock() then discards the partial entry, so no
re-acquire hits it.  The crash needs the OOM caught without a full lock
release, e.g. a PL/pgSQL EXCEPTION handler, where the subtransaction abort
does not run LockReleaseAll and does not touch an entry that never got a
resource owner.  The entry then survives to the next acquire.

The fix is one branch in lock.c.  I confirmed the crash and the fix by
forcing the allocation to fail for advisory locks; the regression suite
passes.

The original diagnosis is Mark Dilger's; I reproduced it on master and
prepared it for submission.

--
Bryan Green
EDB: https://www.enterprisedb.com

Attachment Content-Type Size
0001-Fix-SIGSEGV-in-GrantLockLocal-when-OOM-leaves-LOCALL.patch text/plain 1.8 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Bryan Green 2026-08-09 03:33:30 [PATCH] Release a replication slot leaked by a caught subtransaction error
Previous Message Scott Ray 2026-08-09 03:16:36 Re: pg_xmin_horizon: a system view of everything pinning the xmin horizon