Fix use-after-free when XMLSERIALIZE(... INDENT) output exceeds 1GB

From: Jim Jones <jim(dot)jones(at)uni-muenster(dot)de>
To: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Fix use-after-free when XMLSERIALIZE(... INDENT) output exceeds 1GB
Date: 2026-11-02 00:44:13
Message-ID: bbadb6b2-d226-41a1-ace3-e0eb20648f58@uni-muenster.de
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi

While investigating a libxml2 behaviour I found a bug in
xmltotext_with_options(): xmlserialize(.. indent) can crash the backend.

How to reproduce:

== master ==

psql (20devel)
Type "help" for help.

postgres=# \timing on
Timing is on.
postgres=# select xmlserialize(document ('<r>' || repeat('<b>bar</b>',
100000000) || '</r>')::xml AS text indent)::xml;
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
Time: 111002,809 ms (01:51,003)

The problem I see in this case is that ...

if (xmlSaveClose(ctxt) == -1 || xmlerrcxt->err_occurred)
{
ctxt = NULL; /* don't try to close it again */
}

... never sets ctxt to NULL, because xmlSaveClose succeeded and
xmlerrcxt->err_occurred is false -- no error just yet. Down the road ...

result = cstring_to_text_with_len(str, len)

... tries to palloc a result that is too large and jumps to PG_CATCH(),
which passes "if (ctxt)" but ctxt now points to a dangling address.

The patch attached makes the ctxt = NULL unconditional and stores the
value of xmlSaveClose(ctxt) into a variable, so that we can still call
xml_ereport in case of an error.

== patched ==

psql (20devel)
Type "help" for help.

postgres=# \timing on
Timing is on.
postgres=# select xmlserialize(document ('<r>' || repeat('<b>bar</b>',
100000000) || '</r>')::xml AS text indent)::xml;
ERROR: invalid memory alloc request size 1300000012
Time: 69742,848 ms (01:09,743)

Thoughts?

Best, Jim

Attachment Content-Type Size
v1-0001-Fix-use-after-free-when-XMLSERIALIZE-.-INDENT-out.patch text/x-patch 2.0 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Ayoub Kazar 2026-11-02 00:44:44 Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution
Previous Message Michael Paquier 2026-11-02 00:35:50 Re: [PATCH] pgstat: Add helper to drop entries from a stats kind's hash