OPcache on Windows: a process attaching to freshly created shared memory can read an unset `ZSMMG(app_shared_globals)` and crash in `accel_post_startup()`

Aberta
#25,471 0 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
5/5
Tempo estimado
Mais de uma semana
Facilidade para iniciantes
25/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
c
Domínio
performance

Direção de pesquisa

Start with create_segments() in ext/opcache/shared_alloc_win32.c, which returns ALLOC_SUCCESS after releasing the mapping mutex, then read zend_shared_alloc_startup() in ext/opcache/zend_shared_alloc.c where the zend_smm_shared_globals block is filled, and finally accel_post_startup() in ext/opcache/ZendAccelerator.c where ZSMMG(app_shared_globals) is read. Reproduce with the PowerShell script against official Windows builds (groups of 8, thousands of rounds). Done means the JIT buffer and shared globals are initialized before any attacher can proceed, with zero 0xC0000005 exits.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

Description

On Windows, php-cgi.exe (and php.exe with opcache.enable_cli=1) occasionally crashes during startup with
0xC0000005 in php_opcache.dll, before any script runs. It happens when several processes of the same
installation start at nearly the same time while no other process holds the OPcache mapping, so that one
process creates the mapping and the others attach to it. NTS and ZTS builds are both affected. No other
extension is needed. Linux is not affected, because no backend there attaches to another process's segment.

Analysis (php-8.4.27 sources)

Creating process:

  1. create_segments() (ext/opcache/shared_alloc_win32.c) takes the mapping mutex, creates and maps the
    section, stores the base address in the first bytes of the mapping, and releases the mutex
    (zend_shared_alloc_unlock_win32(), line 332) before it returns ALLOC_SUCCESS.
  2. zend_shared_alloc_startup() (ext/opcache/zend_shared_alloc.c) continues without holding the mutex:
    it allocates the zend_smm_shared_globals block in the segment, zeroes it, and then copies the stack
    variable tmp_shared_globals (line 186) into it (*p_tmp_shared_globals = tmp_shared_globals;, line 288).
    tmp_shared_globals is not zero-initialized, and app_shared_globals is never assigned in it, so the
    field gets whatever was on the creator's stack.
  3. Only later, zend_accel_init_shm() sets ZSMMG(app_shared_globals) = accel_shared_globals;
    (ext/opcache/ZendAccelerator.c, line 2903).

Attaching process:

  1. create_segments() finds the mapping (OpenFileMapping), zend_shared_alloc_reattach() maps it and sets
    smm_shared_globals to the block from step 2 (line 199), and returns SUCCESSFULLY_REATTACHED.
  2. accel_post_startup() takes the lock, reads accel_shared_globals = ZSMMG(app_shared_globals);
    (line 3283), releases it, and right after the switch executes
    ZCG(last_restart_time) = ZCSG(last_restart_time); (line 3309).

If step 5 runs between steps 1 and 3, the attacher gets either NULL (before the copy in step 2) or the
creator's stale stack content (after it). The lock in step 5 does not help, because the creator does not hold
it between steps 1 and 3.

The same code is present on master (shared_alloc_win32.c:330, ZendAccelerator.c:3153, 3564, 3588).

Evidence from crash dumps

168 minidumps from runs without any other zend_extension (46 regular extensions loaded; 114 of the dumps are from
the official NTS and ZTS builds, the rest from a custom NTS build of the same version), all with this pattern:

  • NULL case: NTS php_opcache.dll+0x84222, ZTS php_opcache.dll+0x8bde8. Both are
    mov rax, [accel_shared_globals] / mov rcx, [rax+0x68], AV reading address 0x68. 0x68 is
    offsetof(zend_accel_shared_globals, last_restart_time) on x64. A few instructions earlier, the global is
    loaded from [smm_shared_globals]+0x38 = offsetof(zend_smm_shared_globals, app_shared_globals), followed by
    the zend_interned_strings_set_request_storage_handlers() call and the mutex release, as in the source.
  • Stale case (NTS only in our runs): accel_shared_globals holds a return address inside php8.dll, the same
    value in every dump of a build (official NTS: php8.dll+0x3a452f in all 26 dumps). The read at +0x68
    succeeds (readable code page), and the process crashes a little later in a hash lookup through that pointer
    (php_opcache.dll+0x84629). In the ZTS build the corresponding stack
    slot happened to be 0, so all ZTS dumps show the NULL case.

