mirror of
https://github.com/php/php-src.git
synced 2024-11-24 02:15:04 +08:00
bc558bf7a3
Although the issue was demonstrated using Curl, the issue is purely in the streams layer of PHP. Full analysis is written in GH-11078 [1], but here is the brief version: Here's what actually happens: 1) We're creating a FILE handle from a stream using the casting mechanism. This will create a cookie-based FILE handle using funopen. 2) We're reading stream data using fread from the userspace stream. This will temporarily set a buffer into a field _bf.base [2]. This buffer is now equal to the upload buffer that Curl allocated and note that that buffer is owned by Curl. 3) The fatal error occurs and we bail out from the fread function, notice how the reset code is never executed and so the buffer will still point to Curl's upload buffer instead of FILE's own buffer [3]. 4) The resources are destroyed, this includes our opened stream and because the FILE handle is cached, it gets destroyed as well. In fact, the stream code calls through fclose on purpose in this case. 5) The fclose code frees the _bs.base buffer [4]. However, this is not the buffer that FILE owns but the one that Curl owns because it isn't reset properly due to the bailout! 6) The objects are getting destroyed, and so the curl free logic is invoked. When Curl tries to gracefully clean up, it tries to free the buffer. But that buffer is actually already freed mistakingly by the C library! This also explains why we can't reproduce it on Linux: this bizarre buffer swapping only happens on macOS and BSD, not on Linux. To solve this, we switch to an unbuffered mode for cookie-based FILEs. This avoids any stateful problems related to buffers especially when the bailout mechanism triggers. As streams have their own buffering mechanism, I don't expect this to impact performance. [1] https://github.com/php/php-src/issues/11078#issuecomment-2155616843 [2] |
||
---|---|---|
.. | ||
streams | ||
build-defs.h.in | ||
explicit_bzero.c | ||
fastcgi.c | ||
fastcgi.h | ||
fopen_wrappers.c | ||
fopen_wrappers.h | ||
getopt.c | ||
http_status_codes.h | ||
internal_functions_win32.c | ||
internal_functions.c.in | ||
main.c | ||
network.c | ||
output.c | ||
php_compat.h | ||
php_content_types.c | ||
php_content_types.h | ||
php_getopt.h | ||
php_globals.h | ||
php_ini_builder.c | ||
php_ini_builder.h | ||
php_ini.c | ||
php_ini.h | ||
php_main.h | ||
php_memory_streams.h | ||
php_network.h | ||
php_odbc_utils.c | ||
php_odbc_utils.h | ||
php_open_temporary_file.c | ||
php_open_temporary_file.h | ||
php_output.h | ||
php_reentrancy.h | ||
php_scandir.c | ||
php_scandir.h | ||
php_streams.h | ||
php_syslog.c | ||
php_syslog.h | ||
php_ticks.c | ||
php_ticks.h | ||
php_variables.c | ||
php_variables.h | ||
php_version.h | ||
php.h | ||
reentrancy.c | ||
rfc1867.c | ||
rfc1867.h | ||
safe_bcmp.c | ||
SAPI.c | ||
SAPI.h | ||
snprintf.c | ||
snprintf.h | ||
spprintf.c | ||
spprintf.h | ||
strlcat.c | ||
strlcpy.c |