[php-src] Issue #10885: Memory allocated by stream_context_create not released
| From: | lucasnetau | Date: | Mon, 20 Mar 2023 05:50:41 +0000 |
| Subject: | [php-src] Issue #10885: Memory allocated by stream_context_create not released | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-243935@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/10885
Author: lucasnetau
### Description
I have a long running PHP application that is creating stream_socket_server over time, the memory
allocated by stream_context_create() is never released even after closing and destroying the
stream_socket_server. A minimal reproduction is below (backlog is set to allocate more memory on
each loop however even an empty array to stream_context_create shows this issue). Eventually the
application will crash, this is more evident in memory constrained environments like container
deployments.
I found an old PHP bugs report referencing this with stream_socket_client
(https://bugs.php.net/bug.php?id=61371) `inhibition
for deleting the context was too broad` and a really old one that says that
stream_context_create() memory is never released https://bugs.php.net/bug.php?id=40257 but this is
not documented.
Output from memprof shows the allocated memory from stream_context_create()
<img width="487" alt="image" src="https://user-images.githubusercontent.com/9331242/226255347-0a3b4ac6-f2c5-49b7-a52f-ba76285ae523.png">
```php
<?php
$m0 = memory_get_usage(true);
for ($i=0;$i<50000;++$i){
$context = stream_context_create(['socket'=>['backlog'=>511]]);
$server = @\stream_socket_server(
'tcp://127.0.0.1:0',
$errno,
$errstr,
\STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN,
$context,
);
fclose($server);
unset($server);
unset($context);
unset($errno);
unset($errstr);
}
$m1 = memory_get_usage(true);
echo ($m1-$m0)/1048576,' MB allocated',PHP_EOL;
$cycles = \gc_collect_cycles() + gc_collect_cycles();
echo 'Ran ', $cycles, ' GC Cycles', PHP_EOL;
```
Resulted in this output:
```
46.00390625 MB allocated
Ran 0 GC Cycles
```
But I expected this output instead:
```
0 MB allocated
Ran 0 GC Cycles
```
### PHP Version
PHP 8.0.28 - PHP 8.2.4
### Operating System
_No response_