diff --git a/config/env.ini b/config/env.ini index ea78e7666..c72ebdf8e 100644 --- a/config/env.ini +++ b/config/env.ini @@ -154,7 +154,7 @@ LD=${SPC_DEFAULT_LD} ; default compiler flags, used in CMake toolchain file, openssl and pkg-config build SPC_DEFAULT_CFLAGS="--target=${MAC_ARCH}-apple-darwin -O3 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections" SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}" -SPC_DEFAULT_LDFLAGS="-Wl,-dead_strip" +SPC_DEFAULT_LDFLAGS="" ; phpmicro patches, for more info, see: https://github.com/easysoft/phpmicro/tree/master/patches SPC_MICRO_PATCHES=cli_checks,macos_iconv diff --git a/config/pkg/ext/ext-pqcrypto.yml b/config/pkg/ext/ext-pqcrypto.yml new file mode 100644 index 000000000..dbbc4739c --- /dev/null +++ b/config/pkg/ext/ext-pqcrypto.yml @@ -0,0 +1,18 @@ +ext-pqcrypto: + type: php-extension + artifact: + source: + type: ghtagtar + repo: paragonie/ext-pqcrypto + match: /v\d+\.\d+\.\d+$ + metadata: + license-files: [LICENSE] + license: ISC + php-extension: + build-shared: true + native-libc: true + os: + - Linux + - Darwin + support: + Windows: 'no' diff --git a/config/pkg/target/rust.yml b/config/pkg/target/rust.yml deleted file mode 100644 index f2e107380..000000000 --- a/config/pkg/target/rust.yml +++ /dev/null @@ -1,6 +0,0 @@ -rust: - type: target - artifact: - binary: custom - path: - - '{pkg_root_path}/rust/bin' diff --git a/docs/en/develop/doctor-module.md b/docs/en/develop/doctor-module.md index 083f2483c..4e561b1ce 100644 --- a/docs/en/develop/doctor-module.md +++ b/docs/en/develop/doctor-module.md @@ -54,6 +54,7 @@ The exact list is target-aware. The current core Registry provides these groups: | Common | At least one Registry is loaded; the host OS is Linux, macOS, or Windows | | Linux | Distribution build-tool baseline, CMake 3.22+, `re2c` 1.0.3+, and Linux headers on musl distributions | | macOS | Homebrew or MacPorts, required build commands, GNU Bison 3+, and the selected Homebrew/MacPorts LLVM variant | +| Linux and macOS with `--with-rust` | Host Rust tools and libclang | | Windows target | `vswhere`, Visual Studio C++ tools, Git `patch.exe`, managed MSYS2, `7za.exe`, and the initialized MSVC command environment | | Unix target | StaticPHP-managed and functional `pkg-config` | | Zig toolchain | Installed StaticPHP `zig` tool package | diff --git a/docs/en/develop/package-model.md b/docs/en/develop/package-model.md index 13745f845..c3cb4db3c 100644 --- a/docs/en/develop/package-model.md +++ b/docs/en/develop/package-model.md @@ -111,6 +111,8 @@ ext-{ext-name}: # Package name must start with ext- prefix build-static: true # Optional, whether inline static building (compiled into PHP) is allowed, default true build-with-php: true # Optional, true means the extension is built together via the PHP source tree # (used for built-in extensions) + native-libc: true # Optional, true means the build links host objects (e.g. Rust via + # ext-php-rs), so the target libc must match the build host; default false # display-name affects the php --ri argument in smoke tests and the license export display name # If not set, defaults to the extension name (the part after ext-); if set to empty string, skips --ri check @@ -215,7 +217,7 @@ Allowed fields for `library`: # List of directories injected into the global PATH after the package is installed. # Path placeholders are supported (see below for details). path: - - '{pkg_root_path}/rust/bin' + - '{pkg_root_path}/my-tool/bin' # Environment variables set after the package is installed (overwrites existing values). # Path placeholders are supported. diff --git a/docs/en/develop/performance.md b/docs/en/develop/performance.md index 9ddd88536..f751f3b67 100644 --- a/docs/en/develop/performance.md +++ b/docs/en/develop/performance.md @@ -9,7 +9,7 @@ One caveat up front: no build configuration is fastest for every workload. Resul A default StaticPHP build is already an optimized build. Without passing any extra flags you get: - **`-O3` optimization** for PHP and all dependency libraries, favoring runtime speed over compile time and code size. -- **Dead code elimination**: `-ffunction-sections -fdata-sections` combined with `--gc-sections` (Linux) or `-Wl,-dead_strip` (macOS) removes unused functions and data, keeping binaries smaller. +- **Dead code elimination**: `-ffunction-sections -fdata-sections` combined with `--gc-sections` on Linux removes unused functions and data, keeping binaries smaller. macOS does not enable dead stripping by default: symbols that appear unused to the static linker may still be referenced by dynamically loaded shared extensions, so retaining them preserves extension compatibility. - **Cheaper ELF symbol handling** on Linux: `-fno-semantic-interposition` and `-fno-plt` let the compiler avoid indirection that only matters for interposable shared libraries. - **Link hardening** on Linux: `relro`, `-z now`, `noexecstack`, `--as-needed`. - **Link-time code generation on Windows**: StaticPHP rewrites the final CLI/CGI/micro/embed link rules to include `/LTCG`. diff --git a/docs/en/develop/system-build-tools.md b/docs/en/develop/system-build-tools.md index f3be79788..45f6558c2 100644 --- a/docs/en/develop/system-build-tools.md +++ b/docs/en/develop/system-build-tools.md @@ -152,12 +152,14 @@ During a build, `PKG_CONFIG_PATH` starts with `buildroot/lib/pkgconfig`, and Sta ## Package Build Executors -Package classes use three common executor implementations: +Package classes use the following build executors. | Executor | Platform and build system | Current behavior | |---|---|---| | `UnixAutoconfExecutor` | Linux/macOS, Autoconf | Adds static/PIC and `buildroot` prefix arguments, runs `configure`, parallel `make`, and optionally `make install` | | `UnixCMakeExecutor` | Linux/macOS, CMake | Generates a toolchain file rooted at `buildroot`, pins StaticPHP's compilers and pkg-config, disables shared libraries, then configures, builds, and installs | +| `UnixCargoExecutor` | Linux/macOS, Cargo | Runs locked release builds with the host's Rust toolchain and resolves CFLAGS for the selected C toolchain. Returns the Cargo release directory | +| `UnixExtPhpRsExecutor` | Native Linux/macOS, ext-php-rs | Builds shared and static Rust extensions. For static builds, StaticPHP automatically builds a matching PHP CLI and headers for bindgen when needed. | | `WindowsCMakeExecutor` | Windows, CMake/MSVC | Uses the x64 Visual Studio generator, the static MSVC runtime, a StaticPHP CMake toolchain file, and `cmake --build --target install` | The executors initialize package-specific include, library, and environment paths and use the configured build concurrency. Unix Autoconf failures preserve `config.log`, and the Unix CMake executor copies available configure/error/output logs to `SPC_LOGS_DIR`. The Windows CMake executor currently relies on the general shell and output logs instead of collecting those CMake files separately. diff --git a/docs/en/guide/cli-reference.md b/docs/en/guide/cli-reference.md index eadac773b..1c12d277d 100644 --- a/docs/en/guide/cli-reference.md +++ b/docs/en/guide/cli-reference.md @@ -236,13 +236,14 @@ If no path is given, `craft.yml` in the current working directory is used. See [ Diagnose whether the current environment can compile PHP normally. ```bash -spc doctor [--auto-fix[=never]] +spc doctor [--auto-fix[=never]] [--with-rust] ``` | Option | Description | |--------------------|--------------------------------------------------------------------| | `--auto-fix` | Automatically fix detected issues using the system package manager | | `--auto-fix=never` | Report issues but never attempt automatic fixes | +| `--with-rust` | Check and install Rust tools | ## dev:shell diff --git a/docs/zh/develop/doctor-module.md b/docs/zh/develop/doctor-module.md index bbe34f7c2..4353a6ec7 100644 --- a/docs/zh/develop/doctor-module.md +++ b/docs/zh/develop/doctor-module.md @@ -52,6 +52,7 @@ bin/spc doctor | 通用 | 至少加载了一个 Registry;宿主 OS 是 Linux、macOS 或 Windows | | Linux | 发行版构建工具基线、CMake 3.22+、`re2c` 1.0.3+,以及 musl 发行版的 Linux headers | | macOS | Homebrew 或 MacPorts、必需构建命令、GNU Bison 3+,以及选定的 Homebrew/MacPorts LLVM 变体 | +| Linux 和 macOS,启用 `--with-rust` | 宿主机的 Rust 工具和 libclang | | Windows target | `vswhere`、Visual Studio C++ 工具、Git `patch.exe`、受管理的 MSYS2、`7za.exe` 和初始化后的 MSVC 命令环境 | | Unix target | 由 StaticPHP 管理且可以正常执行的 `pkg-config` | | Zig toolchain | 已安装 StaticPHP 的 `zig` Tool Package | diff --git a/docs/zh/develop/package-model.md b/docs/zh/develop/package-model.md index 2ede9eb1c..e7052e4d4 100644 --- a/docs/zh/develop/package-model.md +++ b/docs/zh/develop/package-model.md @@ -108,6 +108,8 @@ ext-{ext-name}: # 包名必须以 ext- 前缀开头 build-shared: true # 可选,是否允许构建为共享扩展(.so),默认 true build-static: true # 可选,是否允许内联静态构建(编译进 PHP),默认 true build-with-php: true # 可选,true 表示该扩展通过 PHP 源码树一同编译(内置扩展使用) + native-libc: true # 可选,true 表示构建会链接宿主机对象文件(如通过 ext-php-rs 的 Rust), + # 因此目标 libc 必须与构建宿主机一致;默认 false # display-name 影响 smoke test 中 php --ri 的参数及许可证导出显示名称 # 不填时默认使用扩展名(ext- 后缀部分);填空字符串则跳过 --ri 检查 @@ -208,7 +210,7 @@ openssl: # 包安装完成后注入到全局 PATH 的目录列表,支持路径占位符(见下方说明) path: - - '{pkg_root_path}/rust/bin' + - '{pkg_root_path}/my-tool/bin' # 包安装完成后设置的环境变量(覆盖已有值),支持路径占位符 env: diff --git a/docs/zh/develop/performance.md b/docs/zh/develop/performance.md index e623289dc..b7e80069c 100644 --- a/docs/zh/develop/performance.md +++ b/docs/zh/develop/performance.md @@ -9,7 +9,7 @@ 默认的 StaticPHP 构建就是优化过的构建。不传任何额外参数,你就能得到: - **`-O3` 优化**:PHP 和所有依赖库都偏向运行速度而非编译时间和代码体积。 -- **无用代码消除**:`-ffunction-sections -fdata-sections` 配合 `--gc-sections`(Linux)或 `-Wl,-dead_strip`(macOS),移除未使用的函数和数据,保持二进制精简。 +- **无用代码消除**:在 Linux 上,`-ffunction-sections -fdata-sections` 配合 `--gc-sections` 可移除未使用的函数和数据,让二进制更精简。macOS 默认不启用 dead stripping:静态链接器认为未使用的符号仍可能被动态加载的共享扩展引用,因此保留这些符号有助于确保扩展兼容性。 - **更低成本的 ELF 符号处理**(Linux):`-fno-semantic-interposition` 和 `-fno-plt` 避免只在可插入(interposable)共享库场景下才需要的间接调用。 - **链接加固**(Linux):`relro`、`-z now`、`noexecstack`、`--as-needed`。 - **Windows 链接时代码生成**:StaticPHP 改写最终 CLI/CGI/micro/embed 的链接规则并加入 `/LTCG`。 diff --git a/docs/zh/develop/system-build-tools.md b/docs/zh/develop/system-build-tools.md index e02c14c17..fb7500e91 100644 --- a/docs/zh/develop/system-build-tools.md +++ b/docs/zh/develop/system-build-tools.md @@ -152,12 +152,14 @@ Doctor 可以通过 `pkg-config` 工具 Package 安装预构建版本。如果 ## Package 构建 Executor -Package 类使用三种通用 Executor 实现: +Package 类使用以下构建 Executor。 | Executor | 平台与构建系统 | 当前行为 | |---|---|---| | `UnixAutoconfExecutor` | Linux/macOS,Autoconf | 添加静态/PIC 和 `buildroot` 前缀参数,执行 `configure`、并行 `make`,并可选执行 `make install` | | `UnixCMakeExecutor` | Linux/macOS,CMake | 生成以 `buildroot` 为根的 toolchain 文件,固定使用 StaticPHP 的编译器和 pkg-config,禁用共享库,然后执行配置、构建和安装 | +| `UnixCargoExecutor` | Linux/macOS,Cargo | 使用宿主机的 Rust 工具链执行锁定依赖版本的 release 构建,根据所选 C 工具链解析 CFLAGS,并返回 Cargo release 输出目录 | +| `UnixExtPhpRsExecutor` | Linux/macOS 原生构建,ext-php-rs | 构建共享和静态 Rust 扩展。静态构建时,StaticPHP 会按需自动构建与目标配置匹配的 PHP CLI 和头文件,供 bindgen 使用。 | | `WindowsCMakeExecutor` | Windows,CMake/MSVC | 使用 x64 Visual Studio generator、静态 MSVC runtime 和 StaticPHP CMake toolchain 文件,并执行 `cmake --build --target install` | Executor 会初始化 Package 专属的 include、library 和环境路径,并使用配置的构建并发数。Unix Autoconf 失败时会保留 `config.log`,Unix CMake Executor 会把可用的配置/错误/输出日志复制到 `SPC_LOGS_DIR`。Windows CMake Executor 当前依赖通用 shell 和 output 日志,不会另行收集这些 CMake 文件。 diff --git a/docs/zh/guide/cli-reference.md b/docs/zh/guide/cli-reference.md index 956c19237..844790e10 100644 --- a/docs/zh/guide/cli-reference.md +++ b/docs/zh/guide/cli-reference.md @@ -236,13 +236,14 @@ spc craft [path/to/craft.yml] 检查当前环境是否满足编译要求。 ```bash -spc doctor [--auto-fix[=never]] +spc doctor [--auto-fix[=never]] [--with-rust] ``` | 选项 | 说明 | |--------------------|----------------------| | `--auto-fix` | 自动修复检测到的问题(使用系统包管理器) | | `--auto-fix=never` | 仅报告问题,不尝试自动修复 | +| `--with-rust` | 检查并安装 Rust 工具 | ## dev:shell diff --git a/src/Package/Artifact/rust.php b/src/Package/Artifact/rust.php deleted file mode 100644 index cca50c058..000000000 --- a/src/Package/Artifact/rust.php +++ /dev/null @@ -1,85 +0,0 @@ -executeCurl('https://static.rust-lang.org/dist/channel-rust-stable.toml', retries: $downloader->getRetry()); - // parse toml by regex since we want to avoid adding a toml parser dependency just for this - $cnt = preg_match_all('/^version = "([^"]+)"$/m', $toml_config ?: '', $matches); - if (!$cnt) { - throw new DownloaderException('Failed to parse Rust version from channel config'); - } - $versions = $matches[1]; - // strip version num \d.\d.\d (some version number is like "x.x.x (abcdefg 1970-01-01)" - $versions = array_filter(array_map(fn ($v) => preg_match('/^(\d+\.\d+\.\d+)/', $v, $m) ? $m[1] : null, $versions)); - usort($versions, 'version_compare'); - $latest_version = end($versions); - if (!$latest_version) { - throw new DownloaderException('Could not determine latest Rust version'); - } - - // merge download link - $download_url = "https://static.rust-lang.org/dist/rust-{$latest_version}-{$arch}-unknown-linux-{$distro}.tar.xz"; - $path = DOWNLOAD_PATH . DIRECTORY_SEPARATOR . basename($download_url); - default_shell()->executeCurlDownload($download_url, $path, retries: $downloader->getRetry()); - return DownloadResult::archive(basename($path), ['url' => $download_url, 'version' => $latest_version], extract: '{pkg_root_path}/rust-install', verified: false, version: $latest_version); - } - - #[CustomBinaryCheckUpdate('rust', [ - 'linux-x86_64', - 'linux-aarch64', - ])] - public function checkUpdateBinary(?string $old_version, ArtifactDownloader $downloader): CheckUpdateResult - { - $toml_config = default_shell()->executeCurl('https://static.rust-lang.org/dist/channel-rust-stable.toml', retries: $downloader->getRetry()); - $cnt = preg_match_all('/^version = "([^"]+)"$/m', $toml_config ?: '', $matches); - if (!$cnt) { - throw new DownloaderException('Failed to parse Rust version from channel config'); - } - $versions = array_filter(array_map(fn ($v) => preg_match('/^(\d+\.\d+\.\d+)/', $v, $m) ? $m[1] : null, $matches[1])); - usort($versions, 'version_compare'); - $latest_version = end($versions); - if (!$latest_version) { - throw new DownloaderException('Could not determine latest Rust version'); - } - return new CheckUpdateResult( - old: $old_version, - new: $latest_version, - needUpdate: $old_version === null || $latest_version !== $old_version, - ); - } - - #[AfterBinaryExtract('rust', [ - 'linux-x86_64', - 'linux-aarch64', - ])] - public function postExtractRust(string $target_path): void - { - $prefix = PKG_ROOT_PATH . '/rust'; - shell()->exec("cd {$target_path} && ./install.sh --prefix={$prefix}"); - } -} diff --git a/src/Package/Extension/pqcrypto.php b/src/Package/Extension/pqcrypto.php new file mode 100644 index 000000000..a1d460297 --- /dev/null +++ b/src/Package/Extension/pqcrypto.php @@ -0,0 +1,43 @@ +validate(); + } + + public function getInTreeSourceRoot(): string + { + return $this->isBuildStatic() ? (new UnixExtPhpRsExecutor($this))->prepareGlue() : $this->getSourceRoot(); + } + + #[BeforeStage('php', [php::class, 'configureForUnix'], 'ext-pqcrypto')] + public function buildStatic(php $package): void + { + if ($this->isBuildStatic()) { + (new UnixExtPhpRsExecutor($this))->buildStatic($package); + } + } + + #[BuildFor('Linux')] + #[BuildFor('Darwin')] + public function build(): void + { + (new UnixExtPhpRsExecutor($this))->buildShared(); + } +} diff --git a/src/Package/Target/php.php b/src/Package/Target/php.php index 764bb5964..d3d4462cb 100644 --- a/src/Package/Target/php.php +++ b/src/Package/Target/php.php @@ -423,7 +423,7 @@ public function syncExtensionSources(PackageInstaller $installer): void if ($ext->getArtifact() === null) { continue; } - $source_root = $ext->getSourceRoot(); + $source_root = $ext->getInTreeSourceRoot(); if (!is_dir($source_root)) { continue; } diff --git a/src/Package/Target/php/unix.php b/src/Package/Target/php/unix.php index f45bbc252..d8e3e0583 100644 --- a/src/Package/Target/php/unix.php +++ b/src/Package/Target/php/unix.php @@ -88,7 +88,7 @@ public function buildconfForUnix(TargetPackage $package): void } #[Stage] - public function configureForUnix(TargetPackage $package, PackageInstaller $installer): void + public function configureForUnix(TargetPackage $package, PackageInstaller $installer, bool $bootstrap_cli = false): void { InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./configure')); $cmd = getenv('SPC_CMD_PREFIX_PHP_CONFIGURE'); @@ -150,7 +150,7 @@ public function configureForUnix(TargetPackage $package, PackageInstaller $insta $args[] = getenv('SPC_EXTRA_PHP_VARS') ?: null; $args = implode(' ', array_filter($args)); - $static_extension_str = $this->makeStaticExtensionString($installer); + $static_extension_str = $bootstrap_cli ? '--enable-cli' : $this->makeStaticExtensionString($installer); $configure_str = "{$cmd} {$args} {$static_extension_str}"; if ($version_id >= 80600) { @@ -247,14 +247,17 @@ public function patchInfoCForRelease(): void } #[Stage] - public function makeForUnix(TargetPackage $package, PackageInstaller $installer): void + public function makeForUnix(TargetPackage $package, PackageInstaller $installer, bool $bootstrap_cli = false): void { 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']); + if ($bootstrap_cli || $installer->isPackageResolved('php-cli')) { + $package->runStage([self::class, 'makeCliForUnix'], ['deploy' => !$bootstrap_cli]); + } + if ($bootstrap_cli) { + return; } if ($installer->isPackageResolved('php-cgi')) { $package->runStage([self::class, 'makeCgiForUnix']); @@ -271,7 +274,7 @@ public function makeForUnix(TargetPackage $package, PackageInstaller $installer) } #[Stage] - public function makeCliForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void + public function makeCliForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder, bool $deploy = true): void { InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make cli')); $concurrency = $builder->concurrency; @@ -281,8 +284,10 @@ public function makeCliForUnix(TargetPackage $package, PackageInstaller $install ->setEnv($vars) ->exec("make -j{$concurrency} {$makeArgs} cli"); - $builder->deployBinary("{$package->getSourceDir()}/sapi/cli/php", BUILD_BIN_PATH . '/php'); - $package->setOutput('Binary path for cli SAPI', BUILD_BIN_PATH . '/php'); + if ($deploy) { + $builder->deployBinary("{$package->getSourceDir()}/sapi/cli/php", BUILD_BIN_PATH . '/php'); + $package->setOutput('Binary path for cli SAPI', BUILD_BIN_PATH . '/php'); + } } #[Stage] diff --git a/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php b/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php index 4b936547a..8db394008 100644 --- a/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php +++ b/src/StaticPHP/Command/Dev/GenExtTestMatrixCommand.php @@ -276,7 +276,15 @@ private function buildEntriesForRunners( $covered = []; $groups = []; $orphans = []; - $standalone_set = array_fill_keys(self::STANDALONE, true); + // Extensions that link host objects (php-extension.native-libc) cannot target a libc + // different from the runner's, so they always get their own entry. + $host_libc_set = []; + foreach ($os_regular as $pkg_name => $config) { + if ($config['php-extension']['native-libc'] ?? false) { + $host_libc_set[$this->displayName($pkg_name)] = true; + } + } + $standalone_set = array_fill_keys(array_merge(self::STANDALONE, array_keys($host_libc_set)), true); $standalone_isolated = self::STANDALONE_ISOLATED; foreach (array_merge($roots, $non_roots) as $ext) { @@ -325,13 +333,19 @@ private function buildEntriesForRunners( sort($groups); foreach ($groups as $group) { + $build_args = './bin/spc build "' . $group . '" ' . $this->buildTargetsWithExtraFlags($build_targets, $group); + if ($os === 'linux' && $this->requiresHostLibc($group, $host_libc_set)) { + // The default Linux target is static musl, but host objects (Rust/ext-php-rs) + // cannot link into a libc different from the one they were compiled against. + $build_args = 'SPC_TARGET=native-native ' . $build_args; + } $entries[] = [ 'runner' => $os_info['runner'], 'os' => $os, 'arch' => $os_info['arch'], 'sapi' => $sapi, 'extension' => $group, - 'build-args' => './bin/spc build "' . $group . '" ' . $this->buildTargetsWithExtraFlags($build_targets, $group), + 'build-args' => $build_args, ]; } } @@ -463,6 +477,22 @@ private function extraBuildFlags(string $group): string return implode(' ', $flags); } + /** + * Whether a comma-separated extension group contains an extension that must be built + * against the host libc. + * + * @param array $host_libc_set display names keyed for lookup + */ + private function requiresHostLibc(string $group, array $host_libc_set): bool + { + foreach (explode(',', $group) as $name) { + if (isset($host_libc_set[$name])) { + return true; + } + } + return false; + } + private function buildTargetsWithExtraFlags(string $build_targets, string $group): string { $flags = explode(' ', $build_targets); diff --git a/src/StaticPHP/Command/DoctorCommand.php b/src/StaticPHP/Command/DoctorCommand.php index ef4f08266..2d85a63a4 100644 --- a/src/StaticPHP/Command/DoctorCommand.php +++ b/src/StaticPHP/Command/DoctorCommand.php @@ -14,6 +14,7 @@ class DoctorCommand extends BaseCommand public function configure(): void { $this->addOption('auto-fix', 'y', InputOption::VALUE_OPTIONAL, 'Automatically fix failed items (if possible)', false); + $this->addOption('with-rust', null, InputOption::VALUE_NONE, 'Check and install Rust tools'); } public function handle(): int diff --git a/src/StaticPHP/Config/ConfigValidator.php b/src/StaticPHP/Config/ConfigValidator.php index e8dd828b2..80b39d46b 100644 --- a/src/StaticPHP/Config/ConfigValidator.php +++ b/src/StaticPHP/Config/ConfigValidator.php @@ -36,6 +36,7 @@ class ConfigValidator 'build-shared' => ConfigType::BOOL, 'build-static' => ConfigType::BOOL, 'build-with-php' => ConfigType::BOOL, + 'native-libc' => ConfigType::BOOL, 'notes' => ConfigType::BOOL, 'display-name' => ConfigType::STRING, 'os' => ConfigType::LIST_ARRAY, @@ -104,6 +105,7 @@ class ConfigValidator 'build-shared' => false, 'build-static' => false, 'build-with-php' => false, + 'native-libc' => false, 'notes' => false, 'display-name' => false, 'os' => false, diff --git a/src/StaticPHP/Doctor/Item/RustCheck.php b/src/StaticPHP/Doctor/Item/RustCheck.php new file mode 100644 index 000000000..08637f68d --- /dev/null +++ b/src/StaticPHP/Doctor/Item/RustCheck.php @@ -0,0 +1,117 @@ +get(InputInterface::class); + return $input instanceof InputInterface && $input->hasOption('with-rust') && (bool) $input->getOption('with-rust'); + } + + #[CheckItem('if the host Rust toolchain is installed', limit_os: 'Linux')] + #[CheckItem('if the host Rust toolchain is installed', limit_os: 'Darwin')] + public function checkRust(): CheckResult + { + $missing = UnixCargoExecutor::missingCommands(); + if (UnixUtil::findCommand(getenv('RUSTFMT') ?: 'rustfmt') === null) { + $missing[] = 'rustfmt'; + } + if ($missing !== []) { + return CheckResult::fail('Missing Rust tools: ' . implode(', ', $missing), 'install-rust'); + } + + $rustc = getenv('RUSTC') ?: 'rustc'; + [$status, $output] = shell(false)->execWithResult(escapeshellarg($rustc) . ' --version', false); + if ($status !== 0 || !preg_match('/\brustc\s+(\d+\.\d+\.\d+)/', implode("\n", $output), $matches)) { + return CheckResult::fail( + 'Could not determine the Rust compiler version; pqcrypto requires rustc >= ' . self::MINIMUM_RUSTC_VERSION . '. Please upgrade Rust (for example, with rustup).' + ); + } + if (version_compare($matches[1], self::MINIMUM_RUSTC_VERSION, '<')) { + return CheckResult::fail( + 'Rust compiler ' . $matches[1] . ' is too old; pqcrypto requires rustc >= ' . self::MINIMUM_RUSTC_VERSION . '. Please upgrade Rust (for example, with rustup).' + ); + } + + return CheckResult::ok(); + } + + #[FixItem('install-rust')] + public function installRust(): bool + { + if (PHP_OS_FAMILY === 'Darwin') { + $installed = (new MacOSToolCheck())->fixBuildTools(['rust']); + } else { + $distro = LinuxUtil::getOSRelease(); + $family = explode(' ', strtolower($distro['family'])); + $packages = match (true) { + in_array($distro['dist'], ['arch', 'manjaro'], true) || in_array('arch', $family, true) => ['rust'], + LinuxUtil::isDebianDist() => ['rustc', 'cargo', 'rustfmt'], + default => ['rust', 'cargo', 'rustfmt'], + }; + $installed = (new LinuxToolCheck())->fixBuildTools($distro, $packages); + } + return $installed && $this->checkRust()->isOK(); + } + + #[CheckItem('if libclang is installed', limit_os: 'Linux')] + public function checkLinuxLibclang(): CheckResult + { + $distro = LinuxUtil::getOSRelease(); + $family = explode(' ', strtolower($distro['family'])); + if ($distro['dist'] === 'alpine') { + $installed = (glob('/usr/lib/libclang.so*') ?: []) !== []; + } else { + [$status, $libraries] = shell(false)->execWithResult('/sbin/ldconfig -p', false); + $installed = $status === 0 && array_any( + $libraries, + static fn (string $library): bool => preg_match('/^\s*libclang(?:-[\d.]+)?\.so(?:\.[\d.]+)?\s/', $library) === 1 + ); + } + if ($installed) { + return CheckResult::ok(); + } + + $packages = match (true) { + $distro['dist'] === 'alpine' => ['clang-dev'], + in_array($distro['dist'], ['arch', 'manjaro'], true) || in_array('arch', $family, true) => ['clang'], + LinuxUtil::isDebianDist() => ['clang', 'libclang-dev'], + default => ['clang', 'clang-libs'], + }; + return CheckResult::fail('libclang is not installed', 'install-linux-tools', ['distro' => $distro, 'missing' => $packages]); + } + + #[CheckItem('if libclang is installed', limit_os: 'Darwin')] + public function checkMacLibclang(): CheckResult + { + [$status, $output] = shell(false)->execWithResult('xcrun --find clang', false); + $toolchain = dirname(trim($output[0]), 2); + return $status === 0 && is_readable($toolchain . '/lib/libclang.dylib') + ? CheckResult::ok() + : CheckResult::fail('libclang is missing from the selected Xcode toolchain', 'install-xcode-command-line-tools'); + } + + #[FixItem('install-xcode-command-line-tools')] + public function installMacLibclang(): bool + { + shell()->exec('xcode-select --install'); + return $this->checkMacLibclang()->isOK(); + } +} diff --git a/src/StaticPHP/Package/PhpExtensionPackage.php b/src/StaticPHP/Package/PhpExtensionPackage.php index 82613d1fc..f4f08456e 100644 --- a/src/StaticPHP/Package/PhpExtensionPackage.php +++ b/src/StaticPHP/Package/PhpExtensionPackage.php @@ -107,6 +107,11 @@ public function getSourceRoot(): string return parent::getSourceRoot(); } + public function getInTreeSourceRoot(): string + { + return $this->getSourceRoot(); + } + public function getExtensionName(): string { return str_replace('ext-', '', $this->getName()); diff --git a/src/StaticPHP/Runtime/Executor/UnixCargoExecutor.php b/src/StaticPHP/Runtime/Executor/UnixCargoExecutor.php new file mode 100644 index 000000000..ac2860a7d --- /dev/null +++ b/src/StaticPHP/Runtime/Executor/UnixCargoExecutor.php @@ -0,0 +1,77 @@ + $env Build environment overrides + * @return list + */ + public static function missingCommands(array $env = []): array + { + $missing = []; + $paths = isset($env['PATH']) ? explode(PATH_SEPARATOR, $env['PATH']) : []; + $rustc = $env['RUSTC'] ?? (getenv('RUSTC') ?: 'rustc'); + foreach (['cargo' => 'cargo', 'rustc' => $rustc] as $name => $command) { + $path = UnixUtil::findCommand($command, $paths); + if ($path === null || !is_executable($path)) { + $missing[] = $name; + } + } + return $missing; + } + + /** + * Run a locked Cargo release build and return the release directory. + * + * @param array $env Build environment + * @param null|string $rebuild_dependency Cargo package whose cached build output must be invalidated + */ + public function build(array $env = [], ?string $rebuild_dependency = null, bool $staticlib = false): string + { + if (($missing = self::missingCommands($env)) !== []) { + throw new EnvironmentException( + 'Missing Rust build tools: ' . implode(', ', $missing), + 'Run bin/spc doctor --with-rust.' + ); + } + + $source = $this->package->getSourceRoot(); + $arch = SystemTarget::getTargetArch(); + $libc = SystemTarget::getLibc() === 'musl' ? 'musl' : 'gnu'; + $target = SystemTarget::getTargetOS() === 'Darwin' ? "{$arch}-apple-darwin" : "{$arch}-unknown-linux-{$libc}"; + $release_dir = "{$source}/target/{$target}/release"; + $options = '--locked --release --target ' . escapeshellarg($target) . ' --target-dir target'; + + $config = (new SPCConfigUtil(['no_php' => !$this->package instanceof PhpExtensionPackage])) + ->configForResolvedBuild([$this->package->getName()], $this->package->getInstaller()); + $shell = shell()->cd($source)->setEnv(['CFLAGS' => $config['cflags']])->setEnv($env); + if (ToolchainManager::getToolchain() instanceof ZigToolchain) { + // The cc crate adds a Rust target triple that Zig rejects. SPC's wrapper supplies the target. + $shell->setEnv(['CRATE_CC_NO_DEFAULTS' => '1']); + } + + if ($rebuild_dependency !== null && is_dir($release_dir)) { + $shell->exec("cargo clean {$options} -p " . escapeshellarg($rebuild_dependency)); + } + $jobs = $this->package->getBuilder()->concurrency; + $command = $staticlib ? 'cargo rustc --lib --crate-type staticlib' : 'cargo build'; + $shell->exec("{$command} {$options} --jobs {$jobs}"); + + return $release_dir; + } +} diff --git a/src/StaticPHP/Runtime/Executor/UnixExtPhpRsExecutor.php b/src/StaticPHP/Runtime/Executor/UnixExtPhpRsExecutor.php new file mode 100644 index 000000000..36b546234 --- /dev/null +++ b/src/StaticPHP/Runtime/Executor/UnixExtPhpRsExecutor.php @@ -0,0 +1,119 @@ +extension->getName() . ' requires a native build matching the host libc.'); + } + if ($this->extension->isBuildShared() && !$this->extension->getInstaller()->isPackageResolved('php-cli')) { + throw new WrongUsageException($this->extension->getName() . ' requires PHP CLI for bindgen. Use build:php with --build-cli.'); + } + } + + public function prepareGlue(): string + { + $name = $this->extension->getExtensionName(); + $upper = strtoupper($name); + $dir = $this->extension->getSourceRoot() . '/target/php-glue'; + FileSystem::createDir($dir); + FileSystem::writeFile("{$dir}/config.m4", << \$@ + + MAKE); + FileSystem::writeFile("{$dir}/php_{$name}.h", <<extension->getExtensionName(); + $cli = BUILD_BIN_PATH . '/php'; + $version = php::getPHPVersionID(); + $zts = (int) $php->getBuildOption('enable-zts', false); + $headers = BUILD_INCLUDE_PATH . '/php'; + $config = $headers . '/main/php_config.h'; + $probe = escapeshellarg($cli) . " -n -r 'exit((int) (PHP_VERSION_ID !== {$version} || (int) PHP_ZTS !== {$zts}));'"; + if (!is_executable($cli) || !is_executable(BUILD_BIN_PATH . '/php-config') || !is_file($headers . '/main/php.h') + || php::getPHPVersionID($headers, true) !== $version || !is_file($config) + || preg_match('/^#define ZTS 1$/m', FileSystem::readFile($config)) !== $zts + || shell()->execWithResult($probe, false)[0] !== 0) { + logger()->info('Building the PHP CLI and headers for ext-php-rs'); + $php->configureForUnix($php, $php->getInstaller(), bootstrap_cli: true); + $php->runStage([php::class, 'makeForUnix'], ['bootstrap_cli' => true]); + shell()->cd($php->getSourceDir())->exec('make INSTALL_ROOT=' . escapeshellarg(BUILD_ROOT_PATH) . ' install-headers install-programs'); + $php->patchUnixEmbedScripts(); + $cli = $php->getSourceDir() . '/sapi/cli/php'; + } + $release = $this->build(true, $cli); + // A relocatable object also becomes a regular member of a static libphp.a. + $symbol = (SystemTarget::getTargetOS() === 'Darwin' ? '_' : '') . "{$name}_get_module"; + $compiler = getenv('CC') ?: 'cc'; + $object = "{$release}/{$name}_rust.o"; + shell()->cd($release)->exec("{$compiler} -nostdlib -r -Wl,-u,{$symbol} -o " . escapeshellarg($object) . ' ' . escapeshellarg("lib{$name}.a")); + shell()->exec('ln -sf ' . escapeshellarg($object) . ' ' . escapeshellarg($this->extension->getBuildDir() . "/{$name}_rust.o")); + } + + public function buildShared(): void + { + $name = $this->extension->getExtensionName(); + $release = $this->build(false); + $suffix = SystemTarget::getTargetOS() === 'Darwin' ? 'dylib' : 'so'; + $module = BUILD_MODULES_PATH . "/{$name}.so"; + $this->extension->getBuilder()->deployBinary("{$release}/lib{$name}.{$suffix}", $module, false); + $this->extension->setOutput('Shared extension path', $module); + } + + private function build(bool $static, string $cli = BUILD_BIN_PATH . '/php'): string + { + // The PHP ABI may change even when php-config and php keep the same paths. + return (new UnixCargoExecutor($this->extension))->build([ + 'PHP' => $cli, + 'PHP_CONFIG' => BUILD_BIN_PATH . '/php-config', + 'PHPRC' => '/dev/null', + 'PHP_INI_SCAN_DIR' => '/dev/null', + 'EXT_PHP_RS_STATIC_EXT' => $static ? '1' : '0', + 'CARGO_PROFILE_RELEASE_STRIP' => 'none', + ], rebuild_dependency: 'ext-php-rs', staticlib: $static); + } +} diff --git a/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php b/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php index 743b0f01c..23a716baa 100644 --- a/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php +++ b/tests/StaticPHP/Command/Dev/GenExtTestMatrixCommandTest.php @@ -253,6 +253,44 @@ public function testEntryShape(): void } } + /** + * Host-libc-only extensions must be isolated in their own entry. + */ + public function testHostLibcExtensionIsIsolated(): void + { + $matrix = $this->runMatrix(['--os' => 'Linux']); + + $entries = $this->findEntriesContaining($matrix, 'pqcrypto'); + $this->assertCount(1, $entries, 'Expected exactly one entry containing pqcrypto'); + $this->assertSame('pqcrypto', $entries[0]['extension'], 'pqcrypto entry must contain only pqcrypto'); + } + + /** + * Linux entries for host-libc-only extensions must build against the host libc, + * not the default static musl target. + */ + public function testHostLibcExtensionUsesNativeLibcTargetOnLinux(): void + { + $matrix = $this->runMatrix(['--os' => 'Linux']); + + $entries = $this->findEntriesContaining($matrix, 'pqcrypto'); + $this->assertCount(1, $entries); + $this->assertStringStartsWith('SPC_TARGET=native-native ./bin/spc build ', $entries[0]['build-args']); + } + + /** + * macOS is already native, so host-libc-only extensions must not override the target. + */ + public function testHostLibcExtensionKeepsDefaultTargetOnMacos(): void + { + $matrix = $this->runMatrix(['--os' => 'Darwin']); + + $entries = $this->findEntriesContaining($matrix, 'pqcrypto'); + $this->assertCount(1, $entries); + $this->assertStringStartsWith('./bin/spc build ', $entries[0]['build-args']); + $this->assertStringNotContainsString('SPC_TARGET=', $entries[0]['build-args']); + } + // ────────────────────────────────────────────────────────────────────────── // Helpers // ────────────────────────────────────────────────────────────────────────── @@ -298,6 +336,7 @@ private function findEntriesContaining(array $matrix, string ...$names): array * - ext-curl simple orphan, depended on by swoole but must NOT be pulled into swoole entry * - ext-redis simple orphan * - ext-simdjson simple orphan used for combined filter tests + * - ext-pqcrypto host-libc-only extension (isolated, native target on Linux) * - ext-xml depends on lib 'libxml2' * - ext-dom depends on ext-xml (DFS chain) * - ext-imagick depends on imagemagick -> libheif -> libde265 @@ -324,6 +363,9 @@ private static function buildFixture(): array 'ext-redis' => $ext(), 'ext-simdjson' => $ext(), + // Host-libc-only extension: isolated and built with the native libc on Linux + 'ext-pqcrypto' => $ext(['arg-type' => 'standard', 'native-libc' => true]), + // DFS chain: dom depends on xml; xml depends on lib 'libxml2' 'ext-xml' => $ext(['arg-type' => 'standard'], ['depends' => ['libxml2']]), 'ext-dom' => $ext(['arg-type' => 'standard'], ['depends' => ['ext-xml']]), diff --git a/tests/StaticPHP/Config/ConfigValidatorTest.php b/tests/StaticPHP/Config/ConfigValidatorTest.php index 770d0a88a..919182a2f 100644 --- a/tests/StaticPHP/Config/ConfigValidatorTest.php +++ b/tests/StaticPHP/Config/ConfigValidatorTest.php @@ -296,6 +296,7 @@ public function testValidateAndLintPackagesWithPhpExtensionFields(): void 'php-extension' => [ 'zend-extension' => false, 'build-shared' => true, + 'native-libc' => true, ], ], ];