Reproducer

Official windows.php.net builds, php-cgi.exe -n with only
-d zend_extension=<dir>\ext\php_opcache.dll -d opcache.enable=1 -d opcache.cache_id=<unique>, test script
<?php echo "ok";. The script below creates 8 processes with CREATE_SUSPENDED and resumes them back to back
(a few microseconds apart), waits for all of them, and repeats. Each round therefore creates the mapping anew.

powershell -NoProfile -ExecutionPolicy Bypass -File opcache-win-shm-race-repro.ps1 -PhpDir C:\php -Rounds 2000 -Group 8

Result: some processes exit with -1073741819 (0xC0000005), the others print ok:

Build Starts Crashes
8.4.27 NTS x64 (php-8.4.27-nts-Win32-vs17-x64) 20,000 7 (0.04 %)
8.4.27 ZTS x64 (php-8.4.27-Win32-vs17-x64) 20,000 23 (0.12 %)

(2,500 rounds of 8 in two runs. NTS crashed at php_opcache.dll+0x84222 and +0x84629, ZTS at +0x8bde8.)

With a larger extension set (46 extensions, so a longer startup) the rate was higher, about 0.2 % of starts, and
the same for NTS and ZTS: 27 / 12,000 (NTS) and 25 / 12,000 (ZTS) in groups of 8. When the same processes were
started sequentially with ordinary CreateProcess calls (about 2.3 ms apart), 30,000 starts did not crash.
The window is short and needs nearly simultaneous starts.

opcache-win-shm-race-repro.ps1
<#
Reproducer: OPcache on Windows, a process that attaches to freshly created shared memory can read
ZSMMG(app_shared_globals) before the creating process has set it and crashes in accel_post_startup().

Each round starts -Group php-cgi.exe processes CREATE_SUSPENDED and resumes them together (a few us apart),
so one process creates the OPcache mapping while the others attach to it. Only Zend OPcache is loaded
(php-cgi -n -d ...). Crash = exit code 0xC0000005 (-1073741819).

Usage: powershell -NoProfile -ExecutionPolicy Bypass -File opcache-win-shm-race-repro.ps1 -PhpDir C:\php [-Rounds 500] [-Group 8]
#>
param(
    [Parameter(Mandatory = $true)][string]$PhpDir,
    [int]$Rounds = 500,
    [int]$Group = 8
)
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:TEMP 'opcache-race'
New-Item -ItemType Directory $work -Force | Out-Null
$script = Join-Path $work 'test.php'
Set-Content $script -Value '<?php echo "ok";' -Encoding ASCII
$cgi = Join-Path $PhpDir 'php-cgi.exe'
$cgiArgs = '-n -d "zend_extension={0}" -d opcache.enable=1 -d opcache.cache_id=race{1}' -f (Join-Path $PhpDir 'ext\php_opcache.dll'), $PID

