Deprecation warnings on Rocky 10.2 with current dev branch

Поиск
Список
Период
Сортировка
Искать

Deprecation warnings on Rocky 10.2 with current dev branch

От:
"Daniel Westermann (DWE)" <daniel.westermann@dbi-services.com>
Дата:
Hi,

I've just noticed this while building from the dev branch on Rocky 10.2 x64:

[1086/2136] Compiling C object src/backend/postgres_lib.a.p/utils_adt_xml.c.o
../postgresql/src/backend/utils/adt/xml.c: In function ‘xml_parse’:
../postgresql/src/backend/utils/adt/xml.c:1924:25: warning: ‘xmlKeepBlanksDefault’ is deprecated [-Wdeprecated-declarations]
 1924 |                         save_keep_blanks = xmlKeepBlanksDefault(preserve_whitespace ? 1 : 0);
      |                         ^~~~~~~~~~~~~~~~
In file included from ../postgresql/src/backend/utils/adt/xml.c:51:
/usr/include/libxml2/libxml/parser.h:957:17: note: declared here
  957 |                 xmlKeepBlanksDefault    (int val);
      |                 ^~~~~~~~~~~~~~~~~~~~
../postgresql/src/backend/utils/adt/xml.c:1948:25: warning: ‘xmlKeepBlanksDefault’ is deprecated [-Wdeprecated-declarations]
 1948 |                         xmlKeepBlanksDefault(save_keep_blanks);
      |                         ^~~~~~~~~~~~~~~~~~~~
/usr/include/libxml2/libxml/parser.h:957:17: note: declared here
  957 |                 xmlKeepBlanksDefault    (int val);
      |                 ^~~~~~~~~~~~~~~~~~~~
../postgresql/src/backend/utils/adt/xml.c:1961:17: warning: ‘xmlKeepBlanksDefault’ is deprecated [-Wdeprecated-declarations]
 1961 |                 xmlKeepBlanksDefault(save_keep_blanks);
      |                 ^~~~~~~~~~~~~~~~~~~~
/usr/include/libxml2/libxml/parser.h:957:17: note: declared here
  957 |                 xmlKeepBlanksDefault    (int val);
      |                 ^~~~~~~~~~~~~~~~~~~~

Is this known already?

Regards
Daniel

Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Daniel Gustafsson <daniel@yesql.se>
Дата:
> On 17 Jul 2026, at 14:47, Daniel Westermann (DWE)  wrote:

> [1086/2136] Compiling C object src/backend/postgres_lib.a.p/utils_adt_xml.c.o
> ../postgresql/src/backend/utils/adt/xml.c: In function ‘xml_parse’:
> ../postgresql/src/backend/utils/adt/xml.c:1924:25: warning: ‘xmlKeepBlanksDefault’ is deprecated [-Wdeprecated-declarations]
> 1924 |                         save_keep_blanks = xmlKeepBlanksDefault(preserve_whitespace ? 1 : 0);
>      |                         ^~~~~~~~~~~~~~~~
> In file included from ../postgresql/src/backend/utils/adt/xml.c:51:

Which version of libxml2 do you have installed?

--
Daniel Gustafsson



Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
"Daniel Westermann (DWE)" <daniel.westermann@dbi-services.com>
Дата:
>> On 17 Jul 2026, at 14:47, Daniel Westermann (DWE)  wrote:

>> [1086/2136] Compiling C object src/backend/postgres_lib.a.p/utils_adt_xml.c.o
>> ../postgresql/src/backend/utils/adt/xml.c: In function ‘xml_parse’:
>> ../postgresql/src/backend/utils/adt/xml.c:1924:25: warning: ‘xmlKeepBlanksDefault’ is deprecated [-Wdeprecated-declarations]
>> 1924 |                         save_keep_blanks = xmlKeepBlanksDefault(preserve_whitespace ? 1 : 0);
>>      |                         ^~~~~~~~~~~~~~~~
>> In file included from ../postgresql/src/backend/utils/adt/xml.c:51:

>Which version of libxml2 do you have installed?

The standard on Rocky 10:

postgres@rocky10-pgbox:/home/postgres/ [pg20] rpm -qa | grep libxml2
libxml2-2.12.5-10.el10_2.2.x86_64
libxml2-devel-2.12.5-10.el10_2.2.x86_64

Regards
Daniel


Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
"Daniel Westermann (DWE)"  writes:
> I've just noticed this while building from the dev branch on Rocky 10.2 x64:
> ../postgresql/src/backend/utils/adt/xml.c:1961:17: warning: ‘xmlKeepBlanksDefault’ is deprecated [-Wdeprecated-declarations]
>  1961 |                 xmlKeepBlanksDefault(save_keep_blanks);
>       |                 ^~~~~~~~~~~~~~~~~~~~

