From f647f6de39a23730ddd2455d35ed72080cc1e16c Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Mon, 9 Nov 2026 13:04:23 +0800 Subject: [PATCH 01/12] fix(zig-cc): honour BUILD_INCLUDE_PATH The buildroot include rewrite compared a realpath'd -isystem argument against BUILD_ROOT_PATH, i.e. the buildroot root instead of its include/ directory, so it never matched and every -isystem was passed through unchanged. Compare against BUILD_INCLUDE_PATH instead, map -mtune=generic to zig's "baseline" spelling, and drop GCC-only warning flags (-Wlogical-op, -Wduplicated-cond, -Warray-bounds=*, ...) that clang/zig does not know, so they no longer produce -Wunknown-warning-option noise. Port of crazywhalecc/static-php-cli#1138 (4f769426, 8f557aae). --- src/globals/scripts/zig-cc.sh | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/globals/scripts/zig-cc.sh b/src/globals/scripts/zig-cc.sh index 886253ea6..996fb2450 100755 --- a/src/globals/scripts/zig-cc.sh +++ b/src/globals/scripts/zig-cc.sh @@ -1,9 +1,14 @@ #!/usr/bin/env bash SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")" -BUILDROOT_ABS="${BUILD_ROOT_PATH:-$(realpath "$SCRIPT_DIR/../../../buildroot/include" 2>/dev/null || true)}" +BUILDROOT_INC="${BUILD_INCLUDE_PATH:-$SCRIPT_DIR/../../../buildroot/include}" +BUILDROOT_ABS="$(realpath "$BUILDROOT_INC" 2>/dev/null || true)" PARSED_ARGS=() +is_buildroot_inc() { + [[ -n "$BUILDROOT_ABS" && "$1" == "$BUILDROOT_ABS" ]] +} + while [[ $# -gt 0 ]]; do case "$1" in -isystem) @@ -11,13 +16,13 @@ while [[ $# -gt 0 ]]; do ARG="$1" shift ARG_ABS="$(realpath "$ARG" 2>/dev/null || true)" - [[ "$ARG_ABS" == "$BUILDROOT_ABS" ]] && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem" "$ARG") + is_buildroot_inc "$ARG_ABS" && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem" "$ARG") ;; -isystem*) ARG="${1#-isystem}" shift ARG_ABS="$(realpath "$ARG" 2>/dev/null || true)" - [[ "$ARG_ABS" == "$BUILDROOT_ABS" ]] && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem$ARG") + is_buildroot_inc "$ARG_ABS" && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem$ARG") ;; -march=*|-mcpu=*) OPT_NAME="${1%%=*}" @@ -34,6 +39,15 @@ while [[ $# -gt 0 ]]; do PARSED_ARGS+=("${OPT_NAME}=${OPT_VALUE}") shift ;; + -mtune=generic) + # zig knows "baseline" but not generic + PARSED_ARGS+=("-mtune=baseline") + shift + ;; + -Wlogical-op|-Wduplicated-cond|-Wduplicated-branches|-Wno-clobbered|-Wjump-misses-init|-Wformat-truncation|-Warray-bounds=*|-Wimplicit-fallthrough=*) + # GCC-only warning flags that clang/zig doesn't recognize; drop to silence -Wunknown-warning-option noise + shift + ;; *) PARSED_ARGS+=("$1") shift From f6cc2faba060759916f66672b8fe9660cc43e497 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Mon, 9 Nov 2026 13:04:34 +0800 Subject: [PATCH 02/12] fix(download): add curl connect and speed timeouts The only guard was --max-time 3600, so an unreachable host or a mirror that stops sending data blocks the build for up to an hour. Abort when no connection is established within 15s, and when throughput stays below 1 byte/s for 30s. Applies to both executeCurl() and executeCurlDownload(). Port of crazywhalecc/static-php-cli#1138 (7d3e1f8d). --- src/StaticPHP/Runtime/Shell/DefaultShell.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/StaticPHP/Runtime/Shell/DefaultShell.php b/src/StaticPHP/Runtime/Shell/DefaultShell.php index d744b16b9..4b4610540 100644 --- a/src/StaticPHP/Runtime/Shell/DefaultShell.php +++ b/src/StaticPHP/Runtime/Shell/DefaultShell.php @@ -42,7 +42,7 @@ public function executeCurl(string $url, string $method = 'GET', array $headers $header_arg = implode(' ', array_map(fn ($v) => '"-H' . $v . '"', $headers)); $retry_arg = $retries > 0 ? "--retry {$retries}" : ''; $compressed_arg = $compressed ? '--compressed' : ''; - $cmd = SPC_CURL_EXEC . " -sfSL --max-time 3600 {$retry_arg} {$compressed_arg} {$method_arg} {$header_arg} {$url_arg}"; + $cmd = SPC_CURL_EXEC . " -sfSL --connect-timeout 15 --speed-limit 1 --speed-time 30 --max-time 3600 {$retry_arg} {$compressed_arg} {$method_arg} {$header_arg} {$url_arg}"; $this->logCommandInfo($cmd); logger()->debug("[CURL EXECUTE] {$cmd}"); @@ -76,7 +76,7 @@ public function executeCurlDownload(string $url, string $path, array $headers = $header_arg = implode(' ', array_map(fn ($v) => '"-H' . $v . '"', $headers)); $retry_arg = $retries > 0 ? "--retry {$retries}" : ''; $check = $this->console_putput ? '#' : 's'; - $cmd = clean_spaces(SPC_CURL_EXEC . " -{$check}fSL --max-time 3600 {$retry_arg} {$header_arg} -o {$path_arg} {$url_arg}"); + $cmd = clean_spaces(SPC_CURL_EXEC . " -{$check}fSL --connect-timeout 15 --speed-limit 1 --speed-time 30 --max-time 3600 {$retry_arg} {$header_arg} -o {$path_arg} {$url_arg}"); $this->logCommandInfo($cmd); logger()->debug('[CURL DOWNLOAD] ' . $cmd); $this->passthru($cmd, $this->console_putput, capture_output: false, throw_on_error: true); From 1d7099f52354f3b4d274730ae5f24bf949dcd67a Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Mon, 9 Nov 2026 13:04:35 +0800 Subject: [PATCH 03/12] fix(frankenphp): run go clean -cache before xcaddy cgo caches the evaluated include list across builds (FRANKENPHP_VERSION and friends are resolved from generated headers), so a rebuild could keep reporting and compiling against the values from the previous build even after the headers were regenerated. Clear the go build cache before xcaddy runs. Port of crazywhalecc/static-php-cli#1138 (a88e4266). --- src/Package/Target/php/frankenphp.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Package/Target/php/frankenphp.php b/src/Package/Target/php/frankenphp.php index 56c0c0d7d..44941e773 100644 --- a/src/Package/Target/php/frankenphp.php +++ b/src/Package/Target/php/frankenphp.php @@ -104,6 +104,9 @@ public function buildFrankenphpForUnix(TargetPackage $package, PackageInstaller InteractiveTerm::setMessage('Building frankenphp: ' . ConsoleColor::yellow('building with xcaddy')); shell()->cd(BUILD_LIB_PATH) ->setEnv($env) + // cgo caches the evaluated include list (e.g. FRANKENPHP_VERSION); clear it so + // headers regenerated by this build are actually picked up on rebuilds + ->exec('go clean -cache') ->exec("xcaddy build --output frankenphp {$xcaddy_modules}"); $builder->deployBinary(BUILD_LIB_PATH . '/frankenphp', BUILD_BIN_PATH . '/frankenphp'); From 4e2685dc823e1ab0ddfcc6a7323320db9c0c0b53 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Mon, 9 Nov 2026 13:04:43 +0800 Subject: [PATCH 04/12] fix(php): add --with-sysconfdir build option Expose --with-sysconfdir and forward it to PHP's configure as --sysconfdir=..., so packagers can point PHP at a location such as /etc/php-zts. The option is wired into the Unix configure path only; Windows ignores it. Document the option in the bilingual CLI reference and in the craft.yml build-options example. Port of crazywhalecc/static-php-cli#1138 (8f557aae). --- docs/deps-craft-yml.md | 2 ++ docs/en/guide/cli-reference.md | 1 + docs/zh/guide/cli-reference.md | 1 + src/Package/Target/php.php | 1 + src/Package/Target/php/unix.php | 3 +++ 5 files changed, 8 insertions(+) diff --git a/docs/deps-craft-yml.md b/docs/deps-craft-yml.md index 962a477d6..3a4650ef9 100644 --- a/docs/deps-craft-yml.md +++ b/docs/deps-craft-yml.md @@ -30,6 +30,8 @@ build-options: with-config-file-path: "" # PHP configuration options (same as --with-config-file-scan-dir) with-config-file-scan-dir: "" + # PHP configuration options (same as --with-sysconfdir, only on Unix) + with-sysconfdir: "" # Hardcoded INI options for cli and micro SAPI (e.g. "memory_limit=4G", list accepted) with-hardcoded-ini: [ ] # Pretend micro SAPI as cli SAPI to avoid some frameworks to limit the usage of micro SAPI diff --git a/docs/en/guide/cli-reference.md b/docs/en/guide/cli-reference.md index f5678bd8f..2430e8a22 100644 --- a/docs/en/guide/cli-reference.md +++ b/docs/en/guide/cli-reference.md @@ -99,6 +99,7 @@ These flags apply only to the combined `build:php` target. To build a specific S | `--disable-opcache-jit` | | Disable OPcache JIT | | `--with-config-file-path=` | | Directory where PHP looks for `php.ini` (default: `/usr/local/etc/php`) | | `--with-config-file-scan-dir=` | | Directory PHP scans for additional `.ini` files (default: `/usr/local/etc/php/conf.d`) | +| `--with-sysconfdir=` | | Set the `sysconfdir` passed to PHP's `configure` (Unix only, e.g. `/etc/php-zts`) | | `--with-hardcoded-ini=` | `-I` | Bake an INI setting into the binary at compile time (repeatable) | | `--enable-zts` | | Enable thread-safe (ZTS) mode | | `--no-smoke-test` | | Skip the post-build smoke tests | diff --git a/docs/zh/guide/cli-reference.md b/docs/zh/guide/cli-reference.md index 31bd95d2b..d91ac617f 100644 --- a/docs/zh/guide/cli-reference.md +++ b/docs/zh/guide/cli-reference.md @@ -99,6 +99,7 @@ spc build:php [options] | `--disable-opcache-jit` | | 禁用 OPcache JIT | | `--with-config-file-path=` | | PHP 查找 `php.ini` 的目录(默认:`/usr/local/etc/php`) | | `--with-config-file-scan-dir=` | | PHP 扫描追加 `.ini` 文件的目录(默认:`/usr/local/etc/php/conf.d`) | +| `--with-sysconfdir=` | | 传给 PHP `configure` 的 `sysconfdir`(仅 Unix,例如 `/etc/php-zts`) | | `--with-hardcoded-ini=` | `-I` | 编译时将 INI 配置硬编码进二进制(可重复使用) | | `--enable-zts` | | 启用线程安全(ZTS)模式 | | `--no-smoke-test` | | 跳过构建后的冒烟测试 | diff --git a/src/Package/Target/php.php b/src/Package/Target/php.php index 805756e4b..12d484fff 100644 --- a/src/Package/Target/php.php +++ b/src/Package/Target/php.php @@ -142,6 +142,7 @@ public function init(TargetPackage $package): void $package->addBuildOption('disable-opcache-jit', null, null, 'Disable opcache jit'); $package->addBuildOption('with-config-file-path', null, InputOption::VALUE_REQUIRED, 'Set the path in which to look for php.ini', PHP_OS_FAMILY === 'Windows' ? null : '/usr/local/etc/php'); $package->addBuildOption('with-config-file-scan-dir', null, InputOption::VALUE_REQUIRED, 'Set the directory to scan for .ini files after reading php.ini', PHP_OS_FAMILY === 'Windows' ? null : '/usr/local/etc/php/conf.d'); + $package->addBuildOption('with-sysconfdir', null, InputOption::VALUE_REQUIRED, 'Set the sysconfdir (e.g. /etc/php-zts) used by configure (not available on Windows)'); $package->addBuildOption('with-hardcoded-ini', 'I', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Patch PHP source code, inject hardcoded INI'); $package->addBuildOption('enable-zts', null, null, 'Enable thread safe support'); $package->addBuildOption('no-smoke-test', null, InputOption::VALUE_OPTIONAL, 'Disable smoke test for specific SAPIs, or all if no value provided', false); diff --git a/src/Package/Target/php/unix.php b/src/Package/Target/php/unix.php index a05ef7dc9..f4e4e1e93 100644 --- a/src/Package/Target/php/unix.php +++ b/src/Package/Target/php/unix.php @@ -118,6 +118,9 @@ public function configureForUnix(TargetPackage $package, PackageInstaller $insta if ($option = $package->getBuildOption('with-config-file-scan-dir', false)) { $args[] = "--with-config-file-scan-dir={$option}"; } + if ($option = $package->getBuildOption('with-sysconfdir', false)) { + $args[] = "--sysconfdir={$option}"; + } // perform enable cli options // PHP >= 8.6 links the CLI objects into libphp for do_php_cli() $cli = $installer->isPackageResolved('php-cli') From 83781d76ed23e47c0d7459fc493a6499019a54ac Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Mon, 9 Nov 2026 13:29:06 +0800 Subject: [PATCH 05/12] ci(tests): keep doctor in its own step so failures abort the job On Windows the default pwsh shell does not stop a `run: |` block when a native command exits non-zero. `spc doctor --auto-fix` exiting 69 (e.g. its vswhere auto-fix download failed) was therefore swallowed and the build kept running until it failed the environment check, hiding the real cause. Split doctor and build into separate steps so a doctor failure fails the job immediately on every shell. --- .github/workflows/tests.yml | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 690de888f..ad7316698 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -250,13 +250,21 @@ jobs: - name: Install dependencies run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev + # Keep doctor in its own step: on Windows the default pwsh shell does not stop + # a `run: |` block when a native command exits non-zero, so a failed doctor + # (e.g. an auto-fix download error) used to be swallowed and the build kept + # running until it failed on a confusing environment check. + - name: Doctor + env: + SPC_USE_SUDO: "yes" + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: ./bin/spc doctor --auto-fix + - name: Build env: SPC_USE_SUDO: "yes" GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - ./bin/spc doctor --auto-fix - ${{ matrix.combo.build-args }} --dl-with-php=${{ matrix.combo.php-version }} + run: ${{ matrix.combo.build-args }} --dl-with-php=${{ matrix.combo.php-version }} # - name: Setup upterm session # if: ${{ failure() }} From 061af9a53eaa8048ad5ad31e8edd699dff2c5b58 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Mon, 9 Nov 2026 14:38:45 +0800 Subject: [PATCH 06/12] fix(artifact-extraction): ensure stale source directories are removed before extraction --- .../Command/SwitchPhpVersionCommand.php | 25 +++- src/StaticPHP/Artifact/ArtifactExtractor.php | 27 +++- src/StaticPHP/Util/FileSystem.php | 137 ++++++++++++++---- 3 files changed, 157 insertions(+), 32 deletions(-) diff --git a/src/Package/Command/SwitchPhpVersionCommand.php b/src/Package/Command/SwitchPhpVersionCommand.php index fbc335f7b..b1e81e376 100644 --- a/src/Package/Command/SwitchPhpVersionCommand.php +++ b/src/Package/Command/SwitchPhpVersionCommand.php @@ -10,6 +10,7 @@ use StaticPHP\Artifact\DownloaderOptions; use StaticPHP\Command\BaseCommand; use StaticPHP\DI\ApplicationContext; +use StaticPHP\Exception\ExecutionException; use StaticPHP\Registry\PackageLoader; use StaticPHP\Util\FileSystem; use StaticPHP\Util\InteractiveTerm; @@ -65,6 +66,16 @@ public function handle(): int $this->output->writeln('Removing extracted PHP source directory...'); InteractiveTerm::indicateProgress('Removing: ' . $source_dir); FileSystem::removeDir($source_dir); + if (file_exists($source_dir)) { + InteractiveTerm::finish('Failed: ' . $source_dir, false); + throw new ExecutionException( + "Failed to remove the extracted PHP source directory: {$source_dir}\n" . + 'The PHP version switch was aborted: continuing would build the new PHP on top of ' . + 'stale sources and object files from the previous version (wrong headers/ABI, ' . + 'undefined symbols at link time).' . "\n" . + 'Remove the directory manually (on Windows: rmdir /s /q "' . FileSystem::convertPath($source_dir) . '") and retry.', + ); + } InteractiveTerm::finish('Removed: ' . $source_dir); } @@ -105,15 +116,25 @@ public function handle(): int /** * Delete every extracted extension source tree under source/ext-*, returning the count. + * + * @throws ExecutionException When an extracted tree cannot be removed completely */ public static function removeExtensionSources(string $source_path): int { $removed = 0; foreach (glob(FileSystem::convertPath("{$source_path}/ext-*"), GLOB_ONLYDIR) ?: [] as $ext_dir) { if (FileSystem::isLink($ext_dir)) { - FileSystem::removeLink($ext_dir); + $ok = FileSystem::removeLink($ext_dir); } else { - FileSystem::removeDir($ext_dir); + $ok = FileSystem::removeDir($ext_dir); + } + if (!$ok || file_exists($ext_dir) || FileSystem::isLink($ext_dir)) { + throw new ExecutionException( + "Failed to remove extracted extension source directory: {$ext_dir}\n" . + 'Its build state (objects, generated headers, patched sources) is only valid for the ' . + 'PHP version that produced it and would leak into the next build.' . "\n" . + 'Remove it manually (on Windows: rmdir /s /q "' . FileSystem::convertPath($ext_dir) . '") and retry.', + ); } ++$removed; } diff --git a/src/StaticPHP/Artifact/ArtifactExtractor.php b/src/StaticPHP/Artifact/ArtifactExtractor.php index 581ffc1ee..343f355e9 100644 --- a/src/StaticPHP/Artifact/ArtifactExtractor.php +++ b/src/StaticPHP/Artifact/ArtifactExtractor.php @@ -5,6 +5,7 @@ namespace StaticPHP\Artifact; use StaticPHP\DI\ApplicationContext; +use StaticPHP\Exception\ExecutionException; use StaticPHP\Exception\FileSystemException; use StaticPHP\Exception\SPCInternalException; use StaticPHP\Exception\WrongUsageException; @@ -182,10 +183,10 @@ protected function extractSource(Artifact $artifact): int // Remove old directory if hash mismatch if (FileSystem::isLink($target_path)) { logger()->debug("Source [{$name}] is linked to a local directory, relinking..."); - FileSystem::removeLink($target_path); + $this->assertSourceDirClean($name, $target_path, FileSystem::removeLink($target_path)); } elseif (is_dir($target_path)) { logger()->notice("Source [{$name}] hash mismatch, re-extracting..."); - FileSystem::removeDir($target_path); + $this->assertSourceDirClean($name, $target_path, FileSystem::removeDir($target_path)); } logger()->info("Extracting source [{$name}] to {$target_path}..."); @@ -374,6 +375,28 @@ protected function doSelectiveExtract(string $name, array $cache_info, array $fi } } + /** + * Fail loudly when the stale source tree could not be removed before extraction. + * + * Extracting over a partially removed tree silently mixes the old version's sources and + * build artifacts with the new one (e.g. object files built against a previous PHP + * version's headers being linked into the new build). + * + * @throws ExecutionException When the old directory is still there + */ + protected function assertSourceDirClean(string $name, string $target_path, bool $removed): void + { + if ($removed && !file_exists($target_path) && !FileSystem::isLink($target_path)) { + return; + } + $hint = PHP_OS_FAMILY === 'Windows' ? ' (Windows: rmdir /s /q "' . FileSystem::convertPath($target_path) . '")' : ''; + throw new ExecutionException( + "Failed to remove stale source directory for artifact [{$name}]: {$target_path}\n" . + 'Refusing to extract on top of it, because old build artifacts would leak into the new source tree.' . "\n" . + 'Remove it manually and retry.' . $hint, + ); + } + /** * Check if artifact is already extracted with correct hash. * diff --git a/src/StaticPHP/Util/FileSystem.php b/src/StaticPHP/Util/FileSystem.php index 27cbf5c44..c8048a51e 100644 --- a/src/StaticPHP/Util/FileSystem.php +++ b/src/StaticPHP/Util/FileSystem.php @@ -296,6 +296,19 @@ public static function removeDir(string $dir, ?callable $callback = null): bool { $dir = self::convertPath($dir); logger()->debug('Removing path recursively: "' . $dir . '"'); + + // A directory link (symlink or NTFS junction) must be removed as a link: + // recursing into it would delete the target's contents instead. Junctions + // are invisible to file_exists()/is_dir() when dangling, so check isLink() + // before bailing out on a "missing" path. + if (self::isLink($dir)) { + if (!self::removeLink($dir)) { + logger()->warning('Remove link failed: ' . $dir); + return false; + } + return true; + } + if (!file_exists($dir)) { logger()->debug('Scan dir failed, no such file or directory.'); return false; @@ -311,6 +324,12 @@ public static function removeDir(string $dir, ?callable $callback = null): bool logger()->warning('Scan dir failed, cannot scan directory: ' . $dir); return false; } + + // Keep going when a single entry fails: aborting on the first error leaves + // an unpredictable part of the tree behind, which callers cannot detect + // reliably (e.g. stale PHP build objects leaking into the next version). + $success = true; + // 遍历目录 foreach ($scan_list as $v) { if ($callback) { @@ -321,35 +340,35 @@ public static function removeDir(string $dir, ?callable $callback = null): bool continue; } $sub_file = self::convertPath($dir . '/' . $v); - if (is_link($sub_file) || is_file($sub_file)) { - if (!@unlink($sub_file)) { - $last_error = error_get_last(); - logger()->debug("unlink failed for '{$sub_file}': " . ($last_error['message'] ?? 'unknown error') . ', attempting chmod + unlink'); - - // Go module cache files are often read-only; make writable and retry - if (@chmod($sub_file, 0666) && @unlink($sub_file)) { - continue; - } - - // Shell fallback: del /f /q forces deletion of read-only files on Windows - $cmd = PHP_OS_FAMILY === 'Windows' ? 'del /f /q' : 'rm -f'; - f_exec("{$cmd} " . escapeshellarg($sub_file), $out, $ret); - if ($ret !== 0) { - logger()->warning('Remove file failed: ' . $sub_file); - return false; - } + if (self::isLink($sub_file)) { + if (!self::removeLink($sub_file)) { + logger()->warning('Remove link failed: ' . $sub_file); + $success = false; + } + } elseif (is_file($sub_file)) { + if (!self::removeFile($sub_file)) { + $success = false; } } elseif (is_dir($sub_file)) { # 如果是 目录 且 递推 , 则递推添加下级文件 if (!self::removeDir($sub_file)) { - return false; + $success = false; + } + } elseif (file_exists($sub_file)) { + // Reparse point we cannot classify as file/directory (e.g. a + // junction on Windows): remove the link itself. + if (!self::removeLink($sub_file)) { + logger()->warning('Remove path failed: ' . $sub_file); + $success = false; } } } - if (is_link($dir)) { - return @unlink($dir); + if (!@rmdir($dir)) { + $last_error = error_get_last(); + logger()->warning("Remove directory failed: {$dir}: " . ($last_error['message'] ?? 'unknown error')); + $success = false; } - return @rmdir($dir); + return $success; } /** @@ -470,8 +489,13 @@ public static function removeFileIfExists(string $string): void /** * Whether the path is a link to another location. Besides symlinks this also * detects NTFS directory junctions on Windows, which PHP's is_link() does not - * recognize (php-src only flags IO_REPARSE_TAG_SYMLINK as S_IFLNK in lstat), - * while readlink() resolves junctions just fine. + * recognize (php-src only flags IO_REPARSE_TAG_SYMLINK as S_IFLNK in lstat). + * + * Do not rely on readlink() alone: php-src's Win32 implementation falls back to + * GetFinalPathNameByHandleW() for non-reparse paths, so readlink() returns the + * canonical path for every existing path and would make everything look like a + * link. A junction instead has a distinctive stat shape: it exists, but both + * is_dir() and is_file() report false. * * @param string $path Path to check */ @@ -480,7 +504,30 @@ public static function isLink(string $path): bool if (is_link($path)) { return true; } - return PHP_OS_FAMILY === 'Windows' && @readlink($path) !== false; + if (PHP_OS_FAMILY !== 'Windows') { + return false; + } + $path = self::convertPath($path); + // Strip trailing separators (but keep drive/UNC roots) so that is_dir() does + // not follow the reparse point and report the target. + if (strlen($path) > 3) { + $path = rtrim($path, '/\\'); + } + clearstatcache(true, $path); + + // php-src keeps st_mode = 0 for reparse points it cannot classify + // (junctions: FILE_ATTRIBUTE_REPARSE_POINT without IO_REPARSE_TAG_SYMLINK), + // so lstat() reports neither file, directory nor link. + $stat = @lstat($path); + if ($stat !== false && ($stat['mode'] & 0170000) === 0) { + return true; + } + + if (file_exists($path)) { + return !is_dir($path) && !is_file($path); + } + // Dangling junction/symlink: the path does not exist, but the link still does. + return @readlink($path) !== false; } /** @@ -492,10 +539,15 @@ public static function isLink(string $path): bool */ public static function removeLink(string $path): bool { - if (PHP_OS_FAMILY === 'Windows' && is_dir($path)) { - return rmdir($path); + if (PHP_OS_FAMILY === 'Windows') { + // Directory links are removed with rmdir(); file symlinks with unlink(). + // Order matters: junctions are not reported as directories by is_dir(). + if (@rmdir($path)) { + return true; + } + return @unlink($path); } - return unlink($path); + return @unlink($path); } /** @@ -516,7 +568,8 @@ public static function linkDir(string $target, string $link): bool return symlink($target_path, $link_path); } [$code] = cmd(false)->execWithResult('mklink /J "' . $link_path . '" "' . $target_path . '"', false); - return $code === 0 && is_dir($link_path); + // Junctions are invisible to is_dir() on Windows, so verify with isLink(). + return $code === 0 && self::isLink($link_path); } /** @@ -640,6 +693,34 @@ public static function moveFileOrDir(string $source, string $dest): void } } + /** + * Remove a single file, handling read-only files and shell fallbacks. + * + * @param string $file File path to remove + */ + private static function removeFile(string $file): bool + { + if (@unlink($file)) { + return true; + } + $last_error = error_get_last(); + logger()->debug("unlink failed for '{$file}': " . ($last_error['message'] ?? 'unknown error') . ', attempting chmod + unlink'); + + // Go module cache files are often read-only; make writable and retry + if (@chmod($file, 0666) && @unlink($file)) { + return true; + } + + // Shell fallback: del /f /q forces deletion of read-only files on Windows + $cmd = PHP_OS_FAMILY === 'Windows' ? 'del /f /q' : 'rm -f'; + f_exec("{$cmd} " . escapeshellarg($file), $out, $ret); + if ($ret !== 0) { + logger()->warning('Remove file failed: ' . $file); + return false; + } + return true; + } + private static function replaceFile(string $filename, int $replace_type = REPLACE_FILE_STR, mixed $callback_or_search = null, mixed $to_replace = null): false|int { logger()->debug('Replacing file with type[' . $replace_type . ']: ' . $filename); From dd4ebc523558d9f5ef57fcf6eff932ee047a6af8 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Tue, 10 Nov 2026 10:52:27 +0800 Subject: [PATCH 07/12] fix(imagemagick): add patch for Cairo MTA usage compatibility with Windows 7 --- src/Package/Library/imagemagick.php | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Package/Library/imagemagick.php b/src/Package/Library/imagemagick.php index 21ba687b6..935c17c8c 100644 --- a/src/Package/Library/imagemagick.php +++ b/src/Package/Library/imagemagick.php @@ -44,6 +44,8 @@ public function buildWin(LibraryPackage $lib): void // Use the prebuilt Configure tool (building it from source needs the MFC components). default_shell()->executeCurlDownload($configure_url, "{$work}\\Configure\\Configure.Release.x64.exe", retries: 2); + self::patchCairoWin7MtaUsage($work); + // Generate a static, /MT (linkRuntime), x64, Q16-HDRI solution with the configs embedded // (zeroConfigurationSupport) and OpenMP off (no vcomp runtime dependency). $ver = WindowsUtil::findVisualStudio(); @@ -158,4 +160,32 @@ public function buildUnix(LibraryPackage $lib, ToolchainInterface $toolchain): v } $lib->patchLaDependencyPrefix(); } + + /** + * cairo 1.18.6 (vendored by ImageMagick) uses the Windows 8+ COM MTA usage API in + * cairo-win32-system.c, but the VisualMagick projects are generated with + * _WIN32_WINNT=0x0601 (Windows 7), where the Windows SDK hides CO_MTA_USAGE_COOKIE and + * CoIncrementMTAUsage behind "NTDDI_VERSION >= NTDDI_WIN8", breaking the static build. + * + * Those functions are resolved dynamically with GetProcAddress, so only the opaque cookie + * type declaration is missing: provide the DECLARE_HANDLE-compatible definition for Win7 + * targets. No-op when the vendored cairo no longer needs it (patch string not found). + */ + private static function patchCairoWin7MtaUsage(string $work): void + { + $file = "{$work}\\Dependencies\\Dependencies\\cairo\\src\\win32\\cairo-win32-system.c"; + if (!is_file($file)) { + return; + } + FileSystem::replaceFileStr( + $file, + '#include ', + "#include \n\n" + . "#if !defined(NTDDI_WIN8) || (NTDDI_VERSION < NTDDI_WIN8)\n" + . '/* Windows 7 target: mirror DECLARE_HANDLE(CO_MTA_USAGE_COOKIE) from the Win8+ SDK. */' . "\n" + . "struct CO_MTA_USAGE_COOKIE__ { int unused; };\n" + . "typedef struct CO_MTA_USAGE_COOKIE__ *CO_MTA_USAGE_COOKIE;\n" + . '#endif' . "\n", + ); + } } From a68f617094a111d2a40861e03246931dabe2427a Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Tue, 10 Nov 2026 10:54:14 +0800 Subject: [PATCH 08/12] fix(GenExtTestMatrixCommand): exclude ZTS-incompatible extensions from package set --- .../Command/Dev/GenExtTestMatrixCommand.php | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php b/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php index 23bc66be2..4b936547a 100644 --- a/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php +++ b/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php @@ -78,6 +78,19 @@ class GenExtTestMatrixCommand extends BaseCommand 'swoole' => 'swoole-hook-', ]; + /** + * Extensions that cannot be built in ZTS (thread-safe) mode and are therefore dropped from + * SAPI entries that force `--enable-zts` (currently frankenphp). + * + * Keep this in sync with the `#[Validate]` guards of the extension package classes, e.g. + * `src/Package/Extension/imap.php` throws "not thread safe" for ZTS builds. Emitting such an + * extension for a ZTS entry only produces a guaranteed, deterministic job failure. + * Use display names (without ext- prefix). + */ + private const array ZTS_EXCLUDE = [ + 'imap', + ]; + /** * Maximum number of orphan extensions per matrix entry. */ @@ -154,7 +167,7 @@ public function handle(): int [$frankenphp_entries, $frankenphp_ext_lib_deps] = $this->buildEntriesForRunners( self::OS_RUNNERS, [], - $all_regular, + $this->withoutZTSIncompatible($all_regular), $all_virtual, $all_libraries, self::FRANKENPHP_BUILD_TARGETS, @@ -462,6 +475,23 @@ private function buildTargetsWithExtraFlags(string $build_targets, string $group return implode(' ', $flags); } + /** + * Drop extensions that refuse ZTS builds from a package set used for `--enable-zts` entries. + * + * @param array $extensions Regular php-extension configs keyed by package name + * @return array The same set without the ZTS-incompatible extensions + */ + private function withoutZTSIncompatible(array $extensions): array + { + $exclude = array_fill_keys(array_map(static fn (string $name): string => 'ext-' . $name, self::ZTS_EXCLUDE), true); + + return array_filter( + $extensions, + static fn (string $pkg_name): bool => !isset($exclude[$pkg_name]), + ARRAY_FILTER_USE_KEY + ); + } + /** * Resolve the value of a platform-specific array field, applying the suffix fallback chain. * From 3a1086870f5e7057465e97ecc939af62771696ac Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Tue, 10 Nov 2026 10:55:02 +0800 Subject: [PATCH 09/12] fix(ArtifactDownloader): set default retry count to 3 for downloads --- docs/deps-craft-yml.md | 4 ++-- docs/en/guide/cli-reference.md | 2 +- docs/zh/guide/cli-reference.md | 2 +- src/StaticPHP/Artifact/ArtifactDownloader.php | 12 +++++++++-- src/StaticPHP/Artifact/DownloaderOptions.php | 2 +- src/StaticPHP/Runtime/Shell/DefaultShell.php | 20 +++++++++++++++++-- .../Artifact/ArtifactDownloaderTest.php | 15 ++++++++++---- .../Artifact/DownloaderOptionsTest.php | 14 +++++++++++++ .../Dev/GenExtTestMatrixCommandTest.php | 4 ++++ .../Package/PhpUnixConfigureTest.php | 10 ++++++++++ 10 files changed, 72 insertions(+), 13 deletions(-) diff --git a/docs/deps-craft-yml.md b/docs/deps-craft-yml.md index 3a4650ef9..e4d8a75bd 100644 --- a/docs/deps-craft-yml.md +++ b/docs/deps-craft-yml.md @@ -56,8 +56,8 @@ shared-extensions: [ ] download-options: # Number of parallel downloads (default: 1) parallel: 1 - # Retries count for downloading sources (default: 0) - retry: 0 + # Retries count for downloading sources (default: 3) + retry: 3 # Prefer source downloads when both source and binary are available (default: false) prefer-source: false # Prefer binary downloads when both source and binary are available (default: false) diff --git a/docs/en/guide/cli-reference.md b/docs/en/guide/cli-reference.md index 2430e8a22..eadac773b 100644 --- a/docs/en/guide/cli-reference.md +++ b/docs/en/guide/cli-reference.md @@ -35,7 +35,7 @@ spc download [artifacts] [options] | `--source-only` | | Only download source artifacts | | `--binary-only` | | Only download binary artifacts | | `--parallel=` | `-P` | Number of parallel downloads (default: `1`) | -| `--retry=` | `-R` | Number of retries on failure (default: `0`) | +| `--retry=` | `-R` | Number of retries on failure (default: `3`) | | `--ignore-cache=` | `-i` | Force re-download the specified artifacts | | `--no-alt` | | Do not use alternative mirror URLs | | `--no-shallow-clone` | | Do not clone git repositories shallowly | diff --git a/docs/zh/guide/cli-reference.md b/docs/zh/guide/cli-reference.md index d91ac617f..956c19237 100644 --- a/docs/zh/guide/cli-reference.md +++ b/docs/zh/guide/cli-reference.md @@ -35,7 +35,7 @@ spc download [artifacts] [options] | `--source-only` | | 仅下载源码制品 | | `--binary-only` | | 仅下载二进制制品 | | `--parallel=` | `-P` | 并行下载数(默认 `1`) | -| `--retry=` | `-R` | 失败重试次数(默认 `0`) | +| `--retry=` | `-R` | 失败重试次数(默认 `3`) | | `--ignore-cache=` | `-i` | 强制重新下载指定制品 | | `--no-alt` | | 不使用镜像站 | | `--no-shallow-clone` | | 不使用浅层克隆 | diff --git a/src/StaticPHP/Artifact/ArtifactDownloader.php b/src/StaticPHP/Artifact/ArtifactDownloader.php index db5df2080..747fd536d 100644 --- a/src/StaticPHP/Artifact/ArtifactDownloader.php +++ b/src/StaticPHP/Artifact/ArtifactDownloader.php @@ -56,6 +56,14 @@ class ArtifactDownloader 'hosted' => HostedPackageBin::class, ]; + /** + * Default download retry count when no retry option is supplied. + * + * Downloads are idempotent and transient failures are common (a single HTTP 5xx from a + * release mirror used to abort a whole build/CI job), so retry a few times by default. + */ + public const int DEFAULT_RETRY = 3; + /** @var array> */ protected array $downloaders = []; @@ -115,8 +123,8 @@ public function __construct(protected array $options = [], public readonly bool { // Allow setting concurrency via options $this->parallel = max(1, (int) ($options['parallel'] ?? 1)); - // Allow setting retry via options - $this->retry = max(0, (int) ($options['retry'] ?? 0)); + // Allow setting retry via options (falls back to DEFAULT_RETRY) + $this->retry = max(0, (int) ($options['retry'] ?? self::DEFAULT_RETRY)); // Prefer source (default) if (array_key_exists('prefer-source', $options)) { if (is_string($options['prefer-source'])) { diff --git a/src/StaticPHP/Artifact/DownloaderOptions.php b/src/StaticPHP/Artifact/DownloaderOptions.php index 9519cf637..0c970ada6 100644 --- a/src/StaticPHP/Artifact/DownloaderOptions.php +++ b/src/StaticPHP/Artifact/DownloaderOptions.php @@ -63,7 +63,7 @@ public static function getConsoleOptions(string $prefix = ''): array // download behavior options new InputOption("{$p}parallel", $shortP, InputOption::VALUE_REQUIRED, 'Number of parallel downloads (default 1)', '1'), - new InputOption("{$p}retry", $shortR, InputOption::VALUE_REQUIRED, 'Number of download retries on failure (default 0)', '0'), + new InputOption("{$p}retry", $shortR, InputOption::VALUE_REQUIRED, 'Number of download retries on failure (default 3)', (string) ArtifactDownloader::DEFAULT_RETRY), new InputOption("{$p}ignore-cache", $shortI, InputOption::VALUE_OPTIONAL, 'Ignore some caches when downloading, comma separated, e.g "php-src,curl,openssl"', false), new InputOption("{$p}no-alt", null, null, 'Do not use alternative mirror download artifacts for sources'), new InputOption("{$p}no-shallow-clone", null, null, 'Do not clone shallowly repositories when downloading sources'), diff --git a/src/StaticPHP/Runtime/Shell/DefaultShell.php b/src/StaticPHP/Runtime/Shell/DefaultShell.php index 4b4610540..86fbfef4e 100644 --- a/src/StaticPHP/Runtime/Shell/DefaultShell.php +++ b/src/StaticPHP/Runtime/Shell/DefaultShell.php @@ -40,7 +40,7 @@ public function executeCurl(string $url, string $method = 'GET', array $headers default => "-X {$method}", }; $header_arg = implode(' ', array_map(fn ($v) => '"-H' . $v . '"', $headers)); - $retry_arg = $retries > 0 ? "--retry {$retries}" : ''; + $retry_arg = self::curlRetryArgs($retries); $compressed_arg = $compressed ? '--compressed' : ''; $cmd = SPC_CURL_EXEC . " -sfSL --connect-timeout 15 --speed-limit 1 --speed-time 30 --max-time 3600 {$retry_arg} {$compressed_arg} {$method_arg} {$header_arg} {$url_arg}"; @@ -74,7 +74,7 @@ public function executeCurlDownload(string $url, string $path, array $headers = $path_arg = escapeshellarg($path); $header_arg = implode(' ', array_map(fn ($v) => '"-H' . $v . '"', $headers)); - $retry_arg = $retries > 0 ? "--retry {$retries}" : ''; + $retry_arg = self::curlRetryArgs($retries); $check = $this->console_putput ? '#' : 's'; $cmd = clean_spaces(SPC_CURL_EXEC . " -{$check}fSL --connect-timeout 15 --speed-limit 1 --speed-time 30 --max-time 3600 {$retry_arg} {$header_arg} -o {$path_arg} {$url_arg}"); $this->logCommandInfo($cmd); @@ -233,6 +233,22 @@ public function execute7zExtract(string $archive_path, string $target_path): boo return true; } + /** + * Build the cURL retry arguments shared by the request and download helpers. + * + * `--retry` covers transient failures (HTTP 408/429/500/502/503/504 and timeouts) and + * removes the partial output file before retrying; `--retry-connrefused` also retries + * when a mirror refuses the connection for a moment. Both are supported by the cURL + * versions shipped on the supported platforms (7.52+). + */ + private static function curlRetryArgs(int $retries): string + { + if ($retries <= 0) { + return ''; + } + return "--retry {$retries} --retry-delay 2 --retry-connrefused"; + } + /** * Run an extraction command, tolerating symbolic links that the host cannot create. * diff --git a/tests/StaticPHP/Artifact/ArtifactDownloaderTest.php b/tests/StaticPHP/Artifact/ArtifactDownloaderTest.php index 0b033b14f..abcc2dc6d 100644 --- a/tests/StaticPHP/Artifact/ArtifactDownloaderTest.php +++ b/tests/StaticPHP/Artifact/ArtifactDownloaderTest.php @@ -60,7 +60,7 @@ public function testConstructWithDefaultOptions(): void { $downloader = new ArtifactDownloader([], false); - $this->assertSame(0, $downloader->getRetry()); + $this->assertSame(ArtifactDownloader::DEFAULT_RETRY, $downloader->getRetry()); $this->assertFalse($downloader->interactive); $this->assertEmpty($downloader->getArtifacts()); } @@ -81,6 +81,13 @@ public function testConstructWithRetryOption(): void $this->assertSame(3, $downloader->getRetry()); } + public function testConstructWithExplicitZeroRetryDisablesRetries(): void + { + $downloader = new ArtifactDownloader(['retry' => 0], false); + + $this->assertSame(0, $downloader->getRetry()); + } + public function testConstructWithNegativeRetryClampedToZero(): void { $downloader = new ArtifactDownloader(['retry' => -5], false); @@ -93,7 +100,7 @@ public function testConstructWithPreferSourceBoolOption(): void // prefer-source=true sets default to FETCH_PREFER_SOURCE (0) $downloader = new ArtifactDownloader(['prefer-source' => true], false); - $this->assertSame(0, $downloader->getRetry()); // sanity check, object created fine + $this->assertSame(ArtifactDownloader::DEFAULT_RETRY, $downloader->getRetry()); // sanity check, object created fine } public function testConstructWithPreferBinaryBoolOption(): void @@ -184,11 +191,11 @@ public function testConstructWithNoAltOption(): void // ==================== getRetry ==================== - public function testGetRetryDefaultsToZero(): void + public function testGetRetryDefaultsToDefaultRetry(): void { $downloader = new ArtifactDownloader([], false); - $this->assertSame(0, $downloader->getRetry()); + $this->assertSame(ArtifactDownloader::DEFAULT_RETRY, $downloader->getRetry()); } public function testGetRetryReturnsConfiguredValue(): void diff --git a/tests/StaticPHP/Artifact/DownloaderOptionsTest.php b/tests/StaticPHP/Artifact/DownloaderOptionsTest.php index f55c20d01..368d42c4c 100644 --- a/tests/StaticPHP/Artifact/DownloaderOptionsTest.php +++ b/tests/StaticPHP/Artifact/DownloaderOptionsTest.php @@ -5,6 +5,7 @@ namespace Tests\StaticPHP\Artifact; use PHPUnit\Framework\TestCase; +use StaticPHP\Artifact\ArtifactDownloader; use StaticPHP\Artifact\DownloaderOptions; /** @@ -35,4 +36,17 @@ public function testAddToListIgnoresKeysOfTheNames(): void { $this->assertSame('zig', DownloaderOptions::addToList(false, ['zig' => 'zig'])); } + + public function testRetryOptionDefaultsToTheDownloaderDefault(): void + { + $retry = null; + foreach (DownloaderOptions::getConsoleOptions('dl') as $option) { + if ($option->getName() === 'dl-retry') { + $retry = $option; + } + } + + $this->assertNotNull($retry, 'The downloader must expose the --retry option'); + $this->assertSame((string) ArtifactDownloader::DEFAULT_RETRY, $retry->getDefault()); + } } diff --git a/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php b/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php index c638923fd..743b0f01c 100644 --- a/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php +++ b/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php @@ -301,6 +301,7 @@ private function findEntriesContaining(array $matrix, string ...$names): array * - ext-xml depends on lib 'libxml2' * - ext-dom depends on ext-xml (DFS chain) * - ext-imagick depends on imagemagick -> libheif -> libde265 + * - ext-imap ZTS-incompatible (excluded from frankenphp entries) * - ext-linux-only restricted to Linux via os: [Linux] */ private static function buildFixture(): array @@ -338,6 +339,9 @@ private static function buildFixture(): array // OS-restricted to Linux only 'ext-linux-only' => $ext(['os' => ['Linux']]), + + // ZTS-incompatible extension (dropped from --enable-zts entries) + 'ext-imap' => $ext(), ]; } } diff --git a/tests/StaticPHP/Package/PhpUnixConfigureTest.php b/tests/StaticPHP/Package/PhpUnixConfigureTest.php index 8c7e893cf..8356f67b6 100644 --- a/tests/StaticPHP/Package/PhpUnixConfigureTest.php +++ b/tests/StaticPHP/Package/PhpUnixConfigureTest.php @@ -62,6 +62,10 @@ public function testConfigureLinksOnlyRuntimeLibrariesAndResolvedMacOSFrameworks $installer->method('getResolvedPackages')->willReturnCallback(static function () use (&$resolved): array { return $resolved; }); + $installer->method('isPackageResolved')->willReturnCallback(static function (string $name) use (&$resolved): bool { + return $name === 'gettext' && isset($resolved['gettext']); + }); + $installer->method('getLibraryPackage')->willReturnCallback(fn (string $name): ?LibraryPackage => $name === 'libiconv' ? $this->createMock(LibraryPackage::class) : null); $php = new class { use unix; @@ -81,7 +85,13 @@ public function makeStaticExtensionString(PackageInstaller $installer): string $php->configureForUnix($package, $installer); $expected = SystemTarget::getRuntimeLibs(); if (str_contains($target, '-macos')) { + // libintl.a is built against our GNU libiconv, so the gettext configure probe + // needs those static libs (macOS libc has no gettext to fall back to). $expected .= ' -framework Kerberos -framework CoreFoundation'; + $resolved_names = array_keys($resolved); + if (in_array('gettext', $resolved_names, true)) { + $expected .= ' -liconv -lcharset'; + } } $this->assertSame($expected, file_get_contents($output), $target); } From 48313aba046ed2daaf29ddb92b7214e47c4f7db9 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Tue, 10 Nov 2026 10:55:26 +0800 Subject: [PATCH 10/12] fix(SwitchPhpVersionCommand): enhance extension source management during PHP version switch --- .../Command/SwitchPhpVersionCommand.php | 81 ++++++++++++++++--- src/Package/Target/php/unix.php | 76 +++++++++++++++++ 2 files changed, 147 insertions(+), 10 deletions(-) diff --git a/src/Package/Command/SwitchPhpVersionCommand.php b/src/Package/Command/SwitchPhpVersionCommand.php index b1e81e376..df7656da7 100644 --- a/src/Package/Command/SwitchPhpVersionCommand.php +++ b/src/Package/Command/SwitchPhpVersionCommand.php @@ -60,6 +60,10 @@ public function handle(): int $cache->removeSource('php-src', delete_file: true); } + // Collect the extension source trees linked into source/php-src/ext before php-src is + // removed: their build state is only valid for the PHP version that produced it. + $linked_extension_sources = self::collectLinkedExtensionSources(SOURCE_PATH); + // Remove extracted source directory if exists and --keep-source not set $source_dir = SOURCE_PATH . '/php-src'; if (!$this->getOption('keep-source') && is_dir($source_dir)) { @@ -79,10 +83,10 @@ public function handle(): int InteractiveTerm::finish('Removed: ' . $source_dir); } - // Extension sources are extracted to source/ext-* and linked into php-src/ext, so their - // build state (objects, dependency files, patched config.m4, phpize leftovers) lives - // outside source/php-src and is only valid for the PHP version that produced it. - $this->cleanExtensionSources(); + // Extension sources are extracted to source/ and linked into php-src/ext, so their build + // state (objects, dependency files, patched config.m4, phpize leftovers) lives outside + // source/php-src and is only valid for the PHP version that produced it. + $this->cleanExtensionSources($linked_extension_sources); // Download new PHP source $this->output->writeln("Downloading PHP {$php_ver} source..."); @@ -115,14 +119,29 @@ public function handle(): int } /** - * Delete every extracted extension source tree under source/ext-*, returning the count. + * Delete the extracted extension source trees of the previous PHP version, returning the count. + * + * Targets are the source/ext-* directories plus any extra source roots passed in (usually the + * ones linked into php-src/ext, see collectLinkedExtensionSources()). * + * @param string[] $extra_source_dirs Additional source roots to remove + * @return int Number of removed source trees * @throws ExecutionException When an extracted tree cannot be removed completely */ - public static function removeExtensionSources(string $source_path): int + public static function removeExtensionSources(string $source_path, array $extra_source_dirs = []): int { - $removed = 0; + $targets = []; foreach (glob(FileSystem::convertPath("{$source_path}/ext-*"), GLOB_ONLYDIR) ?: [] as $ext_dir) { + $targets[$ext_dir] = true; + } + foreach ($extra_source_dirs as $extra_dir) { + if (is_dir($extra_dir) || FileSystem::isLink($extra_dir)) { + $targets[FileSystem::convertPath($extra_dir)] = true; + } + } + + $removed = 0; + foreach (array_keys($targets) as $ext_dir) { if (FileSystem::isLink($ext_dir)) { $ok = FileSystem::removeLink($ext_dir); } else { @@ -143,16 +162,58 @@ public static function removeExtensionSources(string $source_path): int } /** - * Remove the extracted extension source trees (source/ext-*) of the previous PHP version. + * Collect the extracted source trees linked into source/php-src/ext. + * + * Extension artifacts are extracted under source/ with their artifact name, which is not + * necessarily "ext-" (e.g. the glfw extension uses source/glfw), so cleaning + * source/ext-* alone misses them. Their build state (objects, .dep files, patched configure + * scripts) is only valid for the PHP version that produced it and must be dropped together + * with php-src, otherwise stale dependency files leak into the next version's build. + * + * Must be called before source/php-src is removed. + * + * @return string[] Absolute source root paths managed by spc inside source/ + */ + public static function collectLinkedExtensionSources(string $source_path): array + { + $source_real = realpath($source_path); + $source_root = rtrim(FileSystem::convertPath($source_real !== false ? $source_real : $source_path), '/\\') . DIRECTORY_SEPARATOR; + $php_src_dir = $source_root . 'php-src' . DIRECTORY_SEPARATOR; + $found = []; + + foreach (glob($php_src_dir . 'ext' . DIRECTORY_SEPARATOR . '*') ?: [] as $link_dir) { + if (!FileSystem::isLink($link_dir)) { + continue; + } + $target = realpath($link_dir); + if ($target === false) { + continue; + } + $target = FileSystem::convertPath($target); + // Only remove sources spc manages under source/: never a user-provided local tree, + // and never something inside php-src itself (removed separately). + if (!str_starts_with($target, $source_root) || str_starts_with($target, $php_src_dir)) { + continue; + } + $found[$target] = true; + } + + return array_keys($found); + } + + /** + * Remove the extracted extension source trees of the previous PHP version. * * Extension sources are linked into php-src/ext for in-tree builds, so their objects, * dependency files, patched config.m4 and phpize leftovers live outside source/php-src and * would otherwise leak into the next PHP version's build. The original archives stay in * downloads/ and are re-extracted automatically on the next build. + * + * @param string[] $linked_source_dirs Source roots collected before php-src removal */ - private function cleanExtensionSources(): void + private function cleanExtensionSources(array $linked_source_dirs = []): void { - $removed = self::removeExtensionSources(SOURCE_PATH); + $removed = self::removeExtensionSources(SOURCE_PATH, $linked_source_dirs); if ($removed > 0) { $this->output->writeln("Removed {$removed} extracted extension source director" . ($removed === 1 ? 'y' : 'ies') . '; they will be re-extracted from the cached archives on the next build.'); diff --git a/src/Package/Target/php/unix.php b/src/Package/Target/php/unix.php index f4e4e1e93..70bd27433 100644 --- a/src/Package/Target/php/unix.php +++ b/src/Package/Target/php/unix.php @@ -158,6 +158,15 @@ public function configureForUnix(TargetPackage $package, PackageInstaller $insta if (SystemTarget::getTargetOS() === 'Darwin') { $frameworks = $config_util->getFrameworksString($resolved_package_names); $libs = trim("{$libs} {$frameworks}"); + + // ext/gettext's probe (AC_CHECK_LIB(intl, bindtextdomain)) links the static + // libintl.a built by us, which references GNU libiconv symbols + // (_libiconv/_libiconv_open) because gettext is configured with + // --with-iconv-prefix. macOS libc has no gettext, so the probe cannot fall back + // to -lc and fails with "Unable to find required gettext library". + if ($installer->isPackageResolved('gettext') && $installer->getLibraryPackage('libiconv') !== null) { + $libs = trim("{$libs} -liconv -lcharset"); + } } // run ./configure with args @@ -231,6 +240,7 @@ public function makeForUnix(TargetPackage $package, PackageInstaller $installer) { logger()->info('cleaning up php-src build files'); shell()->cd($package->getSourceDir())->exec('make clean'); + $this->cleanLinkedExtensionBuildState($package->getSourceDir()); if ($installer->isPackageResolved('php-cli')) { $package->runStage([self::class, 'makeCliForUnix']); @@ -659,6 +669,42 @@ public function smokeTestEmbedForUnix(PackageInstaller $installer, ToolchainInte } } + /** + * Remove build artifacts that `make clean` cannot reach. + * + * Extension sources are linked into php-src/ext (symlinks on Unix, junctions on Windows), so + * the `find` commands of `make clean` do not descend into them: *.lo/*.o/*.dep files from an + * earlier build survive. Stale .dep files are not just garbage - they carry absolute header + * prerequisites of the tree that produced them, so a build after a PHP version switch can + * fail with "No rule to make target .../main/php_config.h" (or silently reuse stale objects). + * + * @param string $php_src_dir The extracted php-src directory + */ + protected function cleanLinkedExtensionBuildState(string $php_src_dir): void + { + $php_src_dir = FileSystem::convertPath($php_src_dir); + $php_src_real = realpath($php_src_dir); + if ($php_src_real === false) { + return; + } + $php_src_prefix = rtrim(FileSystem::convertPath($php_src_real), '/\\') . DIRECTORY_SEPARATOR; + + foreach (glob($php_src_dir . '/ext/*') ?: [] as $link_dir) { + if (!FileSystem::isLink($link_dir)) { + continue; + } + $target = realpath($link_dir); + if ($target === false) { + continue; + } + $target = FileSystem::convertPath($target); + if (str_starts_with($target . DIRECTORY_SEPARATOR, $php_src_prefix)) { + continue; + } + self::removeExtensionBuildArtifacts($target); + } + } + /** * Seek php-src/config.log when building PHP, add it to exception. */ @@ -695,6 +741,36 @@ protected function generateMicroExtTests(PackageInstaller $installer): string return $php; } + /** + * Recursively delete libtool/compiler build artifacts (*.lo, *.o, *.dep, *.la, .libs/) inside + * an out-of-tree extension source root. Links themselves are left untouched. + * + * @param string $dir Directory to clean + */ + private static function removeExtensionBuildArtifacts(string $dir): void + { + foreach (scandir($dir) ?: [] as $item) { + if ($item === '.' || $item === '..' || $item === '.git') { + continue; + } + $path = $dir . DIRECTORY_SEPARATOR . $item; + if (is_link($path)) { + continue; + } + if (is_dir($path)) { + if ($item === '.libs') { + FileSystem::removeDir($path); + continue; + } + self::removeExtensionBuildArtifacts($path); + continue; + } + if (preg_match('/\.(?:lo|o|dep|la)$/', $item) === 1) { + @unlink($path); + } + } + } + /** * Remove the extra segment appended by UPX when packing phpmicro. */ From a646e756518a766990067d7e596b9d4a8d7da313 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Tue, 10 Nov 2026 18:35:00 +0800 Subject: [PATCH 11/12] fix(imagemagick): retarget generated VisualMagick projects to Windows 10 --- src/Package/Library/imagemagick.php | 40 ++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Package/Library/imagemagick.php b/src/Package/Library/imagemagick.php index 935c17c8c..63d8e218a 100644 --- a/src/Package/Library/imagemagick.php +++ b/src/Package/Library/imagemagick.php @@ -59,6 +59,8 @@ public function buildWin(LibraryPackage $lib): void cmd()->cd("{$work}\\Configure") ->exec("Configure.Release.x64.exe /noWizard {$vs_arg} /x64 /static /linkRuntime /noOpenMP /zeroConfigurationSupport"); + self::retargetGeneratedProjectsToWindows10($work); + // x64 IM7 defaults to a 64-bit channel mask, whose magick-baseconfig.h #errors unless the // consuming translation unit is C++. ext-imagick is plain C, so force a 32-bit channel mask // (ample: 32 channels >> RGBA/CMYK) before building, keeping libs and the installed header in sync. @@ -169,7 +171,8 @@ public function buildUnix(LibraryPackage $lib, ToolchainInterface $toolchain): v * * Those functions are resolved dynamically with GetProcAddress, so only the opaque cookie * type declaration is missing: provide the DECLARE_HANDLE-compatible definition for Win7 - * targets. No-op when the vendored cairo no longer needs it (patch string not found). + * targets. No-op when the vendored cairo no longer needs it (patch string not found) and when + * the projects were retargeted to Windows 10 with retargetGeneratedProjectsToWindows10(). */ private static function patchCairoWin7MtaUsage(string $work): void { @@ -188,4 +191,39 @@ private static function patchCairoWin7MtaUsage(string $work): void . '#endif' . "\n", ); } + + /** + * Retarget the generated VisualMagick projects from the Configure release's Windows 7 default + * (_WIN32_WINNT=0x0601) to Windows 10 (_WIN32_WINNT=0x0A00). + * + * With _WIN32_WINNT >= _WIN32_WINNT_WIN10 the Windows SDK sets NTDDI_VERSION to + * WDK_NTDDI_VERSION instead of deriving it from _WIN32_WINNT, which is what un-hides the + * DirectWrite RS1/RS3 declarations cairo needs. Configure writes the definition into every + * generated *.vcxproj, so patching those keeps the rest of the generation untouched. + * + * @param string $work VisualMagick work directory (contains ProjectFiles/) + */ + private static function retargetGeneratedProjectsToWindows10(string $work): void + { + $project_files = FileSystem::scanDirFiles("{$work}/ProjectFiles"); + if ($project_files === false) { + logger()->debug("No VisualMagick ProjectFiles in {$work}; skipping _WIN32_WINNT retarget"); + return; + } + + $win7_define = '_WIN32_WINNT=0x0601'; + $win10_define = '_WIN32_WINNT=0x0A00'; + $retargeted = 0; + foreach ($project_files as $project) { + if (!str_ends_with($project, '.vcxproj')) { + continue; + } + if (!str_contains(FileSystem::readFile($project), $win7_define)) { + continue; + } + FileSystem::replaceFileStr($project, $win7_define, $win10_define); + ++$retargeted; + } + logger()->debug("Retargeted {$retargeted} VisualMagick project(s) to {$win10_define}"); + } } From 82f1cda154dd8450a7c8278ae8e06aa1c074bb67 Mon Sep 17 00:00:00 2001 From: crazywhalecc Date: Thu, 12 Nov 2026 15:24:23 +0800 Subject: [PATCH 12/12] fix(SwitchPhpVersionCommand): replace ExecutionException with FileSystemException for directory removal errors --- .../Command/SwitchPhpVersionCommand.php | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/Package/Command/SwitchPhpVersionCommand.php b/src/Package/Command/SwitchPhpVersionCommand.php index df7656da7..6a745904b 100644 --- a/src/Package/Command/SwitchPhpVersionCommand.php +++ b/src/Package/Command/SwitchPhpVersionCommand.php @@ -10,7 +10,7 @@ use StaticPHP\Artifact\DownloaderOptions; use StaticPHP\Command\BaseCommand; use StaticPHP\DI\ApplicationContext; -use StaticPHP\Exception\ExecutionException; +use StaticPHP\Exception\FileSystemException; use StaticPHP\Registry\PackageLoader; use StaticPHP\Util\FileSystem; use StaticPHP\Util\InteractiveTerm; @@ -72,7 +72,7 @@ public function handle(): int FileSystem::removeDir($source_dir); if (file_exists($source_dir)) { InteractiveTerm::finish('Failed: ' . $source_dir, false); - throw new ExecutionException( + throw new FileSystemException( "Failed to remove the extracted PHP source directory: {$source_dir}\n" . 'The PHP version switch was aborted: continuing would build the new PHP on top of ' . 'stale sources and object files from the previous version (wrong headers/ABI, ' . @@ -124,9 +124,9 @@ public function handle(): int * Targets are the source/ext-* directories plus any extra source roots passed in (usually the * ones linked into php-src/ext, see collectLinkedExtensionSources()). * - * @param string[] $extra_source_dirs Additional source roots to remove - * @return int Number of removed source trees - * @throws ExecutionException When an extracted tree cannot be removed completely + * @param string[] $extra_source_dirs Additional source roots to remove + * @return int Number of removed source trees + * @throws FileSystemException When an extracted tree cannot be removed completely */ public static function removeExtensionSources(string $source_path, array $extra_source_dirs = []): int { @@ -140,21 +140,36 @@ public static function removeExtensionSources(string $source_path, array $extra_ } } + // A linked source root can be nested inside an extracted tree: artifacts declaring + // "source-root: ext" (e.g. ext-opentelemetry, ext-swow) link source//ext while the + // glob above also collects the parent source/. Removing the parent already removes + // the child, so process short paths first and skip anything below a tree we just removed. + $paths = array_keys($targets); + usort($paths, static fn (string $a, string $b): int => strlen($a) <=> strlen($b)); + $removed_roots = []; + $removed = 0; - foreach (array_keys($targets) as $ext_dir) { + foreach ($paths as $ext_dir) { + $normalized = rtrim(FileSystem::convertPath($ext_dir), '/\\'); + foreach ($removed_roots as $removed_root) { + if (str_starts_with($normalized . DIRECTORY_SEPARATOR, $removed_root . DIRECTORY_SEPARATOR)) { + continue 2; + } + } if (FileSystem::isLink($ext_dir)) { $ok = FileSystem::removeLink($ext_dir); } else { $ok = FileSystem::removeDir($ext_dir); } if (!$ok || file_exists($ext_dir) || FileSystem::isLink($ext_dir)) { - throw new ExecutionException( + throw new FileSystemException( "Failed to remove extracted extension source directory: {$ext_dir}\n" . 'Its build state (objects, generated headers, patched sources) is only valid for the ' . 'PHP version that produced it and would leak into the next build.' . "\n" . 'Remove it manually (on Windows: rmdir /s /q "' . FileSystem::convertPath($ext_dir) . '") and retry.', ); } + $removed_roots[] = $normalized; ++$removed; }