Skip to content

ext/pdo: Convert def_stmt_ctor_args field from zval to HashTable pointer #17396

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
64 changes: 30 additions & 34 deletions ext/pdo/pdo_dbh.c
Original file line number Diff line number Diff line change
Expand Up @@ -542,15 +542,12 @@ PHP_METHOD(PDO, connect)
}
/* }}} */

static zval *pdo_stmt_instantiate(pdo_dbh_t *dbh, zval *object, zend_class_entry *dbstmt_ce, zval *ctor_args) /* {{{ */
static zval *pdo_stmt_instantiate(pdo_dbh_t *dbh, zval *object, zend_class_entry *dbstmt_ce, const HashTable *ctor_args) /* {{{ */
{
if (!Z_ISUNDEF_P(ctor_args)) {
if (ctor_args && dbstmt_ce->constructor == NULL) {
/* This implies an error within PDO if this does not hold */
ZEND_ASSERT(Z_TYPE_P(ctor_args) == IS_ARRAY);
if (!dbstmt_ce->constructor) {
zend_throw_error(NULL, "User-supplied statement does not accept constructor arguments");
return NULL;
}
zend_throw_error(NULL, "User-supplied statement does not accept constructor arguments");
return NULL;
}

if (UNEXPECTED(object_init_ex(object, dbstmt_ce) != SUCCESS)) {
Expand Down Expand Up @@ -583,10 +580,11 @@ PHP_METHOD(PDO, prepare)
{
pdo_stmt_t *stmt;
zend_string *statement;
zval *options = NULL, *value, *item, ctor_args;
zval *options = NULL, *value, *item;
zend_class_entry *dbstmt_ce, *pce;
pdo_dbh_object_t *dbh_obj = Z_PDO_OBJECT_P(ZEND_THIS);
pdo_dbh_t *dbh = dbh_obj->inner;
HashTable *ctor_args = NULL;

ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STR(statement)
Expand Down Expand Up @@ -633,16 +631,14 @@ PHP_METHOD(PDO, prepare)
zend_zval_value_name(value));
RETURN_THROWS();
}
ZVAL_COPY_VALUE(&ctor_args, item);
} else {
ZVAL_UNDEF(&ctor_args);
ctor_args = Z_ARRVAL_P(item);
}
} else {
dbstmt_ce = dbh->def_stmt_ce;
ZVAL_COPY_VALUE(&ctor_args, &dbh->def_stmt_ctor_args);
ctor_args = dbh->def_stmt_ctor_args;
}

