Skip to content

Method call may leak if releasing EG(This) triggers GC #13687

Open

Description

@arnaud-lb

Description

Method calls may cause their return value to leak if releasing EG(This) triggers GC.

The following code:

<?php

class A {
    public $cycle;
    public function __construct() { $this->cycle = $this; }
}
class B {
    public function get() {
        return new A();
    }
}

$c = new B();
$objs = [];

while (gc_status()['roots']+2 < gc_status()['threshold']) {
    $obj = new stdClass;
    $objs[] = $obj;
}

var_dump($c->get());

Resulted in a memory leak:

Script:  'test.php'
Zend/zend_objects.c(189) :  Freeing 0x00007ffff7a5c840 (56 bytes), script=test.php
=== Total 1 memory leaks detected ===

Here is what is happening:

  • After returning from get(), $c is released, which triggers GC
    • A is removed from buffer, and is not collected because it's referenced by the call stack
  • After returning from var_dump(), zend_vm_stack_free_args() releases A with zval_ptr_dtor_nogc(), so A is not added to the GC buffer
  • At this point nothing references A but itself, and A is not in the GC buffer, so it leaks

I'm not sure how to fix this appart from switching to zval_ptr_dtor().

PHP Version

master

Operating System

No response

Activity

  1. krakjoe commented on Sep 10, 2025

    @krakjoe
    Member

    Can you elaborate on what the side effects or consequences (beyond the obvious perf difference) might be which stopped you proposing the switch ?

    Can we also get some more input from @iluuu1994 and perhaps @dstogov ?

    (note, I didn't add the auto-closing category on purpose, I don't intend to end the conversation, this looks like it needs to be addressed)

  2. arnaud-lb commented on Sep 10, 2025

    @arnaud-lb
    MemberAuthor

    After thinking about it, I don't believe that switching to zval_ptr_dtor() is the right solution.

    The issue is more general, as it may happen for any opcode that produces a TMPVAR and may trigger GC. For example, this also leaks:

    class A {
        public $cycle;
        public function __construct() { $this->cycle = $this; }
        public function __toString() { return __CLASS__; }
    }
    class B {
        public function get() {
            return new A();
        }
    }
    
    $root = new stdClass;
    gc_collect_cycles();
    
    $objs = [];
    while (gc_status()['roots']+2 < gc_status()['threshold']) {
        $obj = new stdClass;
        $objs[] = $obj;
    }
    
    // In FETCH_DIM_R: 
    // - Copy A to result operand
    // - Dtor tmp array, which dtors A and $root, which triggers GC
    // - GC roots are empty, A is still live
    // In FETCH_CLASS_NAME:
    // - zval_ptr_dtor_nogc(A)
    $a = [new A, $root][0]::class;

    In the GC, zend_gc_check_root_tmpvars() is meant to handle this kind of situations, but only when there is a live range for the TMPVAR. Here there is no live range as the TMPVAR is consumed by the next opcode.

    A possible fix is to treat EX(opline)->result as live in zend_gc_check_root_tmpvars(), like we do in ZEND_HANDLE_EXCEPTION:

    php-src/Zend/zend_vm_def.h

    Lines 8089 to 8104 in 94a12d5

    if (throw_op->result_type & (IS_VAR | IS_TMP_VAR)) {
    switch (throw_op->opcode) {
    case ZEND_ADD_ARRAY_ELEMENT:
    case ZEND_ADD_ARRAY_UNPACK:
    case ZEND_ROPE_INIT:
    case ZEND_ROPE_ADD:
    break; /* exception while building structures, live range handling will free those */
    case ZEND_FETCH_CLASS:
    case ZEND_DECLARE_ANON_CLASS:
    break; /* return value is zend_class_entry pointer */
    default:
    /* smart branch opcodes may not initialize result */
    if (!zend_is_smart_branch(throw_op)) {
    zval_ptr_dtor_nogc(EX_VAR(throw_op->result.var));

    I've implemented this solution here: #19787, but I think it's unsafe as-is, since in theory the result operand may not be initialized yet when the GC is triggered. It's safe in ZEND_HANDLE_EXCEPTION because the handler of throw_op has returned at this point.

    To make it safe we may need to delay GC until a safe point: gc_check_possible_root() should set vm_interrupt and a new needs_gc flag. We can then trigger GC from the interrupt handler. This would be a good thing regardless of this issue IMHO.

  3. iluuu1994 commented on Sep 10, 2025

    @iluuu1994
    Member

    gc_check_possible_root() should set vm_interrupt and a new needs_gc flag. We can then trigger GC from the interrupt handler. This would be a good thing regardless of this issue IMHO.

    Agreed. Doesn't this approach solve the issue all on its own? If the problem is the order of zval_ptr_dtor() -> GC -> zval_ptr_dtor_nogc() from the VM, doesn't changing the order to zval_ptr_dtor() -> zval_ptr_dtor_nogc() -> GC already prevent the value being removed from the GC root, hence being considered for the GC run again?

  4. arnaud-lb commented on Sep 10, 2025

    @arnaud-lb
    MemberAuthor

    Not necessarily, as the interrupt may be handled just after the opcode handler that produced the TMPVAR, and just before the one that will consume it. That will be the case for DO_FCALL for instance.

  5. iluuu1994 commented on Sep 10, 2025

    @iluuu1994
    Member

    Right. These two approaches combined make sense to me then! We might have to account for the GC buffer growing over the limit while we're waiting for the interrupt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions