Improve error handling of libxml2 calls in xml.c
authorMichael Paquier <michael@paquier.xyz>
Mon, 30 Jun 2025 23:57:05 +0000 (08:57 +0900)
committerMichael Paquier <michael@paquier.xyz>
Mon, 30 Jun 2025 23:57:05 +0000 (08:57 +0900)
commit2e947217474c15c7fd9011d1ab2b0d4657b3eae2
treed1bcb490466c787b47fdba8af60bb00beb87fffe
parent0836683a8977cac07d8cbdd0462f8a3e7e32565f
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.jones@uni-muenster.de>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Discussion: https://postgr.es/m/aEEingzOta_S_Nu7@paquier.xyz
src/backend/utils/adt/xml.c