Compare commits

...

86 Commits

Author SHA1 Message Date
Marc
422323a41d Fable v3 windows (#1207) 2026-07-10 23:25:39 +07:00
Jerry Ma
6144f7affb fix(windows): survive cmd.exe's 8191 character command line limit (#1209) 2026-07-10 21:02:19 +08:00
m-this
6d58d53f7d fix(imagemagick): build the VisualMagick tree under source/ on windows
- C:\im was outside the project so bin/spc reset could not clean it
- with the command line limit fixed a short base path is no longer
  needed; keep SPC_IMAGEMAGICK_BUILD_DIR as an override
2026-07-10 10:52:14 +02:00
m-this
c54fa78ad1 fix(windows): survive cmd.exe's 8191 character command line limit
- with big extension stacks (imagick) the link command lines exceed what
  cmd.exe allows and fail with 'The command line is too long'
- pass the collected LIBS_CLI/LIBS_CGI/LIBS_MICRO lib lists to link.exe
  through @response files, like php-src already does for its object lists
- compile the frankenphp -mthreads shim instead of generating a .bat:
  batch files run through cmd.exe and cap cgo link lines at 8191 chars,
  a real executable gets the full 32K and past that go writes a response
  file by itself; still probe-gated, still a stopgap for golang/go#80290
2026-07-10 08:04:10 +02:00
crazywhalecc
4d6f334cbb Refactor UPX patching logic for phpmicro binary 2026-07-09 16:52:39 +08:00
crazywhalecc
e99423c7d1 Unify GOPATH with go-win custom binary extraction method 2026-07-09 16:20:52 +09:00
crazywhalecc
44daaad548 Resolve xlswriter dllimport issue 2026-07-09 16:20:29 +09:00
crazywhalecc
4dac0d18b4 Fix windows file delete permissions 2026-07-09 16:20:10 +09:00
Jerry Ma
79db27da04 Merge branch 'v3' into fable-v3-windows 2026-07-09 12:31:39 +09:00
crazywhalecc
d04d82a1f1 Fix strawberry-perl detect time 2026-07-09 12:27:41 +09:00
crazywhalecc
dca24585d4 Add frankenphp test label 2026-07-09 11:56:29 +09:00
crazywhalecc
7edd8359d5 Enhance artifact extraction logic to check for existing files and handle hash storage for both file and directory targets 2026-07-09 11:55:54 +09:00
crazywhalecc
be8f239259 Merge remote-tracking branch 'origin/fable-v3-windows' into fable-v3-windows 2026-07-09 11:24:41 +09:00
crazywhalecc
6c7a47c9b5 Trigger full test when containing 'need-full-test' tag 2026-07-09 11:17:10 +09:00
Jerry Ma
859c06a470 Fix the Windows extension test failures on fable-v3-windows (#1208) 2026-07-09 11:09:33 +09:00
crazywhalecc
274706084a Fix frankenphp package path bug 2026-07-09 11:04:00 +09:00
crazywhalecc
0bd94b0ebd Lint 2026-07-09 11:03:39 +09:00
crazywhalecc
150998723d Fix windows captainhook 2026-07-09 11:03:32 +09:00
crazywhalecc
303dca5f59 Remove doctor item 2026-07-09 11:03:15 +09:00
m-this
d7902b9931 feat(tool): bundle python for the meson build
- add a python-win tool package that unzips the official python.org
  nuget package into the pkgroot (venv and ensurepip included)
- meson uses it to build its venv and only falls back to a system
  python, so no manual environment setup is needed
2026-07-08 14:17:36 +02:00
m-this
43b2da0511 fix(libiconv): only put the static lib on the windows link line
- static-libs@windows listed both libiconv.lib (the dll import lib) and
  libiconv_a.lib; the import lib came first, so php.exe ended up
  importing libiconv.dll and the cli smoke test died with
  STATUS_DLL_NOT_FOUND on machines without it
2026-07-08 11:15:11 +02:00
m-this
6dc5c5b770 fix(pgsql): link secur32 and crypt32 on windows
- libpq authenticates through SSPI and the static libcrypto behind it
  reads the system cert store; php.exe failed to link with unresolved
  Cert* and SSPI symbols when the openssl extension is not in the build
2026-07-08 11:15:11 +02:00
m-this
f3afd81c81 fix(php): pass /FORCE:MULTIPLE when linking php-cgi.exe and micro.sfx
- php.exe already links with /FORCE:MULTIPLE for extension-bundled
  duplicate symbols, cgi and micro did not
- imagick's MagickCore defines gettimeofday, also defined in php's
  time.obj, and both links failed with LNK2005
2026-07-08 11:15:11 +02:00
m-this
1dce506222 fix(postgresql): provision meson, ninja and winflexbison on windows
- the meson build assumed meson/ninja/win_flex/win_bison/perl on PATH,
  which only held on machines that had them installed
- add meson, ninja and winflexbison tool packages and declare them via
  tools@windows on postgresql, together with the existing strawberry-perl
- meson no longer ships a Windows MSI, so the wheel is installed offline
  into a venv: postgres re-invokes meson through find_program, which
  needs the real meson.exe launcher pip generates
2026-07-08 11:15:11 +02:00
crazywhalecc
323f21a6f2 Add gdi32.lib 2026-07-08 17:02:32 +09:00
crazywhalecc
ab30c9dc49 fix: update Visual Studio version handling in imagemagick configuration 2026-07-08 16:27:52 +09:00
Jerry Ma
996cca12c0 [v3] - fix(windows): resolve doctor-installed perl and quote perl path (#1174) 2026-07-08 13:59:05 +08:00
crazywhalecc
5451945972 Use escapeshellarg instead 2026-07-08 13:21:52 +08:00
crazywhalecc
fc1673e37f Merge branch 'refs/heads/v3' into pr/win-openssl-perl-path
# Conflicts:
#	src/Package/Library/openssl.php
2026-07-08 13:19:36 +08:00
Marc
f1722a0f3e Merge branch 'v3' into fable-v3-windows 2026-07-08 11:45:02 +07:00
Marc
8034ae37ea v3 weekly build fix (#1203) 2026-07-08 11:40:37 +07:00
Marc
c9f24b980d [v3] Enable SQLite column metadata (#1205) 2026-07-08 11:39:22 +07:00
Jerry Ma
5ffbf2d5fe fix(frankenphp): strip Go's -mthreads so the Windows build survives Clang >= 20 (#1201) 2026-07-08 11:47:02 +08:00
crazywhalecc
facc7bc5a7 test swoole 2026-07-08 11:43:35 +08:00
crazywhalecc
160d7f5537 fix: disable undefined behavior sanitizer in build flags 2026-07-08 11:41:41 +08:00
Jerry Ma
afa5f535e9 Merge branch 'v3' into v3c/fix-builds 2026-07-08 10:06:19 +08:00
Jerry Ma
0dde151632 Merge branch 'v3' into fix/v3-sqlite-column-metadata 2026-07-08 10:00:57 +08:00
Jerry Ma
e906edb332 Test bot separate (#1206) 2026-07-08 10:00:41 +08:00
mathis
83ce54b62b docs(frankenphp): link golang/go#80290 so the -mthreads workaround can be removed later 2026-07-08 03:59:20 +02:00
crazywhalecc
7d6c082c86 random test 2026-07-07 22:38:39 +08:00
crazywhalecc
db4f7c6a0c feat: separate workflow for posting test bot comments 2026-07-07 22:37:23 +08:00
Jan Jakeš
ca0167c83e Enable SQLite column metadata
Build Unix SQLite with SQLITE_ENABLE_COLUMN_METADATA so the metadata APIs are available on macOS and Linux.

Remove the pdo_sqlite configure override that forced PHP to treat sqlite3_column_table_name() as unavailable, and add sanity checks for both SQLite compile options and PDO column metadata.
2026-07-07 16:25:00 +02:00
m-this
5a5c784c4f fix(frankenphp): strip Go's -mthreads so the Windows build survives Clang >= 20
Go passes the MinGW-only -mthreads flag to the C compiler for cgo builds
(golang/go#16932); Clang >= 20 rejects it for the MSVC target, so the final
frankenphp go build fails on current windows-latest (VS 18 / LLVM 20+).

Wrap Clang with a generated .bat that drops the -mthreads token and forwards
the rest, used only when the detected Clang refuses the flag.
2026-07-07 15:30:52 +02:00
crazywhalecc
331da67049 Fix gen-ext-test-matrix AND bug (should be OR) 2026-07-07 15:48:35 +08:00
crazywhalecc
cc448d463b simdjson test 2026-07-07 15:42:34 +08:00
crazywhalecc
dc55881b78 libde265 fix build 2026-07-07 15:21:19 +08:00
crazywhalecc
a59473e4ab ext-test-matrix generation fix 2026-07-07 15:03:31 +08:00
crazywhalecc
c6a227f4de libde265 test 2026-07-07 14:50:32 +08:00
Jerry Ma
392733b7c3 feat(v3): Tool package refactor (#1200) 2026-07-06 21:59:44 +08:00
Jerry Ma
3870269330 feat(docs): add agent guide, build class patterns, log triage, and AI instructions (#1202) 2026-07-06 21:59:26 +08:00
crazywhalecc
03f1313eec chore 2026-07-06 21:20:38 +08:00
crazywhalecc
b9def51f86 Simplify redundant github instruction 2026-07-06 21:20:20 +08:00
crazywhalecc
8533702cf6 oops 2026-07-06 21:19:55 +08:00
crazywhalecc
fe3cd15f81 feat(docs): add agent guide, build class patterns, log triage, and AI instructions 2026-07-06 20:39:44 +08:00
crazywhalecc
dc33b55fd0 Use binary 2026-07-06 20:12:10 +08:00
crazywhalecc
c9401a0b7a Use redirect instead 2026-07-06 19:35:48 +08:00
crazywhalecc
fa040bc346 Fix mingw patch paths 2026-07-06 19:10:10 +08:00
crazywhalecc
ab37b34fb5 fix: improve Windows patching logic and update file paths for xlsxwriter 2026-07-06 16:46:29 +08:00
crazywhalecc
0b02f62b7e feat: add pkg-config tool package config 2026-07-06 15:36:36 +08:00
crazywhalecc
924fac137c docs: fix hosted repo URL in READMEs
- Update static-php-cli-hosted → static-php/hosted in both README.md and README-zh.md
2026-07-06 15:11:07 +08:00
crazywhalecc
d9c41a73da feat: add --installed flag to check-update, improve CLI and InteractiveTerm
- Add --installed option to check-update command to compare against on-disk version (tool packages)
- Support use_installed parameter in ArtifactDownloader::checkUpdate/checkUpdates
- Add -y shorthand for --auto-fix in doctor command
- Hook InteractiveTerm::init() in ConsoleApplication::doRun() to properly inject Symfony input/output
2026-07-06 15:10:52 +08:00
crazywhalecc
dd1e70a394 feat: declare tool dependencies in package configs via tools field
- Add 'tools' field to ConfigValidator for build-time tool declarations
- Move jom and strawberry-perl from depends@windows to tools@windows in openssl.yml
- Move go-xcaddy/go-win from depends to tools in frankenphp.yml
- Register config/pkg/tool/ path in spc.registry.yml
- Use addInstallPackage for upx tool in php.php (ToolPackage instead of library dep)
- Include 'tool' type in DumpCapabilitiesCommand and InstallPackageCommand package lists
2026-07-06 15:10:22 +08:00
crazywhalecc
1bdbdfc08c refactor: move getLibExtra* to Package base, add ToolPackage support to executors and builders
- Move getLibExtraCFlags/getLibExtraCxxFlags/getLibExtraLdFlags/getLibExtraLibs from LibraryPackage to Package base class so ToolPackage can also use them
- Full ToolPackage implementation: getBuildRootPath, getIncludeDir, getLibDir, getBinDir, getToolField with platform suffix support
- Update PackageBuilder to support building ToolPackage (not just LibraryPackage)
- Update PackageInstaller: support ToolPackage in download/extract/install pipeline, auto-install build-time tools, record installed versions
- Allow LibraryPackage|ToolPackage union type in all Executor classes and UnixShell::initializeEnv
2026-07-06 15:10:08 +08:00
crazywhalecc
90846ab149 refactor: restructure tool target configs into tool package system
- Move tool configs from config/pkg/target/ to config/pkg/tool/
- Add ToolVersionRegistry for tracking installed tool versions
- Delete old Target/pkgconfig.php, move to tool config
- Rename: 7za-win, go-win, go-xcaddy, jom, nasm, protoc, strawberry-perl, upx, vswhere, zig, pkg-config
2026-07-06 15:08:43 +08:00
Jerry Ma
8dd7882869 CRLF to LF (#1199) 2026-07-06 14:14:57 +08:00
crazywhalecc
7f6be12bf1 CRLF to LF 2026-07-06 14:02:38 +08:00
Jerry Ma
45b97581d8 feat(zip): add additional dependencies for Windows zip build (#1198) 2026-07-04 15:42:31 +08:00
crazywhalecc
12a5217f17 feat(zip): add additional dependencies for Windows zip build 2026-07-04 14:10:59 +08:00
Jerry Ma
5913cb07fd [v3] implement tool package support with validation and config (#1196) 2026-06-27 20:17:53 +08:00
crazywhalecc
dd69155539 feat(tool): remove deprecated tool package directory from registry configuration 2026-06-27 15:47:46 +08:00
crazywhalecc
a81dd6d5c9 feat(tool): implement tool package support with validation and configuration 2026-06-27 15:39:30 +08:00
Jerry Ma
b4ed673261 feat(windows): replace php-sdk-binary-tools with MSYS2 + 7za-win (#1193) 2026-06-23 14:36:28 +08:00
crazywhalecc
db2d9a909f feat(gmssl): add patch for pbkdf2_hmac_sm3_genkey rename and update build process 2026-06-22 16:44:44 +08:00
crazywhalecc
38e01a9b88 feat(tests): enhance label information for triggering extension build tests 2026-06-22 13:33:25 +08:00
crazywhalecc
2b210f9403 feat(logging): synchronize logger level and debug mode with output verbosity 2026-06-22 13:33:02 +08:00
crazywhalecc
be329c1d56 feat(build): add patch to Makefile for include order to resolve zip.h conflict 2026-06-22 11:14:14 +08:00
Jerry Ma
227b8f0b0a fix(test): fix redundant terminal output during phpunit (#1194) 2026-06-22 08:08:47 +08:00
crazywhalecc
c88041b7e0 feat(build): add UPX as an optional package for compression 2026-06-21 20:08:27 +08:00
crazywhalecc
3bb84f3b94 feat(build): add zlib as a dependency for Windows 2026-06-21 19:35:07 +08:00
crazywhalecc
c31bf73685 feat(build): add bison and re2c to required packages; bypass phpsdk_version check for MSVC + msys2 2026-06-21 19:28:15 +08:00
crazywhalecc
c4d7ca819b fix(openssl): update perl path for Windows compatibility 2026-06-21 19:27:47 +08:00
crazywhalecc
fd8ab71d80 feat(build): use WinCNG as crypto backend for libssh2 windows 2026-06-21 19:27:32 +08:00
crazywhalecc
2a7966aa4b Fix curl zstd build bug 2026-06-21 19:26:55 +08:00
DubbleClick
f66e68754e fable output 2026-06-14 11:51:07 +07:00
Luther Monson
6c59456c02 fix(windows): consolidate to single canonical strawberry-perl path
Per review: spc's pkg config, doctor, and MSVCToolchain all use
PKG_ROOT_PATH\strawberry-perl. The arch-suffixed strawberry-perl-{arch}-win
path was stale and shouldn't be juggled alongside it. Validate against the
one canonical pkg-root path, falling back to WindowsUtil::findCommand.
2026-05-27 22:30:04 -07:00
Luther Monson
0e8a806640 fix(windows): resolve doctor-installed perl and quote perl path
Two related fixes for OpenSSL builds on Windows:

1. spc doctor installs Strawberry Perl under `pkgroot/strawberry-perl/`,
   but the validate() check only looks at the arch-specific native path
   (`strawberry-perl-x86_64-win`). When a user runs `spc doctor` to
   install perl, the subsequent build fails because the doctor's install
   layout isn't on the lookup list. Add it as a fallback before falling
   through to WindowsUtil::findCommand.

2. Wrap the resolved perl path in quote() when building the Configure
   command. WindowsUtil::findCommand can return a path containing spaces
   (e.g. `C:\Program Files\...`), which then splits the cmd.exe
   invocation. Quoting matches how every other interpolated path in this
   command is handled.
2026-05-27 22:07:57 -07:00
130 changed files with 4367 additions and 1166 deletions

24
.gitattributes vendored Normal file
View File

@@ -0,0 +1,24 @@
# Force LF line endings for all text files.
# Prevents git from auto-converting LF -> CRLF on Windows checkouts.
* text=auto eol=lf
# Explicit binary files — git won't touch line endings for these
*.phar binary
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.zip binary
*.gz binary
*.tgz binary
*.txz binary
*.xz binary
*.bz2 binary
*.7z binary
*.exe binary
*.dll binary
*.sfx binary
*.so binary
*.a binary
*.o binary

23
.github/copilot-instructions.md vendored Normal file
View File

@@ -0,0 +1,23 @@
# StaticPHP v3 Copilot Instructions
> The canonical agent instructions live in [AGENTS.md](./AGENTS.md). This file provides the essential summary for GitHub Copilot; read `AGENTS.md` for the complete project map, working rules, and validation steps.
StaticPHP is a PHP CLI application for building static PHP binaries, PHP SAPIs, extensions, libraries, and helper tools. Prefer the v3 architecture under `src/StaticPHP`, `src/Package`, `config/pkg`, and `config/artifact`.
## Skills
Use the repository skills when the task matches them:
- `.github/skills/staticphp-package-maintenance`: add, modify, review, or validate package, artifact, extension, library, target, or tool definitions.
- `.github/skills/staticphp-build-troubleshooting`: diagnose build, download, doctor, shell, terminal, CI, smoke-test, or log failures.
## Quick Reference
- **Entrypoint**: `php bin/spc`
- **Config lint**: `php bin/spc dev:lint-config`
- **CS fix**: `composer cs-fix`
- **Tests**: `composer test`
- **Static analysis**: `composer analyse`
- **Extension packages**: `config/pkg/ext/ext-*.yml`, prefix with `ext-` in dependencies
- **Platform suffixes**: `@unix`, `@linux`, `@macos`, `@windows` — prefer these over runtime conditionals
- **Do NOT edit generated dirs**: `buildroot/`, `source/`, `downloads/`, `pkgroot/`

View File

@@ -0,0 +1,56 @@
---
name: staticphp-build-troubleshooting
description: Diagnose StaticPHP v3 failures. Use when investigating build, compile, linker, download, doctor, environment, CI, smoke-test, terminal output, spc.output.log, spc.shell.log, config.log, CMake logs, or user-provided error snippets from StaticPHP commands.
---
# StaticPHP Build Troubleshooting
## Overview
Use this skill to triage StaticPHP failures from the outside in: command and environment first, SPC module/stage metadata next, shell/config logs last. The goal is to isolate the failing package, stage, command, and root cause before editing code.
## First Pass
1. Capture the exact command, OS, architecture, PHP version, extensions/libs/targets, and whether the run used `-v`, `-vv`, or `-vvv`.
2. Read the final terminal error first. StaticPHP prints module error info, failed package, failed stage, failed command, log paths, and extra log files when available.
3. If log files exist, inspect them in this order:
- `log/spc.output.log`: user-facing SPC messages and exception summary.
- `log/spc.shell.log`: executed commands, working directories, env, stdout/stderr.
- Extra logs named in the exception output: `php-src.config.log`, `lib.<pkg>.console.log`, `lib.<pkg>.cmake-error.log`, `lib.<pkg>.cmake-configure.log`, `lib.<pkg>.cmake-output.log`.
4. Read `references/log-triage.md` for pattern matching, likely causes, and next checks.
## Diagnosis Rules
- Do not start by changing shared core code. Most failures are package metadata, environment, upstream source, dependency order, or platform flags.
- Prefer evidence from the last failing command over earlier warnings.
- When logs are long, search backward for `Command exited`, `error:`, `undefined reference`, `not found`, `No package`, `CMake Error`, `configure: error`, `fatal error`, `Failed module`, and `Failed stage`.
- Use `config.log` and CMake logs for configure detection failures; use `spc.shell.log` for the actual command and env.
- Be careful with rebuild suggestions. `spc reset --with-download --yes` is destructive to caches; ask before clearing caches unless the user explicitly asked.
## Repro Commands
Use focused commands when reproducing:
```bash
php bin/spc doctor -vvv
php bin/spc download --for-extensions="curl,openssl" --with-php=8.5 --parallel=4 --retry=3 -vvv
php bin/spc build:libs "openssl" -vvv
php bin/spc build:php "bcmath,openssl,curl" --build-cli -vvv
php bin/spc dev:lint-config
```
Choose the smallest command that still reaches the failing package.
## Fix Direction
After finding the failing package/stage:
- Package YAML issue: use `$staticphp-package-maintenance`, then edit `config/pkg/*` or `config/artifact/*`.
- Build command or patch issue: inspect the package class under `src/Package/*`.
- Environment issue: check `doctor`, toolchain classes, and `config/pkg/tool/*`.
- Upstream download issue: check artifact type, regex, GitHub rate limiting, mirror behavior, and `GITHUB_TOKEN`.
- Core exception/logging issue: inspect `src/StaticPHP/Exception`, `src/StaticPHP/Runtime/Shell`, or executor classes only after package-level causes are ruled out.
## Resources
- `references/log-triage.md`: log files, failure categories, search patterns, and likely fixes.

View File

@@ -0,0 +1,4 @@
interface:
display_name: "StaticPHP Build Troubleshooting"
short_description: "Diagnose StaticPHP build and log failures."
default_prompt: "Use $staticphp-build-troubleshooting to investigate a StaticPHP build, download, doctor, or log failure."

View File

@@ -0,0 +1,209 @@
# StaticPHP Log Triage
## Contents
- Log files
- Terminal summary
- Search strategy
- Failure categories
- Rebuild hygiene
- Reporting checklist
## Log Files
Default log directory is `log/`, controlled by `SPC_LOGS_DIR`. The important files are:
- `spc.output.log`: StaticPHP console/logger output and exception summaries.
- `spc.shell.log`: command execution log with command, caller, inline env, working directory, stdout, stderr, and exit code.
- `php-src.config.log`: copied when PHP source configure fails.
- `lib.<pkg>.console.log`: copied Autoconf `config.log` for a library when available.
- `lib.<pkg>.cmake-configure.log`: copied CMake 3.26+ configure log.
- `lib.<pkg>.cmake-error.log`: copied CMake error log.
- `lib.<pkg>.cmake-output.log`: copied CMake output log.
Logs are created when `SPC_ENABLE_LOG_FILE` is true. Old `*.log` files are cleaned unless `SPC_PRESERVE_LOG` is set to a truthy value. The code in `src/bootstrap.php` reads `SPC_PRESERVE_LOG` (no trailing S).
## Terminal Summary
StaticPHP exceptions often print:
- Exception category: build, download, environment, execution, file system, patch, validation, wrong usage, registry, internal.
- Failed module: package name, type, and sometimes class/file/line.
- Failed stage: call chain such as `build` or `build -> configure`.
- Failed command: the command that returned non-zero.
- Command working directory and inline env.
- Paths to `spc.output.log`, `spc.shell.log`, and extra logs.
Use this summary to choose the first files to read. If a package and stage are present, start with that package's YAML and class after reading the relevant log tail.
## Search Strategy
For long logs, search from the end first.
Useful patterns:
```text
Failed module:
Failed stage:
Failed command:
Command exited with non-zero code
configure: error
CMake Error
undefined reference
cannot find -l
fatal error:
No package
Package .* not found
Could NOT find
is not a valid
permission denied
curl: (
HTTP/2 403
rate limit
```
In `spc.shell.log`, each command block begins with `>>>>>>>>>>>>>>>>>>>>>>>>>>`, then prints the command, caller, env, and working dir. The last failed block is usually the highest-value evidence.
## Failure Categories
### Download Failure
Signs:
- `Download failed`
- `curl: (56)`, `curl: (22)`, HTTP 403/404/429
- GitHub API calls in verbose logs
- Asset regex did not match a release asset
Likely checks:
- If GitHub rate limited, ask user to set `GITHUB_TOKEN`.
- Verify artifact source type and regex in `config/pkg/*` or `config/artifact/*`.
- Use `--dl-retry`, `--dl-parallel`, `--ignore-cache`, `--no-alt`, or custom source options only as repro aids.
- Prefer fixing stale URLs/regexes over adding workarounds.
### Doctor or Environment Failure
Signs:
- `Environment check failed`
- missing `make`, `cmake`, `autoconf`, `pkg-config`, compiler, Perl, Visual Studio, MSYS2, Zig, etc.
- `Some check items can not be fixed`
Likely checks:
- Run `php bin/spc doctor -vvv`.
- Inspect `src/StaticPHP/Doctor/Item/*` for the check and fix behavior.
- Inspect `config/pkg/tool/*` for installable helper tools.
- On Windows, some dependencies cannot be auto-installed.
### Configure Failure
Signs:
- `configure: error`
- Autoconf failure before compilation
- extra `config.log` listed
Likely checks:
- Read copied `php-src.config.log` or `lib.<pkg>.console.log`.
- Look for the first compiler/linker probe that failed.
- Check `headers`, `static-libs`, `pkg-configs`, dependency order, and `initializeEnv($pkg)` behavior.
- For extensions, check `php-extension.arg-type` and `#[CustomPhpConfigureArg]`.
### CMake Failure
Signs:
- `CMake Error`
- `Could NOT find`
- missing target, package config, or static library
Likely checks:
- Read `lib.<pkg>.cmake-error.log` and `lib.<pkg>.cmake-configure.log`.
- Inspect `UnixCMakeExecutor`/`WindowsCMakeExecutor` usage in the package class.
- Check CMake options, toolchain root path, `pkg-configs`, and transitive dependency libraries.
### Compile Failure
Signs:
- compiler `fatal error: header.h: No such file or directory`
- syntax/type errors from upstream source
- incompatible PHP API or platform macros
Likely checks:
- Identify the source file and include path from `spc.shell.log`.
- Verify dependency headers are installed in `buildroot/include`.
- Check PHP version compatibility and existing patches in `src/globals/patch`.
- Prefer targeted patches or compile flags in the package class over broad toolchain changes.
### Link Failure
Signs:
- `undefined reference`
- `cannot find -lfoo`
- duplicate symbols
- Windows unresolved external symbol or missing `.lib`
Likely checks:
- Verify `static-libs`, dependency order, and `getStaticLibFiles()` usage.
- Inspect `SPC_EXTRA_LIBS`, `Libs.private` in `.pc` files, and package-specific pkg-config patching.
- On Windows, confirm `.lib` names and required system libraries.
- For OpenSSL/curl-like packages, search existing linker flag hooks before adding a new one.
### Smoke Test or Validation Failure
Signs:
- `Validation failed`
- `php --ri` failure
- extension not loaded after build
- micro/embed runtime smoke test fails
Likely checks:
- Check extension `display-name`; empty string skips `php --ri`.
- Confirm static vs shared build settings.
- Confirm the extension is included in the final SAPI target and not only built as a dependency.
- Inspect `src/globals/ext-tests/*` and common tests for expected runtime behavior.
### Registry or Config Failure
Signs:
- `Registry error`
- unknown package, invalid field, invalid platform suffix, type mismatch
- package referenced by attribute but missing config
Likely checks:
- Run `php bin/spc dev:lint-config`.
- Inspect `ConfigValidator` tests for accepted fields and error expectations.
- Confirm attribute type matches YAML `type`.
- Confirm hooks reference existing package names and stages for the current platform.
## Rebuild Hygiene
Use the smallest cleanup that can invalidate the suspected stale state:
- Redownload one artifact: `--ignore-cache="artifact-name"`.
- Skip downloads to test local source/build logic: `--no-download`.
- Prefer source when debugging build logic: `--dl-prefer-source`.
- Clear build products only when necessary. `spc reset --with-download --yes` removes caches and should not be suggested casually.
## Reporting Checklist
When preparing an issue or PR explanation, include:
- Exact `php bin/spc ...` command.
- OS, architecture, PHP version option, and relevant env vars.
- Failed package and stage.
- Last failed command and exit code.
- Tail of `spc.output.log`, relevant command block from `spc.shell.log`, and any extra config/CMake log.
- Whether the failure reproduces after a focused clean or cache refresh.

View File

@@ -0,0 +1,55 @@
---
name: staticphp-package-maintenance
description: Maintain StaticPHP v3 packages and artifacts. Use when adding, modifying, reviewing, or validating config under config/pkg or config/artifact; package classes under src/Package; extension/library/target/tool dependencies; PHP configure args; build hooks; package metadata; or related tests and docs.
---
# StaticPHP Package Maintenance
## Overview
Use this skill to make focused package changes without re-reading the entire repository. StaticPHP v3 separates declarative package/artifact YAML from package-specific PHP build logic; prefer config-only edits unless current patterns require a class.
## Quick Workflow
1. Identify the package kind and exact name.
- Extension: `config/pkg/ext/ext-name.yml`, class `src/Package/Extension/name.php`.
- Library: `config/pkg/lib/name.yml`, class `src/Package/Library/name.php`.
- Target or virtual target: `config/pkg/target/name.yml`, class `src/Package/Target/name.php`.
- Tool: `config/pkg/tool/name.yml`, class `src/Package/Tool/name.php`.
- Shared/custom artifact: `config/artifact/name.yml`, class `src/Package/Artifact/name.php`.
2. Search for the closest existing package before designing anything new.
- Similar build system: `rg "#\\[BuildFor|UnixCMakeExecutor|UnixAutoconfExecutor|WindowsCMakeExecutor" src/Package`.
- Similar config fields: `rg "static-libs|pkg-configs|arg-type|depends@" config/pkg`.
- Similar download type: `rg "type: ghrel|type: pecl|type: pie|type: git|binary: hosted" config`.
3. Read `references/package-reference.md` when changing YAML fields, artifact definitions, package naming, dependencies, platform suffixes, or validation expectations.
4. Read `references/build-class-patterns.md` when PHP build logic, attributes, lifecycle hooks, custom configure args, source patching, or executor usage is needed.
5. Validate narrowly, then broadly if risk warrants it.
- Config lint: `php bin/spc dev:lint-config`
- Focused tests: `vendor/bin/phpunit tests/StaticPHP/Config tests/StaticPHP/Registry tests/StaticPHP/Util/DependencyResolverTest.php --no-coverage`
- Full project checks: `composer test`, `composer analyse`
## Editing Rules
- Treat `config/pkg/*` and `config/artifact/*` as the source of package truth; package classes augment behavior.
- Use platform suffix fields for declarative OS differences: `@unix`, `@linux`, `@macos`, `@windows`.
- Add a PHP class only for custom build stages, validation, hook behavior, patches, or custom configure arguments.
- Keep extension dependencies prefixed with `ext-`; libraries, tools, and targets use their package names.
- Prefer existing helpers such as `UnixAutoconfExecutor`, `UnixCMakeExecutor`, `WindowsCMakeExecutor`, `shell()`, `cmd()`, and `FileSystem`.
- Do not modify build outputs (`buildroot/`, `source/`, `downloads/`, `pkgroot/`) to fix package definitions.
- If upstream metadata changes, update license metadata and smoke-test/display names when relevant.
## Common Task Paths
- Add a new PECL extension: define `config/pkg/ext/ext-name.yml` with `type: php-extension`, `artifact.source.type: pecl`, dependencies, and `php-extension.arg-type`; add a class only if configure args, patches, or hooks are non-standard.
- Add a library: define `config/pkg/lib/name.yml` with artifact, dependencies, and install verification fields (`headers`, `static-libs`, `pkg-configs`, `static-bins`); add build class methods by OS.
- Fix an existing package build: start from the failing package config/class, then inspect dependencies and hooks targeting that package before changing shared core code.
- Update a version source: prefer artifact fields that support update checking (`ghrel`, `ghtar`, `ghtagtar`, `git` with regex, `filelist`, `pecl`, `pie`) over hard-coded URLs when upstream supports it.
## Resources
- `references/package-reference.md`: YAML package/artifact model, naming, fields, validation, and commands.
- `references/build-class-patterns.md`: PHP package attributes, stages, hooks, executors, and class patterns.

View File

@@ -0,0 +1,4 @@
interface:
display_name: "StaticPHP Package Maintenance"
short_description: "Add, update, and validate StaticPHP v3 package definitions."
default_prompt: "Use $staticphp-package-maintenance to add, modify, or review StaticPHP package and artifact definitions."

View File

@@ -0,0 +1,143 @@
# StaticPHP Build Class Patterns
## Contents
- When a class is needed
- Package attributes
- Stage and hook behavior
- Executor choices
- Common patterns
- Failure-safe edits
## When a Class Is Needed
Do not add a PHP package class for simple metadata. Use YAML alone when StaticPHP can infer the configure args, dependencies, and verification.
Add or update a class when the package needs:
- OS-specific build commands.
- Custom validation before building.
- Custom PHP configure arguments.
- Patches or file edits before build.
- Hooks into another package's stage.
- Custom source/binary download or extraction logic.
- Package info shown by dev tooling.
Package classes live in `src/Package/*` and are discovered through PSR-4 plus attributes. Config must exist first; `PackageLoader` throws if an attribute references an undefined package.
## Package Attributes
Class-level package attributes:
- `#[Extension('curl')]` maps to package `ext-curl` if the prefix is omitted.
- `#[Library('openssl')]`
- `#[Target('php')]`
- `#[Tool('zig')]`
Method-level attributes:
- `#[BuildFor('Linux'|'Darwin'|'Windows')]`: registers the `build` stage for that OS.
- `#[Stage('name')]`: registers a named stage; defaults to the method name when omitted.
- `#[BeforeStage('package', 'stage', 'only-when-package-resolved')]`: hook before a target package stage.
- `#[AfterStage('package', 'stage', 'only-when-package-resolved')]`: hook after a target package stage.
- `#[PatchBeforeBuild]`: runs once before package build unless `.spc-patched` exists; return `true` to write that marker.
- `#[CustomPhpConfigureArg('Linux')]`: supplies custom extension configure args.
- `#[Validate]`: validates environment/source assumptions.
- `#[Info]`: returns package information for tooling.
- `#[InitPackage]`: runs while loading a package class.
- `#[ResolveBuild]`: target package callback for resolving build dependencies.
- `#[ConditionalOn(SomeClass::class)]`: conditionally enables before/after hooks only when DI has the class.
## Stage and Hook Behavior
`PackageBuilder::buildPackage()` does:
1. Ensure build directories exist.
2. Skip if already installed unless forced.
3. Ensure source exists for non-virtual packages.
4. Emit `PatchBeforeBuild` callbacks.
5. Run the `build` stage.
6. Install license data.
7. Record tool package versions where relevant.
`Package::runStage()` wraps a stage with:
1. `BeforeStage` callbacks.
2. The stage method itself.
3. `AfterStage` callbacks.
SPC exceptions bind package and stage metadata. Preserve that behavior by throwing existing `SPCException` subclasses instead of raw exceptions when adding new failure paths.
## Executor Choices
Use existing executors where possible:
- `UnixAutoconfExecutor`: for Unix packages using `./configure && make && make install`. It injects default static flags and copies `config.log` into SPC logs on failure.
- `UnixCMakeExecutor`: for Unix CMake packages. It writes toolchain settings and copies CMake configure/error/output logs on failure.
- `WindowsCMakeExecutor`: for Windows CMake packages.
- `shell()->cd(...)->initializeEnv($pkg)`: for custom Unix command chains.
- `cmd()->cd(...)`: for Windows command chains.
Prefer `FileSystem` helpers for file edits and copies so behavior stays consistent.
## Common Patterns
Minimal library class:
```php
#[Library('example')]
class example
{
#[BuildFor('Linux')]
public function build(LibraryPackage $pkg): void
{
(new UnixAutoconfExecutor($pkg))
->configure()
->make();
}
}
```
Extension hook into PHP build:
```php
#[Extension('curl')]
class curl
{
#[BeforeStage('php', [php::class, 'makeForWindows'], 'ext-curl')]
public function patchBeforePhpBuild(): void
{
// Adjust env, generated build files, or linker flags.
}
}
```
Validation:
```php
#[Validate]
public function validate(): void
{
if (SystemTarget::getTargetOS() === 'Windows' && WindowsUtil::findCommand('perl.exe') === null) {
throw new EnvironmentException('You need to install perl first!');
}
}
```
Custom configure args should be used when YAML `arg-type` is `custom` or when args need package/install context:
```php
#[CustomPhpConfigureArg('Linux')]
public function configureArg(PhpExtensionPackage $ext): string
{
return '--with-example=' . $ext->getBuildRootPath();
}
```
## Failure-Safe Edits
- Make hooks conditional with the third `BeforeStage`/`AfterStage` argument when a dependency must be resolved before the hook should run.
- Keep platform-specific code under matching `#[BuildFor]` methods rather than branching heavily inside one method.
- If a patch changes upstream source, place patch files in `src/globals/patch/` and describe them with `#[PatchDescription]` where appropriate.
- If a class only mutates environment variables for another package, search for existing hooks first to avoid duplicate linker flags.
- After adding attributes, run registry/config tests because invalid stages and unknown packages are caught during loading.

View File

@@ -0,0 +1,157 @@
# StaticPHP Package Reference
## Contents
- Package locations
- Package types
- Artifact model
- Common YAML fields
- PHP extension fields
- Platform suffixes
- Validation and tests
## Package Locations
StaticPHP v3 keeps package metadata in YAML and behavior in PHP classes.
| Kind | YAML | PHP class namespace | Typical attribute |
|---|---|---|---|
| PHP extension | `config/pkg/ext/ext-name.yml` | `Package\Extension` | `#[Extension('name')]` |
| Library | `config/pkg/lib/name.yml` | `Package\Library` | `#[Library('name')]` |
| Target | `config/pkg/target/name.yml` | `Package\Target` | `#[Target('name')]` |
| Virtual target | `config/pkg/target/name.yml` | `Package\Target` | `#[Target('name')]` |
| Tool | `config/pkg/tool/name.yml` | `Package\Tool` | `#[Tool('name')]` |
| Custom artifact | `config/artifact/name.yml` | `Package\Artifact` | artifact attributes |
Prefer one package per YAML file unless an existing file groups related definitions. Match nearby naming and ordering.
## Package Types
`php-extension` packages describe PHP extensions. Config package names must use the `ext-` prefix. Dependencies on extensions also use `ext-`.
`library` packages describe buildable dependency libraries. They usually define source artifacts plus verification fields such as headers, static libraries, pkg-config files, or binaries.
`target` packages represent final build outputs and inherit the library-style fields. StaticPHP automatically exposes build commands for targets.
`virtual-target` packages are abstract dependency/build scheduling nodes. They may omit `artifact`.
`tool` packages are helper programs or toolchains installed into `pkgroot/` or used by builds.
## Artifact Model
Artifacts define downloadable source archives or prebuilt binaries. Use inline artifacts for simple one-package sources and `config/artifact/*.yml` for shared, complex, or custom artifacts.
Top-level artifact sections:
- `source`: source archive, git checkout, PECL/PIE package, local directory, or custom source.
- `binary`: prebuilt binary by platform, or aliases such as `hosted`/`custom`.
- `metadata`: `license`, `license-files`, and `source-root`.
Common source types:
- `url`: fixed URL; supports `filename`, `version`, and `extract`.
- `git`: repository source; use `rev` for a fixed branch/tag/commit or `regex` with named `version` capture for update checks.
- `ghrel`: GitHub release asset by regex filename match.
- `ghtar`: generated GitHub release tarball.
- `ghtagtar`: generated GitHub tag tarball.
- `filelist`: scrape a download index and extract version/filename with regex.
- `pecl`: PECL extension by name.
- `pie`: Packagist PIE extension by `vendor/package`.
- `php-release`: official PHP source selected by build PHP version.
- `local`: local source directory for development/offline use.
- `custom`: PHP artifact class handles source or binary logic.
Use `metadata.source-root` when the actual build directory is inside an extracted subdirectory.
Use `metadata.license-files` for source licenses. `@/file.txt` points to bundled license files in `src/globals/licenses/`.
## Common YAML Fields
Shared fields:
- `type`: required package type.
- `description`: optional human-readable package description.
- `license`: package-level license annotation where applicable.
- `lang`: implementation language such as `c` or `c++`.
- `frameworks`: macOS framework tags.
- `artifact`: string reference or inline artifact object. Required for `library` and `target`; optional for built-in extensions and virtual targets.
- `depends`: hard dependencies.
- `suggests`: optional dependencies.
Library, target, and tool verification/installation fields:
- `headers`: expected files/directories under `buildroot/include`.
- `static-libs`: expected static libraries under `buildroot/lib`.
- `pkg-configs`: expected `.pc` files under `buildroot/lib/pkgconfig`.
- `static-bins`: expected executables under `buildroot/bin`.
- `path`: directories appended to PATH after install.
- `env`: environment variables set after install.
- `append-env`: values appended to existing environment variables.
Path placeholders in `path`, `env`, and `append-env`:
- `{build_root_path}`: `buildroot/`
- `{pkg_root_path}`: `pkgroot/`
- `{working_dir}`: repository or working directory
- `{download_path}`: `downloads/`
- `{source_path}`: `source/`
- `{spc_msys2_path}`: MSYS2 root on Windows
## PHP Extension Fields
Extension-specific fields live under `php-extension`.
- `arg-type`: configure argument behavior. Built-ins include `enable`, `enable-path`, `with`, `with-path`, `custom`, and `none`. Full strings are allowed.
- `zend-extension`: true for Zend extensions such as opcache/xdebug.
- `build-shared`: whether shared builds are allowed.
- `build-static`: whether static builds are allowed.
- `build-with-php`: true when built inside the PHP source tree.
- `display-name`: value used for `php --ri` smoke tests and license display; empty string skips the `--ri` check.
- `os`: allowed OS families: `Linux`, `Darwin`, `Windows`.
Configure string placeholders:
- `@build_root_path@`: absolute buildroot path.
- `@shared_suffix@`: `=shared` in shared builds, empty in static builds.
- `@shared_path_suffix@`: `=shared,{buildroot}` in shared builds, `={buildroot}` in static builds.
## Platform Suffixes
Many fields support platform suffixes:
- `@unix`: Linux and macOS.
- `@linux`: Linux only.
- `@macos`: macOS only.
- `@windows`: Windows only.
For Linux, specific fields override generic fields in this order: `field@linux`, then `field@unix`, then `field`.
Use suffixes for declarative differences in dependencies, headers, libraries, pkg-configs, extension args, and suggestions.
## Validation and Tests
Run config validation for most package edits:
```bash
php bin/spc dev:lint-config
```
Run focused tests after config or registry changes:
```bash
vendor/bin/phpunit tests/StaticPHP/Config tests/StaticPHP/Registry tests/StaticPHP/Util/DependencyResolverTest.php --no-coverage
```
Run broader checks for framework or class changes:
```bash
composer test
composer analyse
```
Build commands are expensive. Use them for user-provided repros, package-specific fixes, or when validation cannot prove the behavior:
```bash
php bin/spc build:libs "openssl,curl" -vvv
php bin/spc build:php "bcmath,openssl,curl" --build-cli -vvv
```

View File

@@ -2,13 +2,14 @@ name: "Extension Matrix Tests"
on: on:
workflow_dispatch: workflow_dispatch:
push: pull_request:
types: [opened, synchronize, labeled]
jobs: jobs:
test: test:
name: "${{ matrix.extension }} (PHP ${{ matrix.php-version }} on ${{ matrix.operating-system }})" name: "${{ matrix.extension }} (PHP ${{ matrix.php-version }} on ${{ matrix.operating-system }})"
runs-on: ${{ matrix.operating-system }} runs-on: ${{ matrix.operating-system }}
if: contains(github.event.head_commit.message, 'extension test') || contains(github.event.head_commit.message, 'test extensions') if: contains(github.event.pull_request.labels.*.name, 'need-full-test')
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:

View File

@@ -0,0 +1,48 @@
name: Post Test Bot Comment
on:
workflow_run:
workflows: ["v3 Tests"]
types: [completed]
permissions:
pull-requests: write
actions: read
jobs:
post-comment:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Download bot output
id: download
uses: actions/download-artifact@v4
continue-on-error: true
with:
name: bot-output
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Post/Update comment
if: steps.download.outcome == 'success'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
COMMENT_BODY=$(jq -r '.comment_body' bot-output.json)
PR_NUMBER=$(jq -r '.pr_number' bot-output.json)
MARKER="<!-- spc-test-bot -->"
# Find existing bot comment id
EXISTING_ID=$(gh api \
"repos/${{ github.repository }}/issues/${PR_NUMBER}/comments" \
--jq "[.[] | select(.body | startswith(\"${MARKER}\")) | .id] | first // empty")
if [ -n "$EXISTING_ID" ]; then
gh api --method PATCH \
"repos/${{ github.repository }}/issues/comments/${EXISTING_ID}" \
-f body="$COMMENT_BODY"
else
gh pr comment "$PR_NUMBER" \
--repo "${{ github.repository }}" \
--body "$COMMENT_BODY"
fi

View File

@@ -131,7 +131,6 @@ jobs:
if: needs.check-gate.outputs.enabled == 'true' if: needs.check-gate.outputs.enabled == 'true'
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
pull-requests: write
contents: read contents: read
outputs: outputs:
need_test: ${{ steps.bot.outputs.need_test }} need_test: ${{ steps.bot.outputs.need_test }}
@@ -168,23 +167,17 @@ jobs:
echo "php_versions=$(echo "$BOT_JSON" | jq -c '.php_versions')" >> "$GITHUB_OUTPUT" echo "php_versions=$(echo "$BOT_JSON" | jq -c '.php_versions')" >> "$GITHUB_OUTPUT"
echo "tier2=$(echo "$BOT_JSON" | jq -r '.tier2')" >> "$GITHUB_OUTPUT" echo "tier2=$(echo "$BOT_JSON" | jq -r '.tier2')" >> "$GITHUB_OUTPUT"
COMMENT_BODY=$(echo "$BOT_JSON" | jq -r '.comment_body') # Save JSON for the comment-posting workflow
MARKER="<!-- spc-test-bot -->" jq -n --argjson bot "$BOT_JSON" \
--arg pr '${{ github.event.pull_request.number }}' \
'$bot + {pr_number: $pr}' > bot-output.json
# Find existing bot comment id - name: Upload bot output
EXISTING_ID=$(gh api \ uses: actions/upload-artifact@v4
repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments \ with:
--jq "[.[] | select(.body | startswith(\"$MARKER\")) | .id] | first // empty") name: bot-output
path: bot-output.json
if [ -n "$EXISTING_ID" ]; then retention-days: 1
gh api --method PATCH \
repos/${{ github.repository }}/issues/comments/"$EXISTING_ID" \
-f body="$COMMENT_BODY"
else
gh pr comment ${{ github.event.pull_request.number }} \
--repo ${{ github.repository }} \
--body "$COMMENT_BODY"
fi
gen-matrix: gen-matrix:
name: "Generate test matrix" name: "Generate test matrix"
@@ -234,7 +227,7 @@ jobs:
echo "matrix=$(echo "$FINAL" | jq -c '{"combo": .}')" >> "$GITHUB_OUTPUT" echo "matrix=$(echo "$FINAL" | jq -c '{"combo": .}')" >> "$GITHUB_OUTPUT"
ext-test: ext-test:
name: "Ext test: ${{ matrix.combo.extension }} (PHP ${{ matrix.combo.php-version }} · ${{ matrix.combo.os }}-${{ matrix.combo.arch }})" name: "Ext test: ${{ matrix.combo.extension }} [${{ matrix.combo.sapi }}] (PHP ${{ matrix.combo.php-version }} - ${{ matrix.combo.os }}-${{ matrix.combo.arch }})"
needs: gen-matrix needs: gen-matrix
runs-on: ${{ matrix.combo.runner }} runs-on: ${{ matrix.combo.runner }}
timeout-minutes: 120 timeout-minutes: 120
@@ -273,5 +266,5 @@ jobs:
if: always() && hashFiles('log/**') != '' if: always() && hashFiles('log/**') != ''
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: logs-${{ matrix.combo.os }}-${{ matrix.combo.arch }}-${{ matrix.combo.extension }}-php${{ matrix.combo.php-version }} name: logs-${{ matrix.combo.os }}-${{ matrix.combo.arch }}-${{ matrix.combo.sapi }}-${{ matrix.combo.extension }}-php${{ matrix.combo.php-version }}
path: log path: log

59
AGENTS.md Normal file
View File

@@ -0,0 +1,59 @@
# StaticPHP v3 Agent Guide
StaticPHP is a PHP CLI application for building static PHP binaries, PHP SAPIs, extensions, libraries, helper tools, and project bundles. Prefer the v3 architecture under `src/StaticPHP`, `src/Package`, `config/pkg`, and `config/artifact`.
This file is the shared entry point for coding agents such as Codex, OpenCode, Claude-compatible agents, and GitHub Copilot agents. GitHub Copilot also has `.github/copilot-instructions.md`.
## Skills
Detailed task workflows live in `.github/skills`. Use them when the task matches:
- `.github/skills/staticphp-package-maintenance`: add, modify, review, or validate package, artifact, extension, library, target, or tool definitions.
- `.github/skills/staticphp-build-troubleshooting`: diagnose build, download, doctor, shell, terminal, CI, smoke-test, or log failures.
If your agent does not automatically discover skills from `.github/skills`, read the matching `SKILL.md` manually before working on that task.
## Project Map
- `bin/spc`: primary CLI entrypoint.
- `composer.json`: PHP 8.4+, Symfony Console, DI, YAML, logger; useful scripts are `composer test`, `composer analyse`, `composer lint-config`, and `composer cs-fix`.
- `spc.registry.yml`: built-in `core` registry.
- `config/pkg/ext`: PHP extension package YAML, usually named `ext-*.yml`.
- `config/pkg/lib`: library package YAML.
- `config/pkg/target`: final build target and virtual target YAML.
- `config/pkg/tool`: helper tool package YAML.
- `config/artifact`: standalone artifact YAML for shared or complex sources/binaries.
- `log/`: build and shell execution logs (`spc.output.log`, `spc.shell.log`, and per-package CMake/config logs); controlled by `SPC_LOGS_DIR` and `SPC_ENABLE_LOG_FILE`.
- `src/StaticPHP`: framework core: registry loading, config validation, dependency resolution, package install/build pipeline, doctor, toolchains, runtime shell/executors, exceptions.
- `src/Package`: package-specific build logic registered by PHP attributes.
- `src/globals`: constants, helper functions, patches, smoke tests, bundled license text.
- `tests`: PHPUnit tests for config, registry, artifacts, dependency resolver, DI, commands, and utilities.
- `docs/en/develop` and `docs/zh/develop`: developer documentation. Some pages may be TODO; verify against source when behavior matters.
## Working Rules
- Keep changes scoped to the requested package, artifact, command, docs, or tests.
- Prefer existing package patterns over new abstractions. Search for a similar package first.
- Use structured YAML config; do not encode dependency logic in PHP when config fields are enough.
- Match package names exactly: extension packages use `ext-` in config and dependencies; `#[Extension('curl')]` expands to `ext-curl`.
- Use platform suffixes such as `@unix`, `@linux`, `@macos`, and `@windows` instead of runtime conditionals when the difference is declarative.
- Add or update PHP package classes only when build commands, validation, custom configure args, hooks, or source patching are required.
- Do not edit generated build directories (`buildroot/`, `source/`, `downloads/`, `pkgroot/`) as a fix.
## Validation
For config or package changes, run CS checks first:
```bash
bin/spc dev:lint-config
composer cs-fix
```
For broader PHP code changes, also run:
```bash
composer test
composer analyse
```
Use build commands only when needed for the task or when the user provided a repro, because full static builds can be slow and platform-sensitive.

View File

@@ -104,7 +104,7 @@ echo '<?php echo "Hello world!\n";' > a.php
## 直接下载 ## 直接下载
如果你暂时不想构建,或只想先测试,可以从 [Actions](https://github.com/static-php/static-php-cli-hosted/actions/workflows/build-php-bulk.yml) 下载示例预编译产物,或从自托管服务器下载。 如果你暂时不想构建,或只想先测试,可以从 [Actions](https://github.com/static-php/hosted/actions/workflows/build-php-bulk.yml) 下载示例预编译产物,或从自托管服务器下载。
我们为每个 PHP 版本提供 2 种扩展集合: 我们为每个 PHP 版本提供 2 种扩展集合:

View File

@@ -104,7 +104,7 @@ see <https://static-php.dev>.
## Direct Download ## Direct Download
If you do not want to build yet or just want to test first, you can download example pre-compiled artifacts from [Actions](https://github.com/static-php/static-php-cli-hosted/actions/workflows/build-php-bulk.yml) or from a self-hosted server. If you do not want to build yet or just want to test first, you can download example pre-compiled artifacts from [Actions](https://github.com/static-php/hosted/actions/workflows/build-php-bulk.yml) or from a self-hosted server.
We offer 2 types of extension sets for each PHP version: We offer 2 types of extension sets for each PHP version:

View File

@@ -20,7 +20,7 @@
] ]
}, },
{ {
"action": "bin/spc dev:lint-config --check", "action": "php bin/spc dev:lint-config --check",
"conditions": [ "conditions": [
{ {
"exec": "\\CaptainHook\\App\\Hook\\Condition\\FileStaged\\InDirectory", "exec": "\\CaptainHook\\App\\Hook\\Condition\\FileStaged\\InDirectory",

View File

@@ -53,8 +53,8 @@ PHP_BUILD_PROVIDER="StaticPHP ${SPC_VERSION}"
SPC_ENABLE_LOG_FILE="yes" SPC_ENABLE_LOG_FILE="yes"
; The LOG DIR for spc logs ; The LOG DIR for spc logs
SPC_LOGS_DIR="${WORKING_DIR}/log" SPC_LOGS_DIR="${WORKING_DIR}/log"
; Preserve old logs when running new builds ; Preserve old logs when running new builds (code checks SPC_PRESERVE_LOG, not SPC_PRESERVE_LOGS)
SPC_PRESERVE_LOGS="no" SPC_PRESERVE_LOG="no"
; EXTENSION_DIR where the built php will look for extension when a .ini instructs to load them ; EXTENSION_DIR where the built php will look for extension when a .ini instructs to load them
; only useful for builds targeting not pure-static linking ; only useful for builds targeting not pure-static linking

View File

@@ -13,4 +13,5 @@ ext-imagick:
os: os:
- Linux - Linux
- Darwin - Darwin
- Windows
arg-type: custom arg-type: custom

View File

@@ -10,6 +10,11 @@ ext-zip:
license: PHP-3.01 license: PHP-3.01
depends: depends:
- libzip - libzip
depends@windows:
- libzip
- zlib
- xz
- bzip2
php-extension: php-extension:
arg-type: custom arg-type: custom
arg-type@windows: enable arg-type@windows: enable

View File

@@ -16,13 +16,59 @@ imagemagick:
- libtiff - libtiff
- libheif - libheif
- bzip2 - bzip2
depends@windows:
- zlib
suggests: suggests:
- zstd - zstd
- xz - xz
- libzip - libzip
- libxml2 - libxml2
headers@windows:
- imagemagick/MagickWand/MagickWand.h
lang: cpp lang: cpp
pkg-configs: pkg-configs:
- Magick++-7.Q16HDRI - Magick++-7.Q16HDRI
- MagickCore-7.Q16HDRI - MagickCore-7.Q16HDRI
- MagickWand-7.Q16HDRI - MagickWand-7.Q16HDRI
static-libs@windows:
- CORE_RL_MagickWand_.lib
- CORE_RL_MagickCore_.lib
- CORE_RL_coders_.lib
- CORE_RL_filters_.lib
- CORE_RL_aom_.lib
- CORE_RL_brotli_.lib
- CORE_RL_bzip2_.lib
- CORE_RL_cairo_.lib
- CORE_RL_croco_.lib
- CORE_RL_de265_.lib
- CORE_RL_exr_.lib
- CORE_RL_ffi_.lib
- CORE_RL_freetype_.lib
- CORE_RL_fribidi_.lib
- CORE_RL_gdk-pixbuf_.lib
- CORE_RL_glib_.lib
- CORE_RL_harfbuzz_.lib
- CORE_RL_heif_.lib
- CORE_RL_highway_.lib
- CORE_RL_imath_.lib
- CORE_RL_jpeg-turbo-12_.lib
- CORE_RL_jpeg-turbo-16_.lib
- CORE_RL_jpeg-turbo_.lib
- CORE_RL_jpeg-xl_.lib
- CORE_RL_lcms_.lib
- CORE_RL_lqr_.lib
- CORE_RL_lzma_.lib
- CORE_RL_openh264_.lib
- CORE_RL_openjpeg_.lib
- CORE_RL_openjph_.lib
- CORE_RL_pango_.lib
- CORE_RL_pixman_.lib
- CORE_RL_png_.lib
- CORE_RL_raqm_.lib
- CORE_RL_raw_.lib
- CORE_RL_rsvg_.lib
- CORE_RL_tiff_.lib
- CORE_RL_webp_.lib
- CORE_RL_xml_.lib
- CORE_RL_zip_.lib
- CORE_RL_zlib_.lib

View File

@@ -9,5 +9,4 @@ libiconv-win:
license-files: [source/COPYING] license-files: [source/COPYING]
license: GPL-3.0-or-later license: GPL-3.0-or-later
static-libs@windows: static-libs@windows:
- libiconv.lib
- libiconv_a.lib - libiconv_a.lib

View File

@@ -9,8 +9,10 @@ libssh2:
metadata: metadata:
license-files: [COPYING] license-files: [COPYING]
license: BSD-3-Clause license: BSD-3-Clause
depends: depends@unix:
- openssl - openssl
depends@windows:
- zlib
headers: headers:
- libssh2.h - libssh2.h
- libssh2_publickey.h - libssh2_publickey.h

View File

@@ -11,6 +11,10 @@ libzip:
license: BSD-3-Clause license: BSD-3-Clause
depends: depends:
- zlib - zlib
depends@windows:
- zlib
- bzip2
- xz
suggests: suggests:
- bzip2 - bzip2
- xz - xz

View File

@@ -17,7 +17,6 @@ openssl:
- zlib - zlib
depends@windows: depends@windows:
- zlib - zlib
- jom
headers: headers:
- openssl - openssl
static-libs@unix: static-libs@unix:
@@ -26,3 +25,7 @@ openssl:
static-libs@windows: static-libs@windows:
- libssl.lib - libssl.lib
- libcrypto.lib - libcrypto.lib
tools@windows:
- jom
- nasm
- strawberry-perl

View File

@@ -5,8 +5,6 @@ postgresql:
type: ghtagtar type: ghtagtar
repo: postgres/postgres repo: postgres/postgres
match: REL_18_\d+ match: REL_18_\d+
binary:
windows-x86_64: { type: url, url: 'https://get.enterprisedb.com/postgresql/postgresql-16.8-1-windows-x64-binaries.zip', extract: { lib/libpq.lib: '{build_root_path}/lib/libpq.lib', lib/libpgport.lib: '{build_root_path}/lib/libpgport.lib', lib/libpgcommon.lib: '{build_root_path}/lib/libpgcommon.lib', include/libpq-fe.h: '{build_root_path}/include/libpq-fe.h', include/postgres_ext.h: '{build_root_path}/include/postgres_ext.h', include/pg_config_ext.h: '{build_root_path}/include/pg_config_ext.h', include/libpq/libpq-fs.h: '{build_root_path}/include/libpq/libpq-fs.h' } }
metadata: metadata:
license-files: ['@/postgresql.txt'] license-files: ['@/postgresql.txt']
license: PostgreSQL license: PostgreSQL
@@ -16,6 +14,9 @@ postgresql:
- openssl - openssl
- zlib - zlib
- libedit - libedit
depends@windows:
- openssl
- zlib
suggests@unix: suggests@unix:
- icu - icu
- libxslt - libxslt
@@ -27,3 +28,9 @@ postgresql:
- libpq.lib - libpq.lib
- libpgport.lib - libpgport.lib
- libpgcommon.lib - libpgcommon.lib
tools@windows:
- python-win
- meson
- ninja
- winflexbison
- strawberry-perl

View File

@@ -10,10 +10,8 @@ frankenphp:
license: MIT license: MIT
depends: depends:
- php-embed - php-embed
- go-xcaddy
depends@windows: depends@windows:
- php-embed - php-embed
- go-win
- pthreads4w - pthreads4w
suggests@unix: suggests@unix:
- brotli - brotli
@@ -24,3 +22,7 @@ frankenphp:
- frankenphp - frankenphp
static-bins@windows: static-bins@windows:
- frankenphp.exe - frankenphp.exe
tools:
- go-xcaddy
tools@windows:
- go-win

View File

@@ -1,9 +0,0 @@
pkg-config:
type: target
artifact:
source: 'https://dl.static-php.dev/static-php-cli/deps/pkg-config/pkg-config-0.29.2.tar.gz'
binary:
linux-x86_64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-x86_64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
linux-aarch64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-aarch64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-x86_64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-x86_64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-aarch64: { type: ghrel, repo: static-php/static-php-cli-hosted, match: pkg-config-aarch64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }

View File

@@ -1,4 +0,0 @@
zig:
type: target
artifact:
binary: custom

View File

@@ -1,5 +1,9 @@
7za-win: 7za-win:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://dl.static-php.dev/v3/tools/7zip/7za.exe', extract: '{pkg_root_path}/bin/7za.exe' } windows-x86_64: { type: url, url: 'https://dl.static-php.dev/v3/tools/7zip/7za.exe', extract: '{pkg_root_path}/bin/7za.exe' }
tool:
provides:
- 7za.exe
binary-subdir: bin

View File

@@ -1,10 +1,15 @@
go-win: go-win:
type: target type: tool
artifact: artifact:
binary: custom binary: custom
env: env:
GOROOT: '{pkg_root_path}/go-win' GOROOT: '{pkg_root_path}/go-win'
GOBIN: '{pkg_root_path}/go-win/bin' GOBIN: '{pkg_root_path}/go-win/bin'
GOPATH: '{pkg_root_path}/go-win/go' GOPATH: '{pkg_root_path}/go-win/gopath'
path@windows: path@windows:
- '{pkg_root_path}/go-win/bin' - '{pkg_root_path}/go-win/bin'
tool:
provides:
- go.exe
- gofmt.exe
binary-subdir: go-win/bin

View File

@@ -1,5 +1,5 @@
go-xcaddy: go-xcaddy:
type: target type: tool
artifact: artifact:
binary: custom binary: custom
env: env:
@@ -8,5 +8,8 @@ go-xcaddy:
GOPATH: '{pkg_root_path}/go-xcaddy/go' GOPATH: '{pkg_root_path}/go-xcaddy/go'
path@unix: path@unix:
- '{pkg_root_path}/go-xcaddy/bin' - '{pkg_root_path}/go-xcaddy/bin'
static-bins: tool:
- xcaddy provides:
- go
- gofmt
binary-subdir: go-xcaddy/bin

View File

@@ -1,7 +1,11 @@
jom: jom:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://download.qt.io/official_releases/jom/jom.zip', extract: '{pkg_root_path}/jom' } windows-x86_64: { type: url, url: 'https://download.qt.io/official_releases/jom/jom.zip', extract: '{pkg_root_path}/jom' }
path@windows: path@windows:
- '{pkg_root_path}\jom' - '{pkg_root_path}\jom'
tool:
provides:
- jom.exe
binary-subdir: jom

11
config/pkg/tool/meson.yml Normal file
View File

@@ -0,0 +1,11 @@
meson:
type: tool
artifact:
binary:
windows-x86_64: { type: url, url: 'https://github.com/mesonbuild/meson/releases/download/1.11.1/meson-1.11.1-py3-none-any.whl', extract: '{pkg_root_path}/meson/meson-1.11.1-py3-none-any.whl' }
path@windows:
- '{pkg_root_path}\meson'
tool:
provides:
- meson.bat
binary-subdir: meson

View File

@@ -1,5 +1,10 @@
nasm: nasm:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://dl.static-php.dev/static-php-cli/deps/nasm/nasm-2.16.01-win64.zip', extract: { nasm.exe: '{pkg_root_path}/bin/nasm.exe', ndisasm.exe: '{pkg_root_path}/bin/ndisasm.exe' } } windows-x86_64: { type: url, url: 'https://dl.static-php.dev/static-php-cli/deps/nasm/nasm-2.16.01-win64.zip', extract: { nasm.exe: '{pkg_root_path}/bin/nasm.exe', ndisasm.exe: '{pkg_root_path}/bin/ndisasm.exe' } }
tool:
provides:
- nasm.exe
- ndisasm.exe
binary-subdir: bin

View File

@@ -0,0 +1,9 @@
ninja:
type: tool
artifact:
binary:
windows-x86_64: { type: url, url: 'https://github.com/ninja-build/ninja/releases/download/v1.13.2/ninja-win.zip', extract: { ninja.exe: '{pkg_root_path}/bin/ninja.exe' } }
tool:
provides:
- ninja.exe
binary-subdir: bin

View File

@@ -0,0 +1,13 @@
pkg-config:
type: tool
artifact:
source: 'https://dl.static-php.dev/static-php-cli/deps/pkg-config/pkg-config-0.29.2.tar.gz'
binary:
linux-x86_64: { type: ghrel, repo: static-php/hosted, match: pkg-config-x86_64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
linux-aarch64: { type: ghrel, repo: static-php/hosted, match: pkg-config-aarch64-linux-musl-1.2.5.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-x86_64: { type: ghrel, repo: static-php/hosted, match: pkg-config-x86_64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
macos-aarch64: { type: ghrel, repo: static-php/hosted, match: pkg-config-aarch64-darwin.txz, extract: { bin/pkg-config: '{pkg_root_path}/bin/pkg-config' } }
tool:
provides:
- pkg-config
binary-subdir: bin

View File

@@ -1,8 +1,12 @@
protoc: protoc:
type: target type: tool
artifact: artifact:
binary: binary:
linux-x86_64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-x86_64\.zip', extract: '{pkg_root_path}/protoc' } linux-x86_64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-x86_64\.zip', extract: '{pkg_root_path}/protoc' }
linux-aarch64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-aarch_64\.zip', extract: '{pkg_root_path}/protoc' } linux-aarch64: { type: ghrel, repo: protocolbuffers/protobuf, match: 'protoc-([0-9.]+)-linux-aarch_64\.zip', extract: '{pkg_root_path}/protoc' }
path: path:
- '{pkg_root_path}/protoc/bin' - '{pkg_root_path}/protoc/bin'
tool:
provides:
- protoc
binary-subdir: protoc/bin

View File

@@ -0,0 +1,8 @@
python-win:
type: tool
artifact:
binary: custom
tool:
provides:
- python.exe
binary-subdir: python-win/tools

View File

@@ -1,5 +1,9 @@
strawberry-perl: strawberry-perl:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://github.com/StrawberryPerl/Perl-Dist-Strawberry/releases/download/SP_5380_5361/strawberry-perl-5.38.0.1-64bit-portable.zip', extract: '{pkg_root_path}/strawberry-perl' } windows-x86_64: { type: url, url: 'https://github.com/StrawberryPerl/Perl-Dist-Strawberry/releases/download/SP_5380_5361/strawberry-perl-5.38.0.1-64bit-portable.zip', extract: '{pkg_root_path}/strawberry-perl' }
tool:
provides:
- perl.exe
binary-subdir: strawberry-perl/perl/bin

View File

@@ -1,7 +1,13 @@
upx: upx:
type: target type: tool
artifact: artifact:
binary: binary:
linux-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-amd64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } } linux-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-amd64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } }
linux-aarch64: { type: ghrel, repo: upx/upx, match: upx.+-arm64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } } linux-aarch64: { type: ghrel, repo: upx/upx, match: upx.+-arm64_linux\.tar\.xz, extract: { upx: '{pkg_root_path}/bin/upx' } }
windows-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-win64\.zip, extract: { upx.exe: '{pkg_root_path}/bin/upx.exe' } } windows-x86_64: { type: ghrel, repo: upx/upx, match: upx.+-win64\.zip, extract: { upx.exe: '{pkg_root_path}/bin/upx.exe' } }
tool:
provides:
- upx
provides@windows:
- upx.exe
binary-subdir: bin

View File

@@ -1,5 +1,9 @@
vswhere: vswhere:
type: target type: tool
artifact: artifact:
binary: binary:
windows-x86_64: { type: url, url: 'https://github.com/microsoft/vswhere/releases/download/3.1.7/vswhere.exe', extract: '{pkg_root_path}/bin/vswhere.exe' } windows-x86_64: { type: url, url: 'https://github.com/microsoft/vswhere/releases/download/3.1.7/vswhere.exe', extract: '{pkg_root_path}/bin/vswhere.exe' }
tool:
provides:
- vswhere.exe
binary-subdir: bin

View File

@@ -0,0 +1,12 @@
winflexbison:
type: tool
artifact:
binary:
windows-x86_64: { type: url, url: 'https://github.com/lexxmark/winflexbison/releases/download/v2.5.25/win_flex_bison-2.5.25.zip', extract: '{pkg_root_path}/winflexbison' }
path@windows:
- '{pkg_root_path}\winflexbison'
tool:
provides:
- win_flex.exe
- win_bison.exe
binary-subdir: winflexbison

14
config/pkg/tool/zig.yml Normal file
View File

@@ -0,0 +1,14 @@
zig:
type: tool
artifact:
binary: custom
tool:
provides:
- zig
- zig-cc
- zig-c++
- zig-ar
- zig-ld.lld
- zig-ranlib
- zig-objcopy
binary-subdir: zig

View File

@@ -10,6 +10,7 @@ package:
- config/pkg/lib/ - config/pkg/lib/
- config/pkg/target/ - config/pkg/target/
- config/pkg/ext/ - config/pkg/ext/
- config/pkg/tool/
artifact: artifact:
config: config:
- config/artifact/ - config/artifact/

View File

@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Package\Artifact;
use StaticPHP\Attribute\Artifact\AfterBinaryExtract;
use StaticPHP\Exception\EnvironmentException;
use StaticPHP\Util\FileSystem;
class meson_win
{
/**
* Meson 1.11 dropped the Windows MSI, so the artifact is the wheel, installed offline
* into a private venv. The venv is not just packaging hygiene: pip generates a real
* meson.exe launcher there, and PostgreSQL needs one because its build re-invokes meson
* through find_program(), which rejects non-executables like the meson.pyz zipapp.
*/
#[AfterBinaryExtract('meson', ['windows-x86_64'])]
public function afterExtract(string $target_path): void
{
$dir = dirname($target_path);
$venv = "{$dir}\\venv";
// Prefer the python-win tool package (installed alongside via tools@windows),
// fall back to whatever Python the machine already has.
$candidates = ['"' . PKG_ROOT_PATH . '\python-win\tools\python.exe"', 'python', 'py -3'];
$python = null;
foreach ($candidates as $candidate) {
[$code] = cmd()->execWithResult("{$candidate} --version", false);
if ($code === 0) {
$python = $candidate;
break;
}
}
if ($python === null) {
throw new EnvironmentException('meson needs Python 3; the python-win tool package did not install and no system Python was found.');
}
if (is_dir($venv)) {
FileSystem::removeDir($venv);
}
cmd()->exec("{$python} -m venv \"{$venv}\"")
->exec("\"{$venv}\\Scripts\\python.exe\" -m pip install --no-index --no-deps \"{$target_path}\"");
FileSystem::writeFile("{$dir}\\meson.bat", "@echo off\r\n\"%~dp0venv\\Scripts\\meson.exe\" %*\r\n");
}
}

View File

@@ -16,7 +16,7 @@ use StaticPHP\Util\GlobalEnvManager;
class msys2_build_essentials class msys2_build_essentials
{ {
// MSYS subsystem packages required for autotools-based builds. // MSYS subsystem packages required for autotools-based builds.
private const REQUIRED_PACKAGES = ['make', 'autoconf', 'automake', 'libtool', 'pkgconf', 'perl']; private const REQUIRED_PACKAGES = ['make', 'autoconf', 'automake', 'libtool', 'pkgconf', 'perl', 'bison', 're2c'];
#[CustomBinary('msys2-build-essentials', ['windows-x86_64'])] #[CustomBinary('msys2-build-essentials', ['windows-x86_64'])]
public function downBinary(ArtifactDownloader $downloader): DownloadResult public function downBinary(ArtifactDownloader $downloader): DownloadResult

View File

@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Package\Artifact;
use StaticPHP\Artifact\ArtifactDownloader;
use StaticPHP\Artifact\Downloader\DownloadResult;
use StaticPHP\Artifact\Downloader\Type\CheckUpdateResult;
use StaticPHP\Attribute\Artifact\AfterBinaryExtract;
use StaticPHP\Attribute\Artifact\CustomBinary;
use StaticPHP\Attribute\Artifact\CustomBinaryCheckUpdate;
use StaticPHP\Exception\DownloaderException;
/**
* Full CPython for Windows from the official python.org nuget package. It is a plain zip
* (python.exe plus stdlib under tools/, venv and ensurepip included), so it installs into
* the pkgroot without touching the system. Used by the meson tool package.
*/
class python_win
{
#[CustomBinary('python-win', [
'windows-x86_64',
])]
public function downBinary(ArtifactDownloader $downloader): DownloadResult
{
$version = $this->getLatestVersion($downloader->getRetry());
$url = "https://api.nuget.org/v3-flatcontainer/python/{$version}/python.{$version}.nupkg";
// .nupkg is a zip; name the cache file .zip so the extractor treats it as one
$path = DOWNLOAD_PATH . DIRECTORY_SEPARATOR . "python-win-{$version}.zip";
default_shell()->executeCurlDownload($url, $path, retries: $downloader->getRetry());
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: '{pkg_root_path}/python-win', version: $version);
}
#[CustomBinaryCheckUpdate('python-win', ['windows-x86_64'])]
public function checkUpdateBinary(?string $old_version): CheckUpdateResult
{
$version = $this->getLatestVersion();
return new CheckUpdateResult(
old: $old_version,
new: $version,
needUpdate: $old_version === null || $version !== $old_version,
);
}
#[AfterBinaryExtract('python-win', ['windows-x86_64'])]
public function afterExtract(string $target_path): void
{
if (!file_exists("{$target_path}\\tools\\python.exe")) {
throw new DownloaderException("Python installation appears incomplete: python.exe not found at {$target_path}\\tools\\python.exe");
}
}
private function getLatestVersion(int $retries = 0): string
{
$index = default_shell()->executeCurl('https://api.nuget.org/v3-flatcontainer/python/index.json', retries: $retries);
$versions = $index ? (json_decode($index, true)['versions'] ?? []) : [];
$stable = array_filter($versions, fn ($v) => preg_match('/^\d+\.\d+\.\d+$/', $v));
if ($stable === []) {
throw new DownloaderException('Failed to get Python versions from the nuget index');
}
return end($stable);
}
}

View File

@@ -20,7 +20,7 @@ class curl
// which requires secur32.lib for SSL/TLS functions (SslEncryptPackage, etc.). // which requires secur32.lib for SSL/TLS functions (SslEncryptPackage, etc.).
$extra_libs = getenv('SPC_EXTRA_LIBS') ?: ''; $extra_libs = getenv('SPC_EXTRA_LIBS') ?: '';
if (!str_contains($extra_libs, 'secur32.lib')) { if (!str_contains($extra_libs, 'secur32.lib')) {
putenv('SPC_EXTRA_LIBS=' . trim($extra_libs . ' secur32.lib')); putenv('SPC_EXTRA_LIBS=' . trim("{$extra_libs} secur32.lib"));
} }
} }
} }

View File

@@ -27,6 +27,18 @@ class gmssl extends PhpExtensionPackage
); );
} }
#[BeforeStage('php', [php::class, 'buildconfForUnix'], 'ext-gmssl')]
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-gmssl')]
#[PatchDescription('Fix ext-gmssl v1.1.1: pbkdf2_hmac_sm3_genkey was renamed to sm3_pbkdf2 in GmSSL >= 3.2.0')]
public function patchPbkdf2Rename(): void
{
FileSystem::replaceFileStr(
"{$this->getSourceDir()}/gmssl.c",
'pbkdf2_hmac_sm3_genkey',
'sm3_pbkdf2'
);
}
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-gmssl')] #[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-gmssl')]
#[PatchDescription('Add CHECK_LIB to config.w32 for static Windows builds')] #[PatchDescription('Add CHECK_LIB to config.w32 for static Windows builds')]
public function patchBeforeBuildconfWin(): bool public function patchBeforeBuildconfWin(): bool

View File

@@ -4,12 +4,17 @@ declare(strict_types=1);
namespace Package\Extension; namespace Package\Extension;
use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\CustomPhpConfigureArg; use StaticPHP\Attribute\Package\CustomPhpConfigureArg;
use StaticPHP\Attribute\Package\Extension; use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Util\FileSystem;
#[Extension('imagick')] #[Extension('imagick')]
class imagick class imagick extends PhpExtensionPackage
{ {
#[CustomPhpConfigureArg('Darwin')] #[CustomPhpConfigureArg('Darwin')]
#[CustomPhpConfigureArg('Linux')] #[CustomPhpConfigureArg('Linux')]
@@ -18,4 +23,35 @@ class imagick
$disable_omp = ' ac_cv_func_omp_pause_resource_all=no'; $disable_omp = ' ac_cv_func_omp_pause_resource_all=no';
return '--with-imagick=' . ($shared ? 'shared,' : '') . $builder->getBuildRootPath() . $disable_omp; return '--with-imagick=' . ($shared ? 'shared,' : '') . $builder->getBuildRootPath() . $disable_omp;
} }
#[CustomPhpConfigureArg('Windows')]
public function getWindowsConfigureArg(bool $shared): string
{
// config.w32 uses PHP_IMAGICK as an extra search path for CORE_RL_*.lib; the static
// ImageMagick libs are installed flat in buildroot/lib (headers in buildroot/include/imagemagick).
return '--with-imagick=' . BUILD_LIB_PATH;
}
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-imagick')]
#[PatchDescription('Add the Win32 system libraries the static ImageMagick stack needs')]
public function patchConfigW32ForWindows(): void
{
$config = $this->getSourceDir() . '/config.w32';
// Idempotency guard (the source dir may be patched in place and reused across builds).
if (str_contains(FileSystem::readFile($config), 'LIBS_IMAGICK')) {
return;
}
// The static ImageMagick stack needs several Win32 system libraries (GDI/GDI+, WIC, urlmon, ...)
// that aren't already pulled in by the other extensions. (imagick itself builds as plain C:
// ImageMagick is built with a 32-bit channel mask, see imagemagick.php buildWin, so the
// MagickCore headers don't require a C++ translation unit.)
FileSystem::replaceFileStr(
$config,
"AC_DEFINE('HAVE_IMAGICK', 1);",
'ADD_FLAG("LIBS_IMAGICK", "gdi32.lib gdiplus.lib urlmon.lib msimg32.lib oleaut32.lib windowscodecs.lib iphlpapi.lib");' . "\n\t\t" .
"AC_DEFINE('HAVE_IMAGICK', 1);"
);
}
} }

