Hi,

I have difficulties cleaning up dependent objects in the destructor and
free-storage handlers during the shutdown phases. It seems that there
is no control over the order of destruction in the shutdown phases,
even if I increment reference counter for the "parent" object.

In the case of my "event" extension, the problem looks like this:

$ cat script.php
<?php
$base = new EventBase();
$e = new Event($base, -1, Event::TIMEOUT, function($fd, $what, $e) {
        echo "0.4 seconds elapsed\n";
});
$e->data = $e;
$e->addTimer(0.4);
$base->loop();

$ MALLOC_PERTURB_=$(($RANDOM % 255 + 1)) \
    php -n -d extension=event.so -dextension_dir=./.libs script.php
0.4 seconds elapsed
php_event_base_dtor_obj
php_event_base_free_obj
php_event_event_dtor_obj
php_event_event_free_obj
Segmentation fault

The segmentation fault occurs when libevent's event_del tries to
acquire lock on the free'd event_base:

#1  0x00007fffee31f099 in event_del (ev=0x158c1a0) at event.c:2204
2204            EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);

In particular, it is clear that the problem is due to the fact that
`$e->data = $e` increments the reference counter for the Event object,
and the Event object is destroyed after EventBase. But how this
situation is supposed to be handled correctly? One naive approach is to
add EventBase's zval to Event's internal structure, and increment its
reference counter in the property write handler, if the variable (`$e`)
is an instance of this Event object, or an instance of any object
dependent from EventBase (this particular instance of EventBase).

Another example: 
https://gist.github.com/235c410bd908d6cf3acddddd0a5bf9f7

If the user doesn't destroy the array of EventHttpConnection objects:

$this->connections = null;

in the shutdown phase, EventBase gets destroyed before the conection
objects, and the user gets a segmentation fault similar when libevent
tries to acquire lock on the event_base as in the first example.

I feel I can not overcome this issue without the help of the
PECL team.

Regards.

-- 
Ruslan Osmanov

Attachment: pgpNcqkFOSb51.pgp
Description: OpenPGP digital signature

Reply via email to