if (!pdo_stmt_instantiate(dbh, return_value, dbstmt_ce, &ctor_args)) {
if (!pdo_stmt_instantiate(dbh, return_value, dbstmt_ce, ctor_args)) {
RETURN_THROWS();
}
stmt = Z_PDO_STMT_P(return_value);
Expand All @@ -656,11 +652,7 @@ PHP_METHOD(PDO, prepare)
stmt->database_object_handle = &dbh_obj->std;

if (dbh->methods->preparer(dbh, statement, stmt, options)) {
if (Z_TYPE(ctor_args) == IS_ARRAY) {
pdo_stmt_construct(stmt, return_value, dbstmt_ce, Z_ARRVAL(ctor_args));
} else {
pdo_stmt_construct(stmt, return_value, dbstmt_ce, /* ctor_args */ NULL);
}
pdo_stmt_construct(stmt, return_value, dbstmt_ce, ctor_args);
return;
}

Expand Down Expand Up @@ -924,17 +916,19 @@ static bool pdo_dbh_attribute_set(pdo_dbh_t *dbh, zend_long attr, zval *value, u
return false;
}
dbh->def_stmt_ce = pce;
if (!Z_ISUNDEF(dbh->def_stmt_ctor_args)) {
zval_ptr_dtor(&dbh->def_stmt_ctor_args);
ZVAL_UNDEF(&dbh->def_stmt_ctor_args);
if (dbh->def_stmt_ctor_args != NULL) {
zend_array_release(dbh->def_stmt_ctor_args);
dbh->def_stmt_ctor_args = NULL;
}
if ((item = zend_hash_index_find(Z_ARRVAL_P(value), 1)) != NULL) {
if (Z_TYPE_P(item) != IS_ARRAY) {
zend_argument_type_error(value_arg_num, "PDO::ATTR_STATEMENT_CLASS constructor_args must be of type ?array, %s given",
zend_zval_value_name(value));
return false;
}
ZVAL_COPY(&dbh->def_stmt_ctor_args, item);
dbh->def_stmt_ctor_args = Z_ARRVAL_P(item);
/* Increase refcount */
GC_TRY_ADDREF(dbh->def_stmt_ctor_args);
}
return true;
}
Expand Down Expand Up @@ -1013,9 +1007,10 @@ PHP_METHOD(PDO, getAttribute)
case PDO_ATTR_STATEMENT_CLASS:
array_init(return_value);
add_next_index_str(return_value, zend_string_copy(dbh->def_stmt_ce->name));
if (!Z_ISUNDEF(dbh->def_stmt_ctor_args)) {
Z_TRY_ADDREF(dbh->def_stmt_ctor_args);
add_next_index_zval(return_value, &dbh->def_stmt_ctor_args);
if (dbh->def_stmt_ctor_args != NULL) {
/* Increase refcount */
GC_TRY_ADDREF(dbh->def_stmt_ctor_args);
add_next_index_array(return_value, dbh->def_stmt_ctor_args);
}
return;

Expand Down Expand Up @@ -1205,7 +1200,7 @@ PHP_METHOD(PDO, query)

PDO_DBH_CLEAR_ERR();

if (!pdo_stmt_instantiate(dbh, return_value, dbh->def_stmt_ce, &dbh->def_stmt_ctor_args)) {
if (!pdo_stmt_instantiate(dbh, return_value, dbh->def_stmt_ce, dbh->def_stmt_ctor_args)) {
RETURN_THROWS();
}
stmt = Z_PDO_STMT_P(return_value);
Expand Down Expand Up @@ -1233,11 +1228,7 @@ PHP_METHOD(PDO, query)
stmt->executed = 1;
}
if (ret) {
if (Z_TYPE(dbh->def_stmt_ctor_args) == IS_ARRAY) {
pdo_stmt_construct(stmt, return_value, dbh->def_stmt_ce, Z_ARRVAL(dbh->def_stmt_ctor_args));
} else {
pdo_stmt_construct(stmt, return_value, dbh->def_stmt_ce, /* ctor_args */ NULL);
}
pdo_stmt_construct(stmt, return_value, dbh->def_stmt_ce, dbh->def_stmt_ctor_args);
return;
}
}
Expand Down Expand Up @@ -1432,7 +1423,10 @@ static HashTable *dbh_get_gc(zend_object *object, zval **gc_data, int *gc_count)
{
pdo_dbh_t *dbh = php_pdo_dbh_fetch_inner(object);
zend_get_gc_buffer *gc_buffer = zend_get_gc_buffer_create();
zend_get_gc_buffer_add_zval(gc_buffer, &dbh->def_stmt_ctor_args);
if (dbh->def_stmt_ctor_args != NULL) {
zend_get_gc_buffer_add_ht(gc_buffer, dbh->def_stmt_ctor_args);
dbh->def_stmt_ctor_args = NULL;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You probably didn't understand the root cause of the issue properly as this is almost certainly wrong.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is indeed wrong. If cycles are registered by not collected then you lose the link to the ctor_args and future invocations may have wrong results.

The problem is that on shutdown the cycles are collected, the array is destroyed first, and then again in free_storage. You can solve this by using a dtor:

diff --git a/ext/pdo/pdo_dbh.c b/ext/pdo/pdo_dbh.c
index be24b23a5ad..8566f58b789 100644
--- a/ext/pdo/pdo_dbh.c
+++ b/ext/pdo/pdo_dbh.c
@@ -1425,7 +1425,6 @@ static HashTable *dbh_get_gc(zend_object *object, zval **gc_data, int *gc_count)
 	zend_get_gc_buffer *gc_buffer = zend_get_gc_buffer_create();
 	if (dbh->def_stmt_ctor_args != NULL) {
 		zend_get_gc_buffer_add_ht(gc_buffer, dbh->def_stmt_ctor_args);
-		dbh->def_stmt_ctor_args = NULL;
 	}
 	if (dbh->methods && dbh->methods->get_gc) {
 		dbh->methods->get_gc(dbh, gc_buffer);
@@ -1438,6 +1437,18 @@ static zend_object_handlers pdo_dbh_object_handlers;
 
 static void pdo_dbh_free_storage(zend_object *std);
 
+static void pdo_dbh_dtor(zend_object *object)
+{
+	pdo_dbh_t *dbh = php_pdo_dbh_fetch_inner(object);
+
+	zend_objects_destroy_object(object);
+
+	if (dbh->def_stmt_ctor_args != NULL) {
+		zend_array_release(dbh->def_stmt_ctor_args);
+		dbh->def_stmt_ctor_args = NULL;
+	}
+}
+
 void pdo_dbh_init(int module_number)
 {
 	pdo_dbh_ce = register_class_PDO();
@@ -1447,6 +1458,7 @@ void pdo_dbh_init(int module_number)
 	memcpy(&pdo_dbh_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
 	pdo_dbh_object_handlers.offset = XtOffsetOf(pdo_dbh_object_t, std);
 	pdo_dbh_object_handlers.free_obj = pdo_dbh_free_storage;
+	pdo_dbh_object_handlers.dtor_obj = pdo_dbh_dtor;
 	pdo_dbh_object_handlers.clone_obj = NULL;
 	pdo_dbh_object_handlers.get_method = dbh_method_get;
 	pdo_dbh_object_handlers.compare = zend_objects_not_comparable;
@@ -1490,11 +1502,6 @@ static void dbh_free(pdo_dbh_t *dbh, bool free_persistent)
 		pefree((char *)dbh->persistent_id, dbh->is_persistent);
 	}
 
-	if (dbh->def_stmt_ctor_args != NULL) {
-		zend_array_release(dbh->def_stmt_ctor_args);
-		dbh->def_stmt_ctor_args = NULL;
-	}
-
 	for (i = 0; i < PDO_DBH_DRIVER_METHOD_KIND__MAX; i++) {
 		if (dbh->cls_methods[i]) {
 			zend_hash_destroy(dbh->cls_methods[i]);

Not sure if the size save is worth the complexity though.

}
if (dbh->methods && dbh->methods->get_gc) {
dbh->methods->get_gc(dbh, gc_buffer);
}
Expand Down Expand Up @@ -1496,8 +1490,9 @@ static void dbh_free(pdo_dbh_t *dbh, bool free_persistent)
pefree((char *)dbh->persistent_id, dbh->is_persistent);
}

if (!Z_ISUNDEF(dbh->def_stmt_ctor_args)) {
zval_ptr_dtor(&dbh->def_stmt_ctor_args);
if (dbh->def_stmt_ctor_args != NULL) {
zend_array_release(dbh->def_stmt_ctor_args);
dbh->def_stmt_ctor_args = NULL;
}

for (i = 0; i < PDO_DBH_DRIVER_METHOD_KIND__MAX; i++) {
Expand Down Expand Up @@ -1542,6 +1537,7 @@ zend_object *pdo_dbh_new(zend_class_entry *ce)
zend_std_get_properties_ex(&dbh->std);
dbh->inner = ecalloc(1, sizeof(pdo_dbh_t));
dbh->inner->def_stmt_ce = pdo_dbstmt_ce;
dbh->inner->def_stmt_ctor_args = NULL;

return &dbh->std;
}
Expand Down
2 changes: 1 addition & 1 deletion ext/pdo/php_pdo_driver.h
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ struct _pdo_dbh_t {

zend_class_entry *def_stmt_ce;

zval def_stmt_ctor_args;
HashTable *def_stmt_ctor_args;

/* when calling PDO::query(), we need to keep the error
* context from the statement around until we next clear it.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
--TEST--
PDO Common: Set PDOStatement class with PDO::ATTR_STATEMENT_CLASS overall test
--EXTENSIONS--
pdo
--SKIPIF--
<?php
$dir = getenv('REDIR_TEST_DIR');
if (false == $dir) die('skip no driver');
require_once $dir . 'pdo_test.inc';
PDOTest::skip();
?>
--FILE--
<?php
if (getenv('REDIR_TEST_DIR') === false) putenv('REDIR_TEST_DIR='.__DIR__ . '/../../pdo/tests/');
require_once getenv('REDIR_TEST_DIR') . 'pdo_test.inc';

$db = PDOTest::factory();
$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);

$table = 'pdo_attr_statement_class_basic';
$db->exec("CREATE TABLE {$table} (id INT, label CHAR(1), PRIMARY KEY(id))");
$db->exec("INSERT INTO {$table} (id, label) VALUES (1, 'a')");
$db->exec("INSERT INTO {$table} (id, label) VALUES (2, 'b')");

$default = $db->getAttribute(PDO::ATTR_STATEMENT_CLASS);
var_dump($default);

// Having a public destructor is allowed
class StatementWithPublicDestructor extends PDOStatement {
public function __destruct() {
echo __METHOD__, PHP_EOL;
}
}

try {
var_dump($db->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['StatementWithPublicDestructor', []]));
} catch (\Throwable $e) {
echo $e::class, ': ', $e->getMessage(), \PHP_EOL;
}
var_dump($db->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['StatementWithPublicDestructor']));
$stmt = $db->query("SELECT id, label FROM {$table} ORDER BY id ASC");
unset($stmt);

echo "Class derived from PDOStatement, with private constructor:\n";
class StatementWithPrivateConstructor extends PDOStatement {
private function __construct($msg) {
echo __METHOD__, PHP_EOL;
var_dump($this);
var_dump($msg);
}
}
var_dump($db->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['StatementWithPrivateConstructor', ['param1']]));
$stmt = $db->query("SELECT id, label FROM {$table} ORDER BY id ASC");
unset($stmt);

echo "Class derived from a child of PDOStatement:\n";
class StatementDerivedFromChild extends StatementWithPrivateConstructor {
public function fetchAll($fetch_style = 1, ...$fetch_args): array {
return [];
}
}

var_dump($db->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['StatementDerivedFromChild', ['param1']]));
$stmt = $db->query("SELECT id, label FROM {$table} ORDER BY id ASC");
var_dump($stmt->fetchAll());
unset($stmt);

echo "Reset to default PDOStatement class:\n";
var_dump($db->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['PDOStatement']));
$stmt = $db->query("SELECT id, label FROM {$table} ORDER BY id ASC");
var_dump($stmt->fetchAll());
unset($stmt);

?>
--CLEAN--
<?php
require_once getenv('REDIR_TEST_DIR') . 'pdo_test.inc';
$db = PDOTest::factory();
PDOTest::dropTableIfExists($db, "pdo_attr_statement_class_basic");
?>
--EXPECT--
array(1) {
[0]=>
string(12) "PDOStatement"
}
bool(true)
bool(true)
StatementWithPublicDestructor::__destruct
Class derived from PDOStatement, with private constructor:
bool(true)
StatementWithPrivateConstructor::__construct
object(StatementWithPrivateConstructor)#2 (1) {
["queryString"]=>
string(68) "SELECT id, label FROM pdo_attr_statement_class_basic ORDER BY id ASC"
}
string(6) "param1"
Class derived from a child of PDOStatement:
bool(true)
StatementWithPrivateConstructor::__construct
object(StatementDerivedFromChild)#2 (1) {
["queryString"]=>
string(68) "SELECT id, label FROM pdo_attr_statement_class_basic ORDER BY id ASC"
}
string(6) "param1"
array(0) {
}
Reset to default PDOStatement class:
bool(true)
array(2) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
[0]=>
string(1) "1"
["label"]=>
string(1) "a"
[1]=>
string(1) "a"
}
[1]=>
array(4) {
["id"]=>
string(1) "2"
[0]=>
string(1) "2"
["label"]=>
string(1) "b"
[1]=>
string(1) "b"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
--TEST--
PDO Common: Set PDOStatement class with ctor_args that are freed with GC intervention
--EXTENSIONS--
pdo
--SKIPIF--
<?php
$dir = getenv('REDIR_TEST_DIR');
if (false == $dir) die('skip no driver');
require_once $dir . 'pdo_test.inc';
PDOTest::skip();
?>
--FILE--
<?php
if (getenv('REDIR_TEST_DIR') === false) putenv('REDIR_TEST_DIR='.__DIR__ . '/../../pdo/tests/');
require_once getenv('REDIR_TEST_DIR') . 'pdo_test.inc';

class Foo extends PDOStatement {
private function __construct($v) {
var_dump($v);
}
}

class Bar extends PDO {
public $statementClass = 'Foo';
function __construct($dsn, $username, $password, $driver_options = []) {
$driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
parent::__construct($dsn, $username, $password, $driver_options);

$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [$this->statementClass, [$this]]);
}
}

$db = PDOTest::factory(Bar::class);

$table = 'pdo_attr_statement_class_ctor_arg_gc';
$db->exec("CREATE TABLE {$table} (id INT, label CHAR(1), PRIMARY KEY(id))");
$db->exec("INSERT INTO {$table} (id, label) VALUES (1, 'a')");
$db->exec("INSERT INTO {$table} (id, label) VALUES (2, 'b')");
$query = "SELECT id, label FROM {$table} ORDER BY id ASC";
$stmt = $db->query($query);

var_dump($stmt instanceof Foo);
var_dump($stmt->queryString === $query);

?>
--CLEAN--
<?php
require_once getenv('REDIR_TEST_DIR') . 'pdo_test.inc';
$db = PDOTest::factory();
PDOTest::dropTableIfExists($db, "pdo_attr_statement_class_ctor_arg_gc");
?>
--EXPECT--
object(Bar)#1 (1) {
["statementClass"]=>
string(3) "Foo"
}
bool(true)
bool(true)
Loading
Loading