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

`eval` is leaking memory

Open mvorisek opened this issue 4 years ago • 5 comments

Description

The following code:

<?php

$m = memory_get_usage();
for ($i = 0; $i < 1000; $i++) {
    $fn = eval('return function ($foo) {};');
    //$fn = function ($foo) {};
    var_dump(memory_get_usage() - $m);
}

https://3v4l.org/LF4Ri https://3v4l.org/1DeC6 - /wo eval, not leaking https://3v4l.org/NtIrU - eval /wo anonymous function is not leaking

Resulted in this output:

int(640)
int(672)
int(672)
int(672)
...
int(197280)

But I expected this output instead:

int(640)
int(672)
int(672)
int(672)
...
int(672)

PHP Version

8.1.x

Operating System

any

mvorisek avatar Feb 11 '22 10:02 mvorisek

This is by design - for now at least. This is not specific to eval, but to any non-top level op_array (i.e. all functions).

Generally, code, once compiled - unless it is top level code - is persisted for the request.

For example, this also leaks:

php -r 'for ($i = 0; $i < 5; ++$i) { var_dump(memory_get_usage()); include "a.php"; }'
int(430072)
int(430888)
int(431256)
int(431624)
int(431992)

with a.php being:

<?php

if (false) {
	class A {
	}
}

But we do currently not have any mechanisms to track unresolved (or Closure) op_arrays (and classes) by their parent op_array to free them on destruction (in this case, triggered by: eval or inclusion returning).

bwoebi avatar Feb 11 '22 12:02 bwoebi

@bwoebi As of PHP 8.1 we do actually. We track these via dynamic_func_defs and release them once unused. The only reason there is still a small leak here, is that the op_array structure itself is still arena-allocated.

Edit: This doesn't apply to classes -- classes are much harder to fix due to preloading, which makes everything very complicated.

nikic avatar Feb 11 '22 21:02 nikic

is the freeing of the arena-allocated op_array structure for the closure easily fixable?

mvorisek avatar Feb 14 '22 17:02 mvorisek

is the freeing of the arena-allocated op_array structure for the closure easily fixable?

Arena allocations are similar to SQL transactions with checkpoints. You can destroy the whole arena or roll back to a certain checkpoint, but you can't free certain parts of the arena. So I don't think this is (easily) fixable.

cmb69 avatar Feb 17 '22 15:02 cmb69

It requires moving away from arena allocation. I believe it's not entirely simple because we have two different ways to share op_arrays, one of them sharing only the resources it points to while having a separately allocated op_array structure, and another where the op_array itself is also shared. This makes it a bit tricky to determine whether or not an op_array needs to be freed when it is released, or only the refcount decremented.

nikic avatar Feb 17 '22 22:02 nikic