Skip to content

Commit 168636a

Browse files
committed
Free libxml2/libxslt resources in a safer order.
Mark Simonetti reported that libxslt sometimes crashes for him, and that swapping xslt_process's object-freeing calls around to do them in reverse order of creation seemed to fix it. I've not reproduced the crash, but valgrind clearly shows a reference to already-freed memory, which is consistent with the idea that shutdown of the xsltTransformContext is trying to reference the already-freed stylesheet or input document. With this patch, valgrind is no longer unhappy. I have an inquiry in to see if this is a libxslt bug or if we're just abusing the library; but even if it's a library bug, we'd want to adjust our code so it doesn't fail with unpatched libraries. Back-patch to all supported branches, because we've been doing this in the wrong(?) order for a long time.
1 parent 95be343 commit 168636a

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

contrib/xml2/xslt_proc.c

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -140,10 +140,10 @@ xslt_process(PG_FUNCTION_ARGS)
140140

141141
if (xslt_sec_prefs_error)
142142
{
143+
xsltFreeTransformContext(xslt_ctxt);
144+
xsltFreeSecurityPrefs(xslt_sec_prefs);
143145
xsltFreeStylesheet(stylesheet);
144146
xmlFreeDoc(doctree);
145-
xsltFreeSecurityPrefs(xslt_sec_prefs);
146-
xsltFreeTransformContext(xslt_ctxt);
147147
xsltCleanupGlobals();
148148
xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION,
149149
"could not set libxslt security preferences");
@@ -154,22 +154,22 @@ xslt_process(PG_FUNCTION_ARGS)
154154

155155
if (restree == NULL)
156156
{
157+
xsltFreeTransformContext(xslt_ctxt);
158+
xsltFreeSecurityPrefs(xslt_sec_prefs);
157159
xsltFreeStylesheet(stylesheet);
158160
xmlFreeDoc(doctree);
159-
xsltFreeSecurityPrefs(xslt_sec_prefs);
160-
xsltFreeTransformContext(xslt_ctxt);
161161
xsltCleanupGlobals();
162162
xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION,
163163
"failed to apply stylesheet");
164164
}
165165

166166
resstat = xsltSaveResultToString(&resstr, &reslen, restree, stylesheet);
167167

168-
xsltFreeStylesheet(stylesheet);
169168
xmlFreeDoc(restree);
170-
xmlFreeDoc(doctree);
171-
xsltFreeSecurityPrefs(xslt_sec_prefs);
172169
xsltFreeTransformContext(xslt_ctxt);
170+
xsltFreeSecurityPrefs(xslt_sec_prefs);
171+
xsltFreeStylesheet(stylesheet);
172+
xmlFreeDoc(doctree);
173173

174174
xsltCleanupGlobals();
175175

0 commit comments

Comments
 (0)