> Is this known already?

Yeah.  It's annoying as heck, because they deprecated that without
providing an adequate replacement.  The replacement is claimed to
be "Use the modern options API with XML_PARSE_NOBLANKS", but there
is no direct equivalent to xmlParseBalancedChunkMemory that takes
an options argument.

So to get rid of this, we're looking at a probably-nontrivial
rewrite of xml_parse(), with possibly some user-visible behavioral
changes, and who-knows-what effects for compatibility across
different libxml2 versions.

If you feel like researching that, have at it.

			regards, tom lane


Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Andrew Dunstan <andrew@dunslane.net>
Дата:

On 2026-07-17 Fr 10:38 AM, Tom Lane wrote:
> "Daniel Westermann (DWE)"  writes:
>> I've just noticed this while building from the dev branch on Rocky 10.2 x64:
>> ../postgresql/src/backend/utils/adt/xml.c:1961:17: warning: ‘xmlKeepBlanksDefault’ is deprecated [-Wdeprecated-declarations]
>>   1961 |                 xmlKeepBlanksDefault(save_keep_blanks);
>>        |                 ^~~~~~~~~~~~~~~~~~~~
>> Is this known already?
> Yeah.  It's annoying as heck, because they deprecated that without
> providing an adequate replacement.  The replacement is claimed to
> be "Use the modern options API with XML_PARSE_NOBLANKS", but there
> is no direct equivalent to xmlParseBalancedChunkMemory that takes
> an options argument.
>
> So to get rid of this, we're looking at a probably-nontrivial
> rewrite of xml_parse(), with possibly some user-visible behavioral
> changes, and who-knows-what effects for compatibility across
> different libxml2 versions.
>
> If you feel like researching that, have at it.
>

I think we can probably use xmlParseInNodeContext(), which does take an 
options argument. Did you look at that?


cheers


andrew


--
Andrew Dunstan
EDB: https://www.enterprisedb.com



Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Andrew Dunstan  writes:
> On 2026-07-17 Fr 10:38 AM, Tom Lane wrote:
>> Yeah.  It's annoying as heck, because they deprecated that without
>> providing an adequate replacement.  The replacement is claimed to
>> be "Use the modern options API with XML_PARSE_NOBLANKS", but there
>> is no direct equivalent to xmlParseBalancedChunkMemory that takes
>> an options argument.

> I think we can probably use xmlParseInNodeContext(), which does take an 
> options argument. Did you look at that?

Hmm ... I think I was confused by the fact that it takes "const char
*data" not "const xmlChar *string".  On further research, those are
more equivalent than I'd thought.  So maybe it'll work.

			regards, tom lane


Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
I wrote:
> After studying the libxml2 source code I realized that
> xmlParseInNodeContext doesn't automatically attach anything at all to
> the passed-in node or its document; those are used only as context.
> So I think we can clean this up noticeably by attaching the content
> node list to that root node instead of returning it separately.
> Essentially, this is moving the data structure hacking that
> xmltotext_with_options did into xml_parse.  Here's a slightly less
> hasty version.

The cfbot pointed out that this patch is drawing warnings since
3ee0edb91 added -Wshadow=local.  Here's a less shadow-y version;
no substantive change.

			regards, tom lane

From f877108f6d7f4156424716ac2eb25f2ae15c0cbb Mon Sep 17 00:00:00 2001
From: Tom Lane 
Date: Wed, 7 Oct 2026 12:07:06 -0400
Subject: [PATCH v3] Modernize our parsing of XML data in CONTENT mode.

The main goal of this patch is to get rid of our use of
xmlKeepBlanksDefault, which libxml2 has deprecated.
To do that, we want to use xmlParseInNodeContext instead of
xmlParseBalancedChunkMemory, so that we can pass an options
mask including XML_PARSE_NOBLANKS.

xmlParseInNodeContext wants an xmlNode rather than an xmlDoc as
context.  This gives us an opportunity for simplification though:
we can make that node be a dummy root node for xml_parse's result
document, and then attach the content node(s) as children of the root,
essentially moving the data structure hack in xmltotext_with_options
into xml_parse.  The main benefit of this is that callers no longer
need to free the content node list separately; freeing the document is
sufficient.  (There were error paths in xmltotext_with_options that
I think would have leaked that list, though they could only be
reached in OOM or similar conditions.)

