Skip to content

fix: remove orphan ADDREF which causes resource leaks (#118)#119

Open
sj-i wants to merge 1 commit into
amphp:0.3.xfrom
sj-i:fix-fd-leak
Open

fix: remove orphan ADDREF which causes resource leaks (#118)#119
sj-i wants to merge 1 commit into
amphp:0.3.xfrom
sj-i:fix-fd-leak

Conversation

@sj-i
Copy link
Copy Markdown

@sj-i sj-i commented May 14, 2026

Resolves #118

First use of PHP_UV_ZVAL_TO_FD() after PHP_UV_FS_SETUP() already adds the refcount, and there are no matching DECREF for those explicit ADDREFs. So those extra additions cause resource leaks.

Note: This leak is hiding another bug. In other words, fixing only the leak exposes a double-close race. Call to PHP_UV_FD_TO_ZVAL() in uv_fs_open() wraps the fd in a php_stream via php_stream_fopen_from_fd(). The stream owns that fd: when the resource hits refcount 0, the stream destructor calls close(fd). But uv_fs_close() also closes the same fd via libuv. The libuv close happens promptly (async, completes before the cb returns to the script). The stream destructor's close happens later, when the PHP-side resource finally drops to refcount 0.

The extra refcount removed by this PR has been preventing that the refcount actually drops to 0, so the double-close bug has been fortunately(?) hidden. The double-close bug is fixed in this PR too.

The following issues should be fixed by this PR.
amphp/file#88
reactphp/filesystem#120

@sj-i sj-i force-pushed the fix-fd-leak branch 2 times, most recently from b2b4f48 to aaee94c Compare May 14, 2026 20:21
First use of PHP_UV_ZVAL_TO_FD already adds the refcount, and there are no matching DECREF for those explicit ADDREFs. So those extra additions cause resource leaks.

Note: This leak is hiding another bug. In other words, fixing only the leak exposes a double-close race.
Call to PHP_UV_FD_TO_ZVAL() in uv_fs_open() wraps the fd in a php_stream via php_stream_fopen_from_fd(). The stream owns that fd: when the resource
hits refcount 0, the stream destructor calls close(fd).
But uv_fs_close() also closes the same fd via libuv. The libuv close happens promptly (async, completes before the cb returns to the script). The stream destructor's close happens later, when the PHP-side resource finally drops to refcount 0.

The extra refcount removed by this commit has been preventing that the refcount actually drops to 0, so the double-close bug has been fortunately(?) hidden. The double-close bug is fixed in this commit too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Resource refcount leak in uv_fs_* (with a hidden uv_fs_close vs php_stream destructor race)

1 participant