php / php-src

The PHP Interpreter
https://www.php.net
Other
38.09k stars 7.74k forks source link

Memory corruption if a fiber is resumed in shutdown handler after an exception #12529

Closed danog closed 11 months ago

danog commented 11 months ago

Description

There's an issue with fibers unrelated to JIT or opcache that causes memory corruption in certain cases if a fiber is resumed in the shutdown handler after an uncaught exception triggered execution of said shutdown handler.

This memory corruption usually manifests as impossible TypeErrors when returning from random functions.

I've been seeing a lot of reports including in the amphp chat (join https://t.me/+RO_PpIt0DDZhvPPs then https://t.me/c/1156566948/47988, https://t.me/c/1156566948/47730, https://t.me/c/1156566948/47048), and got the issue myself several times, but haven't managed to reliably reproduce yet.

The only way I found of sometimes reproducing the issue is running the test.php script from https://paste.daniil.it/jit_1.tar.xz (without JIT or opcache) and randomly hitting ctrl-c multiple times during the handshake, but still it's super hard to reproduce reliably...

The issue itself is triggered by MadelineProto's shutdown handler, which resumes the revoltphp event loop (with a bit of reflection trickery) and continues execution of all fibers currently in scope, also spawning some new ones: https://github.com/danog/MadelineProto/blob/v8/src/Shutdown.php#L55

PHP Version

8.2.12

Operating System

No response

danog commented 11 months ago

100% reliable reproducer: https://paste.daniil.it/ampRepro.tar.xz, repro.php script

danog commented 11 months ago

Turns out this is actually an issue with revolt, fixed in https://github.com/revoltphp/event-loop/pull/71 + https://github.com/revoltphp/event-loop/pull/88