php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Memory leak in Fiber when calling __construct()

Open TimWolla opened this issue 4 years ago • 3 comments

Description

When running the following code:

<?php

$fiber = new Fiber(function (): void {
   $value = Fiber::suspend('fiber');
   echo "Value used to resume fiber: ", $value, PHP_EOL;
});

$value = $fiber->start();

echo "Value from fiber suspending: ", $value, PHP_EOL;

$fiber->__construct(function (): void {
	echo "Bar";
	$value = Fiber::suspend('new');
	echo "Changed: ", $value, PHP_EOL;
});

$fiber->resume('test');

PHP will report a memory leak ("Total 1 memory leaks detected"):

==272678== Memcheck, a memory error detector
==272678== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==272678== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==272678== Command: sapi/cli/php test2.php
==272678== 
Value from fiber suspending: fiber
Value used to resume fiber: test
[Wed Apr 13 20:21:13 2022]  Script:  'php-src/test2.php'
php-src/Zend/zend_closures.c(505) :  Freeing 0x000000000506a480 (328 bytes), script=php-src/test2.php
=== Total 1 memory leaks detected ===
==272678== 
==272678== HEAP SUMMARY:
==272678==     in use at exit: 0 bytes in 0 blocks
==272678==   total heap usage: 14,370 allocs, 14,370 frees, 2,140,328 bytes allocated
==272678== 
==272678== All heap blocks were freed -- no leaks are possible
==272678== 
==272678== For lists of detected and suppressed errors, rerun with: -s
==272678== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

PHP Version

PHP 8.2.0-dev (commit 8233e061091bc442009529d49e4718ea15454e57)

Operating System

Ubuntu 20.04

TimWolla avatar Apr 13 '22 18:04 TimWolla

Apparently the issue is: https://github.com/php/php-src/blob/ec0771c03fb90674f677e3c11a19d2d4cc4080cb/Zend/zend_fibers.c#L653-L654

If fiber->fci is changed, the old fiber->fci.function_name would need to be deref'ed.

Regarding the leak checking in general: if you run with valgrind, always set USE_ZEND_ALLOC=0; otherwise valgrind will not detect any leaks, and the leak detection by the ZendMM isn't that helpful in finding where the leak occurred.

cmb69 avatar Apr 14 '22 12:04 cmb69

The reference to the running fiber function should not be removed while the fiber is running.

A subsequent call to the constructor should throw or do nothing. My vote would be throw.

trowski avatar Apr 14 '22 17:04 trowski

Closed via #9098.

trowski avatar Jul 22 '22 15:07 trowski