Skip to content

Fix memory leak when setting an invalid DOMDocument encoding #12002

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions ext/dom/document.c
Original file line number Diff line number Diff line change
Expand Up @@ -139,19 +139,22 @@ int dom_document_encoding_read(dom_object *obj, zval *retval)
zend_result dom_document_encoding_write(dom_object *obj, zval *newval)
{
xmlDoc *docp = (xmlDocPtr) dom_object_get_node(obj);
zend_string *str;
xmlCharEncodingHandlerPtr handler;

if (docp == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}

str = zval_try_get_string(newval);
if (UNEXPECTED(!str)) {
return FAILURE;
/* Typed property, can only be IS_STRING or IS_NULL. */
ZEND_ASSERT(Z_TYPE_P(newval) == IS_STRING || Z_TYPE_P(newval) == IS_NULL);

if (Z_TYPE_P(newval) == IS_NULL) {
goto invalid_encoding;
}

zend_string *str = Z_STR_P(newval);

handler = xmlFindCharEncodingHandler(ZSTR_VAL(str));

if (handler != NULL) {
Expand All @@ -161,12 +164,14 @@ zend_result dom_document_encoding_write(dom_object *obj, zval *newval)
}
docp->encoding = xmlStrdup((const xmlChar *) ZSTR_VAL(str));
} else {
zend_value_error("Invalid document encoding");
return FAILURE;
goto invalid_encoding;
}

zend_string_release_ex(str, 0);
return SUCCESS;

invalid_encoding:
zend_value_error("Invalid document encoding");
return FAILURE;
}

/* }}} */
Expand Down
38 changes: 38 additions & 0 deletions ext/dom/tests/gh12002.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
--TEST--
GH-12002 (DOMDocument::encoding memory leak with invalid encoding)
--EXTENSIONS--
dom
--FILE--
<?php

function make_nonconst(string $x) {
// Defeat SCCP, even with inlining
return str_repeat($x, random_int(1, 1));
}

$dom = new DOMDocument();
$dom->encoding = make_nonconst('utf-8');
var_dump($dom->encoding);
try {
$dom->encoding = make_nonconst('foobar');
} catch (ValueError $e) {
echo $e->getMessage(), "\n";
}
var_dump($dom->encoding);
$dom->encoding = make_nonconst('utf-16le');
var_dump($dom->encoding);
try {
$dom->encoding = NULL;
} catch (ValueError $e) {
echo $e->getMessage(), "\n";
}
var_dump($dom->encoding);

?>
--EXPECT--
string(5) "utf-8"
Invalid document encoding
string(5) "utf-8"
string(8) "utf-16le"
Invalid document encoding
string(8) "utf-16le"