Re: Memory leak in pg_stat_statements when qtext file contains invalid encoding

From: Heikki Linnakangas <hlinnaka(at)iki(dot)fi>
To: Lukas Fittl <lukas(at)fittl(dot)com>, Gaurav Singh <gaurav(dot)singh(at)yugabyte(dot)com>
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: Memory leak in pg_stat_statements when qtext file contains invalid encoding
Date: 2026-03-27 08:59:32
Message-ID: 178e0d90-26d9-4c3a-9448-2f64f0d35dc8@iki.fi
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On 27/03/2026 10:21, Lukas Fittl wrote:
> Hi Gaurav,
>
> On Fri, Mar 27, 2026 at 12:54 AM Gaurav Singh <gaurav(dot)singh(at)yugabyte(dot)com> wrote:
>> If the qtext file contains an invalid encoding, pg_any_to_server calls ereport(ERROR) which longjmps out of the function.
>> The cleanup code at the bottom of the function is never reached.
>>
>> LWLockRelease(pgss->lock);
>> if (qbuffer)
>> free(qbuffer);
>> On every subsequent call, the malloc'd buffer (the entire file contents) is leaked, and the LWLock release is also skipped.
>
> I don't think the analysis is correct in regards to the LWLock release
> - that should be taken care of by LWLockReleaseAll on abort.
>
> But I think you're correct about qbuffer - because that buffer is
> using malloc (not palloc), its not part of any memory context, and so
> it will happily leak on abort.

Yep

> It appears our use of malloc in pg_stat_statements is so that we can
> fail on OOM and return NULL without a jump. I think that makes sense
> for when a GC cycle was triggered during regular query execution
> (since we don't want to error the original query), but it seems like
> just bubbling up the OOM if needed when querying the
> pg_stat_statements function seems fine.
>
> I wonder if its worth separating the two cases, since the issue you're
> describing (the call to pg_any_to_server failing) only happens when
> returning the query text file contents to the client. I think your
> PG_FINALLY suggestion could also work, but it feels a bit tedious to
> wrap the whole pg_stat_statements_internal function in it.

Hmm, perhaps. But there's a simpler, less invasive fix. When that code
was written, we didn't have MCXT_ALLOC_HUGE nor MCXT_ALLOC_NO_OOM. Now
that we do, we can just use palloc_extended(MCXT_ALLOC_HUGE |
MCXT_ALLOC_NO_OOM) instead of raw malloc(). Per attached.

- Heikki

Attachment Content-Type Size
0001-Avoid-memory-leak-on-error-while-parsing-pg_stat_sta.patch text/x-patch 3.1 KB

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Daniel Gustafsson 2026-03-27 09:05:18 Re: Memory leak in pg_stat_statements when qtext file contains invalid encoding
Previous Message Gaurav Singh 2026-03-27 08:57:37 Re: Memory leak in pg_stat_statements when qtext file contains invalid encoding