View File

@@ -1,25 +0,0 @@
<?php
declare(strict_types=1);
namespace Package\Extension;
use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Package\PackageInstaller;
use StaticPHP\Util\FileSystem;
#[Extension('pdo_sqlite')]
class pdo_sqlite
{
#[BeforeStage('php', [php::class, 'configureForUnix'], 'ext-pdo_sqlite')]
public function patchBeforeConfigure(PackageInstaller $installer): void
{
FileSystem::replaceFileRegex(
"{$installer->getTargetPackage('php')->getSourceDir()}/configure",
'/sqlite3_column_table_name=yes/',
'sqlite3_column_table_name=no'
);
}
}

View File

@@ -5,11 +5,15 @@ declare(strict_types=1);
namespace Package\Extension; namespace Package\Extension;
use Package\Target\php; use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\CustomPhpConfigureArg; use StaticPHP\Attribute\Package\CustomPhpConfigureArg;
use StaticPHP\Attribute\Package\Extension; use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage; use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Package\TargetPackage;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\SPCConfigUtil; use StaticPHP\Util\SPCConfigUtil;
#[Extension('pgsql')] #[Extension('pgsql')]
@@ -39,6 +43,27 @@ class pgsql extends PhpExtensionPackage
return "--with-pgsql={$builder->getBuildRootPath()}"; return "--with-pgsql={$builder->getBuildRootPath()}";
} }
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-pgsql')]
#[PatchDescription('Link the Win32 system libraries the static libpq needs')]
public function patchConfigW32ForWindows(TargetPackage $package): void
{
$config = "{$package->getSourceDir()}\\ext\\pgsql\\config.w32";
if (str_contains(FileSystem::readFile($config), 'LIBS_PGSQL')) {
return;
}
// libpq uses SSPI for Windows auth (secur32) and the static libcrypto behind it
// reads the system cert store (crypt32). Nothing else puts these on the link line
// when the openssl extension itself is not part of the build.
FileSystem::replaceFileStr(
$config,
'EXTENSION("pgsql", "pgsql.c", PHP_PGSQL_SHARED, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1");',
'EXTENSION("pgsql", "pgsql.c", PHP_PGSQL_SHARED, "/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1");' . "\n\t\t" .
'ADD_FLAG("LIBS_PGSQL", "secur32.lib crypt32.lib");'
);
}
public function getSharedExtensionEnv(): array public function getSharedExtensionEnv(): array
{ {
$parent = parent::getSharedExtensionEnv(); $parent = parent::getSharedExtensionEnv();

View File

@@ -50,8 +50,9 @@ class simdjson extends PhpExtensionPackage
if (!str_contains((string) $extra, '-lstdc++')) { if (!str_contains((string) $extra, '-lstdc++')) {
f_putenv('SPC_COMPILER_EXTRA=' . clean_spaces($extra . ' -lstdc++')); f_putenv('SPC_COMPILER_EXTRA=' . clean_spaces($extra . ' -lstdc++'));
} }
$env['CFLAGS'] .= ' -Xclang -target-feature -Xclang +evex512';
$env['CXXFLAGS'] .= ' -Xclang -target-feature -Xclang +evex512'; $env['CFLAGS'] .= ' -fno-sanitize=undefined -Xclang -target-feature -Xclang +evex512';
$env['CXXFLAGS'] .= ' -fno-sanitize=undefined -Xclang -target-feature -Xclang +evex512';
} }
return $env; return $env;
} }
@@ -63,8 +64,8 @@ class simdjson extends PhpExtensionPackage
return; return;
} }
$extra_cflags = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') ?: ''; $extra_cflags = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') ?: '';
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . trim($extra_cflags . ' -Xclang -target-feature -Xclang +evex512')); GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . trim($extra_cflags . ' -fno-sanitize=undefined -Xclang -target-feature -Xclang +evex512'));
$extra_cxxflags = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS') ?: ''; $extra_cxxflags = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS') ?: '';
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS=' . trim($extra_cxxflags . ' -Xclang -target-feature -Xclang +evex512')); GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS=' . trim($extra_cxxflags . ' -fno-sanitize=undefined -Xclang -target-feature -Xclang +evex512'));
} }
} }