Author: Tom Lane 
Fix-suggested-by: Andrew Dunstan 
Discussion: https://postgr.es/m/ZR2PPFF1830B8772632FA23847D7482168FD2C62@ZR2PPFF1830B877.CHEP278.PROD.OUTLOOK.COM
---
 src/backend/utils/adt/xml.c | 133 ++++++++++++++++++------------------
 1 file changed, 66 insertions(+), 67 deletions(-)

diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index 1f75ffcfd9d..dcda62c4606 100644
--- a/src/backend/utils/adt/xml.c
+++ b/src/backend/utils/adt/xml.c
@@ -157,7 +157,6 @@ static bool xml_doctype_in_content(const xmlChar *str);
 static xmlDocPtr xml_parse(text *data, XmlOptionType xmloption_arg,
 						   bool preserve_whitespace, int encoding,
 						   XmlOptionType *parsed_xmloptiontype,
-						   xmlNodePtr *parsed_nodes,
 						   Node *escontext);
 static text *xml_xmlnodetoxmltype(xmlNodePtr cur, PgXmlErrorContext *xmlerrcxt);
 static int	xml_xpathobjtoxmlarray(xmlXPathObjectPtr xpathobj,
@@ -285,7 +284,7 @@ xml_in(PG_FUNCTION_ARGS)
 	 * Note: we don't need to worry about whether a soft error is detected.
 	 */
 	doc = xml_parse(vardata, xmloption, true, GetDatabaseEncoding(),
-					NULL, NULL, fcinfo->context);
+					NULL, fcinfo->context);
 	if (doc != NULL)
 		xmlFreeDoc(doc);
 
@@ -413,7 +412,7 @@ xml_recv(PG_FUNCTION_ARGS)
 	 * Parse the data to check if it is well-formed XML data.  Assume that
 	 * xml_parse will throw ERROR if not.
 	 */
-	doc = xml_parse(result, xmloption, true, encoding, NULL, NULL, NULL);
+	doc = xml_parse(result, xmloption, true, encoding, NULL, NULL);
 	xmlFreeDoc(doc);
 
 	/* Now that we know what we're dealing with, convert to server encoding */
@@ -681,7 +680,6 @@ xmltotext_with_options(xmltype *data, XmlOptionType xmloption_arg, bool indent)
 	text	   *volatile result;
 	xmlDocPtr	doc;
 	XmlOptionType parsed_xmloptiontype;
-	xmlNodePtr	content_nodes;
 	volatile xmlBufferPtr buf = NULL;
 	volatile xmlSaveCtxtPtr ctxt = NULL;
 	ErrorSaveContext escontext = {T_ErrorSaveContext};
@@ -707,7 +705,7 @@ xmltotext_with_options(xmltype *data, XmlOptionType xmloption_arg, bool indent)
 	 * libxml2 will fail to indent elements that have whitespace between them.
 	 */
 	doc = xml_parse(data, xmloption_arg, !indent, GetDatabaseEncoding(),
-					&parsed_xmloptiontype, &content_nodes,
+					&parsed_xmloptiontype,
 					(Node *) &escontext);
 	if (doc == NULL || escontext.error_occurred)
 	{
@@ -772,35 +770,16 @@ xmltotext_with_options(xmltype *data, XmlOptionType xmloption_arg, bool indent)
 				xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
 							"could not save document to xmlBuffer");
 		}
-		else if (content_nodes != NULL)
+		else
 		{
 			/*
-			 * Deal with the case where we have non-singly-rooted XML.
-			 * libxml's dump functions don't work well for that without help.
-			 * We build a fake root node that serves as a container for the
-			 * content nodes, and then iterate over the nodes.
+			 * When we have non-singly-rooted XML, we need to insert newlines
+			 * between the content nodes, else the output is ugly.
 			 */
-			xmlNodePtr	root;
-			xmlNodePtr	oldroot;
+			xmlNodePtr	root = xmlDocGetRootElement(doc);
 			xmlNodePtr	newline;
 
-			root = xmlNewNode(NULL, (const xmlChar *) "content-root");
-			if (root == NULL || xmlerrcxt->err_occurred)
-				xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
-							"could not allocate xml node");
-
-			/*
-			 * This attaches root to doc, so we need not free it separately...
-			 * but instead, we have to free the old root if there was one.
-			 */
-			oldroot = xmlDocSetRootElement(doc, root);
-			if (oldroot != NULL)
-				xmlFreeNode(oldroot);
-
-			if (xmlAddChildList(root, content_nodes) == NULL ||
-				xmlerrcxt->err_occurred)
-				xml_ereport(xmlerrcxt, ERROR, ERRCODE_INTERNAL_ERROR,
-							"could not append xml node list");
+			Assert(root != NULL);
 
 			/*
 			 * We use this node to insert newlines in the dump.  Note: in at
@@ -1035,7 +1014,7 @@ xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace, Node
 	xmlDocPtr	doc;
 
 	doc = xml_parse(data, xmloption_arg, preserve_whitespace,
-					GetDatabaseEncoding(), NULL, NULL, escontext);
+					GetDatabaseEncoding(), NULL, escontext);
 	if (doc)
 		xmlFreeDoc(doc);
 
@@ -1179,7 +1158,7 @@ xml_is_document(xmltype *arg)
 	 * We'll report "true" if no soft error is reported by xml_parse().
 	 */
 	doc = xml_parse((text *) arg, XMLOPTION_DOCUMENT, true,
-					GetDatabaseEncoding(), NULL, NULL, (Node *) &escontext);
+					GetDatabaseEncoding(), NULL, (Node *) &escontext);
 	if (doc)
 		xmlFreeDoc(doc);
 
