SHM_PROTECT/SHM_UNPROTECT race in opcache under ZTS with multiple threads and protect_memory=1
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 4/5
- Tempo estimado
- 3-5 dias
- Facilidade para iniciantes
- 38/100
- Tipo de issue
- Bug
- Clareza
- Razoavelmente clara
- Status de atividade
- Pouca atividade
- Domínio
- backend, performance
Direção de pesquisa
Comece pelo par SHM_PROTECT/SHM_UNPROTECT em ZendAccelerator.c, nas linhas 2714–2778; depois, inspecione a janela do JIT em zend_jit_trace.c por volta da linha 7512 e o local do crash na linha 227. Reproduza com um build ZTS usando o script TrueAsync fornecido e as opções de tracing-JIT. Considera-se concluído quando o teste concorrente não atingir mais SIGSEGV e uma cobertura de regressão adequada tiver sido identificada.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Description
When multiple PHP threads run concurrently in the same process (ZTS build), opcache's SHM_PROTECT()/SHM_UNPROTECT() calls race with each other because mprotect() is process-global, but there is no coordination (refcounting) between threads.
I'm not 100% sure this is a bug vs. a known limitation. But the behavior is surprising and I wanted to report it for discussion.
What happens
SHM_PROTECT() calls mprotect(shm, PROT_READ) and SHM_UNPROTECT() calls mprotect(shm, PROT_READ|PROT_WRITE). These are process-wide — they affect all threads.
In ZEND_RINIT_FUNCTION(zend_accelerator) (ZendAccelerator.c, lines 2714–2778), every php_request_startup() executes an SHM_UNPROTECT() / SHM_PROTECT() pair. In a multi-threaded ZTS process, each thread calls php_request_startup() independently.
When tracing JIT is enabled and compiling a hot trace, it also holds SHM unprotected (zend_jit_trace.c, line 7512). If a second thread's RINIT calls SHM_PROTECT() while the first thread is still writing to SHM inside JIT compilation, the first thread gets SIGSEGV (write to read-only page).
Timeline:
Main thread Worker thread
─────────── ─────────────
zend_jit_compile_root_trace:
zend_shared_alloc_lock()
SHM_UNPROTECT() ← PROT_READ|WRITE
writing to zend_jit_traces[N]... php_request_startup():
... RINIT(accel):
... SHM_UNPROTECT() ← no-op
... ...checks restart_pending...
... SHM_PROTECT() ← mprotect(PROT_READ)
... done, returns
t->code_start = start → SIGSEGV
(page is now read-only)
The zend_shared_alloc_lock() serializes JIT compilation between threads, but it does NOT prevent RINIT's SHM_PROTECT() from running concurrently — RINIT doesn't acquire that lock for its SHM_UNPROTECT/PROTECT pair.
How to reproduce
Any ZTS setup with multiple threads running PHP code concurrently + opcache.protect_memory=1 + opcache.jit=tracing.
Minimal reproduction with TrueAsync threads (but should be reproducible with any ZTS threading extension — parallel, pmmpthread, etc.):
<?php
use Async\ThreadPool;
use function Async\spawn;
use function Async\await;
spawn(function() {
$pool = new ThreadPool(2);
$future = $pool->submit(fn() => 42);
echo await($future) . "\n";
$pool->close();
echo "Done\n";
});
Run with:
php -d opcache.enable_cli=1 \
-d opcache.jit=tracing \
-d opcache.jit_buffer_size=64M \
-d opcache.protect_memory=1 \
-d opcache.jit_hot_loop=1 \
-d opcache.jit_hot_func=1 \
test.php
Result: correct output 42\nDone followed by SIGSEGV in zend_jit_trace_add_code (zend_jit_trace.c:227).
The crash does NOT happen with:
opcache.protect_memory=0(default) —mprotectis never called, no raceopcache.jit=function— functions are compiled before threads start, no runtime compilation during concurrent execution
Notes
- The
krakjoe/parallelextension has the same architecture (callsphp_request_startup()per thread) and avoids this by only testing withopcache.jit=functionoropcache.jit=disablein CI. Their ASAN+JIT job explicitly uses-d opcache.jit=function. run-tests.phphardcodesopcache.protect_memory=1(line 300), so any multi-threaded test suite usingrun-tests.phpwith tracing JIT will hit this.- The underlying issue is that
mprotect()is process-global butSHM_UNPROTECT/PROTECTpairs are not coordinated across threads — there is no refcount to prevent one thread'sPROTECTfrom overriding another thread's activeUNPROTECTwindow.
PHP Version
PHP 8.6.0-dev (cli) (ZTS DEBUG)
Zend Engine v4.6.0-dev
with Zend OPcache v8.6.0-dev
Operating System
Ubuntu 24.04 (Linux 6.17)
- Linguagem predominante
- C
- Estrelas
- 40.4k
- Forks
- 8.2k
- Merge médio
- 2d 15h
- PRs com merge (30d)
- 103
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de php/php-src
-
Bug SAPI: cli_server Status: Verified
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
-
Bug Status: Needs Triage
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
-
Bug Status: Needs Triage
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 90/100
-
Bug Status: Needs Triage
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
-
Flaky hrtime.phpt test AbertaBug Category: Tests Status: Verified
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
Todas as issues de php/php-src
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
zephyrproject-rtos/zephyr#119726 ·
-
[Bounty proposal] fix(web): memory insights count an evening memory on the next day ($25 proposed) Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 84/100
BasedHardware/omi#15320 ·
-
[adam] AdamNet network read doesn't cap to MAX_ADAM_PACKET_LEN, overflows client receive buffers Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
FujiNetWIFI/fujinet-firmware#1649 · 2 comentários ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
HarbourMasters/Shipwright#7229 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
riscv-software-src/riscv-isa-sim#2435 · 1 comentário ·