View File

@@ -30,6 +30,7 @@ class swoole extends PhpExtensionPackage
if ($installer->getPhpExtensionPackage('swoole-hook-odbc') && $installer->getPhpExtensionPackage('pdo_odbc')?->isBuildStatic()) { if ($installer->getPhpExtensionPackage('swoole-hook-odbc') && $installer->getPhpExtensionPackage('pdo_odbc')?->isBuildStatic()) {
throw new WrongUsageException('swoole-hook-odbc provides pdo_odbc, if you enable odbc hook for swoole, you must remove pdo_odbc extension.'); throw new WrongUsageException('swoole-hook-odbc provides pdo_odbc, if you enable odbc hook for swoole, you must remove pdo_odbc extension.');
} }
// swoole-hook-pgsql conflicts with pdo_pgsql // swoole-hook-pgsql conflicts with pdo_pgsql
if ($installer->getPhpExtensionPackage('swoole-hook-pgsql') && $installer->getPhpExtensionPackage('pdo_pgsql')?->isBuildStatic()) { if ($installer->getPhpExtensionPackage('swoole-hook-pgsql') && $installer->getPhpExtensionPackage('pdo_pgsql')?->isBuildStatic()) {
throw new WrongUsageException('swoole-hook-pgsql provides pdo_pgsql, if you enable pgsql hook for swoole, you must remove pdo_pgsql extension.'); throw new WrongUsageException('swoole-hook-pgsql provides pdo_pgsql, if you enable pgsql hook for swoole, you must remove pdo_pgsql extension.');

View File

@@ -11,6 +11,7 @@ use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Attribute\PatchDescription; use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage; use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\SourcePatcher; use StaticPHP\Util\SourcePatcher;
#[Extension('xlswriter')] #[Extension('xlswriter')]
@@ -28,16 +29,30 @@ class xlswriter extends PhpExtensionPackage
return $arg; return $arg;
} }
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-xlswriter')]
#[PatchDescription('Define XML_STATIC so bundled Expat uses plain symbols instead of __declspec(dllimport) in static builds')]
public function patchConfigForStaticExpat(): void
{
FileSystem::replaceFileStr(
"{$this->getSourceDir()}/config.w32",
"' /D USE_SYSTEM_MINIZIP",
"' /D XML_STATIC /D USE_SYSTEM_MINIZIP"
);
}
#[BeforeStage('php', [php::class, 'makeForWindows'], 'ext-xlswriter')] #[BeforeStage('php', [php::class, 'makeForWindows'], 'ext-xlswriter')]
#[PatchDescription('Fix Windows build: apply win32 patch and add UTF-8 BOM to theme.c')] #[PatchDescription('Fix Windows build: apply win32 patch and add UTF-8 BOM to theme.c')]
public function patchBeforeMakeForWindows(): void public function patchBeforeMakeForWindows(): void
{ {
$source_dir = $this->getSourceDir();
$theme_file = "{$source_dir}/library/libxlsx/src/theme.c";
// fix windows build with openssl extension duplicate symbol bug // fix windows build with openssl extension duplicate symbol bug
SourcePatcher::patchFile('spc_fix_xlswriter_win32.patch', $this->getSourceDir()); SourcePatcher::patchFile('spc_fix_xlswriter_win32.patch', $source_dir);
$content = file_get_contents($this->getSourceDir() . '/library/libxlsxwriter/src/theme.c'); $content = file_get_contents($theme_file);
$bom = pack('CCC', 0xEF, 0xBB, 0xBF); $bom = pack('CCC', 0xEF, 0xBB, 0xBF);
if (!str_starts_with($content, $bom)) { if (!str_starts_with($content, $bom)) {
file_put_contents($this->getSourceDir() . '/library/libxlsxwriter/src/theme.c', $bom . $content); file_put_contents($theme_file, $bom . $content);
} }
} }
} }