@@ -1772,9 +1751,8 @@ xml_doctype_in_content(const xmlChar *str)
  * XmlOptionType actually used to parse the input (typically the same as
  * xmloption_arg, but a DOCTYPE node in the input can force DOCUMENT mode).
  *
- * If parsed_nodes isn't NULL and we parse in CONTENT mode, the list
- * of parsed nodes from the xmlParseBalancedChunkMemory call will be returned
- * to *parsed_nodes.  (It is caller's responsibility to free that.)
+ * When we parse in CONTENT mode, the resulting document has a dummy root
+ * node with zero or more child nodes, reflecting the contents found.
  *
  * Errors normally result in ereport(ERROR), but if escontext is an
  * ErrorSaveContext, then "safe" errors are reported there instead, and the
@@ -1790,7 +1768,7 @@ xml_doctype_in_content(const xmlChar *str)
 static xmlDocPtr
 xml_parse(text *data, XmlOptionType xmloption_arg,
 		  bool preserve_whitespace, int encoding,
-		  XmlOptionType *parsed_xmloptiontype, xmlNodePtr *parsed_nodes,
+		  XmlOptionType *parsed_xmloptiontype,
 		  Node *escontext)
 {
 	int32		len;
@@ -1799,7 +1777,6 @@ xml_parse(text *data, XmlOptionType xmloption_arg,
 	PgXmlErrorContext *xmlerrcxt;
 	volatile xmlParserCtxtPtr ctxt = NULL;
 	volatile xmlDocPtr doc = NULL;
-	volatile int save_keep_blanks = -1;
 
 	/*
 	 * This step looks annoyingly redundant, but we must do it to have a
@@ -1827,10 +1804,10 @@ xml_parse(text *data, XmlOptionType xmloption_arg,
 	PG_TRY();
 	{
 		bool		parse_as_document = false;
-		int			res_code;
 		size_t		count = 0;
 		xmlChar    *version = NULL;
 		int			standalone = 0;
+		int			options;
 
 		/* Any errors here are reported as hard ereport's */
 		xmlInitParser();
@@ -1841,6 +1818,8 @@ xml_parse(text *data, XmlOptionType xmloption_arg,
 		else
 		{
 			/* Parse and skip over the XML declaration, if any */
+			int			res_code;
+
 			res_code = parse_xml_decl(utf8string,
 									  &count, &version, NULL, &standalone);
 			if (res_code != 0)
@@ -1857,35 +1836,31 @@ xml_parse(text *data, XmlOptionType xmloption_arg,
 				parse_as_document = true;
 		}
 
-		/* initialize output parameters */
+		/*
+		 * Select parse options.
+		 *
+		 * Note that here we try to apply DTD defaults (XML_PARSE_DTDATTR)
+		 * according to SQL/XML:2008 GR 10.16.7.d: 'Default values defined by
+		 * internal DTD are applied'.  As for external DTDs, we try to support
+		 * them too (see SQL/XML:2008 GR 10.16.7.e), but that doesn't really
+		 * happen because xmlPgEntityLoader prevents it.
+		 */
+		options = XML_PARSE_NOENT | XML_PARSE_DTDATTR
+			| (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS);
+
+		/* initialize output parameter */
 		if (parsed_xmloptiontype != NULL)
 			*parsed_xmloptiontype = parse_as_document ? XMLOPTION_DOCUMENT :
 				XMLOPTION_CONTENT;
-		if (parsed_nodes != NULL)
-			*parsed_nodes = NULL;
 
 		if (parse_as_document)
 		{
-			int			options;
-
 			/* set up parser context used by xmlCtxtReadDoc */
 			ctxt = xmlNewParserCtxt();
 			if (ctxt == NULL || xmlerrcxt->err_occurred)
 				xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
 							"could not allocate parser context");
 
-			/*
-			 * Select parse options.
-			 *
-			 * Note that here we try to apply DTD defaults (XML_PARSE_DTDATTR)
-			 * according to SQL/XML:2008 GR 10.16.7.d: 'Default values defined
-			 * by internal DTD are applied'.  As for external DTDs, we try to
-			 * support them too (see SQL/XML:2008 GR 10.16.7.e), but that
-			 * doesn't really happen because xmlPgEntityLoader prevents it.
-			 */
-			options = XML_PARSE_NOENT | XML_PARSE_DTDATTR
-				| (preserve_whitespace ? 0 : XML_PARSE_NOBLANKS);
-
 			doc = xmlCtxtReadDoc(ctxt, utf8string,
 								 NULL,	/* no URL */
 								 "UTF-8",
@@ -1907,7 +1882,12 @@ xml_parse(text *data, XmlOptionType xmloption_arg,
 		}
 		else
 		{
-			/* set up document that xmlParseBalancedChunkMemory will add to */
+			xmlNodePtr	root;
+
+			/*
+			 * Create our result document and set up its dummy root node,
+			 * which we'll use as the context node for xmlParseInNodeContext.
+			 */
 			doc = xmlNewDoc(version);
 			if (doc == NULL || xmlerrcxt->err_occurred)
 				xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
@@ -1920,16 +1900,40 @@ xml_parse(text *data, XmlOptionType xmloption_arg,
 							"could not allocate XML document");
 			doc->standalone = standalone;
 
-			/* set parse options --- have to do this the ugly way */
-			save_keep_blanks = xmlKeepBlanksDefault(preserve_whitespace ? 1 : 0);
+			root = xmlNewNode(NULL, (const xmlChar *) "content-root");
+			if (root == NULL || xmlerrcxt->err_occurred)
+				xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
+							"could not allocate xml node");
+			xmlDocSetRootElement(doc, root);
 
 			/* allow empty content */
 			if (*(utf8string + count))
 			{
-				res_code = xmlParseBalancedChunkMemory(doc, NULL, NULL, 0,
-													   utf8string + count,
-													   parsed_nodes);
-				if (res_code != 0 || xmlerrcxt->err_occurred)
+				/* for some reason we need "char *" not "xmlChar *" here */
+				const char *content = (const char *) (utf8string + count);
+				xmlNodePtr	nodelist = NULL;
+				xmlParserErrors res_code;
+
+				res_code = xmlParseInNodeContext(root,
+												 content,
+												 strlen(content),
+												 options,
+												 &nodelist);
+
+				/* immediately attach the resulting nodelist to the root */
+				if (nodelist)
+				{
+					if (xmlAddChildList(root, nodelist) == NULL)
+					{
+						/* don't leak the nodelist if we can't attach it */
+						xmlFreeNodeList(nodelist);
+						xml_ereport(xmlerrcxt, ERROR, ERRCODE_INTERNAL_ERROR,
+									"could not append xml node list");
+					}
+					/* now, freeing the document will release the nodelist */
+				}
+
+				if (res_code != XML_ERR_OK || xmlerrcxt->err_occurred)
 				{
 					xml_errsave(escontext, xmlerrcxt,
 								ERRCODE_INVALID_XML_CONTENT,
@@ -1944,8 +1948,6 @@ fail:
 	}
 	PG_CATCH();
 	{
-		if (save_keep_blanks != -1)
-			xmlKeepBlanksDefault(save_keep_blanks);
 		if (doc != NULL)
 			xmlFreeDoc(doc);
 		if (ctxt != NULL)
@@ -1957,9 +1959,6 @@ fail:
 	}
 	PG_END_TRY();
 
-	if (save_keep_blanks != -1)
-		xmlKeepBlanksDefault(save_keep_blanks);
-
 	if (ctxt != NULL)
 		xmlFreeParserCtxt(ctxt);
 
@@ -4648,7 +4647,7 @@ wellformed_xml(text *data, XmlOptionType xmloption_arg)
 	 * We'll report "true" if no soft error is reported by xml_parse().
 	 */
 	doc = xml_parse(data, xmloption_arg, true,
-					GetDatabaseEncoding(), NULL, NULL, (Node *) &escontext);
+					GetDatabaseEncoding(), NULL, (Node *) &escontext);
 	if (doc)
 		xmlFreeDoc(doc);
 
-- 
2.52.0

Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Вложения:
Hi Tom,

Thanks for updating the XML content parser. I compared v3 with master
at 412848dac37 and found two changes in XMLSERIALIZE ... INDENT output
with older libxml2 versions.

I tested with libxml2 2.9.7 from my system, an upstream build of 2.12.5
to match the version reported in this thread, and the latest upstream
release, 2.15.4.

1. With libxml2 2.9.7, v3 drops U+FEFF after the XML declaration.
The attached 0001 fixes this and adds a regression test.

In a UTF8 database:

SELECT xmlserialize(CONTENT xmlparse(CONTENT
  '' || chr(65279) || 'abc') AS text INDENT);

  master:     abc
  v3:         abc
  v3 + 0001:  abc

chr(65279) is U+FEFF, the character used as a byte-order mark (BOM).
Here it follows the XML declaration and is part of the content.
xml_parse() skips the declaration
 before calling xmlParseInNodeContext(), leaving
U+FEFF at the start of its input.
With doc->encoding set to UTF-8, libxml2 2.9.7 calls
xmlSwitchToEncoding() and removes the character as a BOM.

0001 moves the doc->encoding assignment after xmlParseInNodeContext().
The input is already UTF-8, so the parser can read it with doc->encoding
unset.

To check whether setting doc->encoding to UTF-8 later could cause
other problems, I read the libxml2 source. I checked all functions
called between the old and new assignment locations in versions
2.9.7, 2.12.5 and 2.15.4.

xmlDocSetRootElement(), xmlAddChildList() and their helpers do not use
doc->encoding. xmlParseInNodeContext() reads it to set the input
encoding in all three versions. xml_parse() has already converted the
input to UTF-8, which this parser also uses with doc->encoding unset.
Only 2.9.7 strips U+FEFF during explicit encoding setup.
0001 sets doc->encoding to UTF-8 after xmlParseInNodeContext(),
before xml_parse() returns. The XML output still uses the same encoding.
I found no other side effects in these functions.

Master and v3 already retain U+FEFF with libxml2 2.12.5 and 2.15.4.
With libxml2 2.9.7, the new test fails on v3 and passes on v3 + 0001.
It also passes on v3 + 0001 with 2.12.5 and 2.15.4.

2. With libxml2 2.9.7 and 2.12.5, v3 removes the space between 
and  in this mixed-content input:

SELECT replace(xmlserialize(CONTENT 'abc ' AS text INDENT),
               E'\n', E'\\n');

  master:            abc\n \n
  v3:                abc\n\n
  v3 + 0001 + 0002:  abc\n \n

I traced this to areBlanks() in libxml2 2.12.5. One of the checks in
its source keeps whitespace when the parent's first child is a text
node. With the old API, that child is the text node "abc", so the
space between  and  is kept. xmlParseInNodeContext() inserts
a temporary comment before "abc". The first child is then a comment,
so that check no longer preserves the space, and the parser removes it.

With libxml2 2.15.4, both master and v3 retain the space, but PG users
can still use old versions.

0002 fixes this in xml_parse() by adding an empty text child to the
dummy root before xmlParseInNodeContext(), then removing it after
parsing. This gives areBlanks() a text node as the first child again.
It does this when whitespace removal is enabled and the content starts
with nonblank text or a character reference. Leading literal whitespace
is left alone.

0001 applies on top of v3, and 0002 applies on top of 0001. With both
patches, all 239 core regression tests passed on each of the three
libxml2 versions.

3. I also tried keeping xmlParseBalancedChunkMemory() and passing an
xmlSAXHandler to control whitespace instead of calling
xmlKeepBlanksDefault(). In xml_parse(), the key change was:

    xmlSAXHandler sax;

    memset(&sax, 0, sizeof(sax));
    xmlSAXVersion(&sax, 2);
    if (!preserve_whitespace)
        sax.ignorableWhitespace = xmlSAX2IgnorableWhitespace;

    res_code = xmlParseBalancedChunkMemory(doc, &sax, NULL, 0,
                                          utf8string + count,
                                          parsed_nodes);

This is a small change. Both examples above and all 239 core
regression tests passed with all three libxml2 versions.
However, on 2.9.7 and 2.12.5, forcing the parser's internal xmlNewDoc()
to fail aborted the PostgreSQL backend. In libxml2 2.12.5,
xmlParseBalancedChunkMemory() calls
xmlParseBalancedChunkMemoryRecover(), which has these two error paths:

    /* This return does not free the caller's sax. */
    ctxt = xmlCreateDocParserCtxt(string);
    if (ctxt == NULL) return(-1);

    /* This later failure frees it through xmlFreeParserCtxt(). */
    oldsax = ctxt->sax;
    ctxt->sax = sax;
    newDoc = xmlNewDoc(BAD_CAST "1.0");
    if (newDoc == NULL) {
        xmlFreeParserCtxt(ctxt);
        return(-1);
    }

xmlFreeParserCtxt() frees our xmlSAXHandler with:

    xmlFree(ctxt->sax);

This is an invalid free for a stack handler. Normal cleanup restores
oldsax first, but the xmlNewDoc() failure path does not.

Allocating sax on the heap does not solve this: both errors return -1,
but only the second frees sax. PG cannot tell which error occurred.
Calling xmlFree(sax) on every error would double-free it after the
xmlNewDoc() failure. Skipping cleanup would leak it after the
xmlCreateDocParserCtxt() failure.

Since libxml2 2.13.0, the parser makes its own copy of the caller's
xmlSAXHandler, avoiding this error path [1]. But PostgreSQL still
supports the affected older libraries, so I dropped the SAX alternative.

The warning comes from the deprecated xmlKeepBlanksDefault(). Its
documentation recommends parser options with XML_PARSE_NOBLANKS [2].
xmlParseBalancedChunkMemory() has no options parameter, while
xmlParseInNodeContext() does, as Andrew pointed out. Your change thus
removes the deprecated calls while still controlling whitespace.

The docs also suggest xmlCtxtParseContent() as an alternative to
xmlParseInNodeContext(), but it is only available since 2.14. Given
the older versions PostgreSQL supports and the results above, I think
your approach is the best fit for this change, with these two fixes.

[1] https://gitlab.gnome.org/GNOME/libxml2/-/commit/ecfbcc8a
[2] https://gnome.pages.gitlab.gnome.org/libxml2/html/parser_8h.html

Regards,
Rui

Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Rui Zhao  writes:
> Thanks for updating the XML content parser. I compared v3 with master
> at 412848dac37 and found two changes in XMLSERIALIZE ... INDENT output
> with older libxml2 versions.

Thanks for looking at it!

> 1. With libxml2 2.9.7, v3 drops U+FEFF after the XML declaration.

Wow, how'd you find that?  I do replicate this result on the 2.9.13
that Apple is currently shipping, so I agree it might be worth
worrying about.  (But then again, it seems very likely nobody would
ever notice.)

> The attached 0001 fixes this and adds a regression test.

Hmm, 0001 seems quite odd to me.  Why bother to install a value for
doc->encoding at all, if we're not going to do so until after all
the calls that will pay attention to it?   I tried simply commenting
out the assignment:
  
            Assert(doc->encoding == NULL);
+ #ifdef NOT_USED
            doc->encoding = xmlStrdup((const xmlChar *) "UTF-8");
            if (doc->encoding == NULL || xmlerrcxt->err_occurred)
                xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
                            "could not allocate XML document");
+ #endif
            doc->standalone = standalone;

and that seemed to work fine.

> 2. With libxml2 2.9.7 and 2.12.5, v3 removes the space between 
> and  in this mixed-content input:

> SELECT replace(xmlserialize(CONTENT 'abc ' AS text INDENT),
>                E'\n', E'\\n');

Hm.  While that's not great, it sure seems like an edge case.
There is no particularly well-defined behavior for whitespace in
INDENT mode anyway, is there?  How would you tell which whitespace
was in the original input and which was INDENT's responsibility?
So I'm kind of inclined to let it go.  If the proposed fix weren't
so ugly I might feel differently, but it's messy, overly familiar
with libxml2 innards, and perhaps could introduce odd cases of its
own in libxml2 versions other than the ones you tested.  Plus the
comments don't actually agree with what the code is doing AFAICT.
(Why do we not need to take action if the input has leading
whitespace?  Wouldn't the injected comment mess it up anyway?)

On the whole, if this is the biggest behavioral change we can find
from switching to xmlParseInNodeContext, I think we're in pretty
good shape.  I had feared that there might be much worse.  My current
thought is to apply this patch to HEAD only, so if there are any
small behavioral changes that users notice, we can write them off
as expected in a major version update.

> 3. I also tried keeping xmlParseBalancedChunkMemory() and passing an
> xmlSAXHandler to control whitespace instead of calling
> xmlKeepBlanksDefault().

I agree that that isn't a good way to go.  While libxml2 has only
officially deprecated SAX1, I wonder how much they like SAX2 either.
Even if that worry is baseless, it seems like making use of SAX would
greatly expand the amount of libxml2 API we're depending on --- and
their API behavior has not been so stable that I want to have more
surface area for problems.

> The docs also suggest xmlCtxtParseContent() as an alternative to
> xmlParseInNodeContext(), but it is only available since 2.14. Given
> the older versions PostgreSQL supports and the results above, I think
> your approach is the best fit for this change, with these two fixes.

Yeah, that suggestion isn't real helpful for our purposes.

So my current thought is to cut down 0001 so it just removes code
without adding any, and reject 0002 as not worth trying to fix.
OK by you?

Thanks again for reviewing!

			regards, tom lane


Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Hi Tom,

Thanks for your reply.

> Wow, how'd you find that?  I do replicate this result on the 2.9.13
> that Apple is currently shipping, so I agree it might be worth
> worrying about.  (But then again, it seems very likely nobody would
> ever notice.)

I noticed that the main change replaced xmlParseBalancedChunkMemory()
with xmlParseInNodeContext(). I read the latter's source and saw its
handling of doc->encoding, then asked AI to help construct a case
where that could lose XML content.

> Hmm, 0001 seems quite odd to me.  Why bother to install a value for
> doc->encoding at all, if we're not going to do so until after all
> the calls that will pay attention to it?   I tried simply commenting
> out the assignment:
>
>            Assert(doc->encoding == NULL);
> + #ifdef NOT_USED
>            doc->encoding = xmlStrdup((const xmlChar *) "UTF-8");
>            if (doc->encoding == NULL || xmlerrcxt->err_occurred)
>                xml_ereport(xmlerrcxt, ERROR, ERRCODE_OUT_OF_MEMORY,
>                            "could not allocate XML document");
> + #endif
>            doc->standalone = standalone;
>
> and that seemed to work fine.

I kept the assignment at the end of xml_parse() so later calls would
still get doc->encoding set to "UTF-8". I had checked xmlNewNode(),
xmlDocSetRootElement(), xmlParseInNodeContext() and xmlAddChildList()
in libxml2 2.9.7, 2.12.5 and 2.15.4. Leaving doc->encoding unset
during those calls fixed the U+FEFF loss without changing the later
serialization.

After your suggestion, I traced later uses of doc->encoding and asked
AI again to help construct a case. I verified it in PG with libxml2
2.9.7 and 2.12.5, in a UTF8 database:

SELECT xmlserialize(CONTENT '' AS text INDENT);
-- Master:               
-- With 0001:            
-- With #ifdef NOT_USED:  

The reason is that xmlSaveTree() calls xmlBufAttrSerializeTxtContent()
through xmlAttrSerializeContent(), passing attr->doc. It checks the
document's encoding; when that is NULL, non-ASCII attribute characters
are written as character references. Here, é represents the same
é character.

> Hm.  While that's not great, it sure seems like an edge case.
> There is no particularly well-defined behavior for whitespace in
> INDENT mode anyway, is there?  How would you tell which whitespace
> was in the original input and which was INDENT's responsibility?
> So I'm kind of inclined to let it go.  If the proposed fix weren't
> so ugly I might feel differently, but it's messy, overly familiar
> with libxml2 innards, and perhaps could introduce odd cases of its
> own in libxml2 versions other than the ones you tested.  Plus the
> comments don't actually agree with what the code is doing AFAICT.
> (Why do we not need to take action if the input has leading
> whitespace?  Wouldn't the injected comment mess it up anyway?)

Agreed. The workaround could introduce other differences in library
versions. I'm happy to leave this INDENT whitespace behavior to libxml2
and drop 0002.

Regards,
Rui


Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Rui Zhao  writes:
>> Hmm, 0001 seems quite odd to me.  Why bother to install a value for
>> doc->encoding at all, if we're not going to do so until after all
>> the calls that will pay attention to it?   I tried simply commenting
>> out the assignment:
>> ...
>> and that seemed to work fine.

> After your suggestion, I traced later uses of doc->encoding and asked
> AI again to help construct a case. I verified it in PG with libxml2
> 2.9.7 and 2.12.5, in a UTF8 database:

> SELECT xmlserialize(CONTENT '' AS text INDENT);
> -- Master:               
> -- With 0001:            
> -- With #ifdef NOT_USED:  

Interesting!  I had tried substantially the same test, but using
"ñ" as a body-text character, and that case seems to get output
as a hex reference no matter what.  It didn't occur to me that
characters inside tag attributes might get treated differently.

So I'll use 0001 as you have it, but I think while I'm at it
I will add test coverage for these behaviors.

> Agreed. The workaround could introduce other differences in library
> versions. I'm happy to leave this INDENT whitespace behavior to libxml2
> and drop 0002.

We're on the same page then.  Thanks again for the review!

			regards, tom lane


Re: Deprecation warnings on Rocky 10.2 with current dev branch

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
I wrote:
> So I'll use 0001 as you have it, but I think while I'm at it
> I will add test coverage for these behaviors.

Pushed.  I shall now watch the buildfarm from a safe distance.

			regards, tom lane


FAQ