Re: Use-after-free in ER_get_flat_size() when a PL/pgSQL expression references a TOASTed field and the whole record

From: Baji Shaik <baji(dot)pgdev(at)gmail(dot)com>
To: "Lejao, Kristian" <klejao(at)amazon(dot)com>
Cc: "pgsql-hackers(at)postgresql(dot)org" <pgsql-hackers(at)postgresql(dot)org>, "Wang, Xnerv" <xnerv(at)amazon(dot)com>, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Subject: Re: Use-after-free in ER_get_flat_size() when a PL/pgSQL expression references a TOASTed field and the whole record
Date: 2026-12-01 18:14:43
Message-ID: CA+fm-RNmc-O2=MaO_ad7+XnJor_D9ndP1jdetLwg_SdvsPTkZQ@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hello Kristian,

On Sun, Nov 8, 2026 at 3:52 AM Lejao, Kristian <klejao(at)amazon(dot)com> wrote:

> Thoughts and review welcome.
>

Thank you for the report and patch.
I can reproduce both cases on master, and the patches fix them for me.
The new test fails without the fix and passes with it.

One thing I noticed in ER_get_flat_size():

+ * It mustn't pfree the old value, though: a caller may still
+ * be using a field value it fetched earlier. The old value
+ * is just a TOAST pointer, so it can stay around until the
+ * record is deleted.
+ */
+ expanded_record_set_field_worker(erh, i + 1,
+ erh->dvalues[i], false,
+ true,
+ false,
+ false);

"Until the record is deleted" can be a while for a PL/pgSQL variable.
If a function keeps one record and reassigns a toasted field in a loop,
each to_jsonb() leaves one TOAST pointer behind:

select * into r from toasted_hole;
for i in 1..n loop
r.b := (select b from toasted_hole);
j := to_jsonb(r);
end loop;

The "expanded record" context stays at 28kB on master, but grows to
8.4MB at n = 100000 with the patch (~84 bytes per iteration). Small,
but it grows with the loop count. Could the old pointer be remembered
and freed later?

Also, on my build (macOS, cassert) the trigger case with one row in src
didn't crash; the INSERT stored a corrupt value instead, and reading
snap failed with "compressed pglz data is corrupt". With 10 rows it
crashed:

TRAP: failed Assert("VARATT_EXTINFO_IS_COMPRESSED(va_extinfo,
va_rawsize)"),
File: "toast_internals.c", Line: 264

So it can also write bad data without crashing. Might be worth
mentioning in the commit message.

Thanks,
Baji Shaik

In response to

Browse pgsql-hackers by date

  From Date Subject
Previous Message Fujii Masao 2026-12-01 17:40:54 Re: pg_receivewal doesn't truncate compressed WAL files on restart