View File

@@ -45,13 +45,13 @@ class gmssl
->toStep(1) ->toStep(1)
->build(); ->build();
// fix cmake_install.cmake install prefix (GmSSL overrides it internally) cmd()->cd($buildDir)->exec('nmake gmssl XCFLAGS=/MT');
$installCmake = "{$buildDir}\\cmake_install.cmake";
FileSystem::writeFile(
$installCmake,
'set(CMAKE_INSTALL_PREFIX "' . str_replace('\\', '/', $lib->getBuildRootPath()) . '")' . PHP_EOL . FileSystem::readFile($installCmake)
);
cmd()->cd($buildDir)->exec('nmake install XCFLAGS=/MT'); $libPath = "{$lib->getBuildRootPath()}/lib";
$incPath = "{$lib->getBuildRootPath()}/include/gmssl";
FileSystem::createDir($libPath);
FileSystem::createDir($incPath);
FileSystem::copy("{$buildDir}\\bin\\gmssl.lib", "{$libPath}/gmssl.lib");
FileSystem::copyDir("{$lib->getSourceDir()}\\include\\gmssl", $incPath);
} }
} }

View File

@@ -6,15 +6,86 @@ namespace Package\Library;
use StaticPHP\Attribute\Package\BuildFor; use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Library; use StaticPHP\Attribute\Package\Library;
use StaticPHP\Exception\EnvironmentException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor; use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\Interface\ToolchainInterface; use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\System\WindowsUtil;
#[Library('imagemagick')] #[Library('imagemagick')]
class imagemagick class imagemagick
{ {
/**
* Build a fully static, self-contained ImageMagick 7 (Q16-HDRI, /MT) on Windows using the
* official VisualMagick build (the ImageMagick/Windows + Configure + Dependencies repos), which
* bundles every delegate. ImageMagick has no autoconf/CMake build on Windows, so this clones the
* VisualMagick tree, generates a static x64 solution via the Configure tool, and builds it with
* msbuild. The resulting CORE_RL_*.lib static libraries + MagickWand/MagickCore headers are
* installed into the build root for ext-imagick to link.
*
* The VisualMagick tree lives under source/ so bin/spc reset cleans it up like everything
* else; override the location with SPC_IMAGEMAGICK_BUILD_DIR.
*/
#[BuildFor('Windows')]
public function buildWin(LibraryPackage $lib): void
{
$work = getenv('SPC_IMAGEMAGICK_BUILD_DIR') ?: SOURCE_PATH . '\imagemagick-win';
$configure_release = '2026.05.30.2033';
$configure_url = "https://github.com/ImageMagick/Configure/releases/download/{$configure_release}/Configure.Release.x64.exe";
FileSystem::createDir($work);
// Clone the VisualMagick repos (ImageMagick source + Configure + Dependencies + all delegates).
if (!is_dir("{$work}\\ImageMagick")) {
cmd()->cd($work)->exec(SPC_GIT_EXEC . ' clone --depth 1 https://github.com/ImageMagick/Windows.git .');
cmd()->cd($work)->exec('bash clone-repositories.sh --imagemagick7');
}
// 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);
// Generate a static, /MT (linkRuntime), x64, Q16-HDRI solution with the configs embedded
// (zeroConfigurationSupport) and OpenMP off (no vcomp runtime dependency).
$ver = WindowsUtil::findVisualStudio();
$vs_major = is_array($ver) ? $ver['major_version'] : 'unknown';
$vs_arg = match ($vs_major) {
'18',
'17' => '/VS2022',
'16' => '/VS2019',
default => throw new EnvironmentException("Current VS version {$vs_major} is not supported yet!"),
};
cmd()->cd("{$work}\\Configure")
->exec("Configure.Release.x64.exe /noWizard {$vs_arg} /x64 /static /linkRuntime /noOpenMP /zeroConfigurationSupport");
// 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.
FileSystem::replaceFileStr(
"{$work}\\ImageMagick\\MagickCore\\magick-baseconfig.h",
'#define MAGICKCORE_CHANNEL_MASK_DEPTH 64',
'#define MAGICKCORE_CHANNEL_MASK_DEPTH 32'
);
cmd()->cd($work)
->exec('msbuild IM7.Static.x64.sln /m /t:Rebuild /nologo /p:Configuration=Release /p:Platform=x64');
$artifacts = "{$work}\\Artifacts\\lib";
if (!is_dir($artifacts)) {
throw new EnvironmentException('ImageMagick VisualMagick build produced no Artifacts/lib; build failed.');
}
// Install the static libs (flat, onto the build-root lib path) and the public headers.
FileSystem::createDir($lib->getLibDir());
foreach (glob("{$artifacts}\\CORE_RL_*.lib") as $f) {
FileSystem::copy($f, $lib->getLibDir() . '\\' . basename($f));
}
foreach (['MagickWand', 'MagickCore'] as $dir) {
FileSystem::createDir($lib->getIncludeDir() . "\\imagemagick\\{$dir}");
foreach (glob("{$work}\\ImageMagick\\{$dir}\\*.h") as $h) {
FileSystem::copy($h, $lib->getIncludeDir() . "\\imagemagick\\{$dir}\\" . basename($h));
}
}
}
#[BuildFor('Darwin')] #[BuildFor('Darwin')]
#[BuildFor('Linux')] #[BuildFor('Linux')]
public function buildUnix(LibraryPackage $lib, ToolchainInterface $toolchain): void public function buildUnix(LibraryPackage $lib, ToolchainInterface $toolchain): void

View File

@@ -20,6 +20,7 @@ class libde265 extends LibraryPackage
->addConfigureArgs( ->addConfigureArgs(
'-DENABLE_SDL=OFF', '-DENABLE_SDL=OFF',
'-DENABLE_DECODER=OFF', '-DENABLE_DECODER=OFF',
'-DENABLE_SIMD=OFF',
'-DHAVE_NEON=OFF', '-DHAVE_NEON=OFF',
) )
->build(); ->build();

View File

@@ -18,6 +18,7 @@ class libssh2
{ {
WindowsCMakeExecutor::create($lib) WindowsCMakeExecutor::create($lib)
->addConfigureArgs( ->addConfigureArgs(
'-DCRYPTO_BACKEND=WinCNG',
'-DENABLE_ZLIB_COMPRESSION=ON', '-DENABLE_ZLIB_COMPRESSION=ON',
'-DBUILD_TESTING=OFF' '-DBUILD_TESTING=OFF'
) )

View File

@@ -6,43 +6,24 @@ namespace Package\Library;
use StaticPHP\Attribute\Package\BuildFor; use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Library; use StaticPHP\Attribute\Package\Library;
use StaticPHP\Attribute\Package\Validate;
use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\EnvironmentException; use StaticPHP\Exception\EnvironmentException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Package\ToolPackage;
use StaticPHP\Registry\PackageLoader;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\System\LinuxUtil; use StaticPHP\Util\System\LinuxUtil;
use StaticPHP\Util\System\WindowsUtil;
#[Library('openssl')] #[Library('openssl')]
class openssl class openssl
{ {
#[Validate]
public function validate(): void
{
if (SystemTarget::getTargetOS() === 'Windows') {
global $argv;
$perl_path_native = PKG_ROOT_PATH . '\strawberry-perl-' . arch2gnu(php_uname('m')) . '-win\perl\bin\perl.exe';
$perl = file_exists($perl_path_native) ? ($perl_path_native) : WindowsUtil::findCommand('perl.exe');
if ($perl === null) {
throw new EnvironmentException(
'You need to install perl first!',
"Please run \"{$argv[0]} doctor\" to fix the environment.",
);
}
ApplicationContext::set('perl', $perl);
}
}
#[BuildFor('Windows')] #[BuildFor('Windows')]
public function buildWin(LibraryPackage $lib, PackageBuilder $builder): void public function buildWin(LibraryPackage $lib, PackageBuilder $builder): void
{ {
$perl = ApplicationContext::get('perl'); $perl = $this->resolveWindowsPerl();
$cmd = cmd()->cd($lib->getSourceDir()) $cmd = cmd()->cd($lib->getSourceDir())
->exec( ->exec(
"{$perl} Configure zlib VC-WIN64A " . escapeshellarg($perl) . ' Configure zlib VC-WIN64A ' .
'no-shared ' . 'no-shared ' .
'--prefix=' . quote($lib->getBuildRootPath()) . ' ' . '--prefix=' . quote($lib->getBuildRootPath()) . ' ' .
'--with-zlib-lib=' . quote($lib->getLibDir()) . ' ' . '--with-zlib-lib=' . quote($lib->getLibDir()) . ' ' .
@@ -145,4 +126,22 @@ class openssl
FileSystem::replaceFileRegex("{$pkg->getLibDir()}/pkgconfig/libcrypto.pc", '/Libs.private:.*/m', 'Requires.private: zlib'); FileSystem::replaceFileRegex("{$pkg->getLibDir()}/pkgconfig/libcrypto.pc", '/Libs.private:.*/m', 'Requires.private: zlib');
FileSystem::replaceFileRegex("{$pkg->getLibDir()}/cmake/OpenSSL/OpenSSLConfig.cmake", '/set\(OPENSSL_LIBCRYPTO_DEPENDENCIES .*\)/m', 'set(OPENSSL_LIBCRYPTO_DEPENDENCIES "${OPENSSL_LIBRARY_DIR}/libz.a")'); FileSystem::replaceFileRegex("{$pkg->getLibDir()}/cmake/OpenSSL/OpenSSLConfig.cmake", '/set\(OPENSSL_LIBCRYPTO_DEPENDENCIES .*\)/m', 'set(OPENSSL_LIBCRYPTO_DEPENDENCIES "${OPENSSL_LIBRARY_DIR}/libz.a")');
} }
private function resolveWindowsPerl(): string
{
global $argv;
$tool = PackageLoader::getPackage('strawberry-perl');
if ($tool instanceof ToolPackage) {
$perl = $tool->getBinary('perl.exe');
if (file_exists($perl)) {
return $perl;
}
}
throw new EnvironmentException(
'OpenSSL requires strawberry-perl, but it is not installed.',
"Please run \"{$argv[0]} install-pkg strawberry-perl\" or retry the build with downloads enabled.",
);
}
} }

View File

@@ -37,6 +37,10 @@ class postgresql extends LibraryPackage
#[PatchDescription('Various patches before building PostgreSQL')] #[PatchDescription('Various patches before building PostgreSQL')]
public function patchBeforeBuild(): bool public function patchBeforeBuild(): bool
{ {
// These patches target the autoconf/Make build; the Windows build uses Meson (see buildWin).
if (SystemTarget::getTargetOS() === 'Windows') {
return true;
}
// skip the test on platforms where libpq infrastructure may be provided by statically-linked libraries // skip the test on platforms where libpq infrastructure may be provided by statically-linked libraries
FileSystem::replaceFileStr("{$this->getSourceDir()}/src/interfaces/libpq/Makefile", 'invokes exit\'; exit 1;', 'invokes exit\';'); FileSystem::replaceFileStr("{$this->getSourceDir()}/src/interfaces/libpq/Makefile", 'invokes exit\'; exit 1;', 'invokes exit\';');
// disable shared libs build // disable shared libs build
@@ -53,6 +57,73 @@ class postgresql extends LibraryPackage
return true; return true;
} }
#[BuildFor('Windows')]
public function buildWin(LibraryPackage $lib): void
{
$src = $lib->getSourceDir();
$build_root = $lib->getBuildRootPath();
$lib_dir = $lib->getLibDir();
$inc_dir = $lib->getIncludeDir();
$build = "{$src}\\build";
// Export the public pg_char_to_encoding()/pg_encoding_to_char() from libpgcommon.a so a
// statically-linked libpq.a resolves them (PHP's ext/pgsql relies on them too). This mirrors
// the Unix build's -UUSE_PRIVATE_ENCODING_FUNCS patch, but for the Meson build.
FileSystem::replaceFileStr(
"{$src}\\src\\common\\meson.build",
"'c_args': ['-DUSE_PRIVATE_ENCODING_FUNCS'],",
"'c_args': [],"
);
// Fresh Meson build dir (Meson refuses to reuse a dir configured differently).
if (is_dir($build)) {
FileSystem::removeDir($build);
}
// Meson's OpenSSL detection link-tests CRYPTO_new_ex_data; our static libcrypto needs its
// Win32 deps (and zlib, since OpenSSL was built with zlib) on the link line to succeed.
$ld = 'ws2_32.lib gdi32.lib advapi32.lib crypt32.lib user32.lib secur32.lib zlibstatic.lib';
$configure = 'meson setup build'
. ' --prefix=' . escapeshellarg($build_root)
. ' -Ddefault_library=static' // static libpq.a / libpgcommon.a / libpgport.a
. ' -Db_vscrt=mt' // /MT static CRT, matching the rest of the build
. ' -Dssl=openssl'
// Everything libpq doesn't need: keeps deps minimal and avoids server-only detection.
. ' -Dzlib=disabled -Dnls=disabled -Dreadline=disabled -Dicu=disabled'
. ' -Dlz4=disabled -Dzstd=disabled -Dtap_tests=disabled'
. ' -Dplperl=disabled -Dplpython=disabled -Dpltcl=disabled'
. ' -Dgssapi=disabled -Dldap=disabled -Dlibxml=disabled -Dlibxslt=disabled'
. ' -Dextra_include_dirs=' . escapeshellarg("{$build_root}\\include")
. ' -Dextra_lib_dirs=' . escapeshellarg($lib_dir);
// Build only the three frontend static libs (not the server) — keeps it fast and avoids
// needing every backend dependency. meson/ninja/win_bison/win_flex/perl come from the
// tool packages declared in the package config (tools@windows).
$targets = 'src/interfaces/libpq/libpq.a src/common/libpgcommon.a src/port/libpgport.a';
cmd()->cd($src)
->setEnv([
'LIB' => $lib_dir . ';' . (getenv('LIB') ?: ''),
'LDFLAGS' => $ld,
])
->exec($configure)
->exec("ninja -C build {$targets}");
// Install the static libs under the names PHP's ext/pgsql + frankenphp expect (.lib).
FileSystem::createDir($lib_dir);
FileSystem::createDir($inc_dir);
FileSystem::copy("{$build}\\src\\interfaces\\libpq\\libpq.a", "{$lib_dir}\\libpq.lib");
FileSystem::copy("{$build}\\src\\common\\libpgcommon.a", "{$lib_dir}\\libpgcommon.lib");
FileSystem::copy("{$build}\\src\\port\\libpgport.a", "{$lib_dir}\\libpgport.lib");
// Install the public libpq headers (PG18 no longer ships pg_config_ext.h).
FileSystem::copy("{$src}\\src\\interfaces\\libpq\\libpq-fe.h", "{$inc_dir}\\libpq-fe.h");
FileSystem::copy("{$src}\\src\\include\\postgres_ext.h", "{$inc_dir}\\postgres_ext.h");
FileSystem::createDir("{$inc_dir}\\libpq");
FileSystem::copy("{$src}\\src\\include\\libpq\\libpq-fs.h", "{$inc_dir}\\libpq\\libpq-fs.h");
}
#[BuildFor('Darwin')] #[BuildFor('Darwin')]
#[BuildFor('Linux')] #[BuildFor('Linux')]
public function buildUnix(PackageInstaller $installer, PackageBuilder $builder): void public function buildUnix(PackageInstaller $installer, PackageBuilder $builder): void

View File

@@ -19,7 +19,12 @@ class sqlite
#[BuildFor('Linux')] #[BuildFor('Linux')]
public function buildUnix(LibraryPackage $lib): void public function buildUnix(LibraryPackage $lib): void
{ {
UnixAutoconfExecutor::create($lib)->configure()->make(); UnixAutoconfExecutor::create($lib)
->appendEnv([
'CFLAGS' => '-DSQLITE_ENABLE_COLUMN_METADATA=1',
])
->configure()
->make();
$lib->patchPkgconfPrefix(['sqlite3.pc']); $lib->patchPkgconfPrefix(['sqlite3.pc']);
} }

View File

@@ -35,12 +35,16 @@ class curl
#[BuildFor('Windows')] #[BuildFor('Windows')]
public function buildWin(LibraryPackage $lib): void public function buildWin(LibraryPackage $lib): void
{ {
$lib_dir = str_replace('\\', '/', $lib->getLibDir());
$zstd_lib = "{$lib_dir}/zstd_static.lib";
$extra_libs = "{$lib_dir}/libcrypto.lib {$lib_dir}/libssl.lib ws2_32.lib gdi32.lib advapi32.lib crypt32.lib user32.lib";
WindowsCMakeExecutor::create($lib) WindowsCMakeExecutor::create($lib)
->optionalPackage('zstd', ...cmake_boolean_args('CURL_ZSTD')) ->optionalPackage('zstd', ...cmake_boolean_args('CURL_ZSTD'))
->optionalPackage('brotli', ...cmake_boolean_args('CURL_BROTLI')) ->optionalPackage('brotli', ...cmake_boolean_args('CURL_BROTLI'))
->addConfigureArgs( ->addConfigureArgs(
'-DBUILD_CURL_EXE=ON', '-DBUILD_CURL_EXE=ON',
'-DZSTD_LIBRARY=zstd_static.lib', '-DCMAKE_C_STANDARD_LIBRARIES=' . escapeshellarg($extra_libs),
'-DZSTD_LIBRARY=' . escapeshellarg($zstd_lib),
'-DBUILD_TESTING=OFF', '-DBUILD_TESTING=OFF',
'-DBUILD_EXAMPLES=OFF', '-DBUILD_EXAMPLES=OFF',
'-DUSE_LIBIDN2=OFF', '-DUSE_LIBIDN2=OFF',

View File

@@ -255,6 +255,13 @@ class php extends TargetPackage
$installer->addBuildPackage('php-embed'); $installer->addBuildPackage('php-embed');
} }
// UPX compression: ensure the upx tool package is installed when requested.
// upx is a ToolPackage now, so it's installed directly rather than added as a
// library dependency (tool packages bypass the DependencyResolver graph).
if ($package->getBuildOption('with-upx-pack')) {
$installer->addInstallPackage('upx');
}
return [...$extensions_pkg, ...$additional_packages]; return [...$extensions_pkg, ...$additional_packages];
} }

View File

@@ -26,6 +26,55 @@ use ZM\Logger\ConsoleColor;
trait frankenphp trait frankenphp
{ {
/**
* Source of the -mthreads stripping shim, see windowsCgoCompilers(). The %s
* placeholder receives the wrapped compiler path as a C string literal.
*/
private const string MTHREADS_SHIM_C = <<<'C'
// Generated by static-php-cli. Drops the MinGW-only -mthreads flag Go passes to
// cgo (golang/go#80290) and forwards everything else to clang.
#include <windows.h>
#include <wchar.h>
#include <stdlib.h>
static const wchar_t compiler[] = L"%s";
int main(void)
{
const wchar_t *args = GetCommandLineW();
// skip our own (possibly quoted) argv[0]
if (*args == L'"') {
args++;
while (*args && *args != L'"') args++;
if (*args) args++;
} else {
while (*args && *args != L' ' && *args != L'\t') args++;
}
// "<compiler>" + args + trailing space so a flag at the very end still matches
size_t len = wcslen(compiler) + wcslen(args) + 8;
wchar_t *cmd = calloc(len, sizeof(wchar_t));
if (cmd == NULL) return 1;
swprintf(cmd, len, L"\"%%ls\"%%ls ", compiler, args);
// remove every space-delimited -mthreads token
wchar_t *p;
while ((p = wcsstr(cmd, L" -mthreads ")) != NULL) {
wmemmove(p, p + 10, wcslen(p + 10) + 1);
}
STARTUPINFOW si = {sizeof(si)};
PROCESS_INFORMATION pi;
if (!CreateProcessW(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
return 127;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD code = 1;
GetExitCodeProcess(pi.hProcess, &code);
return (int) code;
}
C;
#[Stage] #[Stage]
public function buildFrankenphpForUnix(TargetPackage $package, PackageInstaller $installer, ToolchainInterface $toolchain, PackageBuilder $builder): void public function buildFrankenphpForUnix(TargetPackage $package, PackageInstaller $installer, ToolchainInterface $toolchain, PackageBuilder $builder): void
{ {
@@ -233,10 +282,21 @@ trait frankenphp
$dep_libs = array_unique($dep_libs); $dep_libs = array_unique($dep_libs);
$lib_dir = str_replace('\\', '/', BUILD_LIB_PATH); $lib_dir = str_replace('\\', '/', BUILD_LIB_PATH);
$php_embed_lib = "-lphp{$major}embed"; $php_embed_lib = "-lphp{$major}embed";
$win_sys_libs = '-lkernel32 -lole32 -luser32 -ladvapi32 -lshell32 -lws2_32 -ldnsapi -lpsapi -lbcrypt'; // pathcch: PathCchCanonicalizeEx etc. used by frankenphp/caddy path handling.
// secur32: InitSecurityInterfaceA (curl Schannel/SSPI). crypt32/gdi32: OpenSSL + Schannel.
$win_sys_libs = '-lkernel32 -lole32 -luser32 -ladvapi32 -lshell32 -lws2_32 -ldnsapi -lpsapi -lbcrypt -lpathcch -lsecur32 -lcrypt32 -lgdi32';
$cgo_ldflags = clean_spaces(implode(' ', array_filter([ $cgo_ldflags = clean_spaces(implode(' ', array_filter([
"-L{$lib_dir}", "-L{$lib_dir}",
$php_embed_lib, $php_embed_lib,
// FrankenPHP's cgo code references PHP/lexbor/zend symbols via __declspec(dllimport).
// Their definitions live in php{N}embed.lib but are only pulled in if the plain symbol
// is referenced, so the __imp_ refs go unresolved. Force-include one symbol from each
// defining object (zend_atomic.obj, lexbor url.obj, lexbor idna.obj) to pull them in;
// lld then auto-imports the __imp_ refs. (/WHOLEARCHIVE would also drag in libxml2.res,
// which collides with Go's own resource object: "more than one resource obj file".)
'-Wl,/INCLUDE:zend_atomic_bool_store',
'-Wl,/INCLUDE:lxb_url_parse',
'-Wl,/INCLUDE:lxb_unicode_idna_init',
implode(' ', $dep_libs), implode(' ', $dep_libs),
$win_sys_libs, $win_sys_libs,
'-llibcmt', '-llibcmt',
@@ -262,10 +322,11 @@ trait frankenphp
// Fix: prepend clang's directory to PATH and use plain executable names instead, // Fix: prepend clang's directory to PATH and use plain executable names instead,
// which matches FrankenPHP's official CI approach (CC=clang, CXX=clang++). // which matches FrankenPHP's official CI approach (CC=clang, CXX=clang++).
$clang_dir = dirname($clang_info['clang']); $clang_dir = dirname($clang_info['clang']);
[$cc, $cxx] = $this->windowsCgoCompilers($package, $clang_info['clang']);
$env = [ $env = [
'CGO_ENABLED' => '1', 'CGO_ENABLED' => '1',
'CC' => 'clang.exe', 'CC' => $cc,
'CXX' => 'clang++.exe', 'CXX' => $cxx,
'PATH' => $clang_dir . ';' . getenv('PATH'), 'PATH' => $clang_dir . ';' . getenv('PATH'),
'CGO_CFLAGS' => clean_spaces($cgo_cflags), 'CGO_CFLAGS' => clean_spaces($cgo_cflags),
'CGO_LDFLAGS' => $cgo_ldflags, 'CGO_LDFLAGS' => $cgo_ldflags,
@@ -366,6 +427,48 @@ trait frankenphp
} }
} }
/**
* Return the [CC, CXX] cgo should use to build FrankenPHP on Windows.
*
* Go passes the MinGW-only `-mthreads` flag to the C compiler for cgo builds;
* Clang >= 20 rejects it for the MSVC target. When it does, wrap Clang with a
* small compiled shim that strips the flag before forwarding. An executable and
* not a .bat on purpose: batch files run through cmd.exe, which caps the command
* line at 8191 characters, and cgo link steps with big extension stacks (imagick)
* blow past that. A real process gets the full ~32K limit, and beyond that Go
* switches to a response file by itself.
*
* Workaround for https://github.com/golang/go/issues/80290, remove once Go
* stops passing the flag.
*
* @return array{0: string, 1: string}
*/
protected function windowsCgoCompilers(TargetPackage $package, string $clang): array
{
$probe = $package->getSourceDir() . '\mthreads-probe.c';
file_put_contents($probe, "int main(void){return 0;}\n");
[$ret] = cmd()->execWithResult('"' . $clang . '" -mthreads -c ' . escapeshellarg($probe) . ' -o ' . escapeshellarg($probe . '.o'), false);
FileSystem::removeFileIfExists($probe);
FileSystem::removeFileIfExists($probe . '.o');
if ($ret === 0) {
return ['clang.exe', 'clang++.exe'];
}
logger()->info('Clang rejects -mthreads; wrapping it to strip the flag (golang/go#80290)');
$dir = dirname($clang);
$wrappers = [];
foreach (['cc-nothreads' => 'clang.exe', 'cxx-nothreads' => 'clang++.exe'] as $name => $compiler) {
$src = $package->getSourceDir() . "\\{$name}.c";
$exe = $package->getSourceDir() . "\\{$name}.exe";
file_put_contents($src, sprintf(self::MTHREADS_SHIM_C, str_replace('\\', '\\\\', "{$dir}\\{$compiler}")));
cmd()->cd($package->getSourceDir())
->exec('"' . $clang . '" -O2 ' . escapeshellarg($src) . ' -o ' . escapeshellarg($exe));
$wrappers[] = $exe;
}
return $wrappers;
}
protected function getFrankenPHPVersion(TargetPackage $package): string protected function getFrankenPHPVersion(TargetPackage $package): string
{ {
if ($version = getenv('FRANKENPHP_VERSION')) { if ($version = getenv('FRANKENPHP_VERSION')) {

View File

@@ -59,7 +59,7 @@ trait unix
} }
if (self::getPHPVersionID() >= 80300 && self::getPHPVersionID() < 80400) { if (self::getPHPVersionID() >= 80300 && self::getPHPVersionID() < 80400) {
SourcePatcher::patchFile('spc_fix_avx512_cache_before_80400.patch', $this->getSourceDir()); SourcePatcher::patchFile('spc_fix_avx512_cache_before_80400.patch', $package->getSourceDir());
} }
} }
@@ -289,16 +289,7 @@ trait unix
$builder->deployBinary($package->getSourceDir() . '/sapi/micro/micro.sfx', $dst); $builder->deployBinary($package->getSourceDir() . '/sapi/micro/micro.sfx', $dst);
// patch after UPX-ed micro.sfx (Linux only) // patch after UPX-ed micro.sfx (Linux only)
if (SystemTarget::getTargetOS() === 'Linux' && $builder->getOption('with-upx-pack')) { if (SystemTarget::getTargetOS() === 'Linux' && $builder->getOption('with-upx-pack')) {
// cut binary with readelf to remove UPX extra segment self::patchMicroUpxPackedBinary($dst);
[$ret, $out] = shell()->execWithResult("readelf -l {$dst} | awk '/LOAD|GNU_STACK/ {getline; print \\$1, \\$2, \\$3, \\$4, \\$6, \\$7}'");
$out[1] = explode(' ', $out[1]);
$offset = $out[1][0];
if ($ret !== 0 || !str_starts_with($offset, '0x')) {
throw new PatchException('phpmicro UPX patcher', 'Cannot find offset in readelf output');
}
$offset = hexdec($offset);
// remove upx extra wastes
file_put_contents($dst, substr(file_get_contents($dst), 0, $offset));
} }
$package->setOutput('Binary path for micro SAPI', $dst); $package->setOutput('Binary path for micro SAPI', $dst);
} }
@@ -680,6 +671,43 @@ trait unix
return $php; return $php;
} }
/**
* Remove the extra segment appended by UPX when packing phpmicro.
*/
private static function patchMicroUpxPackedBinary(string $binaryPath): void
{
[$ret, $out] = shell()->execWithResult('readelf -W -l ' . escapeshellarg($binaryPath));
if ($ret !== 0) {
throw new PatchException('phpmicro UPX patcher', 'Cannot find offset in readelf output');
}
$fileSizes = [];
foreach ($out as $index => $line) {
$line = trim($line);
if (!preg_match('/^(LOAD|GNU_STACK)\s+/', $line)) {
continue;
}
$columns = preg_split('/\s+/', $line);
if (isset($columns[4]) && preg_match('/^0x[[:xdigit:]]+$/', $columns[4]) === 1) {
$fileSizes[] = $columns[4];
continue;
}
$next = $out[$index + 1] ?? '';
if (preg_match('/^\s*(0x[[:xdigit:]]+)\s+0x[[:xdigit:]]+/', $next, $matches)) {
$fileSizes[] = $matches[1];
}
}
$offset = $fileSizes[1] ?? null;
if ($offset === null) {
throw new PatchException('phpmicro UPX patcher', 'Cannot find offset in readelf output');
}
file_put_contents($binaryPath, substr(file_get_contents($binaryPath), 0, intval(hexdec($offset))));
}
/** /**
* Rename libphp.so to libphp-<release>.so if -release is set in LDFLAGS. * Rename libphp.so to libphp-<release>.so if -release is set in LDFLAGS.
*/ */

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Package\Target\php; namespace Package\Target\php;
use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage; use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\BuildFor; use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Stage; use StaticPHP\Attribute\Package\Stage;
@@ -39,6 +40,13 @@ trait windows
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./buildconf.bat')); InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./buildconf.bat'));
cmd()->cd($package->getSourceDir())->exec('.\buildconf.bat'); cmd()->cd($package->getSourceDir())->exec('.\buildconf.bat');
// Bypass the phpsdk_version check in configure.js: we use MSVC + msys2 instead of PHP SDK, so phpsdk_version is not available and the check would always fail.
FileSystem::replaceFileStr(
"{$package->getSourceDir()}\\configure.js",
'check_binary_tools_sdk();',
'/* check_binary_tools_sdk(); skipped: using MSVC + msys2 without PHP SDK */'
);
if ($package->getBuildOption('enable-micro-win32') && $installer->isPackageResolved('php-micro')) { if ($package->getBuildOption('enable-micro-win32') && $installer->isPackageResolved('php-micro')) {
SourcePatcher::patchMicroWin32(); SourcePatcher::patchMicroWin32();
} else { } else {
@@ -88,6 +96,17 @@ trait windows
cmd()->cd($package->getSourceDir())->exec(".\\configure.bat {$args} {$static_extension_str}"); cmd()->cd($package->getSourceDir())->exec(".\\configure.bat {$args} {$static_extension_str}");
} }
#[BeforeStage('php', [self::class, 'makeCliForWindows'])]
#[PatchDescription('Patch Makefile to ensure buildroot/include comes before extension CFLAGS (fixes zip.h conflict with minizip)')]
public function patchMakefileIncludeOrder(TargetPackage $package): void
{
FileSystem::replaceFileStr(
"{$package->getSourceDir()}\\Makefile",
'$(CFLAGS_PHP_OBJ) $(CFLAGS)',
'$(CFLAGS) $(CFLAGS_PHP_OBJ)'
);
}
#[BeforeStage('php', [self::class, 'makeCliForWindows'])] #[BeforeStage('php', [self::class, 'makeCliForWindows'])]
#[PatchDescription('Patch Windows Makefile for CLI target')] #[PatchDescription('Patch Windows Makefile for CLI target')]
public function patchCLITarget(TargetPackage $package): void public function patchCLITarget(TargetPackage $package): void
@@ -108,7 +127,10 @@ trait windows
throw new PatchException('Windows Makefile patching for php.exe target', 'Cannot patch windows CLI Makefile, Makefile does not contain "$(BUILD_DIR)\php.exe:" line'); throw new PatchException('Windows Makefile patching for php.exe target', 'Cannot patch windows CLI Makefile, Makefile does not contain "$(BUILD_DIR)\php.exe:" line');
} }
$lines[$line_num] = '$(BUILD_DIR)\php.exe: generated_files $(DEPS_CLI) $(PHP_GLOBAL_OBJS) $(CLI_GLOBAL_OBJS) $(STATIC_EXT_OBJS) $(ASM_OBJS) $(BUILD_DIR)\php.exe.res $(BUILD_DIR)\php.exe.manifest'; $lines[$line_num] = '$(BUILD_DIR)\php.exe: generated_files $(DEPS_CLI) $(PHP_GLOBAL_OBJS) $(CLI_GLOBAL_OBJS) $(STATIC_EXT_OBJS) $(ASM_OBJS) $(BUILD_DIR)\php.exe.res $(BUILD_DIR)\php.exe.manifest';
$lines[$line_num + 1] = "\t" . '"$(LINK)" /nologo $(PHP_GLOBAL_OBJS_RESP) $(CLI_GLOBAL_OBJS_RESP) $(STATIC_EXT_OBJS_RESP) $(STATIC_EXT_LIBS) $(ASM_OBJS) $(LIBS) $(LIBS_CLI) $(BUILD_DIR)\php.exe.res /out:$(BUILD_DIR)\php.exe $(LDFLAGS) $(LDFLAGS_CLI) /ltcg /nodefaultlib:msvcrt /nodefaultlib:msvcrtd /ignore:4286'; // /FORCE:MULTIPLE: extensions may bundle their own static copies of common libraries (e.g.
// imagick's ImageMagick ships its own zlib/png/jpeg, duplicating gd's); let the first
// definition win instead of failing with LNK2005. /ignore:4006 silences the resulting noise.
$lines[$line_num + 1] = "\t" . '"$(LINK)" /nologo $(PHP_GLOBAL_OBJS_RESP) $(CLI_GLOBAL_OBJS_RESP) $(STATIC_EXT_OBJS_RESP) $(STATIC_EXT_LIBS) $(ASM_OBJS) $(LIBS) $(LIBS_CLI) $(BUILD_DIR)\php.exe.res /out:$(BUILD_DIR)\php.exe $(LDFLAGS) $(LDFLAGS_CLI) /ltcg /nodefaultlib:msvcrt /nodefaultlib:msvcrtd /ignore:4286 /FORCE:MULTIPLE /ignore:4006';
FileSystem::writeFile("{$package->getSourceDir()}\\Makefile", implode("\r\n", $lines)); FileSystem::writeFile("{$package->getSourceDir()}\\Makefile", implode("\r\n", $lines));
} }
@@ -153,8 +175,9 @@ trait windows
} }
} }
$libs_cli = $this->makeLibsResponseFile($package, 'cli', "ws2_32.lib shell32.lib {$extra_libs}");
cmd()->cd($package->getSourceDir()) cmd()->cd($package->getSourceDir())
->exec("nmake /nologo {$debug_overrides}LIBS_CLI=\"ws2_32.lib shell32.lib {$extra_libs}\" EXTRA_LD_FLAGS_PROGRAM= php.exe"); ->exec("nmake /nologo {$debug_overrides}LIBS_CLI=\"{$libs_cli}\" EXTRA_LD_FLAGS_PROGRAM= php.exe");
$this->deployWindowsBinary($builder, $package, 'php-cli'); $this->deployWindowsBinary($builder, $package, 'php-cli');
} }
@@ -179,7 +202,10 @@ trait windows
throw new PatchException('Windows Makefile patching for php-cgi.exe target', 'Cannot patch windows CGI Makefile, Makefile does not contain "$(BUILD_DIR)\php-cgi.exe:" line'); throw new PatchException('Windows Makefile patching for php-cgi.exe target', 'Cannot patch windows CGI Makefile, Makefile does not contain "$(BUILD_DIR)\php-cgi.exe:" line');
} }
$lines[$line_num] = '$(BUILD_DIR)\php-cgi.exe: $(DEPS_CGI) $(CGI_GLOBAL_OBJS) $(PHP_GLOBAL_OBJS) $(STATIC_EXT_OBJS) $(ASM_OBJS) $(BUILD_DIR)\php-cgi.exe.res $(BUILD_DIR)\php-cgi.exe.manifest'; $lines[$line_num] = '$(BUILD_DIR)\php-cgi.exe: $(DEPS_CGI) $(CGI_GLOBAL_OBJS) $(PHP_GLOBAL_OBJS) $(STATIC_EXT_OBJS) $(ASM_OBJS) $(BUILD_DIR)\php-cgi.exe.res $(BUILD_DIR)\php-cgi.exe.manifest';
$lines[$line_num + 1] = "\t" . '@"$(LINK)" /nologo $(PHP_GLOBAL_OBJS_RESP) $(CGI_GLOBAL_OBJS_RESP) $(STATIC_EXT_OBJS_RESP) $(STATIC_EXT_LIBS) $(ASM_OBJS) $(LIBS) $(LIBS_CGI) $(BUILD_DIR)\php-cgi.exe.res /out:$(BUILD_DIR)\php-cgi.exe $(LDFLAGS) $(LDFLAGS_CGI) /ltcg /nodefaultlib:msvcrt /nodefaultlib:msvcrtd /ignore:4286'; // /FORCE:MULTIPLE /ignore:4006: same reason as the php.exe target above. Without it the
// CGI link fails with LNK2005 (e.g. imagick's MagickCore defines gettimeofday, which
// php's time.obj also defines).
$lines[$line_num + 1] = "\t" . '@"$(LINK)" /nologo $(PHP_GLOBAL_OBJS_RESP) $(CGI_GLOBAL_OBJS_RESP) $(STATIC_EXT_OBJS_RESP) $(STATIC_EXT_LIBS) $(ASM_OBJS) $(LIBS) $(LIBS_CGI) $(BUILD_DIR)\php-cgi.exe.res /out:$(BUILD_DIR)\php-cgi.exe $(LDFLAGS) $(LDFLAGS_CGI) /ltcg /nodefaultlib:msvcrt /nodefaultlib:msvcrtd /ignore:4286 /FORCE:MULTIPLE /ignore:4006';
FileSystem::writeFile("{$package->getSourceDir()}\\Makefile", implode("\r\n", $lines)); FileSystem::writeFile("{$package->getSourceDir()}\\Makefile", implode("\r\n", $lines));
// Patch cgi-static, comment ZEND_TSRMLS_CACHE_DEFINE() // Patch cgi-static, comment ZEND_TSRMLS_CACHE_DEFINE()
@@ -220,8 +246,9 @@ trait windows
} }
} }
$libs_cgi = $this->makeLibsResponseFile($package, 'cgi', "ws2_32.lib kernel32.lib advapi32.lib {$extra_libs}");
cmd()->cd($package->getSourceDir()) cmd()->cd($package->getSourceDir())
->exec("nmake /nologo {$debug_overrides}LIBS_CGI=\"ws2_32.lib kernel32.lib advapi32.lib {$extra_libs}\" EXTRA_LD_FLAGS_PROGRAM= php-cgi.exe"); ->exec("nmake /nologo {$debug_overrides}LIBS_CGI=\"{$libs_cgi}\" EXTRA_LD_FLAGS_PROGRAM= php-cgi.exe");
$this->deployWindowsBinary($builder, $package, 'php-cgi'); $this->deployWindowsBinary($builder, $package, 'php-cgi');
} }
@@ -246,6 +273,19 @@ trait windows
} }
} }
#[BeforeStage('php', [self::class, 'makeMicroForWindows'])]
#[PatchDescription('Add /FORCE:MULTIPLE to the micro.sfx link, matching the CLI and CGI targets')]
public function patchMicroTarget(TargetPackage $package): void
{
$makefile = "{$package->getSourceDir()}\\Makefile";
if (str_contains(FileSystem::readFile($makefile), 'LDFLAGS_MICRO=/FORCE:MULTIPLE')) {
return;
}
// Same reason as the php.exe and php-cgi.exe targets: extension-bundled libs duplicate
// symbols from php's own objects and the link fails with LNK2005.
FileSystem::replaceFileStr($makefile, "\r\nLDFLAGS_MICRO=", "\r\nLDFLAGS_MICRO=/FORCE:MULTIPLE /ignore:4006 ");
}
#[Stage] #[Stage]
public function makeMicroForWindows(TargetPackage $package, PackageBuilder $builder, PackageInstaller $installer): void public function makeMicroForWindows(TargetPackage $package, PackageBuilder $builder, PackageInstaller $installer): void
{ {
@@ -293,8 +333,9 @@ trait windows
$fake_cli = $package->getBuildOption('with-micro-fake-cli', false) ? ' /DPHP_MICRO_FAKE_CLI' : ''; $fake_cli = $package->getBuildOption('with-micro-fake-cli', false) ? ' /DPHP_MICRO_FAKE_CLI' : '';
$libs_micro = $this->makeLibsResponseFile($package, 'micro', "ws2_32.lib shell32.lib {$extra_libs}");
cmd()->cd($package->getSourceDir()) cmd()->cd($package->getSourceDir())
->exec("nmake /nologo {$debug_overrides}LIBS_MICRO=\"ws2_32.lib shell32.lib {$extra_libs}\" CFLAGS_MICRO=\"/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1{$fake_cli}\" EXTRA_LD_FLAGS_PROGRAM= micro"); ->exec("nmake /nologo {$debug_overrides}LIBS_MICRO=\"{$libs_micro}\" CFLAGS_MICRO=\"/DZEND_ENABLE_STATIC_TSRMLS_CACHE=1{$fake_cli}\" EXTRA_LD_FLAGS_PROGRAM= micro");
$this->deployWindowsBinary($builder, $package, 'php-micro'); $this->deployWindowsBinary($builder, $package, 'php-micro');
} }
@@ -696,12 +737,18 @@ C_CODE;
// MSVC cl.exe format: compiler flags must come before /link, linker flags after // MSVC cl.exe format: compiler flags must come before /link, linker flags after
// ldflags contains /LIBPATH which must be after /link // ldflags contains /LIBPATH which must be after /link
// /FORCE:MULTIPLE: in ZTS mode both zend.obj and php_embed.obj (both packed into the fat php8embed.lib) define _tsrm_ls_cache as a __declspec(thread) variable. // /FORCE:MULTIPLE: in ZTS mode both zend.obj and php_embed.obj (both packed into the fat php8embed.lib) define _tsrm_ls_cache as a __declspec(thread) variable.
// /INCLUDE: php8embed.lib's ext/uri (uri_parser_whatwg.obj) references lexbor lxb_url_*/
// lxb_unicode_idna_* via __declspec(dllimport); their definitions live in url.obj/idna.obj
// but are only pulled in if the plain symbol is referenced. Force-include one symbol from
// each so the objects are linked and the __imp_ refs auto-import. (FrankenPHP needs the same.)
// System libs add pathcch (PathCchCanonicalizeEx), secur32 (curl Schannel InitSecurityInterface),
// crypt32/gdi32 (OpenSSL + Schannel) on top of the Makefile LIBS set.
$compile_cmd = sprintf( $compile_cmd = sprintf(
'cl.exe /nologo /O2 /MT /Z7 %s embed.c /Fe:embed.exe /link /FORCE:MULTIPLE /LIBPATH:"%s\lib" %s %s', 'cl.exe /nologo /O2 /MT /Z7 %s embed.c /Fe:embed.exe /link /FORCE:MULTIPLE /INCLUDE:lxb_url_parse /INCLUDE:lxb_unicode_idna_init /LIBPATH:"%s\lib" %s %s',
$include_flags, $include_flags,
BUILD_ROOT_PATH, BUILD_ROOT_PATH,
$config['libs'], $config['libs'],
'kernel32.lib ole32.lib user32.lib advapi32.lib shell32.lib ws2_32.lib dnsapi.lib psapi.lib bcrypt.lib' // Windows system libs (match Makefile LIBS) 'kernel32.lib ole32.lib user32.lib advapi32.lib shell32.lib ws2_32.lib dnsapi.lib psapi.lib bcrypt.lib pathcch.lib secur32.lib crypt32.lib gdi32.lib' // Windows system libs (match Makefile LIBS) + curl/openssl deps
); );
// Log command explicitly (workaround for cmd() not logging complex commands properly) // Log command explicitly (workaround for cmd() not logging complex commands properly)
@@ -715,9 +762,11 @@ C_CODE;
); );
} }
// Run the embed test // Run the embed test. Use a ".\" prefix: cmd.exe does not resolve a bare "embed.exe" from
// the current directory, while the cwd must remain $test_dir so the script's relative
// "embed.php" is found.
InteractiveTerm::setMessage('Running php-embed run smoke test'); InteractiveTerm::setMessage('Running php-embed run smoke test');
[$ret, $output] = cmd()->cd($test_dir)->execWithResult('embed.exe'); [$ret, $output] = cmd()->cd($test_dir)->execWithResult('.\embed.exe');
$raw_output = implode('', $output); $raw_output = implode('', $output);
if ($ret !== 0 || trim($raw_output) !== 'hello') { if ($ret !== 0 || trim($raw_output) !== 'hello') {
throw new ValidationException( throw new ValidationException(
@@ -838,4 +887,17 @@ C_CODE;
$package->setOutput('PHP headers path for embed SAPI', $php_include_dir); $package->setOutput('PHP headers path for embed SAPI', $php_include_dir);
} }
/**
* Write the collected lib list into a linker response file and return the @file
* token for the nmake command line. With big extension stacks (imagick alone pulls
* in ~60 static libs) the inline list can push the whole command past cmd.exe's
* 8191 character limit; link.exe reads @file without any length limit.
*/
private function makeLibsResponseFile(TargetPackage $package, string $sapi, string $libs): string
{
$file = "{$package->getSourceDir()}\\spc-libs-{$sapi}.rsp";
FileSystem::writeFile($file, $libs);
return "@{$file}";
}
} }

