Skip to content

Commit 6a694bb

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 9880fea commit 6a694bb

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
@@ -139,10 +139,10 @@ xslt_process(PG_FUNCTION_ARGS)
139139

140140
if (xslt_sec_prefs_error)
141141
{
142+
xsltFreeTransformContext(xslt_ctxt);
143+
xsltFreeSecurityPrefs(xslt_sec_prefs);
142144
xsltFreeStylesheet(stylesheet);
143145
xmlFreeDoc(doctree);
144-
xsltFreeSecurityPrefs(xslt_sec_prefs);
145-
xsltFreeTransformContext(xslt_ctxt);
146146
xsltCleanupGlobals();
147147
xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION,
148148
"could not set libxslt security preferences");
@@ -153,22 +153,22 @@ xslt_process(PG_FUNCTION_ARGS)
153153

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

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

167-
xsltFreeStylesheet(stylesheet);
168167
xmlFreeDoc(restree);
169-
xmlFreeDoc(doctree);
170-
xsltFreeSecurityPrefs(xslt_sec_prefs);
171168
xsltFreeTransformContext(xslt_ctxt);
169+
xsltFreeSecurityPrefs(xslt_sec_prefs);
170+
xsltFreeStylesheet(stylesheet);
171+
xmlFreeDoc(doctree);
172172

173173
xsltCleanupGlobals();
174174

0 commit comments

Comments
 (0)