From 8952a372140f8ffca4b4349dc97a1f78e10f767f Mon Sep 17 00:00:00 2001 From: David Carlier Date: Fri, 27 Nov 2026 14:54:42 +0000 Subject: [PATCH] ext/pdo_pgsql: dangling running statement after a failed query(). PDO::query() detaches the handle from a failed statement before releasing it, so pgsql_stmt_dtor() skipped clearing H->running_stmt and the connection kept a pointer to the freed statement that the next lazy query dereferenced in pgsql_stmt_finish(). Clear it as well when the handle is merely detached; an already destroyed handle (bug72294) is still left untouched. Fix GH-25838 --- NEWS | 4 ++++ ext/pdo_pgsql/pgsql_statement.c | 2 +- ext/pdo_pgsql/tests/gh25838.phpt | 30 ++++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 ext/pdo_pgsql/tests/gh25838.phpt diff --git a/NEWS b/NEWS index c599b16bf9f9..06a3676090b1 100644 --- a/NEWS +++ b/NEWS @@ -178,6 +178,10 @@ PHP NEWS . Fixed a crash when executing a prepared statement again after a failed execute() with libmysqlclient. (Ilia Alshanetsky) +- PDO_PGSQL: + . Fixed bug GH-25838 (use-after-free when a lazy statement follows a failed + query). (Yun Dou) + - PDO_SQLite: . Fixed bug GH-25588 (Use-after-free of a string parameter omitted on a later execute() or rebound while fetching). (Ilia Alshanetsky) diff --git a/ext/pdo_pgsql/pgsql_statement.c b/ext/pdo_pgsql/pgsql_statement.c index b2af41a339b1..60199f86269f 100644 --- a/ext/pdo_pgsql/pgsql_statement.c +++ b/ext/pdo_pgsql/pgsql_statement.c @@ -191,7 +191,7 @@ static int pgsql_stmt_dtor(pdo_stmt_t *stmt) pgsql_stmt_finish(S, FIN_DISCARD|(server_obj_usable ? FIN_CLOSE|FIN_ABORT : 0)); - if (server_obj_usable && S->H->running_stmt == S) { + if ((server_obj_usable || stmt->database_object_handle == NULL) && S->H->running_stmt == S) { S->H->running_stmt = NULL; } diff --git a/ext/pdo_pgsql/tests/gh25838.phpt b/ext/pdo_pgsql/tests/gh25838.phpt new file mode 100644 index 000000000000..02b575161279 --- /dev/null +++ b/ext/pdo_pgsql/tests/gh25838.phpt @@ -0,0 +1,30 @@ +--TEST-- +GH-25838 (pdo_pgsql: use-after-free when a lazy statement follows a failed query) +--EXTENSIONS-- +pdo_pgsql +--SKIPIF-- + +--CREDITS-- +Yun Dou +--FILE-- +setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + +try { + $pdo->query('SELECT 1 / 0'); +} catch (PDOException $e) { + echo $e->getCode(), PHP_EOL; +} + +$pdo->setAttribute(PDO::ATTR_PREFETCH, 0); +echo $pdo->query('SELECT 43')->fetchColumn(), PHP_EOL; +?> +--EXPECT-- +22012 +43