View File

@@ -2,17 +2,17 @@
declare(strict_types=1); declare(strict_types=1);
namespace Package\Target; namespace Package\Tool;
use StaticPHP\Attribute\Package\BuildFor; use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\InitPackage; use StaticPHP\Attribute\Package\InitPackage;
use StaticPHP\Attribute\Package\Target; use StaticPHP\Attribute\Package\Tool;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor; use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Toolchain\Interface\ToolchainInterface; use StaticPHP\Toolchain\Interface\ToolchainInterface;
#[Target('pkg-config')] #[Tool('pkg-config')]
class pkgconfig class pkgconfig
{ {
#[InitPackage] #[InitPackage]
@@ -23,7 +23,7 @@ class pkgconfig
#[BuildFor('Linux')] #[BuildFor('Linux')]
#[BuildFor('Darwin')] #[BuildFor('Darwin')]
public function build(TargetPackage $package, ToolchainInterface $toolchain): void public function build(ToolPackage $package, ToolchainInterface $toolchain): void
{ {
UnixAutoconfExecutor::create($package) UnixAutoconfExecutor::create($package)
->appendEnv([ ->appendEnv([

View File

@@ -26,6 +26,7 @@ use StaticPHP\Exception\DownloaderException;
use StaticPHP\Exception\ExecutionException; use StaticPHP\Exception\ExecutionException;
use StaticPHP\Exception\ValidationException; use StaticPHP\Exception\ValidationException;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Package\ToolVersionRegistry;
use StaticPHP\Registry\ArtifactLoader; use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Runtime\Shell\Shell; use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
@@ -346,12 +347,32 @@ class ArtifactDownloader
} }
} }
public function checkUpdate(string $artifact_name, bool $prefer_source = false, bool $bare = false): CheckUpdateResult public function checkUpdate(string $artifact_name, bool $prefer_source = false, bool $bare = false, bool $use_installed = false): CheckUpdateResult
{ {
$artifact = ArtifactLoader::getArtifactInstance($artifact_name); $artifact = ArtifactLoader::getArtifactInstance($artifact_name);
if ($artifact === null) { if ($artifact === null) {
throw new WrongUsageException("Artifact '{$artifact_name}' not found, please check the name."); throw new WrongUsageException("Artifact '{$artifact_name}' not found, please check the name.");
} }
// --installed: prefer the version actually installed on disk (tool packages only) as the
// baseline, instead of the download cache. Falls back to the normal cache/bare logic below
// if this artifact has no recorded installed version (not a tool package, or not installed
// via the package installer yet).
if ($use_installed) {
$installed_version = ToolVersionRegistry::get($artifact_name);
if ($installed_version !== null) {
[$first, $second] = $prefer_source
? [fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name, $installed_version), fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name, $installed_version)]
: [fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name, $installed_version), fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name, $installed_version)];
$result = $first() ?? $second();
if ($result !== null) {
return $result;
}
return new CheckUpdateResult(old: $installed_version, new: null, needUpdate: false, unsupported: true);
}
logger()->warning("Artifact '{$artifact_name}' has no recorded installed version (not a tool package, or not installed yet); falling back to download-cache based check.");
}
if ($bare) { if ($bare) {
[$first, $second] = $prefer_source [$first, $second] = $prefer_source
? [fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name), fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name)] ? [fn () => $this->probeSourceCheckUpdate($artifact, $artifact_name), fn () => $this->probeBinaryCheckUpdate($artifact, $artifact_name)]
@@ -403,16 +424,17 @@ class ArtifactDownloader
* @param bool $prefer_source Whether to prefer source over binary * @param bool $prefer_source Whether to prefer source over binary
* @param bool $bare Check without requiring artifact to be downloaded first * @param bool $bare Check without requiring artifact to be downloaded first
* @param null|callable $onResult Called immediately with (string $name, CheckUpdateResult) as each result arrives * @param null|callable $onResult Called immediately with (string $name, CheckUpdateResult) as each result arrives
* @param bool $use_installed Prefer the installed (on-disk) version over the download cache (tool packages only)
* @return array<string, CheckUpdateResult> Results keyed by artifact name * @return array<string, CheckUpdateResult> Results keyed by artifact name
*/ */
public function checkUpdates(array $artifact_names, bool $prefer_source = false, bool $bare = false, ?callable $onResult = null): array public function checkUpdates(array $artifact_names, bool $prefer_source = false, bool $bare = false, ?callable $onResult = null, bool $use_installed = false): array
{ {
if ($this->parallel > 1 && count($artifact_names) > 1) { if ($this->parallel > 1 && count($artifact_names) > 1) {
return $this->checkUpdatesWithConcurrency($artifact_names, $prefer_source, $bare, $onResult); return $this->checkUpdatesWithConcurrency($artifact_names, $prefer_source, $bare, $onResult, $use_installed);
} }
$results = []; $results = [];
foreach ($artifact_names as $name) { foreach ($artifact_names as $name) {
$result = $this->checkUpdate($name, $prefer_source, $bare); $result = $this->checkUpdate($name, $prefer_source, $bare, $use_installed);
$results[$name] = $result; $results[$name] = $result;
if ($onResult !== null) { if ($onResult !== null) {
($onResult)($name, $result); ($onResult)($name, $result);
@@ -436,7 +458,7 @@ class ArtifactDownloader
return $this->options[$name] ?? $default; return $this->options[$name] ?? $default;
} }
private function checkUpdatesWithConcurrency(array $artifact_names, bool $prefer_source, bool $bare, ?callable $onResult): array private function checkUpdatesWithConcurrency(array $artifact_names, bool $prefer_source, bool $bare, ?callable $onResult, bool $use_installed = false): array
{ {
$results = []; $results = [];
$fiber_pool = []; $fiber_pool = [];
@@ -451,8 +473,8 @@ class ArtifactDownloader
// fill pool // fill pool
while (count($fiber_pool) < $this->parallel && !empty($remaining)) { while (count($fiber_pool) < $this->parallel && !empty($remaining)) {
$name = array_shift($remaining); $name = array_shift($remaining);
$fiber = new \Fiber(function () use ($name, $prefer_source, $bare) { $fiber = new \Fiber(function () use ($name, $prefer_source, $bare, $use_installed) {
return [$name, $this->checkUpdate($name, $prefer_source, $bare)]; return [$name, $this->checkUpdate($name, $prefer_source, $bare, $use_installed)];
}); });
$fiber->start(); $fiber->start();
$fiber_pool[$name] = $fiber; $fiber_pool[$name] = $fiber;
@@ -491,12 +513,12 @@ class ArtifactDownloader
return $results; return $results;
} }
private function probeSourceCheckUpdate(Artifact $artifact, string $artifact_name): ?CheckUpdateResult private function probeSourceCheckUpdate(Artifact $artifact, string $artifact_name, ?string $old_version = null): ?CheckUpdateResult
{ {
if (($callback = $artifact->getCustomSourceCheckUpdateCallback()) !== null) { if (($callback = $artifact->getCustomSourceCheckUpdateCallback()) !== null) {
return ApplicationContext::invoke($callback, [ return ApplicationContext::invoke($callback, [
ArtifactDownloader::class => $this, ArtifactDownloader::class => $this,
'old_version' => null, 'old_version' => $old_version,
]); ]);
} }
$config = $artifact->getDownloadConfig('source'); $config = $artifact->getDownloadConfig('source');
@@ -509,16 +531,16 @@ class ArtifactDownloader
} }
/** @var CheckUpdateInterface $dl */ /** @var CheckUpdateInterface $dl */
$dl = new $cls(); $dl = new $cls();
return $dl->checkUpdate($artifact_name, $config, null, $this); return $dl->checkUpdate($artifact_name, $config, $old_version, $this);
} }
private function probeBinaryCheckUpdate(Artifact $artifact, string $artifact_name): ?CheckUpdateResult private function probeBinaryCheckUpdate(Artifact $artifact, string $artifact_name, ?string $old_version = null): ?CheckUpdateResult
{ {
// custom binary callback takes precedence over config-based binary // custom binary callback takes precedence over config-based binary
if (($callback = $artifact->getCustomBinaryCheckUpdateCallback()) !== null) { if (($callback = $artifact->getCustomBinaryCheckUpdateCallback()) !== null) {
return ApplicationContext::invoke($callback, [ return ApplicationContext::invoke($callback, [
ArtifactDownloader::class => $this, ArtifactDownloader::class => $this,
'old_version' => null, 'old_version' => $old_version,
]); ]);
} }
$binary_config = $artifact->getDownloadConfig('binary'); $binary_config = $artifact->getDownloadConfig('binary');
@@ -532,7 +554,7 @@ class ArtifactDownloader
} }
/** @var CheckUpdateInterface $dl */ /** @var CheckUpdateInterface $dl */
$dl = new $cls(); $dl = new $cls();
return $dl->checkUpdate($artifact_name, $platform_config, null, $this); return $dl->checkUpdate($artifact_name, $platform_config, $old_version, $this);
} }
private function downloadWithType(Artifact $artifact, int $current, int $total, bool $parallel = false): int private function downloadWithType(Artifact $artifact, int $current, int $total, bool $parallel = false): int

View File

@@ -228,6 +228,27 @@ class ArtifactExtractor
$mode = $extract_config['mode']; $mode = $extract_config['mode'];
if ($mode === 'selective') { if ($mode === 'selective') {
// Check if all destination files already exist before extracting
$all_files_exist = true;
foreach ($extract_config['files'] as $src_pattern => $dst_path) {
$resolved = $this->replacePathVariables($dst_path);
// For glob patterns, check if at least the parent directory exists
if (str_contains($src_pattern, '*')) {
$parent = dirname($resolved);
if (!is_dir($parent)) {
$all_files_exist = false;
break;
}
} elseif (!file_exists($resolved) && !is_dir($resolved)) {
$all_files_exist = false;
break;
}
}
if ($all_files_exist) {
logger()->debug("Binary [{$name}] already extracted (selective), skip.");
return SPC_STATUS_ALREADY_EXTRACTED;
}
$this->doSelectiveExtract($name, $cache_info, $extract_config['files']); $this->doSelectiveExtract($name, $cache_info, $extract_config['files']);
$artifact->emitAfterBinaryExtract($target_path, $platform); $artifact->emitAfterBinaryExtract($target_path, $platform);
logger()->debug("Emitted after-binary-extract hooks for [{$name}]"); logger()->debug("Emitted after-binary-extract hooks for [{$name}]");
@@ -251,8 +272,14 @@ class ArtifactExtractor
logger()->debug("Emitted after-binary-extract hooks for [{$name}]"); logger()->debug("Emitted after-binary-extract hooks for [{$name}]");
/* @phpstan-ignore-next-line */ /* @phpstan-ignore-next-line */
if ($hash !== null && $cache_info['cache_type'] !== 'file') { if ($hash !== null) {
FileSystem::writeFile("{$target_path}/.spc-hash", $hash); // Directory targets: store hash inside the directory
if (is_dir($target_path)) {
FileSystem::writeFile("{$target_path}/.spc-hash", $hash);
} elseif (is_file($target_path)) {
// File targets: store hash as a sidecar file (e.g., meson .whl)
FileSystem::writeFile("{$target_path}.spc-hash", $hash);
}
} }
return SPC_STATUS_EXTRACTED; return SPC_STATUS_EXTRACTED;
} }
@@ -332,9 +359,24 @@ class ArtifactExtractor
/** /**
* Check if artifact is already extracted with correct hash. * Check if artifact is already extracted with correct hash.
*
* Handles both directory targets (hash stored in $path/.spc-hash) and
* file targets (hash stored in $path.spc-hash sidecar).
*/ */
protected function isAlreadyExtracted(string $path, ?string $expected_hash): bool protected function isAlreadyExtracted(string $path, ?string $expected_hash): bool
{ {
// File targets: check sidecar hash file (e.g., meson .whl)
if (is_file($path)) {
if ($expected_hash === null) {
return false;
}
$hash_file = "{$path}.spc-hash";
if (!file_exists($hash_file)) {
return false;
}
return FileSystem::readFile($hash_file) === $expected_hash;
}
if (!is_dir($path)) { if (!is_dir($path)) {
return false; return false;
} }

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Attribute\Package;
/**
* Indicates that the annotated class defines a tool package.
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
readonly class Tool
{
public function __construct(public string $name) {}
}

View File

@@ -54,6 +54,10 @@ abstract class BaseCommand extends Command
} }
set_error_handler(static function ($error_no, $error_msg, $error_file, $error_line) { set_error_handler(static function ($error_no, $error_msg, $error_file, $error_line) {
// Respect the @ suppression operator (error_reporting() returns 0 when @ is used)
if (error_reporting() === 0) {
return true;
}
$tips = [ $tips = [
E_WARNING => ['PHP Warning: ', 'warning'], E_WARNING => ['PHP Warning: ', 'warning'],
E_NOTICE => ['PHP Notice: ', 'notice'], E_NOTICE => ['PHP Notice: ', 'notice'],

View File

@@ -23,6 +23,7 @@ class CheckUpdateCommand extends BaseCommand
$this->addArgument('artifact', InputArgument::OPTIONAL, 'The name of the artifact(s) to check for updates, comma-separated (default: all downloaded artifacts)'); $this->addArgument('artifact', InputArgument::OPTIONAL, 'The name of the artifact(s) to check for updates, comma-separated (default: all downloaded artifacts)');
$this->addOption('json', null, null, 'Output result in JSON format'); $this->addOption('json', null, null, 'Output result in JSON format');
$this->addOption('bare', null, null, 'Check update without requiring the artifact to be downloaded first (old version will be null)'); $this->addOption('bare', null, null, 'Check update without requiring the artifact to be downloaded first (old version will be null)');
$this->addOption('installed', null, null, 'Compare against the version actually installed on disk (tool packages only) instead of the download cache; falls back to normal behavior for artifacts with no recorded installed version');
$this->addOption('parallel', 'p', InputOption::VALUE_REQUIRED, 'Number of parallel update checks (default: 10)', 10); $this->addOption('parallel', 'p', InputOption::VALUE_REQUIRED, 'Number of parallel update checks (default: 10)', 10);
// --with-php option for checking updates with a specific PHP version context // --with-php option for checking updates with a specific PHP version context
@@ -45,8 +46,9 @@ class CheckUpdateCommand extends BaseCommand
try { try {
$downloader = new ArtifactDownloader($this->input->getOptions()); $downloader = new ArtifactDownloader($this->input->getOptions());
$bare = (bool) $this->getOption('bare'); $bare = (bool) $this->getOption('bare');
$use_installed = (bool) $this->getOption('installed');
if ($this->getOption('json')) { if ($this->getOption('json')) {
$results = $downloader->checkUpdates($artifacts, bare: $bare); $results = $downloader->checkUpdates($artifacts, bare: $bare, use_installed: $use_installed);
$outputs = []; $outputs = [];
foreach ($results as $artifact => $result) { foreach ($results as $artifact => $result) {
$outputs[$artifact] = [ $outputs[$artifact] = [
@@ -59,7 +61,7 @@ class CheckUpdateCommand extends BaseCommand
$this->output->writeln(json_encode($outputs, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); $this->output->writeln(json_encode($outputs, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
return static::OK; return static::OK;
} }
$downloader->checkUpdates($artifacts, bare: $bare, onResult: function (string $artifact, CheckUpdateResult $result) { $downloader->checkUpdates($artifacts, bare: $bare, use_installed: $use_installed, onResult: function (string $artifact, CheckUpdateResult $result) {
if ($result->unsupported) { if ($result->unsupported) {
$this->output->writeln("Artifact <info>{$artifact}</info> does not support update checking, <comment>skipped</comment>"); $this->output->writeln("Artifact <info>{$artifact}</info> does not support update checking, <comment>skipped</comment>");
} elseif (!$result->needUpdate) { } elseif (!$result->needUpdate) {

View File

@@ -36,6 +36,15 @@ class CraftCommand extends BaseCommand
// set verbosity // set verbosity
$this->output->setVerbosity($craft['verbosity']); $this->output->setVerbosity($craft['verbosity']);
// sync logger level and ApplicationContext debug mode to match the new verbosity
$level = match ($this->output->getVerbosity()) {
OutputInterface::VERBOSITY_VERBOSE => 'info',
OutputInterface::VERBOSITY_VERY_VERBOSE, OutputInterface::VERBOSITY_DEBUG => 'debug',
default => 'warning',
};
logger()->setLevel($level);
ApplicationContext::setDebug($this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG);
// apply env // apply env
array_walk($craft['extra-env'], fn ($v, $k) => f_putenv("{$k}={$v}")); array_walk($craft['extra-env'], fn ($v, $k) => f_putenv("{$k}={$v}"));

View File

@@ -54,8 +54,8 @@ class DumpCapabilitiesCommand extends BaseCommand
{ {
$result = []; $result = [];
// library / target / virtual-target // library / target / virtual-target / tool
foreach (PackageLoader::getPackages(['library', 'target', 'virtual-target']) as $name => $pkg) { foreach (PackageLoader::getPackages(['library', 'target', 'virtual-target', 'tool']) as $name => $pkg) {
$installable = []; $installable = [];
$artifact = $pkg->getArtifact(); $artifact = $pkg->getArtifact();
if ($artifact !== null) { if ($artifact !== null) {

View File

@@ -14,6 +14,12 @@ class GenExtTestMatrixCommand extends BaseCommand
{ {
private const string BUILD_TARGETS = '--build-cli --build-cgi --build-micro --with-suggests -vvv'; private const string BUILD_TARGETS = '--build-cli --build-cgi --build-micro --with-suggests -vvv';
private const string FRANKENPHP_BUILD_TARGETS = '--build-cli --build-frankenphp --enable-zts --with-suggests -vvv';
private const array SUPPORTED_SAPIS = [
'frankenphp',
];
private const array OS_RUNNERS = [ private const array OS_RUNNERS = [
'linux' => ['arch' => 'x86_64', 'runner' => 'ubuntu-latest', 'os_key' => 'Linux'], 'linux' => ['arch' => 'x86_64', 'runner' => 'ubuntu-latest', 'os_key' => 'Linux'],
'windows' => ['arch' => 'x86_64', 'runner' => 'windows-2025', 'os_key' => 'Windows'], 'windows' => ['arch' => 'x86_64', 'runner' => 'windows-2025', 'os_key' => 'Windows'],
@@ -84,6 +90,7 @@ class GenExtTestMatrixCommand extends BaseCommand
$this->addOption('for-extensions', null, InputOption::VALUE_OPTIONAL, 'Filter by extension display names, comma-separated', '') $this->addOption('for-extensions', null, InputOption::VALUE_OPTIONAL, 'Filter by extension display names, comma-separated', '')
->addOption('for-libs', null, InputOption::VALUE_OPTIONAL, 'Filter by lib names (depends+suggests), comma-separated', '') ->addOption('for-libs', null, InputOption::VALUE_OPTIONAL, 'Filter by lib names (depends+suggests), comma-separated', '')
->addOption('os', null, InputOption::VALUE_OPTIONAL, 'Filter by OS (Linux/Darwin/Windows), comma-separated', '') ->addOption('os', null, InputOption::VALUE_OPTIONAL, 'Filter by OS (Linux/Darwin/Windows), comma-separated', '')
->addOption('sapi', null, InputOption::VALUE_OPTIONAL, 'Add extra SAPI build tests, comma-separated (supported: frankenphp)', '')
->addOption('tier2', null, InputOption::VALUE_NONE, 'Use Tier 2 runners (Linux aarch64 + macOS x86_64, no Windows)'); ->addOption('tier2', null, InputOption::VALUE_NONE, 'Use Tier 2 runners (Linux aarch64 + macOS x86_64, no Windows)');
} }
@@ -98,8 +105,15 @@ class GenExtTestMatrixCommand extends BaseCommand
$filter_extensions = $parse_option('for-extensions'); $filter_extensions = $parse_option('for-extensions');
$filter_libs = $parse_option('for-libs'); $filter_libs = $parse_option('for-libs');
$filter_os_keys = $parse_option('os'); $filter_os_keys = $parse_option('os');
$filter_sapis = array_unique($parse_option('sapi'));
$tier2 = (bool) $this->input->getOption('tier2'); $tier2 = (bool) $this->input->getOption('tier2');
$unknown_sapis = array_values(array_diff($filter_sapis, self::SUPPORTED_SAPIS));
if (!empty($unknown_sapis)) {
$this->output->writeln('<error>Unsupported SAPI(s): ' . implode(', ', $unknown_sapis) . '</error>');
return static::USER_ERROR;
}
$base_runners = $tier2 ? self::OS_RUNNERS_TIER2 : self::OS_RUNNERS; $base_runners = $tier2 ? self::OS_RUNNERS_TIER2 : self::OS_RUNNERS;
$all = PackageConfig::getAll(); $all = PackageConfig::getAll();
@@ -107,7 +121,12 @@ class GenExtTestMatrixCommand extends BaseCommand
// Separate into regular and virtual extensions (build-static:false excluded globally) // Separate into regular and virtual extensions (build-static:false excluded globally)
$all_regular = []; $all_regular = [];
$all_virtual = []; $all_virtual = [];
$all_libraries = [];
foreach ($all as $pkg_name => $config) { foreach ($all as $pkg_name => $config) {
if (($config['type'] ?? '') === 'library') {
$all_libraries[$pkg_name] = $config;
continue;
}
if (($config['type'] ?? '') !== 'php-extension') { if (($config['type'] ?? '') !== 'php-extension') {
continue; continue;
} }
@@ -121,6 +140,67 @@ class GenExtTestMatrixCommand extends BaseCommand
} }
} }
[$entries, $all_ext_lib_deps] = $this->buildEntriesForRunners(
$base_runners,
$filter_os_keys,
$all_regular,
$all_virtual,
$all_libraries,
self::BUILD_TARGETS,
'default',
);
if (in_array('frankenphp', $filter_sapis, true)) {
[$frankenphp_entries, $frankenphp_ext_lib_deps] = $this->buildEntriesForRunners(
self::OS_RUNNERS,
[],
$all_regular,
$all_virtual,
$all_libraries,
self::FRANKENPHP_BUILD_TARGETS,
'frankenphp',
);
$entries = array_merge($entries, $frankenphp_entries);
$all_ext_lib_deps = array_replace_recursive($all_ext_lib_deps, $frankenphp_ext_lib_deps);
}
if (!empty($filter_extensions) || !empty($filter_libs)) {
$entries = array_values(array_filter($entries, function (array $entry) use ($filter_extensions, $filter_libs, $all_ext_lib_deps): bool {
$names = explode(',', $entry['extension']);
if (!empty($filter_extensions) && count(array_intersect($names, $filter_extensions)) > 0) {
return true;
}
if (!empty($filter_libs)) {
$lib_deps = $all_ext_lib_deps[$entry['os']] ?? [];
foreach ($names as $name) {
if (count(array_intersect($lib_deps[$name] ?? [], $filter_libs)) > 0) {
return true;
}
}
}
return false;
}));
}
$this->output->write(json_encode($entries, JSON_UNESCAPED_SLASHES));
return static::SUCCESS;
}
/**
* @return array{array<int, array<string, string>>, array<string, array<string, string[]>>}
*/
private function buildEntriesForRunners(
array $base_runners,
array $filter_os_keys,
array $all_regular,
array $all_virtual,
array $all_libraries,
string $build_targets,
string $sapi,
): array {
$os_runners = empty($filter_os_keys) $os_runners = empty($filter_os_keys)
? $base_runners ? $base_runners
: array_filter($base_runners, fn ($info) => in_array($info['os_key'], $filter_os_keys, true)); : array_filter($base_runners, fn ($info) => in_array($info['os_key'], $filter_os_keys, true));
@@ -154,10 +234,7 @@ class GenExtTestMatrixCommand extends BaseCommand
$raw, $raw,
fn ($d) => isset($pool_set[$d]) && $d !== $pkg_name fn ($d) => isset($pool_set[$d]) && $d !== $pkg_name
)); ));
$os_lib_deps[$this->displayName($pkg_name)] = array_values(array_filter( $os_lib_deps[$this->displayName($pkg_name)] = $this->collectLibraryDeps($raw, $all_libraries, $os);
$raw,
fn ($d) => !str_starts_with($d, 'ext-')
));
} }
$all_ext_lib_deps[$os] = $os_lib_deps; $all_ext_lib_deps[$os] = $os_lib_deps;
@@ -235,39 +312,18 @@ class GenExtTestMatrixCommand extends BaseCommand
sort($groups); sort($groups);
foreach ($groups as $group) { foreach ($groups as $group) {
$extra = $this->extraBuildFlags($group);
$entries[] = [ $entries[] = [
'runner' => $os_info['runner'], 'runner' => $os_info['runner'],
'os' => $os, 'os' => $os,
'arch' => $os_info['arch'], 'arch' => $os_info['arch'],
'sapi' => $sapi,
'extension' => $group, 'extension' => $group,
'build-args' => './bin/spc build "' . $group . '" ' . self::BUILD_TARGETS . ($extra !== '' ? ' ' . $extra : ''), 'build-args' => './bin/spc build "' . $group . '" ' . $this->buildTargetsWithExtraFlags($build_targets, $group),
]; ];
} }
} }
if (!empty($filter_extensions)) { return [$entries, $all_ext_lib_deps];
$entries = array_values(array_filter($entries, function (array $entry) use ($filter_extensions): bool {
$names = explode(',', $entry['extension']);
return count(array_intersect($names, $filter_extensions)) > 0;
}));
}
if (!empty($filter_libs)) {
$entries = array_values(array_filter($entries, function (array $entry) use ($filter_libs, $all_ext_lib_deps): bool {
$names = explode(',', $entry['extension']);
$lib_deps = $all_ext_lib_deps[$entry['os']] ?? [];
foreach ($names as $name) {
if (count(array_intersect($lib_deps[$name] ?? [], $filter_libs)) > 0) {
return true;
}
}
return false;
}));
}
$this->output->write(json_encode($entries, JSON_UNESCAPED_SLASHES));
return static::SUCCESS;
} }
/** /**
@@ -300,6 +356,41 @@ class GenExtTestMatrixCommand extends BaseCommand
return str_starts_with($pkg_name, 'ext-') ? substr($pkg_name, 4) : $pkg_name; return str_starts_with($pkg_name, 'ext-') ? substr($pkg_name, 4) : $pkg_name;
} }
/**
* Collect direct and transitive library dependencies from a package dependency list.
*
* @param string[] $deps
* @param array<string, mixed[]> $library_configs
* @param array<string, true> $seen
*
* @return string[]
*/
private function collectLibraryDeps(array $deps, array $library_configs, string $platform, array $seen = []): array
{
$collected = [];
foreach ($deps as $dep) {
if (str_starts_with($dep, 'ext-') || isset($seen[$dep])) {
continue;
}
$seen[$dep] = true;
$collected[$dep] = $dep;
if (!isset($library_configs[$dep])) {
continue;
}
$child_deps = array_merge(
$this->resolvePlatformList($library_configs[$dep], 'depends', $platform),
$this->resolvePlatformList($library_configs[$dep], 'suggests', $platform),
);
foreach ($this->collectLibraryDeps($child_deps, $library_configs, $platform, $seen) as $child_dep) {
$collected[$child_dep] = $child_dep;
}
}
return array_values($collected);
}
/** /**
* Split orphans into batches such that no two conflicting extensions share a batch. * Split orphans into batches such that no two conflicting extensions share a batch.
* Uses a greedy graph-coloring approach. * Uses a greedy graph-coloring approach.
@@ -359,6 +450,18 @@ class GenExtTestMatrixCommand extends BaseCommand
return implode(' ', $flags); return implode(' ', $flags);
} }
private function buildTargetsWithExtraFlags(string $build_targets, string $group): string
{
$flags = explode(' ', $build_targets);
foreach (explode(' ', $this->extraBuildFlags($group)) as $extra) {
if ($extra === '' || in_array($extra, $flags, true)) {
continue;
}
$flags[] = $extra;
}
return implode(' ', $flags);
}
/** /**
* Resolve the value of a platform-specific array field, applying the suffix fallback chain. * Resolve the value of a platform-specific array field, applying the suffix fallback chain.
* *

View File

@@ -25,6 +25,10 @@ class TestBotCommand extends BaseCommand
private const string TIER2_LABEL = 'test/tier2'; private const string TIER2_LABEL = 'test/tier2';
private const array SAPI_LABELS = [
'sapi/frankenphp' => 'frankenphp',
];
/** PHP version labels → version string (8.5 is always included as default) */ /** PHP version labels → version string (8.5 is always included as default) */
private const array PHP_VERSION_LABELS = [ private const array PHP_VERSION_LABELS = [
'test/php-83' => '8.3', 'test/php-83' => '8.3',
@@ -93,6 +97,12 @@ class TestBotCommand extends BaseCommand
} }
$tier2 = in_array(self::TIER2_LABEL, $label_names, true); $tier2 = in_array(self::TIER2_LABEL, $label_names, true);
$need_test = in_array('need-test', $label_names, true); $need_test = in_array('need-test', $label_names, true);
$sapis = [];
foreach (self::SAPI_LABELS as $label => $sapi) {
if (in_array($label, $label_names, true)) {
$sapis[] = $sapi;
}
}
// Resolve PHP versions (default always included) // Resolve PHP versions (default always included)
$php_versions = [self::DEFAULT_PHP_VERSION]; $php_versions = [self::DEFAULT_PHP_VERSION];
@@ -119,6 +129,9 @@ class TestBotCommand extends BaseCommand
if (!empty($os_keys)) { if (!empty($os_keys)) {
$flag_parts[] = '--os=' . implode(',', $os_keys); $flag_parts[] = '--os=' . implode(',', $os_keys);
} }
if (!empty($sapis)) {
$flag_parts[] = '--sapi=' . implode(',', $sapis);
}
$gen_matrix_args = implode(' ', $flag_parts); $gen_matrix_args = implode(' ', $flag_parts);
if ($tier2) { if ($tier2) {
@@ -128,7 +141,7 @@ class TestBotCommand extends BaseCommand
fn ($k) => $k !== 'Windows' fn ($k) => $k !== 'Windows'
)); ));
if (!empty($tier2_os)) { if (!empty($tier2_os)) {
$tier2_parts = array_values(array_filter($flag_parts, fn ($f) => !str_starts_with($f, '--os='))); $tier2_parts = array_values(array_filter($flag_parts, fn ($f) => !str_starts_with($f, '--os=') && !str_starts_with($f, '--sapi=')));
$tier2_parts[] = '--os=' . implode(',', $tier2_os); $tier2_parts[] = '--os=' . implode(',', $tier2_os);
$tier2_parts[] = '--tier2'; $tier2_parts[] = '--tier2';
$gen_matrix_args_tier2 = implode(' ', $tier2_parts); $gen_matrix_args_tier2 = implode(' ', $tier2_parts);
@@ -143,6 +156,7 @@ class TestBotCommand extends BaseCommand
$label_names, $label_names,
$os_keys, $os_keys,
$tier2, $tier2,
$sapis,
$php_versions, $php_versions,
$need_test, $need_test,
); );
@@ -156,6 +170,7 @@ class TestBotCommand extends BaseCommand
'gen_matrix_args_tier2' => $gen_matrix_args_tier2, 'gen_matrix_args_tier2' => $gen_matrix_args_tier2,
'php_versions' => $php_versions, 'php_versions' => $php_versions,
'tier2' => $tier2, 'tier2' => $tier2,
'sapis' => $sapis,
'comment_body' => $comment_body, 'comment_body' => $comment_body,
]; ];
@@ -239,6 +254,7 @@ class TestBotCommand extends BaseCommand
array $label_names, array $label_names,
array $os_keys, array $os_keys,
bool $tier2, bool $tier2,
array $sapis,
array $php_versions, array $php_versions,
bool $need_test, bool $need_test,
): string { ): string {
@@ -253,6 +269,14 @@ class TestBotCommand extends BaseCommand
$fmt($targets), $fmt($targets),
); );
$available_labels = implode(', ', [
'`need-test` (gate)',
'`test/linux` `test/windows` `test/macos` (platform)',
'`test/tier2` (extra arch)',
'`test/php-83` `test/php-84` (PHP version)',
'`sapi/frankenphp` (extra FrankenPHP SAPI build)',
]);
// Case 1: need-test absent → invite the author to add it // Case 1: need-test absent → invite the author to add it
if (!$need_test) { if (!$need_test) {
return implode("\n", [ return implode("\n", [
@@ -261,11 +285,9 @@ class TestBotCommand extends BaseCommand
'', '',
$detected, $detected,
'', '',
'To trigger extension build tests on this PR, add the `need-test` label:', 'To trigger extension build tests on this PR, add the `need-test` label.',
'', '',
'**Gate**: `need-test`', '**Available labels**: ' . $available_labels,
'**Platform filter** (optional, default all): `test/linux` `test/windows` `test/macos` · `test/tier2`',
'**PHP version** (optional, default 8.5): `test/php-83` `test/php-84`',
]); ]);
} }
@@ -298,7 +320,8 @@ class TestBotCommand extends BaseCommand
} }
$php_str = implode(', ', array_map(fn ($v) => "PHP {$v}", $php_versions)) . ' NTS'; $php_str = implode(', ', array_map(fn ($v) => "PHP {$v}", $php_versions)) . ' NTS';
$active_test_labels = array_values(array_filter($label_names, fn ($l) => str_starts_with($l, 'test/'))); $sapi_str = !empty($sapis) ? ' + SAPI: ' . implode(', ', $sapis) . ' (Tier1 Linux/macOS/Windows)' : '';
$active_test_labels = array_values(array_filter($label_names, fn ($l) => str_starts_with($l, 'test/') || str_starts_with($l, 'sapi/')));
$labels_str = !empty($active_test_labels) ? '`' . implode('`, `', $active_test_labels) . '`' : '_none_'; $labels_str = !empty($active_test_labels) ? '`' . implode('`, `', $active_test_labels) . '`' : '_none_';
return implode("\n", [ return implode("\n", [
@@ -307,7 +330,8 @@ class TestBotCommand extends BaseCommand
'', '',
$detected, $detected,
'**Active labels**: ' . $labels_str, '**Active labels**: ' . $labels_str,
'**Config**: ' . implode(' + ', $platform_parts) . ' | ' . $php_str, '**Available labels**: ' . $available_labels,
'**Config**: ' . implode(' + ', $platform_parts) . ' | ' . $php_str . $sapi_str,
]); ]);
} }
} }

