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

Exception thrown in destructor during shutdown causes memory leak

Open arnaud-lb opened this issue 6 months ago • 1 comments

Description

The following code:

class A {
    function __destruct() {
        throw new Exception();
    }
}

$a = new A;

Resulted in this output:

==1812075==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 40 byte(s) in 1 object(s) allocated from:
    #0 0x0000004a8818 in malloc (sapi/cli/php+0x4a8818) (BuildId: e414f1239350aba6564003d39b1933a7981c13a3)
    #1 0x000002dec753 in __zend_malloc Zend/zend_alloc.c:3543:14
    #2 0x000002debde6 in _emalloc Zend/zend_alloc.c:2778:10
    #3 0x000003fa7786 in zend_objects_new Zend/zend_objects.c:190:24
    #4 0x000002e25dc3 in _object_and_properties_init Zend/zend_API.c:1819:22
    #5 0x000002e264b0 in object_init_ex Zend/zend_API.c:1842:9
    #6 0x00000389e125 in ZEND_NEW_SPEC_CONST_UNUSED_TAILCALL_HANDLER Zend/zend_vm_execute.h:63944:17
    #7 0x00000311dfb8 in execute_ex Zend/zend_vm_execute.h:110168:12
    #8 0x00000311f2bb in zend_execute Zend/zend_vm_execute.h:115586:2
    #9 0x0000040c16cf in zend_execute_script Zend/zend.c:1971:3
    #10 0x00000285c6d4 in php_execute_script_ex main/main.c:2646:13
    #11 0x00000285d088 in php_execute_script main/main.c:2686:9
    #12 0x0000040cdd00 in do_cli sapi/cli/php_cli.c:947:5
    #13 0x0000040cabd8 in main sapi/cli/php_cli.c:1370:18

Impact is likely low, since the heap is going to be freed at this point.

Found while investigating https://github.com/php/php-src/issues/21999.

PHP Version

master (c417deaf0f6e0a44da2315dd631b2f918a295782)

Operating System

No response

arnaud-lb avatar May 11 '26 12:05 arnaud-lb

Hi, while testing session shutdown behavior on 8.5.13 (46bcb661d) I noticed a related re-entry that the current guards do not cover: a user save handler whose close() calls session_write_close() recurses close -> write_close -> flush -> s_close -> close indefinitely. The write side is guarded, but s_close is not. The 8.3 call stack limit eventually terminates it (observed more than 75,000 recursive frames, with CPU and memory burn until then), so it is a resource exhaustion issue rather than a crash. Given the history of incomplete fixes in this area, the missing s_close re-entry guard may be worth covering by the same change.

Minimal repro (user save handler):

public function close(): bool {
    session_write_close();  // re-enters close() forever
    return true;
}

Hope this is useful.

lhjnano avatar Nov 20 '26 06:11 lhjnano