Add-Type -TypeDefinition @'
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
public static class Race {
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct STARTUPINFO {
        public int cb; public string lpReserved; public string lpDesktop; public string lpTitle;
        public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
        public short wShowWindow, cbReserved2; public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
    }
    [StructLayout(LayoutKind.Sequential)]
    struct PROCESS_INFORMATION { public IntPtr hProcess, hThread; public int dwProcessId, dwThreadId; }
    [StructLayout(LayoutKind.Sequential)]
    struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; }
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern bool CreateProcessW(string app, StringBuilder cmd, IntPtr pa, IntPtr ta, bool inherit, uint flags,
        IntPtr env, string dir, ref STARTUPINFO si, out PROCESS_INFORMATION pi);
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern IntPtr CreateFileW(string name, uint access, uint share, ref SECURITY_ATTRIBUTES sa, uint disp, uint flags, IntPtr tmpl);
    [DllImport("kernel32.dll")] static extern uint ResumeThread(IntPtr h);
    [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr h, uint ms);
    [DllImport("kernel32.dll")] static extern bool GetExitCodeProcess(IntPtr h, out uint code);
    [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);

    public static Dictionary<int, int> Run(string exe, string args, string dir, string script, int rounds, int group) {
        var d = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        foreach (DictionaryEntry e in Environment.GetEnvironmentVariables()) d[(string)e.Key] = (string)e.Value;
        d["REDIRECT_STATUS"] = "1"; d["REQUEST_METHOD"] = "GET"; d["GATEWAY_INTERFACE"] = "CGI/1.1"; d["SCRIPT_FILENAME"] = script;
        var eb = new StringBuilder();
        foreach (var kv in d) eb.Append(kv.Key).Append('=').Append(kv.Value).Append('\0');
        eb.Append('\0');
        IntPtr env = Marshal.StringToHGlobalUni(eb.ToString());
        var sa = new SECURITY_ATTRIBUTES(); sa.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); sa.bInheritHandle = true;
        IntPtr nul = CreateFileW("NUL", 0xC0000000, 3, ref sa, 3, 0, IntPtr.Zero);
        var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(typeof(STARTUPINFO));
        si.dwFlags = 0x100; si.hStdInput = nul; si.hStdOutput = nul; si.hStdError = nul;
        const uint flags = 0x4 | 0x400 | 0x08000000; // CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW
        var pi = new PROCESS_INFORMATION[group];
        var codes = new Dictionary<int, int>();
        for (int i = 0; i < rounds; i++) {
            for (int j = 0; j < group; j++) {
                var cmd = new StringBuilder("\"" + exe + "\" " + args);
                if (!CreateProcessW(null, cmd, IntPtr.Zero, IntPtr.Zero, true, flags, env, dir, ref si, out pi[j]))
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateProcess");
            }
            for (int j = 0; j < group; j++) ResumeThread(pi[j].hThread);
            for (int j = 0; j < group; j++) {
                uint c;
                WaitForSingleObject(pi[j].hProcess, 0xFFFFFFFF);
                GetExitCodeProcess(pi[j].hProcess, out c);
                int k = unchecked((int)c);
                int n; codes.TryGetValue(k, out n); codes[k] = n + 1;
                CloseHandle(pi[j].hThread); CloseHandle(pi[j].hProcess);
            }
        }
        CloseHandle(nul); Marshal.FreeHGlobal(env);
        return codes;
    }
}
'@

if (Get-Process php-cgi -ErrorAction SilentlyContinue) { Write-Warning 'other php-cgi processes are running; they may keep the mapping alive' }
$check = & $cgi -n -d "zend_extension=$(Join-Path $PhpDir 'ext\php_opcache.dll')" -v 2>&1 | Out-String
Write-Host ($check.Trim() -split "`r?`n" | Select-Object -First 1)
if ($check -notmatch 'Zend OPcache') { throw 'OPcache not loaded' }
$t = Get-Date
$codes = [Race]::Run($cgi, $cgiArgs, $work, $script, $Rounds, $Group)
$total = 0; $crash = 0
foreach ($k in $codes.Keys) { $total += $codes[$k]; if ($k -ne 0) { $crash += $codes[$k] } }
Write-Host ('{0} rounds x {1} processes = {2} starts in {3:0} s' -f $Rounds, $Group, $total, ((Get-Date) - $t).TotalSeconds)
foreach ($k in ($codes.Keys | Sort-Object)) { Write-Host ('  exit {0} (0x{1:X8}): {2}' -f $k, $k, $codes[$k]) }
Write-Host ('crashed: {0} of {1} ({2:0.00} %)' -f $crash, $total, (100.0 * $crash / [math]::Max(1, $total)))

Real-world impact

FastCGI process managers that let all php-cgi processes exit when idle and then spawn several at once
(mod_fcgid with FcgidMinProcessesPerClass 0, IIS FastCGI) hit this as sporadic HTTP 500 errors. Scheduled CLI
jobs that start together with opcache.enable_cli=1 can hit it too. These reports may be related:
#7915 (concurrent CLI processes, crash in accel_new_interned_strings), #12010, #11549.

Proposed fix (tested)