View File

@@ -13,7 +13,7 @@ class DoctorCommand extends BaseCommand
{ {
public function configure(): void public function configure(): void
{ {
$this->addOption('auto-fix', null, InputOption::VALUE_OPTIONAL, 'Automatically fix failed items (if possible)', false); $this->addOption('auto-fix', 'y', InputOption::VALUE_OPTIONAL, 'Automatically fix failed items (if possible)', false);
} }
public function handle(): int public function handle(): int

View File

@@ -23,7 +23,7 @@ class InstallPackageCommand extends BaseCommand
'The package to install (name or path)', 'The package to install (name or path)',
suggestedValues: function (CompletionInput $input) { suggestedValues: function (CompletionInput $input) {
$packages = []; $packages = [];
foreach (PackageLoader::getPackages(['target', 'virtual-target']) as $name => $_) { foreach (PackageLoader::getPackages(['target', 'virtual-target', 'tool']) as $name => $_) {
$packages[] = $name; $packages[] = $name;
} }
$val = $input->getCompletionValue(); $val = $input->getCompletionValue();

View File

@@ -38,7 +38,7 @@ class ArtifactConfig
*/ */
public static function loadFromFile(string $file, string $registry_name): string public static function loadFromFile(string $file, string $registry_name): string
{ {
$content = file_get_contents($file); $content = @file_get_contents($file);
if ($content === false) { if ($content === false) {
throw new WrongUsageException("Failed to read artifact config file: {$file}"); throw new WrongUsageException("Failed to read artifact config file: {$file}");
} }

View File

@@ -19,6 +19,7 @@ enum ConfigType
'php-extension', 'php-extension',
'target', 'target',
'virtual-target', 'virtual-target',
'tool',
]; ];
public static function validateLicenseField(mixed $value): bool public static function validateLicenseField(mixed $value): bool

View File

@@ -24,6 +24,10 @@ class ConfigValidator
'lang' => ConfigType::STRING, 'lang' => ConfigType::STRING,
'frameworks' => ConfigType::LIST_ARRAY, // @ 'frameworks' => ConfigType::LIST_ARRAY, // @
// build-time tool dependency declaration (resolved independently of the library
// dependency graph, see PackageInstaller::collectRequiredTools())
'tools' => ConfigType::LIST_ARRAY, // @
// php-extension type fields // php-extension type fields
'php-extension' => ConfigType::ASSOC_ARRAY, 'php-extension' => ConfigType::ASSOC_ARRAY,
'zend-extension' => ConfigType::BOOL, 'zend-extension' => ConfigType::BOOL,
@@ -44,6 +48,13 @@ class ConfigValidator
'path' => ConfigType::LIST_ARRAY, // @ 'path' => ConfigType::LIST_ARRAY, // @
'env' => ConfigType::ASSOC_ARRAY, // @ 'env' => ConfigType::ASSOC_ARRAY, // @
'append-env' => ConfigType::ASSOC_ARRAY, // @ 'append-env' => ConfigType::ASSOC_ARRAY, // @
// tool type fields (nested under 'tool' key)
'tool' => ConfigType::ASSOC_ARRAY,
'provides' => ConfigType::LIST_ARRAY,
'binary-subdir' => ConfigType::STRING,
'install-root' => ConfigType::STRING,
'min-version' => ConfigType::STRING,
]; ];
public const array PACKAGE_FIELDS = [ public const array PACKAGE_FIELDS = [
@@ -56,6 +67,9 @@ class ConfigValidator
'lang' => false, 'lang' => false,
'frameworks' => false, // @ 'frameworks' => false, // @
// build-time tool dependency declaration
'tools' => false, // @
// php-extension type fields // php-extension type fields
'php-extension' => false, 'php-extension' => false,
@@ -67,6 +81,9 @@ class ConfigValidator
'path' => false, // @ 'path' => false, // @
'env' => false, // @ 'env' => false, // @
'append-env' => false, // @ 'append-env' => false, // @
// tool fields (nested object)
'tool' => false,
]; ];
public const array SUFFIX_ALLOWED_FIELDS = [ public const array SUFFIX_ALLOWED_FIELDS = [
@@ -78,6 +95,7 @@ class ConfigValidator
'path', 'path',
'env', 'env',
'append-env', 'append-env',
'tools',
]; ];
public const array PHP_EXTENSION_FIELDS = [ public const array PHP_EXTENSION_FIELDS = [
@@ -92,6 +110,13 @@ class ConfigValidator
'os' => false, 'os' => false,
]; ];
public const array TOOL_FIELDS = [
'provides' => true,
'binary-subdir' => false,
'install-root' => false,
'min-version' => false,
];
public const array ARTIFACT_TYPE_FIELDS = [ // [required_fields, optional_fields] public const array ARTIFACT_TYPE_FIELDS = [ // [required_fields, optional_fields]
'filelist' => [['url', 'regex'], ['extract']], 'filelist' => [['url', 'regex'], ['extract']],
'git' => [['url'], ['extract', 'submodules', 'rev', 'regex']], 'git' => [['url'], ['extract', 'submodules', 'rev', 'regex']],
@@ -220,8 +245,8 @@ class ConfigValidator
$fields = self::SUFFIX_ALLOWED_FIELDS; $fields = self::SUFFIX_ALLOWED_FIELDS;
self::validateSuffixAllowedFields($name, $pkg, $fields, $suffixes); self::validateSuffixAllowedFields($name, $pkg, $fields, $suffixes);
// check if "library|target" package has artifact field for target and library types // check if "library|target|tool" package has artifact field
if (in_array($pkg['type'], ['target', 'library']) && !isset($pkg['artifact'])) { if (in_array($pkg['type'], ['target', 'library', 'tool']) && !isset($pkg['artifact'])) {
throw new ValidationException("Package [{$name}] in {$config_file_name} of type '{$pkg['type']}' must have an 'artifact' field"); throw new ValidationException("Package [{$name}] in {$config_file_name} of type '{$pkg['type']}' must have an 'artifact' field");
} }
@@ -235,6 +260,11 @@ class ConfigValidator
self::validatePhpExtensionFields($name, $pkg); self::validatePhpExtensionFields($name, $pkg);
} }
// check if "tool" package has tool specific fields and validate inside
if ($pkg['type'] === 'tool') {
self::validateToolFields($name, $pkg);
}
// check for unknown fields // check for unknown fields
self::validateNoInvalidFields('package', $name, $pkg, array_keys(self::PACKAGE_FIELD_TYPES)); self::validateNoInvalidFields('package', $name, $pkg, array_keys(self::PACKAGE_FIELD_TYPES));
} }
@@ -397,6 +427,29 @@ class ConfigValidator
self::validateNoInvalidFields('php-extension', $name, $pkg['php-extension'], array_keys(self::PHP_EXTENSION_FIELDS)); self::validateNoInvalidFields('php-extension', $name, $pkg['php-extension'], array_keys(self::PHP_EXTENSION_FIELDS));
} }
/**
* Validate tool specific fields for tool package type.
*/
private static function validateToolFields(int|string $name, mixed $pkg): void
{
if (!isset($pkg['tool'])) {
throw new ValidationException("Package {$name} of type 'tool' must have a 'tool' field");
}
if (!is_assoc_array($pkg['tool'])) {
throw new ValidationException("Package {$name} [tool] must be an object");
}
foreach (self::TOOL_FIELDS as $field => $required) {
if ($required && !isset($pkg['tool'][$field])) {
throw new ValidationException("Package {$name} [tool] must have required field [{$field}]");
}
if (isset($pkg['tool'][$field])) {
self::validatePackageFieldType($field, $pkg['tool'][$field], $name);
}
}
// check for unknown fields in tool
self::validateNoInvalidFields('tool', $name, $pkg['tool'], array_keys(self::TOOL_FIELDS));
}
private static function validateNoInvalidFields(string $config_type, int|string $item_name, mixed $item_content, array $allowed_fields): void private static function validateNoInvalidFields(string $config_type, int|string $item_name, mixed $item_content, array $allowed_fields): void
{ {
foreach ($item_content as $k => $v) { foreach ($item_content as $k => $v) {

View File

@@ -16,7 +16,7 @@ class PackageConfig
/** /**
* Load package configurations from a specified directory. * Load package configurations from a specified directory.
* It will look for files matching the pattern 'pkg.*.json' and 'pkg.json'. * Only processes .json, .yml, and .yaml files (skips .gitkeep etc.).
*/ */
public static function loadFromDir(string $dir, string $registry_name): array public static function loadFromDir(string $dir, string $registry_name): array
{ {
@@ -28,6 +28,10 @@ class PackageConfig
$files = FileSystem::scanDirFiles($dir, false); $files = FileSystem::scanDirFiles($dir, false);
if (is_array($files)) { if (is_array($files)) {
foreach ($files as $file) { foreach ($files as $file) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array($ext, ['json', 'yml', 'yaml'], true)) {
continue;
}
self::loadFromFile($file, $registry_name); self::loadFromFile($file, $registry_name);
$loaded[] = $file; $loaded[] = $file;
} }

View File

@@ -32,7 +32,10 @@ use StaticPHP\Command\SPCConfigCommand;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Registry\PackageLoader; use StaticPHP\Registry\PackageLoader;
use StaticPHP\Registry\Registry; use StaticPHP\Registry\Registry;
use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Application; use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleApplication extends Application class ConsoleApplication extends Application
{ {
@@ -104,4 +107,15 @@ class ConsoleApplication extends Application
{ {
self::$additional_commands = array_merge(self::$additional_commands, $additional_commands); self::$additional_commands = array_merge(self::$additional_commands, $additional_commands);
} }
/**
* Hook Symfony's doRun() to inject the real input/output into InteractiveTerm before
* any command executes. From this point forward, InteractiveTerm uses the configured
* Console (respecting --no-ansi, --verbose, etc.) instead of the lazy STDERR fallback.
*/
public function doRun(InputInterface $input, OutputInterface $output): int
{
InteractiveTerm::init($input, $output);
return parent::doRun($input, $output);
}
} }

View File

@@ -12,7 +12,6 @@ use StaticPHP\Package\PackageInstaller;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\ToolchainManager; use StaticPHP\Toolchain\ToolchainManager;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\GlobalEnvManager;
use StaticPHP\Util\System\WindowsUtil; use StaticPHP\Util\System\WindowsUtil;
#[OptionalCheck([self::class, 'optional'])] #[OptionalCheck([self::class, 'optional'])]
@@ -74,27 +73,6 @@ class WindowsToolCheck
return CheckResult::ok($path); return CheckResult::ok($path);
} }
#[CheckItem('if nasm installed', level: 995)]
public function checkNasm(): ?CheckResult
{
if (($a = WindowsUtil::findCommand('nasm.exe')) === null) {
return CheckResult::fail('nasm.exe not found in path.', 'install-nasm');
}
return CheckResult::ok($a);
}
#[CheckItem('if perl(strawberry) installed', limit_os: 'Windows', level: 994)]
public function checkPerl(): ?CheckResult
{
if (($path = WindowsUtil::findCommand('perl.exe')) === null) {
return CheckResult::fail('perl not found in path.', 'install-perl');
}
if (!str_contains(implode('', cmd()->execWithResult(quote($path) . ' -v', false)[1]), 'MSWin32')) {
return CheckResult::fail($path . ' is not built for msvc.', 'install-perl');
}
return CheckResult::ok($path);
}
#[CheckItem('if environment is properly set up', level: 1)] #[CheckItem('if environment is properly set up', level: 1)]
public function checkenv(): ?CheckResult public function checkenv(): ?CheckResult
{ {
@@ -113,16 +91,6 @@ class WindowsToolCheck
return CheckResult::ok(); return CheckResult::ok();
} }
#[FixItem('install-perl')]
public function installPerl(): bool
{
$installer = new PackageInstaller();
$installer->addInstallPackage('strawberry-perl');
$installer->run(true);
GlobalEnvManager::addPathIfNotExists(PKG_ROOT_PATH . '\strawberry-perl');
return true;
}
#[FixItem('install-msys2-build-essentials')] #[FixItem('install-msys2-build-essentials')]
public function installMsys2(): bool public function installMsys2(): bool
{ {
@@ -141,15 +109,6 @@ class WindowsToolCheck
return true; return true;
} }
#[FixItem('install-nasm')]
public function installNasm(): bool
{
$installer = new PackageInstaller(interactive: false);
$installer->addInstallPackage('nasm');
$installer->run(true);
return true;
}
#[FixItem('install-vswhere')] #[FixItem('install-vswhere')]
public function installVSWhere(): bool public function installVSWhere(): bool
{ {

View File

@@ -111,7 +111,7 @@ class ExceptionHandler
private static function logError($message, int $indent_space = 0, bool $output_log = true, string $color = 'red'): void private static function logError($message, int $indent_space = 0, bool $output_log = true, string $color = 'red'): void
{ {
$spc_log = fopen(SPC_OUTPUT_LOG, 'a'); $spc_log = spc_log_stream(SPC_OUTPUT_LOG);
$msg = explode("\n", (string) $message); $msg = explode("\n", (string) $message);
foreach ($msg as $v) { foreach ($msg as $v) {
$line = str_pad($v, strlen($v) + $indent_space, ' ', STR_PAD_LEFT); $line = str_pad($v, strlen($v) + $indent_space, ' ', STR_PAD_LEFT);

View File

@@ -113,60 +113,6 @@ class LibraryPackage extends Package
} }
} }
/**
* Get extra CFLAGS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_CFLAGS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_CFLAGS.
*/
public function getLibExtraCFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CFLAGS') ?: '';
// get default c flags
$arch_c_flags = getenv('SPC_DEFAULT_CFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CFLAGS')) && !str_contains($env, $arch_c_flags)) {
$env .= ' ' . $arch_c_flags;
}
return trim($env);
}
/**
* Get extra CXXFLAGS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_CXXFLAGS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_CXXFLAGS.
*/
public function getLibExtraCxxFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CXXFLAGS') ?: '';
// get default cxx flags
$arch_cxx_flags = getenv('SPC_DEFAULT_CXXFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CXXFLAGS')) && !str_contains($env, $arch_cxx_flags)) {
$env .= ' ' . $arch_cxx_flags;
}
return trim($env);
}
/**
* Get extra LDFLAGS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_LDFLAGS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_LDFLAGS.
*/
public function getLibExtraLdFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_LDFLAGS') ?: '';
// get default ld flags
$arch_ld_flags = getenv('SPC_DEFAULT_LDFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_LDFLAGS')) && !str_contains($env, $arch_ld_flags)) {
$env .= ' ' . $arch_ld_flags;
}
return trim($env);
}
/** /**
* Patch pkgconfig file prefix, exec_prefix, libdir, includedir for correct build. * Patch pkgconfig file prefix, exec_prefix, libdir, includedir for correct build.
* *
@@ -364,17 +310,6 @@ class LibraryPackage extends Package
return $res['libs']; return $res['libs'];
} }
/**
* Get extra LIBS for current package.
* You need to define the environment variable in the format of {LIBRARY_NAME}_LIBS
* where {LIBRARY_NAME} is the snake_case name of the library.
* For example, for libjpeg, the environment variable should be libjpeg_LIBS.
*/
public function getLibExtraLibs(): string
{
return getenv($this->getSnakeCaseName() . '_LIBS') ?: '';
}
/** /**
* Get tar compress options from suffix * Get tar compress options from suffix
* *

View File

@@ -120,6 +120,20 @@ abstract class Package
return false; return false;
} }
/**
* Get the target directory where this package's artifacts should be placed.
*
* Libraries install to BUILD_ROOT_PATH (static-libs, headers, pkg-configs).
* Tools install to PKG_ROOT_PATH (executables).
* Extensions install to php-src/ext/ (shared objects).
*
* Override in subclasses to change the default.
*/
public function getInstallTarget(): string
{
return BUILD_ROOT_PATH;
}
/** /**
* Add a stage to the package. * Add a stage to the package.
*/ */
@@ -270,6 +284,71 @@ abstract class Package
return $this->getArtifact()?->hasPlatformBinary() ?? false; return $this->getArtifact()?->hasPlatformBinary() ?? false;
} }
/**
* Get extra CFLAGS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_CFLAGS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_CFLAGS.
*/
public function getLibExtraCFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CFLAGS') ?: '';
// get default c flags
$arch_c_flags = getenv('SPC_DEFAULT_CFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CFLAGS')) && !str_contains($env, $arch_c_flags)) {
$env .= ' ' . $arch_c_flags;
}
return trim($env);
}
/**
* Get extra CXXFLAGS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_CXXFLAGS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_CXXFLAGS.
*/
public function getLibExtraCxxFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_CXXFLAGS') ?: '';
// get default cxx flags
$arch_cxx_flags = getenv('SPC_DEFAULT_CXXFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_CXXFLAGS')) && !str_contains($env, $arch_cxx_flags)) {
$env .= ' ' . $arch_cxx_flags;
}
return trim($env);
}
/**
* Get extra LDFLAGS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_LDFLAGS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_LDFLAGS.
*/
public function getLibExtraLdFlags(): string
{
// get environment variable
$env = getenv($this->getSnakeCaseName() . '_LDFLAGS') ?: '';
// get default ld flags
$arch_ld_flags = getenv('SPC_DEFAULT_LDFLAGS') ?: '';
if (!empty(getenv('SPC_DEFAULT_LDFLAGS')) && !str_contains($env, $arch_ld_flags)) {
$env .= ' ' . $arch_ld_flags;
}
return trim($env);
}
/**
* Get extra LIBS for current package.
* You need to define the environment variable in the format of {PACKAGE_NAME}_LIBS
* where {PACKAGE_NAME} is the snake_case name of the package.
* For example, for libjpeg, the environment variable should be libjpeg_LIBS.
*/
public function getLibExtraLibs(): string
{
return getenv($this->getSnakeCaseName() . '_LIBS') ?: '';
}
/** /**
* Get the snake_case name of the package. * Get the snake_case name of the package.
*/ */

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace StaticPHP\Package; namespace StaticPHP\Package;
use StaticPHP\Artifact\ArtifactCache;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\SPCException; use StaticPHP\Exception\SPCException;
@@ -39,8 +40,8 @@ class PackageBuilder
public function buildPackage(Package $package, bool $force = false): int public function buildPackage(Package $package, bool $force = false): int
{ {
// init build dirs // init build dirs
if (!$package instanceof LibraryPackage) { if (!$package instanceof LibraryPackage && !$package instanceof ToolPackage) {
throw new SPCInternalException('Please, never try to build non-library packages directly.'); throw new SPCInternalException('Please, never try to build non-library, non-tool packages directly.');
} }
FileSystem::createDir($package->getBuildRootPath()); FileSystem::createDir($package->getBuildRootPath());
FileSystem::createDir($package->getIncludeDir()); FileSystem::createDir($package->getIncludeDir());
@@ -78,6 +79,14 @@ class PackageBuilder
$this->installLicense($package, $license); $this->installLicense($package, $license);
} }
} }
// Record the installed version for tool packages built from source, so
// `check-update --installed` reflects what's actually on disk (mirrors the
// binary-install recording in PackageInstaller::installBinary()).
if ($package instanceof ToolPackage) {
$source_info = ApplicationContext::get(ArtifactCache::class)->getSourceInfo($package->getName());
ToolVersionRegistry::record($package->getName(), $source_info['version'] ?? null);
}
} catch (SPCException $e) { } catch (SPCException $e) {
// Ensure package information is bound if not already // Ensure package information is bound if not already
if ($e->getPackageInfo() === null) { if ($e->getPackageInfo() === null) {

View File

@@ -11,6 +11,7 @@ use StaticPHP\Artifact\ArtifactExtractor;
use StaticPHP\Artifact\DownloaderOptions; use StaticPHP\Artifact\DownloaderOptions;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\EnvironmentException;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Registry\PackageLoader; use StaticPHP\Registry\PackageLoader;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
@@ -174,7 +175,7 @@ class PackageInstaller
// These must always download binary (not source), regardless of global prefer-source setting. // These must always download binary (not source), regardless of global prefer-source setting.
$binary_only_packages = array_filter( $binary_only_packages = array_filter(
$this->packages, $this->packages,
fn ($p) => $p instanceof LibraryPackage fn ($p) => ($p instanceof LibraryPackage || $p instanceof ToolPackage)
&& !$this->isBuildPackage($p) && !$this->isBuildPackage($p)
&& !$p->hasStage('build') && !$p->hasStage('build')
&& ($p->getArtifact()?->hasPlatformBinary() ?? false) && ($p->getArtifact()?->hasPlatformBinary() ?? false)
@@ -212,8 +213,8 @@ class PackageInstaller
$builder = ApplicationContext::get(PackageBuilder::class); $builder = ApplicationContext::get(PackageBuilder::class);
foreach ($this->packages as $package) { foreach ($this->packages as $package) {
$is_to_build = $this->isBuildPackage($package); $is_to_build = $this->isBuildPackage($package);
$has_build_stage = $package instanceof LibraryPackage && $package->hasStage('build'); $has_build_stage = ($package instanceof LibraryPackage || $package instanceof ToolPackage) && $package->hasStage('build');
$should_use_binary = $package instanceof LibraryPackage && ($package->getArtifact()?->shouldUseBinary() ?? false); $should_use_binary = ($package instanceof LibraryPackage || $package instanceof ToolPackage) && ($package->getArtifact()?->shouldUseBinary() ?? false);
$has_source = $package->hasSource(); $has_source = $package->hasSource();
if (!$is_to_build && $should_use_binary) { if (!$is_to_build && $should_use_binary) {
// install binary // install binary
@@ -276,6 +277,11 @@ class PackageInstaller
// perform after-install actions and emit post-install events // perform after-install actions and emit post-install events
$this->emitPostInstallEvents(); $this->emitPostInstallEvents();
// Final verification: declared build-time tools should have been auto-installed by the
// pipeline above (they were merged into $this->packages in resolvePackages()). This only
// throws if a tool genuinely failed to become available (e.g. no artifact for this platform).
$this->ensureRequiredTools();
} }
public function isBuildPackage(Package|string $package): bool public function isBuildPackage(Package|string $package): bool
@@ -353,12 +359,16 @@ class PackageInstaller
} }
// Fallback: if the download cache is missing (e.g. download failed or cache was cleared), // Fallback: if the download cache is missing (e.g. download failed or cache was cleared),
// still check whether the files are physically present in buildroot. // still check whether the files are physically present in buildroot.
// Note: TargetPackage extends LibraryPackage, but target packages (e.g. zig) have no // Note: TargetPackage extends LibraryPackage, but target packages have no
// static-libs/headers configured, so isInstalled() would trivially return true for them. // static-libs/headers configured, so isInstalled() would trivially return true for them.
// Only apply this fallback to pure library packages. // Only apply this fallback to pure library packages.
if ($package instanceof LibraryPackage && !($package instanceof TargetPackage)) { if ($package instanceof LibraryPackage && !($package instanceof TargetPackage)) {
return $package->isInstalled(); return $package->isInstalled();
} }
// Tool packages: fall back to checking their provided binaries directly on disk.
if ($package instanceof ToolPackage) {
return $package->isInstalled();
}
return false; return false;
} }
@@ -507,6 +517,16 @@ class PackageInstaller
} }
$status = $extractor->extract($artifact); $status = $extractor->extract($artifact);
// Record the installed version for tool packages, so `check-update --installed` can
// compare against what's actually on disk instead of only the download cache (which
// only reflects the last download and may be stale or cleared). Recorded regardless of
// $status so the registry self-heals if it was deleted separately from the install dir.
if ($package instanceof ToolPackage) {
$cache_info = ApplicationContext::get(ArtifactCache::class)->getBinaryInfo($artifact->getName(), SystemTarget::getCurrentPlatformString());
ToolVersionRegistry::record($artifact->getName(), $cache_info['version'] ?? null);
}
if ($status === SPC_STATUS_ALREADY_EXTRACTED) { if ($status === SPC_STATUS_ALREADY_EXTRACTED) {
return SPC_STATUS_ALREADY_INSTALLED; return SPC_STATUS_ALREADY_INSTALLED;
} }
@@ -574,6 +594,66 @@ class PackageInstaller
return null; return null;
} }
/**
* Collect all tool packages required by the currently resolved packages.
*
* Reads the 'tools' field from each resolved package's YAML config.
* The field supports platform suffixes (tools@windows, tools@linux, etc.)
* resolved automatically by PackageConfig::get().
*
* Tools are NOT part of the library dependency graph — they are
* build-time prerequisites that must be installed before any library
* build begins.
*
* @return string[] Unique tool package names required for this build
*/
public function collectRequiredTools(): array
{
$tools = [];
foreach ($this->packages as $package) {
$deps = PackageConfig::get($package->getName(), 'tools', []);
foreach ((array) $deps as $tool_name) {
$tools[$tool_name] = true;
}
}
return array_keys($tools);
}
/**
* Check that all required tools are installed.
*
* Iterates through tools collected by collectRequiredTools(),
* resolves each to a ToolPackage instance, and checks isInstalled().
*
* @return array{missing: array<string>, installed: array<string>}
*/
public function checkRequiredTools(): array
{
$missing = [];
$installed = [];
foreach ($this->collectRequiredTools() as $tool_name) {
try {
$tool = PackageLoader::getPackage($tool_name);
} catch (WrongUsageException) {
$missing[] = $tool_name;
logger()->warning("Required tool '{$tool_name}' is not registered as a package.");
continue;
}
if (!$tool instanceof ToolPackage) {
logger()->warning("Package '{$tool_name}' is declared as a tool dependency but is not a ToolPackage (type: {$tool->getType()}).");
continue;
}
if ($tool->isInstalled()) {
$installed[] = $tool_name;
} else {
$missing[] = $tool_name;
}
}
return ['missing' => $missing, 'installed' => $installed];
}
/** /**
* @param Package[] $packages * @param Package[] $packages
*/ */
@@ -597,8 +677,8 @@ class PackageInstaller
*/ */
private function validatePackageArtifact(Package $package): void private function validatePackageArtifact(Package $package): void
{ {
// target and library must have at least source or platform binary // target, library and tool packages must have at least source or platform binary
if (in_array($package->getType(), ['library', 'target']) && !$package->getArtifact()?->hasSource() && !$package->getArtifact()?->hasPlatformBinary()) { if (in_array($package->getType(), ['library', 'target', 'tool']) && !$package->getArtifact()?->hasSource() && !$package->getArtifact()?->hasPlatformBinary()) {
throw new WrongUsageException("Validation failed: Target package '{$package->getName()}' has no source or current platform (" . SystemTarget::getCurrentPlatformString() . ') binary defined.'); throw new WrongUsageException("Validation failed: Target package '{$package->getName()}' has no source or current platform (" . SystemTarget::getCurrentPlatformString() . ') binary defined.');
} }
} }
@@ -631,11 +711,62 @@ class PackageInstaller
$this->packages[$pkg_name] = PackageLoader::getPackage($pkg_name); $this->packages[$pkg_name] = PackageLoader::getPackage($pkg_name);
} }
// Merge in build-time tool packages declared via 'tools'/'tools@platform' fields on the
// packages resolved above. Tools are intentionally NOT part of the library dependency graph
// (DependencyResolver), but still need to ride the normal download/extract/install pipeline
// so they get auto-installed like any other package.
//
// Tools are prepended so they install BEFORE any package that declares them — otherwise a
// library that invokes e.g. jom.exe during its build stage would fail because the tool
// hasn't been extracted yet (tools were appended after the dependency graph in insertion
// order, which is also the build-loop iteration order).
$tool_packages = [];
foreach ($this->collectRequiredTools() as $tool_name) {
if (isset($this->packages[$tool_name])) {
continue;
}
try {
$tool = PackageLoader::getPackage($tool_name);
} catch (WrongUsageException) {
continue; // will be reported as missing by ensureRequiredTools()
}
if ($tool instanceof ToolPackage) {
$tool_packages[$tool_name] = $tool;
}
}
// Prepend: tools first, then the dependency-resolved packages.
$this->packages = [...$tool_packages, ...$this->packages];
foreach ($this->packages as $package) { foreach ($this->packages as $package) {
$this->injectPackageEnvs($package); $this->injectPackageEnvs($package);
} }
} }
/**
* Ensure all required tools are installed, throwing if any are missing.
*
* Called at the end of run(), after the normal download/extract/build/install pipeline
* has had a chance to auto-install any tool package merged in resolvePackages(). This is
* a final safety net: it only throws if a declared tool still isn't available afterward
* (e.g. no artifact defined for the current platform, or the tool name doesn't resolve to
* a registered ToolPackage). "General" tools not declared via any package's 'tools' field
* (e.g. zig, musl-toolchain) are not covered here and remain purely Doctor-driven.
*/
private function ensureRequiredTools(): void
{
$status = $this->checkRequiredTools();
if (empty($status['missing'])) {
if (!empty($status['installed'])) {
logger()->info('Required tools: ' . implode(', ', $status['installed']) . ' — all installed.');
}
return;
}
$msg = 'Missing required build tools: ' . implode(', ', $status['missing']) . "\n";
$msg .= "Run 'bin/spc doctor' to check your environment, or install the missing tools manually.";
throw new EnvironmentException($msg);
}
private function injectPackageEnvs(Package $package): void private function injectPackageEnvs(Package $package): void
{ {
$name = $package->getName(); $name = $package->getName();

View File

@@ -0,0 +1,233 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Package;
use StaticPHP\Config\PackageConfig;
use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\FileSystem;
/**
* Represents a build-time tool package.
*
* Tool packages are NOT link-time dependencies. They provide executables
* that are needed during the build process (compilers, code generators,
* assemblers, etc.) and are installed into PKG_ROOT_PATH.
*
* Tool packages do NOT produce static-libs, headers, or pkg-config files.
* They are resolved and installed independently from the library dependency graph.
*
* YAML config schema (config/pkg/tool/<name>.yml):
*
* nasm:
* type: tool
* tool:
* provides: [nasm.exe, ndisasm.exe] # executables this tool installs
* binary-subdir: '' # subdirectory under install root (default: '')
* min-version: '2.16' # minimum required version (optional)
*
* Fields nested under 'tool' support the same '@windows'/'@unix'/'@macos'/'@linux' suffix
* overrides as top-level package fields (e.g. 'provides@windows' overrides 'provides' when
* building on Windows), useful when a tool provides differently-named binaries per OS
* (e.g. upx vs upx.exe).
* artifact:
* binary:
* windows-x86_64:
* type: url
* url: 'https://...'
* extract:
* nasm.exe: '{php_sdk_path}/bin/nasm.exe'
*/
class ToolPackage extends Package
{
/**
* Get the build root ('--prefix') for a tool that builds from source.
*
* Unlike LibraryPackage (which installs into BUILD_ROOT_PATH), tool packages that build
* from source (e.g. pkg-config, via UnixAutoconfExecutor/UnixCMakeExecutor) install into
* their own install root (PKG_ROOT_PATH by default), consistent with pre-built tool binaries.
*/
public function getBuildRootPath(): string
{
return $this->getInstallRoot();
}
/**
* Tool packages don't produce headers for other packages to consume. Kept self-contained
* under the tool's own install root so a from-source build never accidentally picks up
* unrelated headers from BUILD_ROOT_PATH.
*/
public function getIncludeDir(): string
{
return $this->getInstallRoot() . DIRECTORY_SEPARATOR . 'include';
}
/**
* Tool packages don't produce libraries for other packages to consume. Kept self-contained
* under the tool's own install root (see getIncludeDir()).
*/
public function getLibDir(): string
{
return $this->getInstallRoot() . DIRECTORY_SEPARATOR . 'lib';
}
/**
* Where this tool's own executables live, i.e. {install-root}/{binary-subdir}.
*/
public function getBinDir(): string
{
return $this->getBinaryDir();
}
/**
* Get the install root directory for this tool.
*
* Defaults to PKG_ROOT_PATH. Override via 'tool.install-root' in YAML
* or via the TOOL_INSTALL_ROOT_{NAME} environment variable.
*/
public function getInstallRoot(): string
{
$env_var = 'TOOL_INSTALL_ROOT_' . strtoupper(str_replace('-', '_', $this->name));
if ($root = getenv($env_var)) {
return $root;
}
$config_root = $this->getToolField('install-root');
if ($config_root !== null) {
return FileSystem::replacePathVariable((string) $config_root);
}
return PKG_ROOT_PATH;
}
/**
* Get the directory where this tool's binaries reside.
*
* This is {install-root}/{binary-subdir}. If binary-subdir is not
* configured, returns the install root directly.
*/
public function getBinaryDir(): string
{
$subdir = $this->getToolField('binary-subdir') ?? '';
if ($subdir === '') {
return $this->getInstallRoot();
}
return $this->getInstallRoot() . DIRECTORY_SEPARATOR . $subdir;
}
/**
* Get the list of executables this tool provides.
*
* Reads from YAML 'tool.provides' field (with '@windows'/'@unix'/'@macos'/'@linux'
* suffix override support). Each entry is a bare filename (e.g. 'nasm.exe'), resolved
* relative to getBinaryDir().
*
* @return string[] Bare executable names (not full paths)
*/
public function getProvides(): array
{
return $this->getToolField('provides') ?? [];
}
/**
* Get the full path to a specific binary provided by this tool.
*
* @param string $name Bare executable name (must be listed in tool.provides).
* If empty, defaults to the first entry in provides.
* @return string Full absolute path to the binary
*/
public function getBinary(string $name = ''): string
{
$provides = $this->getProvides();
if ($name === '') {
$name = $provides[0] ?? throw new \RuntimeException("Tool '{$this->name}' has no 'tool.provides' configured.");
}
if (!in_array($name, $provides, true)) {
throw new \RuntimeException("Binary '{$name}' is not listed in tool.provides for '{$this->name}'. Available: " . implode(', ', $provides));
}
return $this->getBinaryDir() . DIRECTORY_SEPARATOR . $name;
}
/**
* Check whether this tool is installed (all provided binaries exist on disk).
*/
public function isInstalled(): bool
{
return array_all($this->getProvides(), fn ($binary) => file_exists($this->getBinary($binary)));
}
/**
* Get the version currently installed on disk, as recorded by ToolVersionRegistry when this
* tool's binary was last (re-)installed via PackageInstaller::installBinary().
*
* Returns null if the tool was never installed through the package installer (e.g. installed
* manually, or not installed at all), or if its artifact doesn't expose a version string.
* This reflects what's actually on disk, unlike the download cache which only reflects the
* last download and may be stale or cleared.
*/
public function getInstalledVersion(): ?string
{
return ToolVersionRegistry::get($this->name);
}
/**
* Get the minimum required version for this tool, if specified.
*
* Returns null if no version constraint is configured.
*/
public function getMinVersion(): ?string
{
$version = $this->getToolField('min-version');
return $version !== null ? (string) $version : null;
}
/**
* Tools install to PKG_ROOT_PATH (or the configured install-root),
* not BUILD_ROOT_PATH.
*/
public function getInstallTarget(): string
{
return $this->getBinaryDir();
}
/**
* Get the 'tool' sub-config for this package.
*
* Returns the nested array under the 'tool' key in the package YAML,
* or an empty array if not configured.
*
* @return array<string, mixed>
*/
private function getToolConfig(): array
{
$config = PackageConfig::get($this->name);
if (!is_array($config) || !isset($config['tool']) || !is_array($config['tool'])) {
return [];
}
return $config['tool'];
}
/**
* Get a field from the nested 'tool' config block, honoring the same
* '@windows'/'@unix'/'@macos'/'@linux'/'@bsd'/'@freebsd' suffix override priority
* that PackageConfig::get() applies to top-level fields. This lets a tool declare a
* per-OS override, e.g. 'provides' + 'provides@windows', without needing platform-
* specific package config files.
*/
private function getToolField(string $field): mixed
{
$tool = $this->getToolConfig();
$suffixes = match (SystemTarget::getTargetOS()) {
'Windows' => ['@windows', ''],
'Darwin' => ['@macos', '@unix', ''],
'Linux' => ['@linux', '@unix', ''],
'BSD' => ['@freebsd', '@bsd', '@unix', ''],
};
foreach ($suffixes as $suffix) {
$key = "{$field}{$suffix}";
if (isset($tool[$key])) {
return $tool[$key];
}
}
return null;
}
}

View File

@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Package;
use StaticPHP\Runtime\SystemTarget;
/**
* Tracks the version actually installed on disk for tool packages (PKG_ROOT_PATH), separate from
* the download cache (ArtifactCache). Tools are installed once and reused across many builds, so
* the download cache (which only reflects the last download) can drift from what's really on disk
* (e.g. cache cleared, or installed a long time ago via `doctor`). This registry is the source of
* truth for "what version is currently installed", used by ToolPackage::getInstalledVersion() and
* the `check-update --installed` flag.
*
* Backed by a small JSON file at PKG_ROOT_PATH/.spc-tool-versions.json, mirroring the same
* read-once/write-through pattern used by StaticPHP\Artifact\ArtifactCache.
*/
class ToolVersionRegistry
{
/** @var null|array<string, array{version: null|string, platform: string, installed_at: string}> */
private static ?array $data = null;
/**
* Get the recorded installed version for a tool, or null if never recorded (not a tool
* package, not installed yet, or the artifact doesn't expose a version).
*/
public static function get(string $tool_name): ?string
{
self::load();
return self::$data[$tool_name]['version'] ?? null;
}
/**
* Record the version currently installed for a tool. Called after a tool package's binary
* has been (re-)installed, regardless of whether extraction actually ran (keeps the registry
* self-healing if it was deleted separately from the installed files).
*/
public static function record(string $tool_name, ?string $version): void
{
self::load();
self::$data[$tool_name] = [
'version' => $version,
'platform' => SystemTarget::getCurrentPlatformString(),
'installed_at' => date('c'),
];
self::save();
}
private static function getPath(): string
{
return PKG_ROOT_PATH . '/.spc-tool-versions.json';
}
private static function load(): void
{
if (self::$data !== null) {
return;
}
$path = self::getPath();
if (!file_exists($path)) {
self::$data = [];
return;
}
$content = file_get_contents($path);
self::$data = is_string($content) ? (json_decode($content, true) ?: []) : [];
}
private static function save(): void
{
$path = self::getPath();
$dir = dirname($path);
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
file_put_contents($path, json_encode(self::$data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
}

View File

@@ -17,6 +17,7 @@ use StaticPHP\Attribute\Package\PatchBeforeBuild;
use StaticPHP\Attribute\Package\ResolveBuild; use StaticPHP\Attribute\Package\ResolveBuild;
use StaticPHP\Attribute\Package\Stage; use StaticPHP\Attribute\Package\Stage;
use StaticPHP\Attribute\Package\Target; use StaticPHP\Attribute\Package\Target;
use StaticPHP\Attribute\Package\Tool;
use StaticPHP\Attribute\Package\Validate; use StaticPHP\Attribute\Package\Validate;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
@@ -27,6 +28,7 @@ use StaticPHP\Package\Package;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage; use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
class PackageLoader class PackageLoader
@@ -88,6 +90,7 @@ class PackageLoader
'target', 'virtual-target' => new TargetPackage($name, $item['type']), 'target', 'virtual-target' => new TargetPackage($name, $item['type']),
'library' => new LibraryPackage($name, $item['type']), 'library' => new LibraryPackage($name, $item['type']),
'php-extension' => new PhpExtensionPackage($name, $item['type']), 'php-extension' => new PhpExtensionPackage($name, $item['type']),
'tool' => new ToolPackage($name, $item['type']),
default => null, default => null,
}; };
if ($pkg !== null) { if ($pkg !== null) {
@@ -190,7 +193,8 @@ class PackageLoader
$attribute_instance = $attribute->newInstance(); $attribute_instance = $attribute->newInstance();
if ($attribute_instance instanceof Target === false && if ($attribute_instance instanceof Target === false &&
$attribute_instance instanceof Library === false && $attribute_instance instanceof Library === false &&
$attribute_instance instanceof Extension === false) { $attribute_instance instanceof Extension === false &&
$attribute_instance instanceof Tool === false) {
// not a package attribute // not a package attribute
continue; continue;
} }
@@ -216,6 +220,7 @@ class PackageLoader
Target::class => ['target', 'virtual-target'], Target::class => ['target', 'virtual-target'],
Library::class => ['library'], Library::class => ['library'],
Extension::class => ['php-extension'], Extension::class => ['php-extension'],
Tool::class => ['tool'],
default => null, default => null,
}; };
if (!in_array($package_type, $pkg_type_attr, true)) { if (!in_array($package_type, $pkg_type_attr, true)) {
@@ -370,7 +375,10 @@ class PackageLoader
// match condition // match condition
$installer = ApplicationContext::get(PackageInstaller::class); $installer = ApplicationContext::get(PackageInstaller::class);
$stages = self::$before_stages[$package_name][$stage] ?? []; $stages = self::$before_stages[$package_name][$stage] ?? [];
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) { foreach ($stages as $entry) {
$callback = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
$conditionals = $entry[2] ?? [];
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) { if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
continue; continue;
} }
@@ -389,7 +397,10 @@ class PackageLoader
$installer = ApplicationContext::get(PackageInstaller::class); $installer = ApplicationContext::get(PackageInstaller::class);
$stages = self::$after_stages[$package_name][$stage] ?? []; $stages = self::$after_stages[$package_name][$stage] ?? [];
$result = []; $result = [];
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) { foreach ($stages as $entry) {
$callback = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
$conditionals = $entry[2] ?? [];
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) { if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
continue; continue;
} }
@@ -433,7 +444,9 @@ class PackageLoader
} }
$pkg = self::getPackage($package_name); $pkg = self::getPackage($package_name);
foreach ($stages as $stage_name => $before_events) { foreach ($stages as $stage_name => $before_events) {
foreach ($before_events as [$event_callable, $only_when_package_resolved, $conditionals]) { foreach ($before_events as $entry) {
$event_callable = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
// check only_when_package_resolved package exists // check only_when_package_resolved package exists
if ($only_when_package_resolved !== null && !self::hasPackage($only_when_package_resolved)) { if ($only_when_package_resolved !== null && !self::hasPackage($only_when_package_resolved)) {
throw new RegistryException("{$event_name} event in package [{$package_name}] for stage [{$stage_name}] has unknown only_when_package_resolved package [{$only_when_package_resolved}]."); throw new RegistryException("{$event_name} event in package [{$package_name}] for stage [{$stage_name}] has unknown only_when_package_resolved package [{$only_when_package_resolved}].");

View File

@@ -5,12 +5,13 @@ declare(strict_types=1);
namespace StaticPHP\Runtime\Executor; namespace StaticPHP\Runtime\Executor;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\ToolPackage;
abstract class Executor abstract class Executor
{ {
public function __construct(protected LibraryPackage $package) {} public function __construct(protected LibraryPackage|ToolPackage $package) {}
public static function create(LibraryPackage $package): static public static function create(LibraryPackage|ToolPackage $package): static
{ {
return new static($package); return new static($package);
} }

View File

@@ -10,6 +10,7 @@ use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Shell\UnixShell; use StaticPHP\Runtime\Shell\UnixShell;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
use ZM\Logger\ConsoleColor; use ZM\Logger\ConsoleColor;
@@ -22,7 +23,7 @@ class UnixAutoconfExecutor extends Executor
protected PackageInstaller $installer; protected PackageInstaller $installer;
public function __construct(protected LibraryPackage $package, ?PackageInstaller $installer = null) public function __construct(protected LibraryPackage|ToolPackage $package, ?PackageInstaller $installer = null)
{ {
parent::__construct($package); parent::__construct($package);
if ($installer !== null) { if ($installer !== null) {

View File

@@ -11,6 +11,7 @@ use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Shell\UnixShell; use StaticPHP\Runtime\Shell\UnixShell;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
@@ -40,7 +41,7 @@ class UnixCMakeExecutor extends Executor
protected PackageInstaller $installer; protected PackageInstaller $installer;
public function __construct(protected LibraryPackage $package, ?PackageInstaller $installer = null) public function __construct(protected LibraryPackage|ToolPackage $package, ?PackageInstaller $installer = null)
{ {
parent::__construct($package); parent::__construct($package);
if ($installer !== null) { if ($installer !== null) {

View File

@@ -9,6 +9,7 @@ use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\Shell\WindowsCmd; use StaticPHP\Runtime\Shell\WindowsCmd;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
@@ -35,7 +36,7 @@ class WindowsCMakeExecutor extends Executor
protected PackageInstaller $installer; protected PackageInstaller $installer;
public function __construct(protected LibraryPackage $package) public function __construct(protected LibraryPackage|ToolPackage $package)
{ {
parent::__construct($this->package); parent::__construct($this->package);
$this->builder = ApplicationContext::get(PackageBuilder::class); $this->builder = ApplicationContext::get(PackageBuilder::class);

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace StaticPHP\Runtime\Shell; namespace StaticPHP\Runtime\Shell;
use StaticPHP\Exception\ExecutionException;
use StaticPHP\Exception\InterruptException; use StaticPHP\Exception\InterruptException;
use StaticPHP\Exception\SPCInternalException; use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
@@ -153,7 +154,7 @@ class DefaultShell extends Shell
$this->logCommandInfo($cmd); $this->logCommandInfo($cmd);
logger()->debug("[TAR EXTRACT] {$cmd}"); logger()->debug("[TAR EXTRACT] {$cmd}");
$this->passthru($cmd, $this->console_putput); $this->passthruTolerateSymlinks($cmd);
return true; return true;
} }
@@ -200,7 +201,7 @@ class DefaultShell extends Shell
$run = function ($cmd) { $run = function ($cmd) {
$this->logCommandInfo($cmd); $this->logCommandInfo($cmd);
logger()->debug("[7Z EXTRACT] {$cmd}"); logger()->debug("[7Z EXTRACT] {$cmd}");
$this->passthru($cmd, $this->console_putput); $this->passthruTolerateSymlinks($cmd);
}; };
$extname = FileSystem::extname($archive_path); $extname = FileSystem::extname($archive_path);
@@ -214,4 +215,67 @@ class DefaultShell extends Shell
return true; return true;
} }
/**
* Run an extraction command, tolerating symbolic links that the host cannot create.
*
* Windows tar.exe (bsdtar) cannot create the symbolic links some archives ship (e.g. zstd's
* tests/cli-tests/bin/unzstd -> zstd), failing each with "Can't create '...': Invalid argument"
* and exiting non-zero. Those entries are never needed to build, so on Windows we swallow a
* failure whose only errors are such symlink creations and continue. Any other failure still throws.
*/
private function passthruTolerateSymlinks(string $cmd): void
{
// Symlink creation only fails on a Windows host; elsewhere extraction handles symlinks fine.
if (PHP_OS_FAMILY !== 'Windows') {
$this->passthru($cmd, $this->console_putput);
return;
}
$result = $this->passthru($cmd, $this->console_putput, capture_output: true, throw_on_error: false);
if ($result['code'] === 0) {
return;
}
if ($this->isSymlinkOnlyExtractFailure($result['output'])) {
logger()->warning('Some symbolic links could not be created during extraction and were skipped (not supported on this Windows host). This is harmless for building.');
return;
}
throw new ExecutionException(
cmd: $cmd,
message: "Command exited with non-zero code: {$result['code']}",
code: $result['code'],
cd: $this->cd,
env: $this->env,
);
}
/**
* Decide whether an extraction failure was caused solely by symbolic links that could not be
* created on Windows. Returns true only when at least one such error is present and no other
* error-looking output is found, so genuine extraction failures still propagate.
*/
private function isSymlinkOnlyExtractFailure(string $output): bool
{
$saw_symlink_error = false;
foreach (preg_split('/\r\n|\r|\n/', $output) ?: [] as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
// bsdtar's trailing summary line; not an error on its own.
if (str_contains($line, 'Error exit delayed from previous errors')) {
continue;
}
// The symlink (or other unsupported special file) that Windows refused to create.
if (str_contains($line, "Can't create") && str_contains($line, 'Invalid argument')) {
$saw_symlink_error = true;
continue;
}
// Any other error-looking line means this was not a clean symlink-only failure.
if (preg_match('/\berror\b|cannot|can\'t|failed|denied|no space|not permitted/i', $line)) {
return false;
}
}
return $saw_symlink_error;
}
} }

View File

@@ -114,8 +114,8 @@ abstract class Shell
if (!$this->enable_log_file) { if (!$this->enable_log_file) {
return; return;
} }
// write executed command to log file using spc_write_log // write executed command to log file using spc_write_log (shared handle, see spc_log_stream)
$log_file = fopen(SPC_SHELL_LOG, 'a'); $log_file = spc_log_stream(SPC_SHELL_LOG);
spc_write_log($log_file, "\n>>>>>>>>>>>>>>>>>>>>>>>>>> [" . date('Y-m-d H:i:s') . "]\n"); spc_write_log($log_file, "\n>>>>>>>>>>>>>>>>>>>>>>>>>> [" . date('Y-m-d H:i:s') . "]\n");
spc_write_log($log_file, "> Executing command: {$cmd}\n"); spc_write_log($log_file, "> Executing command: {$cmd}\n");
// get the backtrace to find the file and line number // get the backtrace to find the file and line number
@@ -154,8 +154,8 @@ abstract class Shell
): array { ): array {
$file_res = null; $file_res = null;
if ($this->enable_log_file) { if ($this->enable_log_file) {
// write executed command to the log file using spc_write_log // write executed command to the log file using spc_write_log (shared handle, see spc_log_stream)
$file_res = fopen(SPC_SHELL_LOG, 'a'); $file_res = spc_log_stream(SPC_SHELL_LOG);
} }
if ($console_output) { if ($console_output) {
$console_res = STDOUT; $console_res = STDOUT;
@@ -263,9 +263,7 @@ abstract class Shell
} }
fclose($pipes[1]); fclose($pipes[1]);
fclose($pipes[2]); fclose($pipes[2]);
if ($file_res !== null) { // $file_res is a shared, process-wide handle (see spc_log_stream); do not close it here.
fclose($file_res);
}
proc_close($process); proc_close($process);
} }
} }

View File

@@ -6,6 +6,7 @@ namespace StaticPHP\Runtime\Shell;
use StaticPHP\Exception\SPCInternalException; use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use ZM\Logger\ConsoleColor; use ZM\Logger\ConsoleColor;
@@ -40,9 +41,9 @@ class UnixShell extends Shell
/** /**
* Init the environment variable that common build will be used. * Init the environment variable that common build will be used.
* *
* @param LibraryPackage $library Library package * @param LibraryPackage|ToolPackage $library Library or tool package
*/ */
public function initializeEnv(LibraryPackage $library): UnixShell public function initializeEnv(LibraryPackage|ToolPackage $library): UnixShell
{ {
$this->setEnv([ $this->setEnv([
'CFLAGS' => $library->getLibExtraCFlags(), 'CFLAGS' => $library->getLibExtraCFlags(),

Some files were not shown because too many files have changed in this diff Show More