pgsql: Improve error handling of libxml2 calls in xml.c

From: Michael Paquier <michael(at)paquier(dot)xyz>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Improve error handling of libxml2 calls in xml.c
Date: 2025-06-30 23:59:38
Message-ID: E1uWOPS-0046p0-0q@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Improve error handling of libxml2 calls in xml.c

This commit fixes some defects in the backend's xml.c, found upon
inspection of the internals of libxml2:
- xmlEncodeSpecialChars() can fail on malloc(), returning NULL back to
the caller. xmltext() assumed that this could never happen. Like other
code paths, a TRY/CATCH block is added there, covering also the fact
that cstring_to_text_with_len() could fail a memory allocation, where
the backend would miss to free the buffer allocated by
xmlEncodeSpecialChars().
- Some libxml2 routines called in xmlelement() can return NULL, like
xmlAddChildList() or xmlTextWriterStartElement(). Dedicated errors are
added for them.
- xml_xmlnodetoxmltype() missed that xmlXPathCastNodeToString() can fail
on an allocation failure. In this case, the call can just be moved to
the existing TRY/CATCH block.

All these code paths would cause the server to crash. As this is
unlikely a problem in practice, no backpatch is done. Jim and I have
caught these defects, not sure who has scored the most. The contrib
module xml2/ has similar defects, which will be addressed in a separate
change.

Reported-by: Jim Jones <jim(dot)jones(at)uni-muenster(dot)de>
Reviewed-by: Jim Jones <jim(dot)jones(at)uni-muenster(dot)de>
Discussion: https://postgr.es/m/aEEingzOta_S_Nu7@paquier.xyz

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/2e947217474c15c7fd9011d1ab2b0d4657b3eae2

Modified Files
--------------
src/backend/utils/adt/xml.c | 78 +++++++++++++++++++++++++++++++++++----------
1 file changed, 62 insertions(+), 16 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Michael Paquier 2025-07-01 00:52:22 pgsql: Fix typo in system_views.sql's definition of pg_stat_activity
Previous Message Tom Lane 2025-06-30 21:06:46 pgsql: Improve error report for PL/pgSQL reserved word used as a field