The process that creates the segment keeps the mapping mutex until the shared memory is fully initialized,
including the JIT buffer: create_segments() returns ALLOC_SUCCESS with the mutex still locked, and
accel_post_startup() releases it via a new helper zend_shared_alloc_startup_done() after the JIT startup and
zend_shared_alloc_save_state(). Releasing it right after zend_accel_init_shm() (our first attempt) is not
enough: an attacher can then run zend_jit_startup(..., reattached=true) before the creator has initialized the
JIT buffer and crashes in dasm_encode. The Win32 mutex is recursive, so the locks taken inside the
initialization still work. tmp_shared_globals is zero-initialized as well (could be a separate commit). The diff below is shown against the 8.4.27 sources; the pull request targets PHP-8.5 (the same change applies cleanly to PHP-8.6 and master):

diff --git a/ext/opcache/ZendAccelerator.c b/ext/opcache/ZendAccelerator.c
--- a/ext/opcache/ZendAccelerator.c
+++ b/ext/opcache/ZendAccelerator.c
@@ -3288,6 +3288,7 @@
 #endif
 			case ALLOC_SUCCESS:
 				if (zend_accel_init_shm() == FAILURE) {
+					zend_shared_alloc_startup_done();
 					accel_startup_ok = false;
 					return FAILURE;
 				}
@@ -3346,6 +3347,10 @@
 		zend_shared_alloc_save_state();
 		zend_shared_alloc_unlock();
 
+		/* A newly created segment, including the JIT buffer, is fully initialized now:
+		 * let other processes attach to it */
+		zend_shared_alloc_startup_done();
+
 		SHM_PROTECT();
 	} else if (!ZCG(accel_directives).file_cache) {
 		accel_startup_ok = false;
diff --git a/ext/opcache/shared_alloc_win32.c b/ext/opcache/shared_alloc_win32.c
--- a/ext/opcache/shared_alloc_win32.c
+++ b/ext/opcache/shared_alloc_win32.c
@@ -40,6 +40,8 @@
 #define ACCEL_BASE_POINTER_SIZE (2 * sizeof(void*))
 
 static HANDLE memfile = NULL, memory_mutex = NULL;
+/* create_segments() created a new segment and still holds memory_mutex for its initialization */
+static bool startup_lock_held = false;
 static void *mapping_base;
 
 #define MAX_MAP_RETRIES 25
@@ -114,6 +116,14 @@
 	ReleaseMutex(memory_mutex);
 }
 
+void zend_shared_alloc_win32_startup_done(void)
+{
+	if (startup_lock_held) {
+		startup_lock_held = false;
+		zend_shared_alloc_unlock_win32();
+	}
+}
+
 static int zend_shared_alloc_reattach(size_t requested_size, const char **error_in)
 {
 	int err;
@@ -329,7 +339,9 @@
 	shared_segment->pos = ACCEL_BASE_POINTER_SIZE;
 	shared_segment->size = requested_size;
 
-	zend_shared_alloc_unlock_win32();
+	/* Keep the mutex locked: the new segment is not initialized yet, and a process that attached now
+	 * would read uninitialized shared memory. zend_shared_alloc_startup_done() releases it. */
+	startup_lock_held = true;
 
 	return ALLOC_SUCCESS;
 }
diff --git a/ext/opcache/zend_shared_alloc.c b/ext/opcache/zend_shared_alloc.c
--- a/ext/opcache/zend_shared_alloc.c
+++ b/ext/opcache/zend_shared_alloc.c
@@ -196,7 +196,9 @@
 
 	/* shared_free must be valid before we call zend_shared_alloc()
 	 * - make it temporarily point to a local variable
+	 * It is copied by value into shared memory below, so it must not contain stack garbage.
 	 */
+	memset(&tmp_shared_globals, 0, sizeof(tmp_shared_globals));
 	smm_shared_globals = &tmp_shared_globals;
 	ZSMMG(shared_free) = requested_size - reserved_size; /* goes to tmp_shared_globals.shared_free */
 
@@ -268,7 +270,7 @@
 	shared_segments_array_size = ZSMMG(shared_segments_count) * S_H(segment_type_size)();
 
 	/* move shared_segments and shared_free to shared memory */
