Skip to content
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
5 changes: 5 additions & 0 deletions ext/json/json_encoder.c
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,8 @@ static zend_result php_json_encode_serializable_object(smart_str *buf, zval *val

ZEND_GUARD_PROTECT_RECURSION(guard, JSON);

GC_ADDREF(obj);

ZVAL_STRING(&fname, "jsonSerialize");

if (FAILURE == call_user_function(NULL, val, &fname, &retval, 0, NULL) || Z_TYPE(retval) == IS_UNDEF) {
Expand All @@ -610,6 +612,7 @@ static zend_result php_json_encode_serializable_object(smart_str *buf, zval *val
smart_str_appendl(buf, "null", 4);
}
ZEND_GUARD_UNPROTECT_RECURSION(guard, JSON);
OBJ_RELEASE(obj);
return FAILURE;
}

Expand All @@ -622,6 +625,7 @@ static zend_result php_json_encode_serializable_object(smart_str *buf, zval *val
smart_str_appendl(buf, "null", 4);
}
ZEND_GUARD_UNPROTECT_RECURSION(guard, JSON);
OBJ_RELEASE(obj);
return FAILURE;
}

Expand All @@ -638,6 +642,7 @@ static zend_result php_json_encode_serializable_object(smart_str *buf, zval *val

zval_ptr_dtor(&retval);
zval_ptr_dtor(&fname);
OBJ_RELEASE(obj);

return return_code;
}
Expand Down
21 changes: 21 additions & 0 deletions ext/json/tests/gh21024.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
--TEST--
GH-21024 (UAF in json_encode() when jsonSerialize()'s error handler frees the object)
--EXTENSIONS--
json
--FILE--
<?php
class Bar implements JsonSerializable {
public function jsonSerialize(): mixed {
trigger_error("free me");
return ['k' => 1];
}
}
$arr = [new Bar];
$ref = &$arr[0];
set_error_handler(function () use (&$ref) { $ref = null; });
var_dump(json_encode($arr));
echo "survived\n";
?>
--EXPECT--
string(9) "[{"k":1}]"
survived
Loading