-	ZCG(locked) = 1; /* no need to perform a real lock at this point */
+	ZCG(locked) = 1; /* no other process can access the new segment yet, see zend_shared_alloc_startup_done() */
 
 	p_tmp_shared_globals = (zend_smm_shared_globals *) zend_shared_alloc(sizeof(zend_smm_shared_globals));
 	if (!p_tmp_shared_globals) {
@@ -314,6 +316,13 @@
 	return res;
 }
 
+void zend_shared_alloc_startup_done(void)
+{
+#ifdef ZEND_WIN32
+	zend_shared_alloc_win32_startup_done();
+#endif
+}
+
 void zend_shared_alloc_shutdown(void)
 {
 	zend_shared_segment **tmp_shared_segments;
diff --git a/ext/opcache/zend_shared_alloc.h b/ext/opcache/zend_shared_alloc.h
--- a/ext/opcache/zend_shared_alloc.h
+++ b/ext/opcache/zend_shared_alloc.h
@@ -127,7 +127,11 @@
 
 BEGIN_EXTERN_C()
 
+/* If this returns ALLOC_SUCCESS, this process has created a new segment that other processes may only
+ * use once it is fully initialized. The caller must call zend_shared_alloc_startup_done() when that is
+ * the case (on Windows, the mapping mutex stays locked until then). */
 int zend_shared_alloc_startup(size_t requested_size, size_t reserved_size);
+void zend_shared_alloc_startup_done(void);
 void zend_shared_alloc_shutdown(void);
 
 /* allocate shared memory block */
@@ -218,6 +222,7 @@
 void zend_shared_alloc_create_lock(void);
 void zend_shared_alloc_lock_win32(void);
 void zend_shared_alloc_unlock_win32(void);
+void zend_shared_alloc_win32_startup_done(void);
 #endif
 
 END_EXTERN_C()

How we tested it (Windows Server 2019, 4 vCPUs):

  • Build: php_opcache.dll 8.4.27 x64 NTS and ZTS, with and without JIT, from the 8.4.27 sources against the
    official devel packs, each unpatched and patched, cross-compiled with clang-cl 19 / lld-link against the MSVC
    CRT and Windows SDK (HAVE_BUILTIN_CONSTANT_P disabled to match the MSVC build of php8.dll). Exports and
    imported DLLs match the official DLL. Not the official toolchain.

  • Forced window: test-only builds with Sleep(50) right after the segment is created and right before the JIT
    startup, JIT on, groups of 8 started simultaneously, 1,600 starts each:

    build NTS ZTS
    unpatched + sleeps 1,196 crashes 1,181 crashes
    first attempt (unlock after zend_accel_init_shm()) + sleeps 1,346 (all in dasm_encode) 1,353 (all in dasm_encode)
    this patch + sleeps 0 0
  • Without sleeps: groups of 8, 46-extension configuration, 12,000 starts per variant, variants interleaved in
    10 rounds, 60 s timeout per process to detect deadlocks:

    php_opcache.dll NTS, JIT on ZTS, JIT on NTS, no JIT ZTS, no JIT
    official 8.4.27 43 38 27 24
    own build, unpatched 33 27 15 13
    own build, patched 0 0 0 0

    No hangs. The unpatched builds crash at the NULL read at +0x68, at the hash lookup through the stale pointer
    and, with JIT, in dasm_encode during the attacher's JIT startup.

  • Function: with a long-running process holding the mapping, a second process attaches and sees the cache
    hits of the first one; JIT emits the same amount of code as with the official DLL.

  • Regression: ext/opcache/tests with run-tests.php -j4 and the own DLL, the same for unpatched and patched:
    814 passed / 0 failed without JIT, 817 passed / 0 failed with opcache.jit=tracing (including 475 tests in
    jit/).

PHP Version

PHP 8.4.27 (cgi-fcgi), NTS and ZTS, official windows.php.net x64 builds (vs17). The locking and initialization
order is unchanged on master.

Operating System

Windows Server 2019 Standard x64 (10.0.17763), VM with 4 vCPUs

Linguagem predominante
C
Estrelas
41.8k
Forks
8.6k
Merge médio
2d 15h
PRs com merge (30d)
125

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de php/php-src

Todas as issues de php/php-src

Issues semelhantes

Mais issues de C

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.