Compare commits

..

30 Commits

Author SHA1 Message Date
crazywhalecc
6c52febf5f Apply suggestion 2026-07-16 15:02:58 +08:00
crazywhalecc
77a13fb02b Revert "Apply event changes in feat/pgo-v3"
This reverts commit 977ea4a8f8.
2026-07-16 15:00:18 +08:00
crazywhalecc
3a3602214d Revert RANLIB in env.ini 2026-07-16 14:59:53 +08:00
crazywhalecc
55697ce801 Remove LinuxMuslCheck 2026-07-16 14:59:36 +08:00
Jerry Ma
9cad5fb557 Merge branch 'v3' into feat/pgo-v3-split 2026-07-16 14:39:30 +08:00
Jerry Ma
62a4a5f77a Docs ai (#1212) 2026-07-16 14:24:23 +08:00
crazywhalecc
8a7cf24b70 Apply phpmicro phar patch changes in feat/pgo-v3 2026-07-16 14:07:50 +08:00
crazywhalecc
0f92692f4e Apply github token header injection changes in feat/pgo-v3 2026-07-16 14:00:14 +08:00
crazywhalecc
977ea4a8f8 Apply event changes in feat/pgo-v3 2026-07-16 13:58:25 +08:00
crazywhalecc
df0bc83aeb Disable musl-wrapper installation on default situation 2026-07-15 15:04:48 +08:00
crazywhalecc
42c343d44d Revert krb5 patch changes in feat/pgo-v3 2026-07-15 14:07:01 +08:00
crazywhalecc
0de02d743d Fix openssl patch changes in feat/pgo-v3 2026-07-15 13:20:36 +08:00
crazywhalecc
873222299b Apply openssl patch changes in feat/pgo-v3 2026-07-15 13:02:52 +08:00
crazywhalecc
b46bc39a3d Apply ncurses patch changes in feat/pgo-v3 2026-07-15 13:01:28 +08:00
crazywhalecc
521b949d2c Apply libheif patch changes in feat/pgo-v3 2026-07-15 13:00:36 +08:00
crazywhalecc
7ff2ccb81e Apply libffi patch changes in feat/pgo-v3 2026-07-15 13:00:04 +08:00
crazywhalecc
d6b2b96aa8 Apply go_xcaddy patch changes in feat/pgo-v3 2026-07-15 12:59:20 +08:00
crazywhalecc
fbbcc80126 Update libaom configuration to support target architecture detection 2026-07-15 12:57:15 +08:00
crazywhalecc
b872c425e7 Apply krb5 patch changes in feat/pgo-v3 2026-07-15 12:52:04 +08:00
crazywhalecc
3e48d8fea2 Apply jbig patch changes in feat/pgo-v3 2026-07-15 12:51:43 +08:00
crazywhalecc
fb4d151c08 Apply icu patch changes in feat/pgo-v3 2026-07-15 12:50:21 +08:00
crazywhalecc
21c624eaa5 Apply fastlz patch changes in feat/pgo-v3 2026-07-15 12:49:52 +08:00
crazywhalecc
5d76b852cf Apply bzip2 patch changes in feat/pgo-v3 2026-07-15 12:48:56 +08:00
crazywhalecc
768e1a048c Apply gmssl extension patch changes in feat/pgo-v3 2026-07-15 12:47:53 +08:00
crazywhalecc
6bf0ea18ca Apply config/env.ini changes in feat/pgo-v3 2026-07-15 12:46:46 +08:00
crazywhalecc
db83778663 Apply ext-brotli,ext-zstd,gmssl changes in feat/pgo-v3 2026-07-15 12:46:29 +08:00
crazywhalecc
71d20a8322 fix(docs): update Windows SAPI warning and download links in CliGenerator.vue 2026-07-14 23:27:46 +08:00
crazywhalecc
01a0b26a2a feat(docs): update package model documentation to include new package types and clarify definitions 2026-07-14 23:03:15 +08:00
crazywhalecc
abc6e3695f feat(docs): add staticphp-documentation-sync skill for bilingual documentation synchronization 2026-07-14 23:02:33 +08:00
crazywhalecc
a1ccaaca36 fix(docs): update build scripts and dependencies for VitePress 2026-07-14 23:00:56 +08:00
32 changed files with 1750 additions and 1092 deletions

View File

@@ -10,6 +10,7 @@ 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-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. - `.github/skills/staticphp-build-troubleshooting`: diagnose build, download, doctor, shell, terminal, CI, smoke-test, or log failures.
- `.github/skills/staticphp-documentation-sync`: synchronize bilingual documentation (`docs/en/` and `docs/zh/`) when features, commands, configuration, APIs, or behavior change.
## Quick Reference ## Quick Reference

View File

@@ -0,0 +1,160 @@
---
name: staticphp-documentation-sync
description: Synchronize bilingual documentation when StaticPHP v3 user-facing or developer-facing documentation must change. Use when adding, modifying, deprecating, or removing documented features, CLI commands/options, environment variables, configuration formats, public APIs/extension points, workflows, installation requirements, migration guidance, or user-visible behavior. Do not use solely for internal implementation changes, package/library additions, or build bug fixes unless they change documented behavior or require updating existing docs.
---
# StaticPHP Documentation Sync
## Overview
StaticPHP maintains bilingual documentation under `docs/en/` (English) and `docs/zh/` (Chinese). User-facing or developer-facing documentation changes must be reflected in both languages. Use this skill to identify affected docs, update them in sync, and validate sidebar/config consistency.
## When to Use This Skill
Invoke this skill when the change involves:
- New or modified CLI commands, options, or arguments
- New or changed environment variables
- Package (extension/library/target/tool) additions, removals, or behavioral changes that affect documented support, dependencies, commands, or workflows
- Configuration format changes (YAML fields, artifact definitions, registry)
- Build lifecycle, doctor, or toolchain changes
- API or extension point changes (attributes, hooks, DI, custom artifacts)
- Workflow changes (installation, first build, migration)
- Deprecation or removal of any documented feature
Do not update docs just because code changed. Internal refactors, new libraries used only as dependencies, package build fixes, CI-only changes, and bug fixes that preserve documented behavior usually do not need documentation changes. If existing docs mention the changed behavior, command, package support, dependency, caveat, or workaround, update them.
## Documentation Map
```
docs/
├── en/ # English docs (canonical source)
│ ├── index.md # Home page hero/features
│ ├── guide/ # User-facing guides
│ │ ├── index.md # Overview
│ │ ├── installation.md # Installation instructions
│ │ ├── first-build.md # First build walkthrough
│ │ ├── sapi-reference.md # PHP SAPI options
│ │ ├── cli-reference.md # CLI commands and options
│ │ ├── cli-generator.md # Build command generator
│ │ ├── migrate-from-v2.md # v2 → v3 migration
│ │ ├── extensions.md # Supported extensions list
│ │ ├── extension-notes.md # Per-extension notes
│ │ ├── env-vars.md # Environment variables
│ │ ├── deps-map.md # Dependency map
│ │ └── troubleshooting.md # Troubleshooting guide
│ ├── develop/ # Developer docs
│ │ ├── index.md # Dev overview
│ │ ├── structure.md # Project structure
│ │ ├── registry.md # Registry model
│ │ ├── package-model.md # Package YAML model
│ │ ├── artifact-model.md # Artifact YAML model
│ │ ├── craft-yml.md # craft.yml reference
│ │ ├── build-lifecycle.md # Build stages/lifecycle
│ │ ├── system-build-tools.md # System tool requirements
│ │ ├── doctor-module.md # Doctor module
│ │ ├── php-src-changes.md # PHP source patches
│ │ └── extending/ # Extension authoring
│ │ ├── index.md
│ │ ├── package-classes.md
│ │ ├── annotations.md
│ │ ├── lifecycle-hooks.md
│ │ ├── dependency-injection.md
│ │ └── custom-artifact.md
│ ├── contributing/
│ │ └── index.md
│ └── faq/
│ └── index.md
├── zh/ # Chinese docs (mirrors en/ structure)
│ └── (same structure as en/)
├── .vitepress/
│ ├── sidebar.en.ts # English sidebar config
│ ├── sidebar.zh.ts # Chinese sidebar config
│ └── config.ts # VitePress site config
└── deps-craft-yml.md # Shared craft.yml include used by both languages
```
Other documentation files outside this tree may also matter, especially root-level `ext-support.md`.
**Key rule**: `docs/en/` and `docs/zh/` have identical file trees. Every `.md` file under `en/` must have a corresponding file under `zh/`.
## Workflow
### Step 1: Identify Impact Scope
Map the change to affected documentation:
| Change Type | Likely Affected Docs |
|---|---|
| New/removed CLI command | `guide/cli-reference.md`, `guide/cli-generator.md` |
| New/removed CLI option | `guide/cli-reference.md`, `guide/first-build.md` |
| New env var | `guide/env-vars.md` |
| New/removed documented extension package | `guide/extensions.md`, `guide/extension-notes.md`, `guide/deps-map.md`, root `ext-support.md` |
| Package config field change | `develop/package-model.md`, `develop/artifact-model.md` |
| Build lifecycle change | `develop/build-lifecycle.md` |
| Doctor change | `develop/doctor-module.md`, `develop/system-build-tools.md` |
| New attribute/hook/DI | `develop/extending/annotations.md`, `develop/extending/lifecycle-hooks.md`, `develop/extending/dependency-injection.md` |
| PHP source patch | `develop/php-src-changes.md` |
| Registry change | `develop/registry.md` |
| Install/setup change | `guide/installation.md`, `guide/first-build.md` |
| Deprecation/removal | All docs referencing the feature |
| New doc page | `sidebar.en.ts`, `sidebar.zh.ts` |
### Step 2: Read Current Docs
Before editing, read BOTH the English and Chinese versions of each affected file to understand the current content and existing translation patterns.
```bash
# Example: check both language versions of the CLI reference
cat docs/en/guide/cli-reference.md
cat docs/zh/guide/cli-reference.md
```
### Step 3: Update English Docs First
1. Update `docs/en/` files with accurate, complete English content.
2. Follow existing formatting conventions (headings, code blocks, tables, admonitions).
3. If adding a new page:
- Create the file under `docs/en/<category>/<name>.md`
- Add the corresponding entry in `docs/.vitepress/sidebar.en.ts`
- Ensure the file has proper VitePress frontmatter if needed
### Step 4: Sync Chinese Docs
1. Update `docs/zh/` files to match the English changes.
2. Translate all changed or added prose. Do not leave placeholder text or untranslated English in Chinese docs.
3. Match the structure and formatting of the English version exactly.
4. If a new page was added in English, create the corresponding `docs/zh/` file and update `docs/.vitepress/sidebar.zh.ts`.
5. Treat `docs/deps-craft-yml.md` as a special shared include for both languages. If it needs prose changes, either keep the shared content acceptable for both languages or split the included content before adding language-specific prose.
### Step 5: Validate
Run these checks before considering the task complete:
```bash
# Check that en/ and zh/ have matching file trees
diff <(find docs/en -name '*.md' | sed 's|docs/en/||' | sort) \
<(find docs/zh -name '*.md' | sed 's|docs/zh/||' | sort)
# Check that all sidebar links point to existing files
# (manual check: every 'link' in sidebar.*.ts must resolve to an actual .md file)
# Build docs when Node dependencies are available; this catches many broken links/config issues
npm run docs:build
```
## Translation Guidelines
- **Chinese docs must be complete**: Every section, paragraph, and table in the English docs must have a Chinese equivalent. Never skip sections.
- **Code blocks and command examples**: Keep executable code and commands identical in both languages. Translate surrounding prose; translate comments inside examples only when they are explanatory docs rather than copy-pasteable source/config.
- **Technical terms**: Use consistent translations. Refer to existing Chinese docs for established term translations. When in doubt, prefer the term used elsewhere in `docs/zh/`.
- **Links**: Internal links in Chinese docs should point to `/zh/...` paths (not `/en/...`).
- **YAML frontmatter**: Keep frontmatter identical between languages (layout, etc.) unless the title/tagline field is translated.
## Common Pitfalls
- **Don't update only one language**: This is the most common mistake. Always update both `en/` and `zh/` in the same change.
- **Don't forget sidebar configs**: When adding, renaming, or removing doc pages, update both `sidebar.en.ts` and `sidebar.zh.ts`.
- **Don't forget shared/root docs**: root `ext-support.md` and `docs/deps-craft-yml.md` are also documentation. Update them if relevant.
- **Don't leave TODO markers**: Do not commit TODO translation placeholders unless the user explicitly allows it or the task is blocked; if that happens, call it out in the final response.
- **Don't translate file paths or URLs**: Only translate human-readable content, not paths, URLs, command names, or code identifiers.

View File

@@ -27,9 +27,14 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- uses: actions/setup-node@v3 - name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: yarn
- run: npm install - name: Install documentation dependencies
run: yarn install --frozen-lockfile
- name: "Install PHP for official runners" - name: "Install PHP for official runners"
uses: shivammathur/setup-php@v2 uses: shivammathur/setup-php@v2
@@ -57,7 +62,7 @@ jobs:
run: "composer install --no-interaction --no-progress" run: "composer install --no-interaction --no-progress"
- name: Build - name: Build
run: npm run docs:build run: yarn docs:build
# Deploy to GitHub Pages only when the workflow is triggered by a push to the v3 branch # Deploy to GitHub Pages only when the workflow is triggered by a push to the v3 branch
- name: Deploy to GitHub Pages - name: Deploy to GitHub Pages

1
.gitignore vendored
View File

@@ -52,6 +52,7 @@ packlib_files.txt
/node_modules/ /node_modules/
/docs/.vitepress/dist/ /docs/.vitepress/dist/
/docs/.vitepress/cache/ /docs/.vitepress/cache/
/docs/.vitepress/.temp/
/docs/.vitepress/ext-data.json /docs/.vitepress/ext-data.json
/docs/.vitepress/deps-data.json /docs/.vitepress/deps-data.json
package-lock.json package-lock.json

View File

@@ -10,6 +10,7 @@ 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-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. - `.github/skills/staticphp-build-troubleshooting`: diagnose build, download, doctor, shell, terminal, CI, smoke-test, or log failures.
- `.github/skills/staticphp-documentation-sync`: synchronize bilingual documentation (`docs/en/` and `docs/zh/`) when features, commands, configuration, APIs, or behavior change.
If your agent does not automatically discover skills from `.github/skills`, read the matching `SKILL.md` manually before working on that task. If your agent does not automatically discover skills from `.github/skills`, read the matching `SKILL.md` manually before working on that task.

View File

@@ -102,7 +102,7 @@ CXX=${SPC_DEFAULT_CXX}
AR=${SPC_DEFAULT_AR} AR=${SPC_DEFAULT_AR}
LD=${SPC_DEFAULT_LD} LD=${SPC_DEFAULT_LD}
; default compiler flags, used in CMake toolchain file, openssl and pkg-config build ; default compiler flags, used in CMake toolchain file, openssl and pkg-config build
SPC_DEFAULT_CFLAGS="-fPIC -O3 -pipe -fno-plt -fno-semantic-interposition -fstack-clash-protection -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections" SPC_DEFAULT_CFLAGS="-fPIC -O3 -pipe -fno-plt -fno-semantic-interposition -fstack-clash-protection -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections -Wno-unused-command-line-argument"
SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}" SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}"
SPC_DEFAULT_LDFLAGS="-Wl,-z,relro -Wl,--as-needed -Wl,-z,now -Wl,-z,noexecstack -Wl,--gc-sections" SPC_DEFAULT_LDFLAGS="-Wl,-z,relro -Wl,--as-needed -Wl,-z,now -Wl,-z,noexecstack -Wl,--gc-sections"
; upx executable path ; upx executable path
@@ -125,6 +125,8 @@ SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS="-g -fstack-protector-strong -fno-ident -fPIE
SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS="-g -fstack-protector-strong -fno-ident -fPIE -fvisibility=hidden -fvisibility-inlines-hidden ${SPC_DEFAULT_CXXFLAGS}" SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS="-g -fstack-protector-strong -fno-ident -fPIE -fvisibility=hidden -fvisibility-inlines-hidden ${SPC_DEFAULT_CXXFLAGS}"
; EXTRA_LDFLAGS for `make` php, can use -release to set a soname for libphp.so ; EXTRA_LDFLAGS for `make` php, can use -release to set a soname for libphp.so
SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS="" SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS=""
; EXTRA_LDFLAGS_PROGRAM for `make` php; appended only to SAPI executable links (cli/fpm/cgi/micro/embed). Used by PGO to inject -fprofile-use= without polluting libphp.{a,so}.
SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS_PROGRAM=""
; optional, path to openssl conf. This affects where openssl will look for the default CA. ; optional, path to openssl conf. This affects where openssl will look for the default CA.
; default on Debian/Alpine: /etc/ssl, default on RHEL: /etc/pki/tls ; default on Debian/Alpine: /etc/ssl, default on RHEL: /etc/pki/tls
@@ -163,5 +165,7 @@ SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS="-g -fstack-protector-strong -fpic -fpie -fvis
SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS="-g -fstack-protector-strong -fno-ident -fpie -fvisibility=hidden -fvisibility-inlines-hidden -Werror=unknown-warning-option ${SPC_DEFAULT_CXXFLAGS}" SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS="-g -fstack-protector-strong -fno-ident -fpie -fvisibility=hidden -fvisibility-inlines-hidden -Werror=unknown-warning-option ${SPC_DEFAULT_CXXFLAGS}"
; EXTRA_LDFLAGS for `make` php, can use -release to set a soname for libphp.dylib ; EXTRA_LDFLAGS for `make` php, can use -release to set a soname for libphp.dylib
SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS="" SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS=""
; EXTRA_LDFLAGS_PROGRAM for `make` php; appended only to SAPI executable links (cli/fpm/cgi/micro/embed). Used by PGO to inject -fprofile-use= without polluting libphp.{a,dylib}.
SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS_PROGRAM=""
; minimum compatible macOS version (LLVM vars, availability not guaranteed) ; minimum compatible macOS version (LLVM vars, availability not guaranteed)
MACOSX_DEPLOYMENT_TARGET=12.0 MACOSX_DEPLOYMENT_TARGET=12.0

View File

@@ -2,12 +2,13 @@ ext-brotli:
type: php-extension type: php-extension
artifact: artifact:
source: source:
type: git type: ghtagtar
repo: kjdev/php-ext-brotli
extract: php-src/ext/brotli extract: php-src/ext/brotli
rev: master
url: 'https://github.com/kjdev/php-ext-brotli'
metadata: metadata:
license-files: [LICENSE] license-files: [LICENSE]
license: MIT license: MIT
depends: depends:
- brotli - brotli
php-extension:
arg-type: '--enable-brotli@shared_suffix@ --with-libbrotli'

View File

@@ -2,9 +2,8 @@ ext-zstd:
type: php-extension type: php-extension
artifact: artifact:
source: source:
type: git type: ghtar
url: 'https://github.com/kjdev/php-ext-zstd' repo: kjdev/php-ext-zstd
rev: master
extract: php-src/ext/zstd extract: php-src/ext/zstd
metadata: metadata:
license-files: [LICENSE] license-files: [LICENSE]

View File

@@ -2,8 +2,9 @@ gmssl:
type: library type: library
artifact: artifact:
source: source:
type: ghtar type: git
repo: guanzhi/GmSSL url: 'https://github.com/guanzhi/GmSSL.git'
rev: master
metadata: metadata:
license-files: [LICENSE] license-files: [LICENSE]
license: Apache-2.0 license: Apache-2.0

View File

@@ -45,7 +45,7 @@
<label :for="'build_' + item">{{ item }}</label> <label :for="'build_' + item">{{ item }}</label>
</div> </div>
</div> </div>
<div v-if="selectedSystem === 'windows' && (checkedTargets.includes('fpm') || checkedTargets.includes('embed') || checkedTargets.includes('frankenphp'))" class="warning custom-block"> <div v-if="selectedSystem === 'windows' && checkedTargets.includes('fpm')" class="warning custom-block">
<p class="custom-block-title">WARNING</p> <p class="custom-block-title">WARNING</p>
<p>{{ I18N[lang].windowsSAPIUnavailable }}</p> <p>{{ I18N[lang].windowsSAPIUnavailable }}</p>
</div> </div>
@@ -157,7 +157,7 @@
<div class="warning custom-block"> <div class="warning custom-block">
<p class="custom-block-title">WARNING</p> <p class="custom-block-title">WARNING</p>
<p>{{ I18N[lang].windowsDownSPCWarning }}</p> <p>{{ I18N[lang].windowsDownSPCWarning }}</p>
<a href="https://dl.static-php.dev/v3/spc-bin/latest/spc-windows-x86_64.exe" target="_blank">https://dl.static-php.dev/v3/spc-bin/latest/spc-windows-x86_64.exe</a> <a href="https://dl.static-php.dev/v3/spc-bin/nightly/spc-windows-x86_64.exe" target="_blank">https://dl.static-php.dev/v3/spc-bin/nightly/spc-windows-x86_64.exe</a>
</div> </div>
</div> </div>
</div> </div>
@@ -278,7 +278,7 @@ const spcCommand = computed(() => {
const spcDownloadCommand = computed(() => { const spcDownloadCommand = computed(() => {
const os = selectedSystem.value === 'macos' ? 'macos' : 'linux'; const os = selectedSystem.value === 'macos' ? 'macos' : 'linux';
const arch = selectedArch.value; const arch = selectedArch.value;
return `curl -#fSL https://dl.static-php.dev/v3/spc-bin/latest/spc-${os}-${arch} -o spc && chmod +x spc`; return `curl -#fSL https://dl.static-php.dev/v3/spc-bin/nightly/spc-${os}-${arch} -o spc && chmod +x spc`;
}); });
const doctorCommandString = computed(() => `${spcCommand.value} doctor --auto-fix`); const doctorCommandString = computed(() => `${spcCommand.value} doctor --auto-fix`);
@@ -425,7 +425,7 @@ const I18N: Record<string, Record<string, string>> = {
downloadPhpVersion: '下载 PHP 版本', downloadPhpVersion: '下载 PHP 版本',
downloadSPCBinaryCommand: '下载 spc 二进制命令', downloadSPCBinaryCommand: '下载 spc 二进制命令',
selectedSystem: '选择操作系统', selectedSystem: '选择操作系统',
windowsSAPIUnavailable: 'Windows 目前不支持 fpm、embed、frankenphp 构建!', windowsSAPIUnavailable: 'Windows 目前不支持 fpm 构建!',
useUPX: '是否开启 UPX 压缩(减小二进制体积)', useUPX: '是否开启 UPX 压缩(减小二进制体积)',
windowsDownSPCWarning: 'Windows 下请手动下载 spc.exe 二进制文件!', windowsDownSPCWarning: 'Windows 下请手动下载 spc.exe 二进制文件!',
usePreBuilt: '如果可能,使用预编译的依赖库(减少编译时间)', usePreBuilt: '如果可能,使用预编译的依赖库(减少编译时间)',
@@ -459,7 +459,7 @@ const I18N: Record<string, Record<string, string>> = {
downloadPhpVersion: 'PHP version', downloadPhpVersion: 'PHP version',
downloadSPCBinaryCommand: 'Download spc binary', downloadSPCBinaryCommand: 'Download spc binary',
selectedSystem: 'Select OS', selectedSystem: 'Select OS',
windowsSAPIUnavailable: 'Windows does not support fpm, embed and frankenphp build!', windowsSAPIUnavailable: 'Windows does not support fpm build!',
useUPX: 'Enable UPX compression (reduce binary size)', useUPX: 'Enable UPX compression (reduce binary size)',
windowsDownSPCWarning: 'Please download the spc.exe binary manually on Windows!', windowsDownSPCWarning: 'Please download the spc.exe binary manually on Windows!',
usePreBuilt: 'Use pre-built dependencies where available (reduce compile time)', usePreBuilt: 'Use pre-built dependencies where available (reduce compile time)',

View File

@@ -51,7 +51,6 @@ export default {
{ text: 'Build Lifecycle', link: '/en/develop/build-lifecycle' }, { text: 'Build Lifecycle', link: '/en/develop/build-lifecycle' },
{ text: 'Compilation Tools', link: '/en/develop/system-build-tools' }, { text: 'Compilation Tools', link: '/en/develop/system-build-tools' },
{ text: 'Doctor', link: '/en/develop/doctor-module' }, { text: 'Doctor', link: '/en/develop/doctor-module' },
{ text: 'Performance Engineering', link: '/en/develop/performance' },
{ text: 'PHP Source Modifications', link: '/en/develop/php-src-changes' }, { text: 'PHP Source Modifications', link: '/en/develop/php-src-changes' },
], ],
}, },

View File

@@ -51,7 +51,6 @@ export default {
{ text: '构建生命周期', link: '/zh/develop/build-lifecycle' }, { text: '构建生命周期', link: '/zh/develop/build-lifecycle' },
{ text: '编译工具', link: '/zh/develop/system-build-tools' }, { text: '编译工具', link: '/zh/develop/system-build-tools' },
{ text: 'Doctor 环境检查', link: '/zh/develop/doctor-module' }, { text: 'Doctor 环境检查', link: '/zh/develop/doctor-module' },
{ text: '性能工程', link: '/zh/develop/performance' },
{ text: '对 PHP 源码的修改', link: '/zh/develop/php-src-changes' }, { text: '对 PHP 源码的修改', link: '/zh/develop/php-src-changes' },
], ],
}, },

View File

@@ -4,14 +4,15 @@
A Package is the core concept in StaticPHP's build system, representing a buildable/installable unit such as a PHP extension, library, or build target. A Package is the core concept in StaticPHP's build system, representing a buildable/installable unit such as a PHP extension, library, or build target.
Each Package contains build information, dependencies, and build logic, forming StaticPHP's build model. Package definitions are primarily implemented through YAML/JSON configuration files. The package configuration files for the `core` registry are located in the `config/pkg/` directory, and the corresponding build classes are in the `src/Package/` directory. Each Package contains build information, dependencies, and build logic, forming StaticPHP's build model. Package definitions are primarily implemented through YAML/JSON configuration files. The package configuration files for the `core` registry are located in the `config/pkg/` directory, and optional recipe classes are in the corresponding subdirectories of `src/Package/`.
Packages are primarily divided into four types: Packages are divided into five types:
- **php-extension**: A PHP extension package containing build information and logic for a PHP extension. - **php-extension**: A PHP extension package containing build information and logic for a PHP extension.
- **library**: A library package containing build information and logic for build tools, dependency libraries, etc. - **library**: A dependency library package, usually installed into `buildroot/` for other packages to compile and link against.
- **target**: A build target package representing the final build artifact, such as a PHP binary or curl binary. Inherits from the `library` package type. - **target**: A build target package representing the final build artifact, such as a PHP binary or curl binary. Inherits from the `library` package type.
- **virtual-target**: A virtual build target package representing an abstract build target that doesn't directly correspond to a build artifact, primarily used for dependency management and build scheduling. - **virtual-target**: A virtual build target package representing an abstract build target that doesn't directly correspond to a build artifact, primarily used for dependency management and build scheduling.
- **tool**: A host-side build tool package, installed separately under `pkgroot/` and not treated as a link-time library dependency.
```yaml ```yaml
{pkg-name}: {pkg-name}:
@@ -21,7 +22,7 @@ Packages are primarily divided into four types:
## Artifact Definition ## Artifact Definition
An Artifact is a definition independent of Packages. It contains the source archive file or pre-built binary for building packages. Each Artifact defines download URLs, extraction methods, and build artifact file paths. Packages can reference one or more Artifacts via the `artifact` field to obtain the source or binaries needed for building. An Artifact is a definition independent of Packages. It contains the source archive file or pre-built binary for building packages. Each Artifact defines download URLs, extraction methods, and build artifact file paths. A Package can reference one Artifact via the `artifact` field to obtain the source or binary needed for building.
In simple terms, by default one Package corresponds to one Artifact; if multiple Packages share the same source, you can define a single Artifact for multiple Packages to reference. Artifact definitions are located in the `config/artifact/` directory, and the corresponding custom download/extract logic classes are in the `src/Package/Artifact/` directory. For special package types like virtual targets and PHP built-in extensions, a Package may also omit the Artifact field entirely. In simple terms, by default one Package corresponds to one Artifact; if multiple Packages share the same source, you can define a single Artifact for multiple Packages to reference. Artifact definitions are located in the `config/artifact/` directory, and the corresponding custom download/extract logic classes are in the `src/Package/Artifact/` directory. For special package types like virtual targets and PHP built-in extensions, a Package may also omit the Artifact field entirely.
@@ -40,7 +41,7 @@ For more on Artifact definitions, see the [Artifact Model](./artifact-model) cha
## php-extension Package Type ## php-extension Package Type
A php-extension package represents a PHP extension. Its configuration file is located in the `config/pkg/ext/` directory, and its build class inherits from `PhpExtensionPackage` in the `src/Package/Extension/` directory. PHP extension package configurations include extension name, version, dependencies, build options, and more. A php-extension package represents a PHP extension. Its configuration file is located in the `config/pkg/ext/` directory. Optional recipe classes are normally placed in `src/Package/Extension/`, registered with `#[Extension]`, and receive the corresponding `PhpExtensionPackage` through callback context. Inheriting from `PhpExtensionPackage` is supported but is not required by the current core recipes.
```yaml ```yaml
ext-lz4: ext-lz4:
@@ -57,7 +58,7 @@ ext-lz4:
depends: depends:
- liblz4 - liblz4
php-extension: php-extension:
arg-type@unix: '--enable-lz4=@shared_suffix@ --with-lz4-includedir=@build_root_path@' arg-type@unix: '--enable-lz4@shared_suffix@ --with-lz4-includedir=@build_root_path@'
arg-type@windows: '--enable-lz4' arg-type@windows: '--enable-lz4'
``` ```
@@ -72,16 +73,18 @@ ext-{ext-name}: # Package name must start with ext- prefix
lang: c # Optional, implementation language of the extension (c / c++ etc.) lang: c # Optional, implementation language of the extension (c / c++ etc.)
frameworks: [] # Optional, list of related macOS framework dependencies frameworks: [] # Optional, list of related macOS framework dependencies
artifact: '{artifact-name}' # Optional; when a string, references an Artifact definition artifact: '{artifact-name}' # Optional; when a string, references the named Artifact definition;
# with the same name; when an object, is an inline Artifact # when an object, it is an inline Artifact
# (built-in extensions don't need this field) # (built-in extensions don't need this field)
# depends / suggests support @windows / @unix / @linux / @macos suffixes # depends / suggests / tools support @windows / @unix / @linux / @macos suffixes
depends: [] # Optional, hard dependency list (library names as-is, PHP extensions need ext- prefix) depends: [] # Optional, hard dependency list (library names as-is, PHP extensions need ext- prefix)
depends@unix: [] # Optional, hard dependencies only effective on Unix platforms depends@unix: [] # Optional, hard dependencies only effective on Unix platforms
depends@windows: [] # Optional, hard dependencies only effective on Windows platforms depends@windows: [] # Optional, hard dependencies only effective on Windows platforms
suggests: [] # Optional, optional dependency list (same format as depends) suggests: [] # Optional, optional dependency list (same format as depends)
suggests@unix: [] suggests@unix: []
tools: [] # Optional, host-side build tool dependencies; resolved separately
tools@windows: [] # Optional, platform-specific tool dependencies
# ── php-extension Specific Fields (nested under php-extension: object) ──── # ── php-extension Specific Fields (nested under php-extension: object) ────
php-extension: php-extension:
@@ -100,7 +103,7 @@ ext-{ext-name}: # Package name must start with ext- prefix
# @shared_path_suffix@ → Expands to =shared,{buildroot} in shared builds, # @shared_path_suffix@ → Expands to =shared,{buildroot} in shared builds,
# expands to ={buildroot} in static builds # expands to ={buildroot} in static builds
arg-type: enable arg-type: enable
arg-type@unix: '--enable-{extname}=@shared_suffix@' arg-type@unix: '--enable-my-extension@shared_suffix@'
arg-type@windows: with-path arg-type@windows: with-path
zend-extension: false # Optional, true indicates this is a Zend extension (e.g., opcache, xdebug) zend-extension: false # Optional, true indicates this is a Zend extension (e.g., opcache, xdebug)
@@ -121,7 +124,7 @@ ext-{ext-name}: # Package name must start with ext- prefix
## library Package Type ## library Package Type
A library package represents a dependency library that needs to be compiled from source (such as openssl, zlib, etc.). Its configuration file is located in the `config/pkg/lib/` directory, and its build class inherits from `LibraryPackage` in the `src/Package/Library/` directory. A library package represents a dependency library, such as openssl or zlib, installed from source or a pre-built binary. Its configuration file is located in the `config/pkg/lib/` directory. Optional recipe classes are normally placed in `src/Package/Library/`, registered with `#[Library]`, and receive a `LibraryPackage` through callback context; they do not need to inherit from it.
Taking openssl as an example: Taking openssl as an example:
@@ -161,22 +164,27 @@ Allowed fields for `library`:
# ── Common Fields ───────────────────────────────────────────────────────── # ── Common Fields ─────────────────────────────────────────────────────────
description: '..' # Optional, human-readable package description description: '..' # Optional, human-readable package description
license: MIT # Optional, SPDX license identifier (for license export) license: # Optional, license material copied after a source build
type: file # type is file or text; a list of entries is also accepted
path: LICENSE
lang: c # Optional, implementation language of the library (c / c++ etc.) lang: c # Optional, implementation language of the library (c / c++ etc.)
frameworks: [] # Optional, list of related framework tags frameworks: [] # Optional, list of related framework tags
artifact: '{artifact-name}' # Required; when a string, references an Artifact definition artifact: '{artifact-name}' # Required; when a string, references the named Artifact definition;
# with the same name; when an object, is an inline Artifact # when an object, it is an inline Artifact
# depends / suggests support @windows / @unix / @linux / @macos suffixes # depends / suggests / tools support @windows / @unix / @linux / @macos suffixes
depends: [] # Optional, hard dependency list (library names or PHP extension names with ext- prefix) depends: [] # Optional, hard dependency list (library names or PHP extension names with ext- prefix)
depends@unix: [] depends@unix: []
depends@windows: [] depends@windows: []
suggests: [] # Optional, optional dependency list (same format as depends) suggests: [] # Optional, optional dependency list (same format as depends)
tools: [] # Optional, ToolPackage names required only while building
tools@windows: []
# ── library / target Specific Fields ─────────────────────────────────────── # ── library / target Specific Fields ───────────────────────────────────────
# The following fields are used to verify that artifacts have been correctly # The following fields are used to verify that artifacts have been correctly
# installed after the build. They support @unix / @windows / @linux / @macos suffixes. # installed after the build. headers, static-libs, and static-bins support
# @unix / @windows / @linux / @macos suffixes.
# Verify that specified header files or directories exist under buildroot/include/ # Verify that specified header files or directories exist under buildroot/include/
# Relative paths are based on buildroot/include/, absolute paths are used directly # Relative paths are based on buildroot/include/, absolute paths are used directly
@@ -231,17 +239,49 @@ The following path placeholders are supported in string values of the `path`, `e
| `{source_path}` | Extracted source directory (`source/`) | | `{source_path}` | Extracted source directory (`source/`) |
| `{spc_msys2_path}` | MSYS2 root directory (`msys64/`) — Windows only | | `{spc_msys2_path}` | MSYS2 root directory (`msys64/`) — Windows only |
## tool Package Type
A `tool` package represents an executable needed while building another package, rather than a library linked into the final target. Tool packages may use a pre-built binary or build from source, and install under `pkgroot/` by default, using either a shared `bin/` directory or a configured subdirectory. Packages request them through the top-level `tools` field; this dependency set is resolved independently of `depends` and `suggests`.
```yaml
nasm:
type: tool
artifact:
binary:
windows-x86_64:
type: url
url: 'https://example.com/nasm-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
min-version: '2.16'
```
The nested `tool` object supports:
| Field | Required | Meaning |
|---|---|---|
| `provides` | Yes | Executable filenames used to decide whether the tool is installed |
| `binary-subdir` | No | Directory below `install-root` containing the executables; defaults to the install root |
| `install-root` | No | Installation root; defaults to `PKG_ROOT_PATH` and supports path placeholders |
| `min-version` | No | Declared minimum version metadata exposed by `ToolPackage`; the installer does not currently enforce it |
Fields inside `tool` may use `@windows`, `@unix`, `@linux`, and `@macos` suffixes. For example, `provides@windows` can list `.exe` names while `provides@unix` lists Unix names.
## target Package Type ## target Package Type
A `target` package represents a final build artifact. It inherits from `library`, so it includes all definition fields of `library`. The configuration file for `target` packages is located in the `config/pkg/target/` directory, and its build class inherits from `TargetPackage` in the `src/Package/Target/` directory. A `target` package represents a final build artifact. It inherits from `library`, so it includes all definition fields of `library`. Its configuration file is located in `config/pkg/target/`. Optional recipe classes are normally placed in `src/Package/Target/`, registered with `#[Target]`, and receive a `TargetPackage`; inheriting from `TargetPackage` is optional.
The only difference from `library` is that a `target` package can be registered as a build target and automatically registers the build command `spc build:{target-name}`. The only difference from `library` is that a `target` package can be registered as a build target and automatically registers the build command `spc build:{target-name}`.
## virtual-target Package Type ## virtual-target Package Type
Unlike `target`, a `virtual-target` may not include an `artifact`, meaning it doesn't directly correspond to a buildable entity but is instead an abstract build target, primarily used for dependency management and build scheduling. The configuration file for `virtual-target` is located in the `config/pkg/target/` directory, and its build class inherits from `TargetPackage` in the `src/Package/Target/` directory. Its definition is essentially the same as `target`, but the `artifact` field is optional and typically not set. `virtual-target` is primarily used in the following scenarios: Unlike `target`, a `virtual-target` may omit `artifact`, meaning it doesn't directly correspond to a buildable entity but is instead an abstract build target, primarily used for dependency management and build scheduling. Its configuration and optional recipe classes use the same directories and `#[Target]` registration mechanism as `target`. Its definition is otherwise essentially the same, but the `artifact` field is optional and typically not set. `virtual-target` is primarily used in the following scenarios:
- Defining an abstract build target for other packages to depend on, without directly corresponding to a buildable entity. - Defining an abstract build target for other packages to depend on, without directly corresponding to a buildable entity.
- Serving as a common dependency for multiple `target` packages, simplifying dependency management. - Serving as a common dependency for multiple `target` packages, simplifying dependency management.
A typical example is the `php-cli`, `php-fpm` build targets for PHP. They have no independent source code and depend on `php-src`, with the final build outcome (CLI or FPM binary) determined through build scheduling. Typical examples are the `php-cli` and `php-fpm` build targets. They have no independent source and depend on the `php` target, whose Artifact is `php-src`; build scheduling determines whether the CLI or FPM binary is produced.

View File

@@ -1,301 +0,0 @@
# Performance Engineering
StaticPHP controls how PHP, its extensions, dependency libraries, and SAPIs are compiled. These choices can affect runtime throughput and latency, startup time, memory use, binary size, portability, and build time. They are related, but they are not the same metric: a smaller binary is not necessarily faster, and a slower build can still produce a faster program.
This page records the current v3 defaults, the optimization work already incorporated into the build, and the areas still being investigated. On Linux, libc and linkage form the first layer: the default fully static musl build and a dynamically linked glibc build have different portability, extension-loading, and performance characteristics. Compiler flags, PGO, and LTO form later layers of the same ongoing work.
This page does not claim that a StaticPHP binary is always faster than another PHP distribution. Results depend on the PHP version, CPU, toolchain, extension set, SAPI, libc, linkage, runtime configuration, and workload.
::: warning Current v3 status
The v3 branch does not currently expose stable `--pgi`, `--pgo`, or `--lto` CLI options. PGO orchestration and broader LTO compatibility remain active areas of investigation. The sections below describe their design, current constraints, and the direction of that work rather than a supported release recipe.
:::
## Linux Linkage and libc
StaticPHP's Linux default optimizes for a self-contained artifact, not for the highest possible score on every server workload. `config/env.ini` selects `${GNU_ARCH}-linux-musl`; with the default Zig toolchain this produces a fully static musl binary.
Current performance investigations distinguish three Linux targets:
| Target | libc and final linkage | Runtime requirements | Shared extensions / FFI | Current role |
|---|---|---|---|---|
| `native-native-musl` | musl, fully static | Linux kernel on a compatible CPU | No | Default portable single-file release |
| `native-native-musl -dynamic` | musl, dynamically linked | Compatible musl loader and libraries | Yes | Isolate static-versus-dynamic effects while keeping musl |
| `native-native-gnu.2.17` | glibc, dynamically linked with a 2.17 baseline | glibc 2.17 or newer | Yes | Broad GNU/Linux compatibility and a glibc performance baseline |
The architecture may replace either `native` component, for example `x86_64-linux-musl`. A `-gnu` target without an explicit version targets the selected/current glibc ABI instead of promising the 2.17 floor.
In this context, “dynamically linked PHP” does not mean every dependency is a system `.so`. StaticPHP still builds most selected third-party libraries and PHP extensions as static archives and links them into the PHP executable. The dynamic part is primarily the libc/runtime loader and any extensions explicitly requested through `--build-shared`. This differs from a conventional distribution PHP in which PHP and many dependencies are separate shared objects.
Likewise, a “static extension” and a “static libc” are independent choices. A glibc-dynamic PHP can contain all PHP extensions statically, while a musl-dynamic PHP can load selected `.so` extensions. Only a fully static musl target prevents runtime loading because no dynamic loader participates in the process.
### What Static versus Dynamic Linking Changes
Static and dynamic linkage mainly change startup work, relocation, symbol resolution, deployment, and library sharing. They do not automatically change PHP VM code generation.
- A fully static process does not start through a runtime dynamic loader or relocate a set of DSOs. This can help very short-lived CLI startup, but PHP initialization, extension startup, script parsing, and Opcache often cost more.
- A dynamic process pays loader and relocation costs at startup. Long-running FPM or FrankenPHP workers amortize this cost over many requests.
- Static linking gives the linker a larger closed world for section garbage collection and, when explicitly enabled, LTO. Static linking alone does not perform cross-object optimization.
- Dynamic glibc allows shared extensions, FFI, NSS integration, and replacement or security updates of runtime libraries without rebuilding PHP. A fully static artifact must be rebuilt to receive libc or embedded-library fixes.
- Shared-library code pages can be reused across different programs. Identical static PHP worker processes still share file-backed executable pages with one another, so “static means every worker duplicates all code in RAM” is not an accurate model.
StaticPHP's [performance testing issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838) recorded one PHP 8.4 test in which static and dynamic builds stayed within about 1% in either direction across repeated runs. This is useful evidence that linkage alone may not dominate steady-state PHP execution, but it is not a universal result. Short CLI programs, many DSOs, different loaders, and I/O-heavy extensions can produce a different outcome.
### musl versus glibc Performance Surfaces
libc differences appear only when a workload reaches libc or behavior implemented around it. Pure PHP code spends much of its time in the Zend VM, Opcache, and Zend Memory Manager. PHP's own [Zend Memory Manager](https://wiki.php.net/internals/zend_mm) handles most request-bound allocations, so a microbenchmark dominated by PHP arrays and opcodes may expose less of the system allocator than a C extension or server runtime does.
| Workload area | Why the libc can matter | Main observed signals |
|---|---|---|
| CPU-bound PHP opcodes | Usually dominated by PHP VM, compiler, CPU target, and Opcache rather than libc | Same PHP/VM/compiler first; then change only libc/linkage |
| Persistent and native allocations | Persistent PHP allocations, C extensions, libraries, and server code can call libc allocation directly | throughput, allocation contention, RSS, fragmentation after a long soak |
| ZTS and FrankenPHP | Thread creation, TLS, mutexes, allocator contention, and per-thread caches differ | scaling by worker/thread count, p95/p99, RSS per thread |
| DNS and name services | Resolver strategy, NSS, `/etc/resolv.conf`, and caching differ | cached and uncached lookup latency, failure/failover latency, query volume |
| Locale, iconv, regex, and stdio | Implementations and supported behavior differ, not merely speed | correctness first, then throughput with production locale/data |
| Very short CLI commands | Loader/relocation and initialization are a larger fraction of total time | cold and warm wall time over many process launches |
| Long-running workers | Startup is amortized; allocator, threading, syscalls, and application behavior become more important | sustained throughput, tail latency, peak/steady RSS |
glibc's allocator provides per-thread caches and multiple arenas whose limits can be tuned; these can improve concurrent allocation throughput at the cost of retained memory. The [glibc allocation tunables](https://sourceware.org/glibc/manual/latest/html_node/Memory-Allocation-Tunables.html) therefore belong in a benchmark record. musl uses a different allocator and prioritizes low baseline overhead, bounded fragmentation, and static-linking suitability; neither design guarantees lower latency or RSS for every PHP application.
Resolver behavior can reverse an apparent “libc performance” result. The [musl functional-differences documentation](https://wiki.musl-libc.org/functional-differences-from-glibc.html) notes that musl queries configured nameservers in parallel, while traditional glibc behavior tries them sequentially. This can improve failover latency but increase DNS traffic. glibc also participates in configurable NSS modules. StaticPHP's DNS comparisons therefore keep resolver, cache state, search domains, and failure conditions consistent instead of treating resolver results as a CPU-only benchmark.
musl uses a much smaller default thread stack than typical glibc configurations. That can reduce reserved address space for thread-heavy programs but can also expose stack assumptions in extensions. It is a deployment and memory characteristic, not proof that one libc executes PHP opcodes faster.
### Current Comparison Model
A direct comparison between the default musl-static binary and a distribution glibc PHP changes libc, linker, compiler, flags, PHP configuration, extensions, dependency versions, and INI at once. It therefore cannot attribute the full difference to libc.
The project uses a controlled matrix with the same StaticPHP commit, PHP source, Zig version, flags, extensions, and SAPI. The three builds are represented by the following commands:
```bash
EXTENSIONS="bcmath,curl,openssl,opcache"
# A: default-style, fully static musl
SPC_TARGET=native-native-musl spc build:php "$EXTENSIONS" --build-cli
# B: dynamically linked musl; requires a musl runtime
SPC_TARGET="native-native-musl -dynamic" spc build:php "$EXTENSIONS" --build-cli
# C: dynamically linked glibc with a defined compatibility floor
SPC_TARGET=native-native-gnu.2.17 spc build:php "$EXTENSIONS" --build-cli
```
Each result is associated with its output, build manifest, `php -i`, and logs. The actual linkage is identified from the binary rather than inferred from its filename:
```bash
file buildroot/bin/php
readelf -l buildroot/bin/php | grep 'Requesting program interpreter'
```
A versus B estimates the linkage effect while holding musl constant. B versus C estimates libc/runtime effects with dynamic linkage on both sides. A distribution PHP remains useful as an external reference, but it is reported separately because its compiler and packaging configuration are different.
The current comparison set covers both no-op startup and real CLI scripts. FPM and FrankenPHP measurements separate worker warmup from sustained throughput and tail latency. libc-sensitive coverage includes allocation-heavy extension work, concurrent requests, DNS cache hit/miss/failure cases, file I/O, and long-running RSS/fragmentation behavior.
### Deployment Characteristics
- **musl static** is the StaticPHP default and represents the portable, self-contained deployment profile without shared extensions or FFI.
- **glibc dynamic** represents integration with a GNU/Linux runtime, including `.so` extensions, FFI, the host name-service stack, and workloads for which glibc produces better measured behavior.
- **musl dynamic** represents a musl-based runtime that still requires shared extensions. It also provides the middle point in the controlled comparison above, while giving up much of the default's single-file portability.
The default is designed to remain predictable and broadly deployable. The fastest target is workload-specific and continues to be evaluated against the actual CPU, PHP version, SAPI, and application behavior.
## Where Optimization Enters the v3 Build
The v3 build passes optimization settings through several layers:
1. `config/env.ini` supplies platform defaults. `config/env.custom.ini` or the process environment can override them.
2. `ToolchainManager` selects Zig on Linux, MSVC on Windows, and system, Homebrew, or MacPorts Clang on macOS by default. It initializes `CC`, `CXX`, `AR`, `RANLIB`, and `LD`.
3. Package executors and `Package::getLibExtra*Flags()` pass the default flags into Autoconf, CMake, and package-specific builds.
4. The PHP target passes its PHP-specific flags to both `./configure` and `make` on Unix. Static extensions compiled as part of php-src see the same compiler environment.
5. The FrankenPHP target links the PHP embed library through CGO. Its `CGO_CFLAGS` and `CGO_LDFLAGS` include the PHP and dependency-library flags, followed by Go and external-linker settings.
6. Deployment extracts separate debug information and strips Unix binaries by default. UPX is optional and affects size and startup behavior, not generated PHP code.
This propagation is intentionally broad, but it is not yet perfectly uniform. Packages with hand-written compiler commands or unusual upstream build systems may ignore part of the global flag set. Extending consistent C, C++, and linker-flag propagation across those adapters remains part of the optimization work.
## Current Default Configuration
The authoritative values are in `config/env.ini`. The following tables explain the current v3 defaults rather than replacing that file.
### Linux Compiler Defaults
These compiler defaults apply to the Linux targets above. The v3 toolchain manager selects Zig unless a maintainer-level `SPC_TOOLCHAIN` override is used.
| Variable | Current default | Purpose |
|---|---|---|
| `SPC_DEFAULT_CFLAGS` | `-fPIC -O3 -pipe -fno-plt -fno-semantic-interposition -fstack-clash-protection -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections` | Common C flags for libraries and PHP |
| `SPC_DEFAULT_CXXFLAGS` | `${SPC_DEFAULT_CFLAGS}` | Common C++ flags |
| `SPC_DEFAULT_LDFLAGS` | `-Wl,-z,relro -Wl,--as-needed -Wl,-z,now -Wl,-z,noexecstack -Wl,--gc-sections` | Link hardening, dependency pruning, and unused-section removal |
| `SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS` | `-g -fstack-protector-strong -fno-ident -fPIE -fvisibility=hidden -fvisibility-inlines-hidden ${SPC_DEFAULT_CFLAGS}` | PHP and in-tree extension C flags |
| `SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS` | The corresponding C++ form | PHP and in-tree extension C++ flags |
| `SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS` | Empty | Additional PHP program linker flags |
The important performance-related defaults are:
- `-O3` favors runtime speed over compilation time and code size.
- `-fno-semantic-interposition` gives the optimizer more freedom for ELF symbols that cannot be interposed in the final program.
- `-fno-plt` avoids the traditional ELF procedure linkage table sequence where the toolchain can do so.
- `-ffunction-sections -fdata-sections` combined with `--gc-sections` lets the linker remove unused functions and data.
- Frame pointers and `-g` are deliberately retained during compilation for profiling and debugging. The deployed Unix binary is stripped by default, while separate debug information is written under `buildroot/debug/`.
The default PHP configure command also enables `--enable-re2c-cgoto`, disables unused SAPIs and shared PHP libraries, and builds only the requested extensions. These choices reduce unnecessary code; their runtime effect remains workload-dependent.
### macOS
macOS uses the native target and system Clang by default. v3 also supports the newer upstream LLVM distributions from Homebrew and MacPorts through `SPC_USE_LLVM=brew` and `SPC_USE_LLVM=port`. The Homebrew variant selects its `clang`, `clang++`, `llvm-ar`, and `llvm-ranlib` as one coherent toolchain rather than mixing them with the Apple-provided tools.
Homebrew LLVM is one of StaticPHP's current macOS performance paths. Its newer optimizer and code-generation backend can produce faster PHP binaries for some PHP versions and workloads, while also allowing the project to evaluate compiler improvements without waiting for Apple's system Clang release cycle. This is not a guaranteed uplift: PHP VM changes, CPU architecture, extensions, Opcache, and compiler flags can change the result. The project's [performance testing issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838) shows that compiler and optimization-level effects are version- and workload-specific, while the later [v3 toolchain discussion](https://github.com/crazywhalecc/static-php-cli/issues/985#issuecomment-3860775962) records access to an up-to-date compiler as the motivation for the additional macOS LLVM path.
| Variable | Current default | Purpose |
|---|---|---|
| `SPC_DEFAULT_CFLAGS` | `--target=${MAC_ARCH}-apple-darwin -O3 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections` | Target selection, optimization, observability, and section splitting |
| `SPC_DEFAULT_CXXFLAGS` | `${SPC_DEFAULT_CFLAGS}` | Common C++ flags |
| `SPC_DEFAULT_LDFLAGS` | `-Wl,-dead_strip` | Removes unreachable Mach-O code and data |
| PHP extra flags | `-g`, stack protection, PIC/PIE, hidden visibility, and the defaults above | PHP and in-tree extension compilation |
### Windows
Windows uses MSVC and the static CRT patches described in [PHP Source Modifications](./php-src-changes). PHP's release configuration supplies its upstream optimization flags, while StaticPHP rewrites the final CLI, CGI, micro, and embed link rules to include `/LTCG`. Dependency CMake builds commonly use `/MT /Os /Ob1 /DNDEBUG`; individual packages may choose other release flags.
`--no-strip` preserves PDB/debug information while keeping `/O2` optimization in StaticPHP's rewritten build command. This is intentional: debug symbols and disabled optimization are separate concerns.
Windows FrankenPHP uses Clang/LLD for the CGO link. Some Windows libraries explicitly avoid `/GL` because MSVC LTCG objects are not accepted by this link path. `/LTCG` on the final link line therefore does not mean every input participates in whole-program optimization.
## Optimization Dimensions
StaticPHP treats performance as several related metrics rather than one score. Each dimension is affected by a different part of the build:
| Goal | Usually measured as | Main influencing controls |
|---|---|---|
| Request throughput | requests/s at fixed concurrency | SAPI mode, Opcache, worker model, PHP version, compiler and CPU target |
| Tail latency | p50/p95/p99 and error rate | workload, warmup, contention, worker count, JIT/Opcache, memory pressure |
| CLI execution | wall time, CPU time, peak RSS | startup cost, Opcache CLI setting, extension set, PHP/compiler version |
| Binary size | deployed bytes and debug-file bytes | extension set, section GC/dead stripping, symbol stripping, UPX |
| Portability | oldest CPU/OS/libc that runs the binary | `SPC_TARGET`, CPU ISA flags, static versus dynamic libc |
| Build speed | clean build wall time and peak disk/RAM | `SPC_CONCURRENCY`, toolchain, LTO/PGO, number of packages |
Comparable results keep the PHP version, commit, extensions, dependency versions, SAPI, ZTS/NTS mode, INI, target libc, compiler, CPU frequency policy, and workload constant.
## Runtime Optimization Surfaces
### 1. Reproducible Configuration Overrides
`config/env.custom.ini` provides the reproducible override layer while leaving `config/env.ini` as the project baseline. Values replace the complete default string rather than being appended automatically, so performance investigations preserve the baseline and isolate one changed factor.
For example, an x86-64-v3-specific investigation retains the Linux defaults and adds the ISA level:
```ini
[linux]
SPC_DEFAULT_CFLAGS="-fPIC -O3 -pipe -fno-plt -fno-semantic-interposition -fstack-clash-protection -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections -march=x86-64-v3"
SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}"
```
This may allow more vector and instruction selection, but the output no longer runs on CPUs below that ISA level. `-march=native` narrows portability further by coupling the result to the build host's CPU class.
PHP-only investigations are represented by `SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS` and its C++ counterpart rather than the global defaults. Individual-package investigations use snake-case variables such as `libaom_CFLAGS`, `libaom_CXXFLAGS`, and `libaom_LDFLAGS`. Package-specific flags are combined with the defaults when that package uses the common v3 executors.
### 2. Toolchain and PHP-Version Effects
The compiler can matter more than an individual optimization flag. [Issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838) found large GCC-versus-Clang differences for some PHP 8.4 x86-64 tests because PHP's older VM can use GCC global register variables. That result is not universal: architecture, PHP version, VM implementation, and workload all matter, and PHP 8.5 changes the comparison with its newer VM.
Linux v3 defaults to Zig for target flexibility and reproducible libc selection, not because it is guaranteed to produce the fastest binary for every workload. The project's performance work compares this predictable baseline with native toolchains on deployment architectures. `SPC_TOOLCHAIN` remains an internal/maintainer control until a stable user-facing selector is documented.
### 3. SAPI, Thread Safety, and Runtime Settings
- FrankenPHP requires ZTS. CLI, FPM, CGI, micro, and embed remain NTS by default unless the selected SAPI or application requires thread safety.
- Historical tests in issue #838 observed small ZTS/NTS differences in that particular suite; the result remains specific to that workload.
- Including `ext-opcache` only builds the extension. Its performance characteristics also depend on runtime INI, including `opcache.enable_cli` for repeated CLI execution and application-specific JIT settings.
- `--disable-opcache-jit` changes build capability; it is not a substitute for runtime benchmarking. StaticPHP disables the undefined-behavior sanitizer where necessary when Opcache JIT is built on Linux.
- FrankenPHP performance also depends on worker versus classic mode, worker count, application boot behavior, Caddy modules, and Go runtime settings. Compiler flags cannot compensate for an unrepresentative server configuration.
### 4. Speed, Symbols, and Compression
The default Unix deployment extracts debug information, strips the runtime binary, and keeps the debug file separately. `--no-strip` represents the unstripped variant while current v3 keeps optimization enabled.
`--with-upx-pack` is a size optimization for Linux and Windows. It can change startup time, memory mapping, security-tool behavior, and debuggability, so the project treats it as a packaging tradeoff rather than a PHP execution optimization.
## Profile-Guided Optimization (PGO)
PGO builds an instrumented program, runs a representative workload to collect profiles, and recompiles using the observed branch, call, and value frequencies. The compiler can then improve code layout, inlining, and hot/cold decisions beyond static heuristics.
A complete PGO design contains three distinct phases:
1. **Instrumentation** builds the same PHP version, SAPI, extensions, dependencies, and target with profile-generation flags.
2. **Training** covers startup and important production paths at representative traffic mixes and concurrency, including a clean shutdown so raw profiles are flushed.
3. **Profile use** merges the raw profiles with the matching toolchain utility and rebuilds the identical source/configuration with profile-use flags.
Profiles are inputs to the build, not portable benchmark artifacts. Meaningful changes to PHP, extensions, dependencies, compiler version, flags, SAPI linkage, or workload invalidate them. A narrow or stale profile can improve the trained route while making untrained behavior worse.
### StaticPHP PGO Status
The experimental v3 design explores a dedicated PGO context and lifecycle hooks for CLI, CGI, FPM, micro, embed, and FrankenPHP. The concepts under evaluation include:
- instrument and profile-use phases, plus an optional context-sensitive second instrumentation phase;
- per-SAPI raw-profile directories and merged `.profdata` files;
- clean rebuilds when switching the active SAPI profile;
- shutdown patches for php-src and FrankenPHP, because the Go/CGO process does not reliably run the libc `atexit` path that normally flushes profiles;
- LLVM profile tooling and special linker/runtime handling for Zig, Clang, GCC, and FrankenPHP.
This work is not part of the stable v3 feature set. The current v3 tree contains some preparatory compatibility handling—for example, FrankenPHP detects manual `-fprofile*` C flags when using native GCC, suppresses missing-profile errors, and links `libgcov`—but complete training, merging, invalidation, and rebuilding orchestration remains under investigation.
A raw `-fprofile-generate` addition to the global defaults is not equivalent to this orchestration: it also instruments dependency libraries, changes link requirements, increases build and runtime cost, and may fail to flush usable data. For that reason, the current internal variables do not yet constitute a stable release workflow.
### FrankenPHP's Go PGO
[PR #1142](https://github.com/crazywhalecc/static-php-cli/pull/1142) added FrankenPHP's upstream `default.pgo` to the v2 xcaddy build when present. That profile optimizes the Go portion using a profile distributed with FrankenPHP. It does not train php-src, the PHP embed library, extensions, or CGO glue against your application.
A future end-to-end FrankenPHP PGO design may therefore contain two profile sources:
- FrankenPHP's upstream Go profile for the Go/Caddy code;
- application-specific compiler profiles for PHP, static extensions, and CGO-linked C code.
Their ownership and invalidation rules are separate concerns in the current design exploration.
## Link-Time Optimization (LTO)
LTO retains compiler intermediate representation until link time so the optimizer can work across translation units. Full LTO processes the combined program more aggressively; ThinLTO distributes more work and usually reduces memory and build-time cost.
Static linking does not automatically enable LTO. Conversely, adding `-flto` to only the final link is insufficient: relevant objects and archives must be produced with a compatible compiler, LTO mode, archiver, ranlib, and linker plugin.
Unix v3 does not enable LTO by default. Historical work made more archive commands respect the selected `AR`, but the project later removed default LTO work because compatibility fixes across dependency libraries were costly. In [issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838), one test environment observed only about 2% runtime improvement while ThinLTO roughly doubled build time and full LTO increased it by about seven times. These are historical measurements on one setup, not a promised ratio.
Current Unix LTO investigations account for the following constraints:
1. Objects, archives, and the final link need one compatible LLVM/Clang or GCC toolchain family.
2. C, C++, PHP, and linker flags need the same mode, such as `-flto=thin`.
3. Limiting the initial scope to PHP and its in-tree extensions separates core results from dependency-library compatibility.
4. Archive contents and the final link log reveal whether LTO reached the intended objects; build completion alone does not.
5. SAPI and extension smoke tests, clean build time, binary size, throughput, and tail latency together describe the result.
LTO can expose package bugs, unsupported assembly, incompatible archives, symbol-export problems, and Go/CGO linker limitations. It can also increase code size or regress instruction-cache behavior. These compatibility and maintenance costs are why Unix LTO remains opt-in while its benefits continue to be evaluated.
## Performance Evidence and Reproducibility
StaticPHP performance investigations record enough context for another maintainer to reproduce the result:
- StaticPHP commit and registry/package revisions;
- PHP, FrankenPHP, Go, compiler, linker, and profile-tool versions;
- host and target OS, libc, architecture, and exact `SPC_TARGET`;
- CPU model, available instruction set, power/frequency policy, memory, and virtualization;
- complete extension and dependency set, ZTS/NTS, SAPI, static/dynamic linkage, and INI;
- all overridden environment variables and whether the binary was stripped or UPX-packed;
- workload source revision, dataset, route mix, concurrency, duration, warmup, and repetitions;
- median result, variation, p95/p99 where relevant, peak RSS, binary size, and clean build time.
The project alternates a baseline and one changed build on the same machine. Multiple repetitions and confidence intervals carry more weight than a single best run, and benchmark scripts remain part of the result alongside the raw measurements.
## History and Design Lessons
The following merged changes and issue discussions explain why the current defaults and cautions exist. Unmerged implementation work is represented only by its technical concepts elsewhere on this page.
| Record | Outcome and lesson |
|---|---|
| [Issue #385](https://github.com/crazywhalecc/static-php-cli/issues/385), performance degradation | A v2 `--no-strip` path also selected `-O0`, making one reported Laravel test about three times slower. This led to customizable PHP compiler variables and reinforced that debug symbols must not silently disable optimization. Current v3 keeps optimized flags with `--no-strip`. |
| [PR #806](https://github.com/crazywhalecc/static-php-cli/pull/806), Zig toolchain | Added target-flexible Zig support and documented its build/compatibility tradeoffs. Its discussion also contains the static/dynamic within-1% observation and early GCC/Clang/Zig comparisons. Toolchain choice is partly about portability and libc targeting, not only benchmark speed. |
| [Issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838), performance testing | Established reproducible compiler, ZTS/NTS, Opcache, LTO, architecture, and PHP VM comparisons. Its results provide background for the `-O3` defaults but also show why conclusions must remain version- and workload-specific. The issue remains the main historical performance notebook. |
| [Issue #985](https://github.com/crazywhalecc/static-php-cli/issues/985), v3 toolchains | Recorded the decision to prefer predictable defaults while retaining performance-oriented alternatives. On Linux this means Zig alongside native GCC paths; on macOS the discussion also motivated access to a current upstream LLVM instead of being limited to Apple's compiler release cycle. |
| [Issue #862](https://github.com/crazywhalecc/static-php-cli/issues/862), `--pgo=script.php` proposal | Closed after concluding that one universal training script interface was unrealistic. PGO needs SAPI-aware lifecycle orchestration and user-owned representative training. |
| [PR #966](https://github.com/crazywhalecc/static-php-cli/pull/966), flags and stripping | Unified PHP make flags and improved separate debug stripping, helping decouple optimization from symbol handling. |
| [PR #1142](https://github.com/crazywhalecc/static-php-cli/pull/1142), FrankenPHP Go PGO | Added use of FrankenPHP's bundled Go `default.pgo` in the v2 build. This is distinct from application-trained PHP/CGO PGO. |
| [Issue #1088](https://github.com/crazywhalecc/static-php-cli/issues/1088), native intrinsics | Open design request for declaring CPU intrinsic levels across both libraries and PHP/extensions instead of managing every ISA flag manually. |
| [PR #1150](https://github.com/crazywhalecc/static-php-cli/pull/1150), macOS `-fno-plt` | Removed an ELF-only flag from the macOS defaults after it broke dependency configure checks. Optimization flags must be target-format aware. |
Most of this investigation and implementation has been led by [@henderkes](https://github.com/henderkes), with reviews, integration, platform fixes, and testing from the other StaticPHP contributors. The project continues to preserve workloads, raw results, and rationale as this work evolves; an individual compiler flag is only the last line of a much broader performance decision.

View File

@@ -1,20 +1,18 @@
# Package 模型 # Package 模型
<!-- TODO: 统一 Package 模型说明library / php-extension / target 类型。
config/pkg/ 下 per-package YAML 格式、depends 字段、平台覆盖(@windows / @unix 写法)。
artifact.source 和 artifact.binary 字段。附注释的 library 和 extension YAML 示例。 -->
## Package 定义 ## Package 定义
Package 是 StaticPHP 构建系统中的核心概念,代表一个可构建/可安装的单元,如 PHP 扩展、库、构建目标等。 Package 是 StaticPHP 构建系统中的核心概念,代表一个可构建/可安装的单元,如 PHP 扩展、库、构建目标等。
每个 Package 包含构建信息、依赖关系、构建逻辑等,构成了 StaticPHP 的构建模型。Package 的定义主要通过 YAML/JSON 配置文件来实现。`core` 注册表的包配置文件位于 `config/pkg/` 目录下,对应的构建类位于 `src/Package/` 目录 每个 Package 包含构建信息、依赖关系、构建逻辑等,构成了 StaticPHP 的构建模型。Package 的定义主要通过 YAML/JSON 配置文件来实现。`core` Registry 的 Package 配置位于 `config/pkg/` 目录下,可选 recipe class 位于 `src/Package/` 对应的子目录
Package 主要分为种类型: Package 分为种类型:
- **php-extension**PHP 扩展包,包含 PHP 扩展的构建信息和构建逻辑。 - **php-extension**PHP 扩展包,包含 PHP 扩展的构建信息和构建逻辑。
- **library**库包,包含构建工具链、依赖库等的构建信息和构建逻辑 - **library**依赖库 Package通常安装到 `buildroot/`,供其他 Package 编译和链接
- **target**:构建目标包,代表最终的构建产物,如 PHP 二进制、curl 二进制等,继承自 `library` 包类型。 - **target**:构建目标包,代表最终的构建产物,如 PHP 二进制、curl 二进制等,继承自 `library` 包类型。
- **virtual-target**:虚构建目标包,代表一个抽象的构建目标,不直接对应构建产物,主要用于依赖管理和构建调度。 - **virtual-target**:虚构建目标包,代表一个抽象的构建目标,不直接对应构建产物,主要用于依赖管理和构建调度。
- **tool**:宿主机侧构建工具 Package单独安装在 `pkgroot/` 下,不作为链接期库依赖处理。
```yaml ```yaml
{pkg-name}: {pkg-name}:
@@ -24,7 +22,7 @@ Package 主要分为四种类型:
## Artifact 定义 ## Artifact 定义
Artifact 是独立于 Package 的定义,它包含构建包的源码归档文件或预构建的二进制文件。每个 Artifact 定义了下载 URL、解压方式、构建产物的文件路径等信息。Package 可以通过 `artifact` 字段引用一个或多个 Artifact获取构建所需的源码或二进制文件。 Artifact 是独立于 Package 的定义,它包含构建包的源码归档文件或预构建的二进制文件。每个 Artifact 定义了下载 URL、解压方式、构建产物的文件路径等信息。一个 Package 可以通过 `artifact` 字段引用一个 Artifact,以获取构建所需的源码或二进制文件。
简单来说,默认情况下,一个 Package 对应一个 Artifact如果多个 Package 共用一份源码时,可以定义一个 Artifact 供多个 Package 引用。Artifact 的定义位于 `config/artifact/` 目录下,对应的自定义下载/解压逻辑类位于 `src/Package/Artifact/` 目录下对于虚拟目标、PHP 内置扩展等特殊包类型Package 也可以不设置 Artifact 字段。 简单来说,默认情况下,一个 Package 对应一个 Artifact如果多个 Package 共用一份源码时,可以定义一个 Artifact 供多个 Package 引用。Artifact 的定义位于 `config/artifact/` 目录下,对应的自定义下载/解压逻辑类位于 `src/Package/Artifact/` 目录下对于虚拟目标、PHP 内置扩展等特殊包类型Package 也可以不设置 Artifact 字段。
@@ -43,7 +41,7 @@ example-library-package:
## php-extension 包类型 ## php-extension 包类型
php-extension 一个包代表一个 PHP 扩展,它的配置文件位于 `config/pkg/ext/` 目录下,构建类继承自 `PhpExtensionPackage`,位于 `src/Package/Extension/` 目录下。PHP 扩展包的配置文件包含扩展名称、版本、依赖关系、构建选项等信息 php-extension Package 代表一个 PHP 扩展,它的配置文件位于 `config/pkg/ext/` 目录下。可选的 recipe class 通常放在 `src/Package/Extension/`,通过 `#[Extension]` 注册,并从 callback context 接收对应的 `PhpExtensionPackage`。当前 core recipe 支持继承 `PhpExtensionPackage`,但并不要求继承
```yaml ```yaml
ext-lz4: ext-lz4:
@@ -60,7 +58,7 @@ ext-lz4:
depends: depends:
- liblz4 - liblz4
php-extension: php-extension:
arg-type@unix: '--enable-lz4=@shared_suffix@ --with-lz4-includedir=@build_root_path@' arg-type@unix: '--enable-lz4@shared_suffix@ --with-lz4-includedir=@build_root_path@'
arg-type@windows: '--enable-lz4' arg-type@windows: '--enable-lz4'
``` ```
@@ -75,15 +73,17 @@ ext-{ext-name}: # 包名必须以 ext- 前缀开头
lang: c # 可选扩展的实现语言c / c++ 等) lang: c # 可选扩展的实现语言c / c++ 等)
frameworks: [] # 可选相关macOS框架依赖列表 frameworks: [] # 可选相关macOS框架依赖列表
artifact: '{artifact-name}' # 可选;字符串时引用同名 Artifact 定义, artifact: '{artifact-name}' # 可选;字符串时引用指定名称的 Artifact 定义,
# 对象时为内联 Artifact内置扩展无需此字段 # 对象时为内联 Artifact内置扩展无需此字段
# depends / suggests 支持 @windows / @unix / @linux / @macos 后缀 # depends / suggests / tools 支持 @windows / @unix / @linux / @macos 后缀
depends: [] # 可选硬依赖列表库名直接写PHP 扩展需加 ext- 前缀) depends: [] # 可选硬依赖列表库名直接写PHP 扩展需加 ext- 前缀)
depends@unix: [] # 可选,仅 Unix 平台生效的硬依赖 depends@unix: [] # 可选,仅 Unix 平台生效的硬依赖
depends@windows: [] # 可选,仅 Windows 平台生效的硬依赖 depends@windows: [] # 可选,仅 Windows 平台生效的硬依赖
suggests: [] # 可选,可选依赖列表(格式同 depends suggests: [] # 可选,可选依赖列表(格式同 depends
suggests@unix: [] suggests@unix: []
tools: [] # 可选,宿主机侧构建工具依赖,单独解析
tools@windows: [] # 可选,特定平台的工具依赖
# ── php-extension 专属字段(嵌套在 php-extension: 对象中)───────────────── # ── php-extension 专属字段(嵌套在 php-extension: 对象中)─────────────────
php-extension: php-extension:
@@ -101,7 +101,7 @@ ext-{ext-name}: # 包名必须以 ext- 前缀开头
# @shared_suffix@ → 共享构建时展开为 =shared静态构建时为空 # @shared_suffix@ → 共享构建时展开为 =shared静态构建时为空
# @shared_path_suffix@ → 共享构建时展开为 =shared,{buildroot},静态构建时为 ={buildroot} # @shared_path_suffix@ → 共享构建时展开为 =shared,{buildroot},静态构建时为 ={buildroot}
arg-type: enable arg-type: enable
arg-type@unix: '--enable-{extname}=@shared_suffix@' arg-type@unix: '--enable-my-extension@shared_suffix@'
arg-type@windows: with-path arg-type@windows: with-path
zend-extension: false # 可选true 表示这是 Zend 扩展(如 opcache、xdebug zend-extension: false # 可选true 表示这是 Zend 扩展(如 opcache、xdebug
@@ -120,7 +120,7 @@ ext-{ext-name}: # 包名必须以 ext- 前缀开头
## library 包类型 ## library 包类型
library 包代表一个需要从源码编译的依赖库(如 openssl、zlib 等),其配置文件位于 `config/pkg/lib/` 目录下,构建类继承自 `LibraryPackage`位于 `src/Package/Library/` 目录下 library Package 代表 openssl、zlib 等依赖库,可以从源码或预构建二进制安装。其配置文件位于 `config/pkg/lib/` 目录下。可选的 recipe class 通常放在 `src/Package/Library/`通过 `#[Library]` 注册,并从 callback context 接收 `LibraryPackage`;不要求继承该类
以 openssl 为例: 以 openssl 为例:
@@ -160,20 +160,25 @@ openssl:
# ── 通用字段 ───────────────────────────────────────────────────────────── # ── 通用字段 ─────────────────────────────────────────────────────────────
description: '...' # 可选,人类可读的包描述 description: '...' # 可选,人类可读的包描述
license: MIT # 可选,SPDX 许可证标识符(用于许可证导出) license: # 可选,从源码构建后复制的许可证内容
type: file # type 可为 file 或 text也可填写多个条目的列表
path: LICENSE
lang: c # 可选库的实现语言c / c++ 等) lang: c # 可选库的实现语言c / c++ 等)
frameworks: [] # 可选,相关框架标签列表 frameworks: [] # 可选,相关框架标签列表
artifact: '{artifact-name}' # 必填;字符串时引用同名 Artifact 定义,对象时为内联 Artifact artifact: '{artifact-name}' # 必填;字符串时引用指定名称的 Artifact 定义,对象时为内联 Artifact
# depends / suggests 支持 @windows / @unix / @linux / @macos 后缀 # depends / suggests / tools 支持 @windows / @unix / @linux / @macos 后缀
depends: [] # 可选,硬依赖列表(库名或 ext- 前缀的 PHP 扩展名) depends: [] # 可选,硬依赖列表(库名或 ext- 前缀的 PHP 扩展名)
depends@unix: [] depends@unix: []
depends@windows: [] depends@windows: []
suggests: [] # 可选,可选依赖列表(格式同 depends suggests: [] # 可选,可选依赖列表(格式同 depends
tools: [] # 可选,仅构建时需要的 ToolPackage 名称
tools@windows: []
# ── library / target 专属字段 ──────────────────────────────────────────── # ── library / target 专属字段 ────────────────────────────────────────────
# 以下字段用于构建完成后验证产物是否已正确安装,支持 @unix / @windows / @linux / @macos 后缀 # 以下字段用于构建完成后验证产物是否已正确安装headers、static-libs、static-bins
# 支持 @unix / @windows / @linux / @macos 后缀
# 验证 buildroot/include/ 下是否存在指定头文件或目录 # 验证 buildroot/include/ 下是否存在指定头文件或目录
# 相对路径基于 buildroot/include/,绝对路径直接使用 # 相对路径基于 buildroot/include/,绝对路径直接使用
@@ -225,17 +230,49 @@ openssl:
| `{source_path}` | 解压源码目录(`source/` | | `{source_path}` | 解压源码目录(`source/` |
| `{spc_msys2_path}` | MSYS2 根目录(`msys64/`)——仅 Windows | | `{spc_msys2_path}` | MSYS2 根目录(`msys64/`)——仅 Windows |
## tool 包类型
`tool` Package 表示构建其他 Package 时需要的可执行工具,而不是链接进最终 target 的库。Tool Package 可以使用预构建二进制,也可以从源码构建,默认安装在 `pkgroot/` 下的共享 `bin/` 或配置的子目录。其他 Package 通过顶层 `tools` 字段请求这些工具;该依赖集合与 `depends``suggests` 分开解析。
```yaml
nasm:
type: tool
artifact:
binary:
windows-x86_64:
type: url
url: 'https://example.com/nasm-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
min-version: '2.16'
```
嵌套的 `tool` 对象支持:
| 字段 | 是否必填 | 含义 |
|---|---|---|
| `provides` | 是 | 用于判断工具是否已经安装的可执行文件名 |
| `binary-subdir` | 否 | `install-root` 下存放可执行文件的目录;默认就是安装根目录 |
| `install-root` | 否 | 安装根目录;默认为 `PKG_ROOT_PATH`,支持路径占位符 |
| `min-version` | 否 | 由 `ToolPackage` 暴露的最低版本元数据installer 当前不会强制校验 |
`tool` 内的字段可以使用 `@windows``@unix``@linux``@macos` 后缀。例如,`provides@windows` 可以列出 `.exe` 名称,`provides@unix` 列出 Unix 名称。
## target 包类型 ## target 包类型
`target` 代表一个最终的构建产物,它继承于 `library`,所以包含 `library` 的所有定义字段。`target` 包的配置文件位于 `config/pkg/target/` 目录下,构建类继承自 `TargetPackage`,位于 `src/Package/Target/` 目录下 `target` Package 代表一个最终的构建产物,它继承于 `library`,所以包含 `library` 的所有定义字段。配置文件位于 `config/pkg/target/`。可选的 recipe class 通常放在 `src/Package/Target/`,通过 `#[Target]` 注册,并接收 `TargetPackage`;是否继承 `TargetPackage` 是可选的
`library` 的唯一区别是,`target` 包可以注册成为构建目标,且自动注册构建命令 `spc build:{target-name}` `library` 的唯一区别是,`target` 包可以注册成为构建目标,且自动注册构建命令 `spc build:{target-name}`
## virtual-target 包类型 ## virtual-target 包类型
`target` 不同的是`virtual-target` 可以不包含 `artifact`,即不直接对应一个可构建的实体,而是一个抽象的构建目标,主要用于依赖管理和构建调度。`virtual-target` 的配置文件位于 `config/pkg/target/` 目录下,构建类继承自 `TargetPackage`,位于 `src/Package/Target/` 目录下。它的定义与 `target` 基本相同,但 `artifact` 字段可选且通常不设置。`virtual-target` 主要用于以下场景: `target` 不同,`virtual-target` 可以省略 `artifact`,即不直接对应一个可构建的实体,而是用于依赖管理和构建调度的抽象构建目标。它与 `target` 使用相同的配置目录、可选 recipe class 目录和 `#[Target]` 注册方式。其余定义基本相同,但 `artifact` 字段可选且通常不设置。`virtual-target` 主要用于以下场景:
- 定义一个抽象的构建目标,供其他包依赖,但不直接对应一个可构建的实体。 - 定义一个抽象的构建目标,供其他包依赖,但不直接对应一个可构建的实体。
- 作为多个 `target` 包的公共依赖,简化依赖关系管理。 - 作为多个 `target` 包的公共依赖,简化依赖关系管理。
典型例子 PHP 包的 `php-cli``php-fpm` 构建目标,他们没有独立源码,依赖 `php-src`,通过构建调度决定最终构建成 CLI 还是 FPM 二进制。 典型例子是 `php-cli``php-fpm` 构建目标。它们没有独立源码,依赖 Artifact 为 `php-src``php` target构建调度决定最终成 CLI 还是 FPM 二进制。

View File

@@ -1,301 +0,0 @@
# 性能工程
StaticPHP 控制 PHP、扩展、依赖库以及各个 SAPI 的编译方式。这些选择会影响运行时吞吐量与延迟、启动时间、内存占用、二进制体积、可移植性和构建时间。不过它们并不是同一个指标:更小的二进制不一定更快,更慢的构建过程也可能生成更快的程序。
本页记录当前 v3 的默认值、已经进入构建流程的优化,以及仍在探索的方向。在 Linux 上libc 和链接模型构成第一层:默认的 musl 全静态构建与 glibc 动态构建在可移植性、扩展加载和性能方面具有不同特征编译参数、PGO 和 LTO 则是这项持续优化工作的后续层次。
本页并不宣称 StaticPHP 二进制在所有情况下都比其他 PHP 发行方式更快。结果取决于 PHP 版本、CPU、工具链、扩展集合、SAPI、libc、链接方式、运行时配置和实际负载。
::: warning 当前 v3 状态
v3 分支目前没有提供稳定的 `--pgi``--pgo``--lto` CLI 选项。PGO 编排和更广泛的 LTO 兼容性仍处于持续探索阶段。下文描述的是设计、当前约束和优化方向,而不是受支持的正式版本构建方法。
:::
## Linux 链接方式与 libc
StaticPHP 的 Linux 默认配置优先保证产物自包含,并不追求在所有服务器负载中获得最高分。`config/env.ini` 默认选择 `${GNU_ARCH}-linux-musl`;配合默认 Zig 工具链,会生成完全静态链接 musl 的二进制。
当前性能研究会区分以下三个 Linux target
| Target | libc 与最终链接方式 | 运行时要求 | 共享扩展 / FFI | 当前定位 |
|---|---|---|---|---|
| `native-native-musl` | musl全静态 | 兼容 CPU 上的 Linux 内核 | 不支持 | 默认的可移植单文件发布 |
| `native-native-musl -dynamic` | musl动态链接 | 兼容的 musl loader 和库 | 支持 | 保持 musl 不变,隔离静态/动态链接影响 |
| `native-native-gnu.2.17` | glibc动态链接以 2.17 为基线 | glibc 2.17 或更高版本 | 支持 | 广泛兼容 GNU/Linux并作为 glibc 性能基线 |
可以用具体架构替换任一 `native`,例如 `x86_64-linux-musl`。不指定版本的 `-gnu` target 会面向所选/当前 glibc ABI而不是承诺兼容 glibc 2.17。
这里的“动态链接 PHP”并不意味着每个依赖都是系统 `.so`。StaticPHP 仍会把大多数选中的第三方库和 PHP 扩展构建为静态 archive并链接进 PHP 可执行文件。动态部分主要是 libc/runtime loader以及通过 `--build-shared` 明确选择的扩展。这与 PHP 和许多依赖都作为独立共享对象提供的传统发行版 PHP 不同。
同样,“静态扩展”和“静态 libc”是两个独立选择。glibc 动态 PHP 可以把所有 PHP 扩展静态编入musl 动态 PHP 也可以加载指定的 `.so` 扩展。只有 musl 全静态 target 因进程中不存在动态 loader 而无法在运行时加载扩展。
### 静态与动态链接改变了什么
静态和动态链接主要改变启动工作、重定位、符号解析、部署方式和库共享,并不会自动改变 PHP VM 的代码生成方式。
- 全静态进程不会通过 runtime dynamic loader 启动,也不需要重定位一组 DSO。这可能有利于极短 CLI 的启动,但 PHP 初始化、扩展启动、脚本解析和 Opcache 往往占据更多时间。
- 动态进程需要在启动时支付 loader 和 relocation 成本。长时间运行的 FPM 或 FrankenPHP worker 会把这部分成本分摊到许多请求上。
- 静态链接为 section garbage collection 以及显式启用的 LTO 提供了更完整的 closed world但静态链接本身不会进行跨 object 优化。
- glibc 动态构建支持共享扩展、FFI、NSS 集成,并允许在不重建 PHP 的情况下替换或安全更新运行时库。全静态产物则必须重建才能获得 libc 或内嵌依赖修复。
- 不同程序可以复用共享库的代码页;相同的静态 PHP worker 进程之间也会共享文件映射的可执行代码页,因此“静态链接会让每个 worker 在内存里复制所有代码”并不准确。
StaticPHP 的[性能测试 Issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838) 记录过一组 PHP 8.4 测试:多次运行时,静态和动态构建在两个方向上的差异都不超过约 1%。这说明仅链接方式未必会主导 PHP 稳态执行性能,但不能把它当作普遍结论。短 CLI、大量 DSO、不同 loader 以及 I/O 密集扩展都可能得到不同结果。
### musl 与 glibc 的性能影响面
只有负载实际进入 libc 或围绕 libc 实现的功能时,两者差异才会出现。纯 PHP 代码的大量时间会花在 Zend VM、Opcache 和 Zend Memory Manager 中。PHP 自己的 [Zend Memory Manager](https://wiki.php.net/internals/zend_mm) 处理大多数 request-bound allocation因此以 PHP array 和 opcode 为主的 microbenchmark对系统 allocator 的敏感度可能低于 C 扩展或服务器 runtime。
| 负载领域 | libc 可能产生影响的原因 | 主要观测项 |
|---|---|---|
| CPU 密集 PHP opcode | 通常由 PHP VM、编译器、CPU target 和 Opcache 主导,而不是 libc | 先保持 PHP/VM/编译器一致,再只改变 libc/链接方式 |
| 持久及原生内存分配 | PHP persistent allocation、C 扩展、依赖库和服务器代码可能直接调用 libc allocator | 吞吐量、allocation contention、RSS、长时间运行后的 fragmentation |
| ZTS 与 FrankenPHP | 线程创建、TLS、mutex、allocator contention 和 per-thread cache 存在差异 | 随 worker/thread 数量的扩展性、p95/p99、每线程 RSS |
| DNS 与名称服务 | resolver 策略、NSS、`/etc/resolv.conf` 和缓存不同 | 有/无缓存的查询延迟、失败/切换延迟、查询量 |
| Locale、iconv、regex、stdio | 实现和支持行为不同,不只是速度不同 | 先验证正确性,再用生产 locale/数据测试吞吐量 |
| 极短 CLI 命令 | loader/relocation 和初始化占总时间的比例更大 | 大量进程启动的 cold/warm wall time |
| 长时间运行的 worker | 启动成本被分摊allocator、线程、系统调用和应用行为更加重要 | 持续吞吐量、尾延迟、峰值/稳定 RSS |
glibc allocator 提供 per-thread cache 和多个 arena并允许调整其上限这可能提高并发分配吞吐量但代价是保留更多内存。因此StaticPHP 的基准记录会包含 [glibc allocation tunable](https://sourceware.org/glibc/manual/latest/html_node/Memory-Allocation-Tunables.html)。musl 使用不同的 allocator更关注较低基线开销、受控 fragmentation 及静态链接适用性;两种设计都不能保证在所有 PHP 应用中具有更低延迟或 RSS。
Resolver 行为甚至可能反转一个表面上的“libc 性能”结果。[musl 功能差异文档](https://wiki.musl-libc.org/functional-differences-from-glibc.html)指出musl 会并行查询配置的 nameserver而传统 glibc 行为会依次尝试。这可能改善故障切换延迟,也可能增加 DNS 流量glibc 还会参与可配置的 NSS module。因此StaticPHP 的 DNS 对比会保持 resolver、缓存状态、search domain 和失败条件一致,而不会把 resolver 结果当作单纯 CPU benchmark。
musl 的默认线程栈明显小于典型 glibc 配置。这可以减少线程密集程序保留的地址空间,也可能暴露扩展对栈大小的假设。它属于部署和内存特征,不能证明某个 libc 执行 PHP opcode 更快。
### 当前对比模型
默认 musl 静态二进制与发行版 glibc PHP 的直接对比会同时改变 libc、linker、编译器、参数、PHP 配置、扩展、依赖版本和 INI因此无法把全部差异归因于 libc。
项目采用相同 StaticPHP commit、PHP 源码、Zig 版本、参数、扩展和 SAPI 形成受控矩阵。三个构建对应以下命令:
```bash
EXTENSIONS="bcmath,curl,openssl,opcache"
# A默认形式的 musl 全静态构建
SPC_TARGET=native-native-musl spc build:php "$EXTENSIONS" --build-cli
# Bmusl 动态构建,需要 musl runtime
SPC_TARGET="native-native-musl -dynamic" spc build:php "$EXTENSIONS" --build-cli
# Cglibc 动态构建,并指定兼容性下限
SPC_TARGET=native-native-gnu.2.17 spc build:php "$EXTENSIONS" --build-cli
```
每项结果都与其产物、build manifest、`php -i` 和日志一起保存。实际链接方式由二进制本身确认,而不是根据文件名推断:
```bash
file buildroot/bin/php
readelf -l buildroot/bin/php | grep 'Requesting program interpreter'
```
A 对比 B 用于在保持 musl 不变时估计链接方式的影响B 对比 C 用于在两者均动态链接时估计 libc/runtime 的影响。发行版 PHP 仍可作为外部参考,但由于编译器和打包配置不同,会单独记录。
当前对比集合同时覆盖 no-op 启动和实际 CLI 脚本。FPM 与 FrankenPHP 会把 worker 预热和持续吞吐量、尾延迟分开记录。libc 敏感场景则包括使用扩展的大量内存分配、并发请求、DNS cache hit/miss/failure、文件 I/O以及长时间运行后的 RSS/fragmentation。
### 部署特征
- **musl 静态**是 StaticPHP 默认值,代表不依赖共享扩展或 FFI 的可移植、自包含部署形态。
- **glibc 动态**代表与 GNU/Linux runtime 集成的部署形态,包括 `.so` 扩展、FFI、宿主名称服务栈以及实测更适合 glibc 的负载。
- **musl 动态**代表仍需要共享扩展的 musl runtime同时也是上述受控对比的中间项它会放弃默认构建的大部分单文件可移植性。
默认值以可预测和广泛部署为目标。最快 target 与具体负载相关,项目仍在结合实际 CPU、PHP 版本、SAPI 和应用行为持续评估。
## 优化配置如何进入 v3 构建
v3 会通过多个层次传递优化配置:
1. `config/env.ini` 提供各平台默认值;`config/env.custom.ini` 或进程环境变量可以覆盖它们。
2. `ToolchainManager` 默认在 Linux 选择 Zig、Windows 选择 MSVC、macOS 选择系统/Homebrew/MacPorts Clang并初始化 `CC``CXX``AR``RANLIB``LD`
3. Package executor 和 `Package::getLibExtra*Flags()` 把默认参数传入 Autoconf、CMake 及包专用构建过程。
4. Unix 上的 PHP target 会把 PHP 专用参数同时传给 `./configure``make`。作为 php-src 一部分编译的静态扩展会看到相同的编译环境。
5. FrankenPHP target 通过 CGO 链接 PHP embed 库。它的 `CGO_CFLAGS``CGO_LDFLAGS` 会包含 PHP 与依赖库参数,再加入 Go 和外部链接器配置。
6. 部署阶段默认提取单独的调试信息并精简 Unix 二进制。UPX 是可选项,它影响体积和启动行为,而不会优化生成的 PHP 机器码。
这种传递有意覆盖较大范围,但目前还不是完全一致。使用手写编译命令或特殊上游构建系统的包可能忽略部分全局参数。让这些 adapter 一致传递 C、C++ 和 linker 参数,仍是当前优化工作的组成部分。
## 当前默认配置
权威值位于 `config/env.ini`。下面的表格用于解释当前 v3 默认值,不能替代该文件。
### Linux 编译器默认值
这些编译器默认值适用于上文各 Linux target。除非使用维护者级别的 `SPC_TOOLCHAIN` 覆盖项,否则 v3 toolchain manager 会选择 Zig。
| 变量 | 当前默认值 | 用途 |
|---|---|---|
| `SPC_DEFAULT_CFLAGS` | `-fPIC -O3 -pipe -fno-plt -fno-semantic-interposition -fstack-clash-protection -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections` | 依赖库和 PHP 共用的 C 参数 |
| `SPC_DEFAULT_CXXFLAGS` | `${SPC_DEFAULT_CFLAGS}` | 共用 C++ 参数 |
| `SPC_DEFAULT_LDFLAGS` | `-Wl,-z,relro -Wl,--as-needed -Wl,-z,now -Wl,-z,noexecstack -Wl,--gc-sections` | 链接加固、依赖裁剪及未使用 section 移除 |
| `SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS` | `-g -fstack-protector-strong -fno-ident -fPIE -fvisibility=hidden -fvisibility-inlines-hidden ${SPC_DEFAULT_CFLAGS}` | PHP 和源码树内扩展的 C 参数 |
| `SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS` | 对应的 C++ 形式 | PHP 和源码树内扩展的 C++ 参数 |
| `SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS` | 空 | PHP 程序的附加链接参数 |
其中与性能最相关的默认项是:
- `-O3` 偏向运行速度,而不是编译时间和代码体积。
- `-fno-semantic-interposition` 让优化器能够更自由地处理最终程序中不会被 interpose 的 ELF 符号。
- `-fno-plt` 在工具链允许时避免传统的 ELF procedure linkage table 调用序列。
- `-ffunction-sections -fdata-sections` 配合 `--gc-sections`,使链接器可以移除未使用的函数和数据。
- 编译阶段有意保留 frame pointer 和 `-g`,方便性能分析和调试。部署 Unix 二进制时默认会执行 strip同时把独立调试信息写入 `buildroot/debug/`
默认 PHP configure 命令还会启用 `--enable-re2c-cgoto`、禁用未选择的 SAPI 和共享 PHP 库,并只构建请求的扩展。这些选择能减少无关代码,实际运行效果仍取决于具体负载。
### macOS
macOS 默认使用 native target 和系统 Clang。v3 也通过 `SPC_USE_LLVM=brew``SPC_USE_LLVM=port` 支持 Homebrew、MacPorts 提供的较新 upstream LLVM。Homebrew 变体会把其中的 `clang``clang++``llvm-ar``llvm-ranlib` 作为一套完整工具链使用,避免与 Apple 自带工具混用。
Homebrew LLVM 是 StaticPHP 当前在 macOS 上采用的性能优化路径之一。较新的 optimizer 和 code-generation backend 在部分 PHP 版本及负载中可以生成运行性能更好的 PHP 二进制,也让项目不必等待 Apple 系统 Clang 的发布节奏即可评估新的编译器优化。这并不是固定的性能保证PHP VM 变化、CPU 架构、扩展、Opcache 和编译参数都会改变结果。项目的[性能测试 Issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838)表明编译器及优化等级的影响与版本和负载相关,后续的 [v3 工具链讨论](https://github.com/crazywhalecc/static-php-cli/issues/985#issuecomment-3860775962)则记录了增加 macOS LLVM 路径的动机,即获得不受 Apple 编译器版本限制的较新工具链。
| 变量 | 当前默认值 | 用途 |
|---|---|---|
| `SPC_DEFAULT_CFLAGS` | `--target=${MAC_ARCH}-apple-darwin -O3 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections` | 目标选择、优化、可观测性及 section 拆分 |
| `SPC_DEFAULT_CXXFLAGS` | `${SPC_DEFAULT_CFLAGS}` | 共用 C++ 参数 |
| `SPC_DEFAULT_LDFLAGS` | `-Wl,-dead_strip` | 移除不可达的 Mach-O 代码和数据 |
| PHP 附加参数 | `-g`、stack protection、PIC/PIE、hidden visibility 以及上述默认项 | PHP 和源码树内扩展编译 |
### Windows
Windows 使用 MSVC以及[对 PHP 源码的修改](./php-src-changes)中介绍的静态 CRT 补丁。PHP release 配置提供上游优化参数StaticPHP 会改写最终 CLI、CGI、micro 和 embed 的链接规则并加入 `/LTCG`。依赖的 CMake 构建通常使用 `/MT /Os /Ob1 /DNDEBUG`,个别 Package 可能选择其他 release 参数。
使用 `--no-strip`StaticPHP 会保留 PDB/调试信息,同时在改写的构建命令中继续使用 `/O2`。这是有意设计:调试符号与关闭优化是两件不同的事。
Windows FrankenPHP 通过 Clang/LLD 完成 CGO 链接。部分 Windows 库会明确禁用 `/GL`,因为该链接路径无法接受 MSVC LTCG object。最终链接行出现 `/LTCG`,并不意味着每个输入都参与了 whole-program optimization。
## 优化维度
StaticPHP 将性能视为多个彼此相关的指标,而不是单一分数。每个维度受到不同构建环节影响:
| 目标 | 通常记录为 | 主要影响项 |
|---|---|---|
| 请求吞吐量 | 固定并发下的 requests/s | SAPI 模式、Opcache、worker 模型、PHP 版本、编译器和 CPU target |
| 尾延迟 | p50/p95/p99 和错误率 | 负载、预热、竞争、worker 数量、JIT/Opcache、内存压力 |
| CLI 执行 | wall time、CPU time、peak RSS | 启动成本、Opcache CLI 设置、扩展集合、PHP/编译器版本 |
| 二进制体积 | 部署文件和调试文件字节数 | 扩展集合、section GC/dead stripping、符号精简、UPX |
| 可移植性 | 能运行该二进制的最旧 CPU/OS/libc | `SPC_TARGET`、CPU ISA 参数、静态或动态 libc |
| 构建速度 | 干净构建 wall time、峰值磁盘和内存 | `SPC_CONCURRENCY`、工具链、LTO/PGO、Package 数量 |
可比较的结果会保持 PHP 版本、commit、扩展、依赖版本、SAPI、ZTS/NTS、INI、目标 libc、编译器、CPU 频率策略及负载一致。
## 运行时优化层面
### 1. 可复现的配置覆盖
`config/env.custom.ini` 提供可复现的覆盖层,同时让 `config/env.ini` 保持为项目基线。配置值会替换完整默认字符串而不会自动追加,因此性能研究会保留基线,并一次隔离一个变化因素。
例如,面向 x86-64-v3 的研究会保留 Linux 默认值并加入对应 ISA level
```ini
[linux]
SPC_DEFAULT_CFLAGS="-fPIC -O3 -pipe -fno-plt -fno-semantic-interposition -fstack-clash-protection -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections -march=x86-64-v3"
SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}"
```
这可能让编译器使用更多向量和指令选择,但产物无法在低于该 ISA level 的 CPU 上运行。`-march=native` 会进一步收窄可移植性,使产物与构建机的 CPU 类型绑定。
PHP 范围的研究由 `SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS` 及其 C++ 对应项表示,而不是改变全局默认值。单个 Package 的研究使用 snake-case 变量,例如 `libaom_CFLAGS``libaom_CXXFLAGS``libaom_LDFLAGS`。当 Package 使用 v3 通用 executor 时Package 专用参数会与默认参数合并。
### 2. 工具链和 PHP 版本的影响
编译器造成的差异可能大于单个优化参数。[Issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838) 在部分 PHP 8.4 x86-64 测试中发现 GCC 与 Clang 之间有较大差异,因为较旧的 PHP VM 可以使用 GCC global register variable。该结果并不普遍适用架构、PHP 版本、VM 实现和负载都会影响结论PHP 8.5 的新 VM 也改变了这项比较。
Linux v3 默认使用 Zig是为了 target 灵活性和可复现的 libc 选择,并不代表它在所有负载下都一定生成最快的二进制。项目的性能工作会在实际部署架构上对比这个可预测基线与 native toolchain。在稳定的用户级选择器得到正式文档前`SPC_TOOLCHAIN` 仍属于内部/维护者控制项。
### 3. SAPI、线程安全及运行时配置
- FrankenPHP 要求 ZTS。CLI、FPM、CGI、micro 和 embed 默认保持 NTS只有所选 SAPI 或应用确实需要线程安全时才涉及 ZTS。
- Issue #838 的历史测试在特定测试集中观察到的 ZTS/NTS 差异较小;该结论仍局限于当时的负载。
- 加入 `ext-opcache` 只代表构建该扩展;它的性能特征还取决于运行时 INI包括重复 CLI 执行中的 `opcache.enable_cli` 和应用特定的 JIT 配置。
- `--disable-opcache-jit` 改变的是构建能力,不能代替运行时测试。在 Linux 构建 Opcache JIT 时StaticPHP 会在必要位置禁用 undefined-behavior sanitizer。
- FrankenPHP 性能还取决于 worker/classic 模式、worker 数量、应用启动行为、Caddy 模块及 Go runtime 设置。编译参数无法弥补不具代表性的服务器配置。
### 4. 速度、符号和压缩
Unix 默认部署流程会提取调试信息、精简运行时二进制,并单独保留调试文件。`--no-strip` 代表未精简形态,当前 v3 在这种形态下仍会保留优化参数。
`--with-upx-pack` 是 Linux 和 Windows 的体积优化。它可能改变启动时间、内存映射、安全工具行为和可调试性,因此项目将它视为打包取舍,而不是 PHP 执行性能优化。
## Profile-Guided OptimizationPGO
PGO 会先生成插桩程序,运行具有代表性的负载收集 profile然后根据观察到的分支、调用和值频率重新编译。这样编译器能够在代码布局、inline 和 hot/cold 决策方面超越静态启发式规则。
完整的 PGO 设计包含三个独立阶段:
1. **插桩阶段**使用相同的 PHP 版本、SAPI、扩展、依赖和 target并加入 profile-generation 参数完成构建。
2. **训练阶段**以具有代表性的流量比例和并发覆盖启动及重要生产路径,也包含正常关闭进程以 flush raw profile。
3. **Profile-use 阶段**通过匹配工具链的 profile 工具合并 raw profile并用 profile-use 参数重新构建完全一致的源码和配置。
Profile 是构建输入不是可移植的基准产物。PHP、扩展、依赖、编译器版本、参数、SAPI 链接方式或负载发生实质变化后,原有 profile 即会失效。范围过窄或已经过期的 profile 可能加速训练过的 route却让未训练路径变慢。
### StaticPHP PGO 状态
v3 的实验性设计正在探索面向 CLI、CGI、FPM、micro、embed 和 FrankenPHP 的独立 PGO context 与 lifecycle hook。目前评估的概念包括
- 插桩和 profile-use 阶段,以及可选的第二轮 context-sensitive 插桩;
- 每个 SAPI 独立的 raw-profile 目录和合并后的 `.profdata` 文件;
- 切换活动 SAPI profile 时执行干净重建;
- php-src 和 FrankenPHP 的 shutdown 补丁,因为 Go/CGO 进程不会可靠执行通常负责 flush profile 的 libc `atexit` 路径;
- LLVM profile 工具,以及 Zig、Clang、GCC 和 FrankenPHP 所需的特殊链接/runtime 处理。
这项工作尚未进入稳定的 v3 功能集。当前 v3 源码已经包含部分前置兼容处理,例如 FrankenPHP 在 native GCC 下发现手动 `-fprofile*` C 参数时,会忽略 missing-profile error 并链接 `libgcov`;完整的训练、合并、失效和重建编排仍在探索中。
仅把 `-fprofile-generate` 加入全局默认值并不等同于完整编排:它还会同时插桩依赖库、改变链接要求、增加构建和运行成本,并且可能无法 flush 出可用数据。因此,当前内部变量尚不构成稳定的发布流程。
### FrankenPHP 的 Go PGO
[PR #1142](https://github.com/crazywhalecc/static-php-cli/pull/1142) 在 v2 xcaddy 构建中加入了对 FrankenPHP 上游 `default.pgo` 的使用。这个 profile 使用随 FrankenPHP 分发的数据优化 Go 部分;它不会针对你的应用训练 php-src、PHP embed 库、扩展或 CGO glue。
未来的端到端 FrankenPHP PGO 设计可能同时包含两类 profile
- FrankenPHP 上游为 Go/Caddy 代码提供的 Go profile
- 针对 PHP、静态扩展和 CGO 链接 C 代码的应用专用编译器 profile。
两者的归属及失效规则,是当前设计探索中彼此独立的问题。
## Link-Time OptimizationLTO
LTO 会把编译器中间表示保留到链接阶段,让优化器跨 translation unit 工作。Full LTO 会更激进地处理合并后的程序ThinLTO 会分散更多工作,通常能降低内存及构建时间成本。
静态链接不会自动启用 LTO。反过来只给最终链接加入 `-flto` 也不够:相关 object 和 archive 必须由兼容的编译器、LTO mode、archiver、ranlib 及 linker plugin 生成。
Unix v3 默认不启用 LTO。历史工作让更多 archive 命令使用所选 `AR`,但项目后来移除了默认 LTO 尝试,因为跨依赖库维护兼容修复的成本过高。在 [Issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838) 的一个测试环境中,运行时提升只有约 2%ThinLTO 构建时间约变成两倍Full LTO 约变成七倍。这只是特定环境的历史测量结果,不是承诺的固定比例。
当前 Unix LTO 研究会考虑以下约束:
1. object、archive 和最终链接需要使用同一个兼容的 LLVM/Clang 或 GCC 工具链家族。
2. C、C++、PHP 和 linker 参数需要采用相同模式,例如 `-flto=thin`
3. 初期只覆盖 PHP 和源码树内扩展,有助于把核心结果与依赖库兼容性分开。
4. archive 内容和最终链接日志可以确认 LTO 是否进入预期 object仅构建成功并不能说明这一点。
5. SAPI 与扩展 smoke test、干净构建时间、二进制体积、吞吐量和尾延迟共同构成结果。
LTO 可能暴露 Package bug、不支持的汇编、archive 不兼容、符号导出问题以及 Go/CGO 链接限制,也可能增加代码体积或造成 instruction cache 退化。这些兼容性与维护成本,是 Unix LTO 在持续评估收益期间仍保持 opt-in 的原因。
## 性能证据与可复现性
StaticPHP 的性能研究会记录足够的上下文,使其他维护者可以复现结果:
- StaticPHP commit 以及 registry/Package revision
- PHP、FrankenPHP、Go、编译器、链接器和 profile 工具版本;
- 宿主与目标 OS、libc、架构以及完整的 `SPC_TARGET`
- CPU 型号、可用指令集、电源/频率策略、内存和虚拟化环境;
- 完整扩展与依赖集合、ZTS/NTS、SAPI、静态/动态链接方式和 INI
- 所有覆盖的环境变量,以及二进制是否 strip 或使用 UPX
- 负载源码 revision、数据集、route 比例、并发、持续时间、预热和重复次数;
- 中位数、波动范围、适用时的 p95/p99、peak RSS、二进制体积和干净构建时间。
项目会在同一台机器上交替运行基线和单项改动构建。多次重复和置信区间比一次最佳结果更有意义,基准脚本也会和原始测量结果一起保留。
## 历史记录与设计经验
以下已合并修改和 Issue 讨论解释了当前默认值和注意事项的来源。未合并的实现工作仅以技术概念的形式出现在本文其他位置。
| 记录 | 结果与经验 |
|---|---|
| [Issue #385](https://github.com/crazywhalecc/static-php-cli/issues/385),性能退化 | v2 的一条 `--no-strip` 路径同时选择了 `-O0`,使报告中的一个 Laravel 测试约慢了三倍。这促成了可定制 PHP 编译变量,并再次说明调试符号不能静默关闭优化。当前 v3 的 `--no-strip` 会保留优化参数。 |
| [PR #806](https://github.com/crazywhalecc/static-php-cli/pull/806)Zig 工具链 | 加入 target 灵活的 Zig 支持并记录构建/兼容性取舍;讨论中还包含静态/动态差异在 1% 内的观察,以及早期 GCC/Clang/Zig 对比。工具链选择部分是为了可移植性与 libc target而不只是基准速度。 |
| [Issue #838](https://github.com/crazywhalecc/static-php-cli/issues/838),性能测试 | 建立了可复现的编译器、ZTS/NTS、Opcache、LTO、架构及 PHP VM 对比。其结果为 `-O3` 默认值提供了背景,也展示了为什么结论必须绑定版本和负载。该 Issue 仍是主要的历史性能笔记。 |
| [Issue #985](https://github.com/crazywhalecc/static-php-cli/issues/985)v3 工具链 | 记录了优先采用可预测默认值同时保留性能导向替代方案的决策。Linux 对应 Zig 与 native GCC 路径macOS 的讨论也促成了较新 upstream LLVM 的接入,使构建不受 Apple 编译器发布节奏限制。 |
| [Issue #862](https://github.com/crazywhalecc/static-php-cli/issues/862)`--pgo=script.php` 提案 | 因一个通用训练脚本接口并不现实而关闭。PGO 需要感知 SAPI 的 lifecycle 编排,以及由用户负责的代表性训练。 |
| [PR #966](https://github.com/crazywhalecc/static-php-cli/pull/966),参数和 strip | 统一 PHP make 参数并改进独立调试信息精简流程,帮助解耦优化与符号处理。 |
| [PR #1142](https://github.com/crazywhalecc/static-php-cli/pull/1142)FrankenPHP Go PGO | 在 v2 构建中加入 FrankenPHP 自带 Go `default.pgo` 的使用;它不同于应用训练的 PHP/CGO PGO。 |
| [Issue #1088](https://github.com/crazywhalecc/static-php-cli/issues/1088)native intrinsic | 尚未关闭的设计需求,希望在依赖库与 PHP/扩展之间统一声明 CPU intrinsic level而不是手工管理每一项 ISA 参数。 |
| [PR #1150](https://github.com/crazywhalecc/static-php-cli/pull/1150)macOS `-fno-plt` | 因一个 ELF 专用参数破坏依赖 configure 检查,将其从 macOS 默认值移除。优化参数必须感知目标文件格式。 |
其中大部分调查和性能优化由 [@henderkes](https://github.com/henderkes) 主导,其他 StaticPHP 贡献者参与了 review、集成、平台修复和测试。随着这项工作继续推进项目会保留负载、原始结果和决策理由单个编译参数只是更广泛性能决策的最后一行。

View File

@@ -2,12 +2,12 @@
"scripts": { "scripts": {
"docs:dev": "node docs/.vitepress/gen-meta.js && vitepress dev docs", "docs:dev": "node docs/.vitepress/gen-meta.js && vitepress dev docs",
"docs:gen-meta": "node docs/.vitepress/gen-meta.js", "docs:gen-meta": "node docs/.vitepress/gen-meta.js",
"docs:build": "npm run docs:gen-meta && vitepress build docs", "docs:build": "node docs/.vitepress/gen-meta.js && vitepress build docs",
"docs:preview": "vitepress preview docs" "docs:preview": "vitepress preview docs"
}, },
"devDependencies": { "devDependencies": {
"mermaid": "^11.0.0", "mermaid": "^11.0.0",
"vitepress": "^2.0.0-alpha.5", "vitepress": "2.0.0-alpha.18",
"vue": "^3.2.47" "vue": "^3.2.47"
} }
} }

View File

@@ -17,4 +17,11 @@ class gmssl
FileSystem::replaceFileStr($target_path . '/src/hex.c', 'unsigned char *OPENSSL_hexstr2buf(const char *str, size_t *len)', 'unsigned char *GMSSL_hexstr2buf(const char *str, size_t *len)'); FileSystem::replaceFileStr($target_path . '/src/hex.c', 'unsigned char *OPENSSL_hexstr2buf(const char *str, size_t *len)', 'unsigned char *GMSSL_hexstr2buf(const char *str, size_t *len)');
FileSystem::replaceFileStr($target_path . '/src/hex.c', 'OPENSSL_hexchar2int', 'GMSSL_hexchar2int'); FileSystem::replaceFileStr($target_path . '/src/hex.c', 'OPENSSL_hexchar2int', 'GMSSL_hexchar2int');
} }
#[AfterSourceExtract('ext-gmssl')]
#[PatchDescription('Rename pbkdf2_hmac_sm3_genkey() to sm3_pbkdf2() (renamed upstream in GmSSL 3.2+; identical signature)')]
public function patchExt(string $target_path): void
{
FileSystem::replaceFileStr($target_path . '/gmssl.c', 'pbkdf2_hmac_sm3_genkey(', 'sm3_pbkdf2(');
}
} }

View File

@@ -25,7 +25,6 @@ class go_xcaddy
])] ])]
public function downBinary(ArtifactDownloader $downloader): DownloadResult public function downBinary(ArtifactDownloader $downloader): DownloadResult
{ {
$pkgroot = PKG_ROOT_PATH;
$name = SystemTarget::getCurrentPlatformString(); $name = SystemTarget::getCurrentPlatformString();
$arch = match (explode('-', $name)[1]) { $arch = match (explode('-', $name)[1]) {
'x86_64' => 'amd64', 'x86_64' => 'amd64',
@@ -64,7 +63,7 @@ class go_xcaddy
if ($file_hash !== $hash) { if ($file_hash !== $hash) {
throw new DownloaderException("Hash mismatch for downloaded go-xcaddy binary. Expected {$hash}, got {$file_hash}"); throw new DownloaderException("Hash mismatch for downloaded go-xcaddy binary. Expected {$hash}, got {$file_hash}");
} }
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: "{$pkgroot}/go-xcaddy", verified: true, version: $version); return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: '{pkg_root_path}/go-xcaddy', verified: true, version: $version);
} }
#[CustomBinaryCheckUpdate('go-xcaddy', [ #[CustomBinaryCheckUpdate('go-xcaddy', [
@@ -109,7 +108,7 @@ class go_xcaddy
'GOROOT' => "{$target_path}", 'GOROOT' => "{$target_path}",
'GOBIN' => "{$target_path}/bin", 'GOBIN' => "{$target_path}/bin",
'GOPATH' => "{$target_path}/go", 'GOPATH' => "{$target_path}/go",
])->exec('CC=cc go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest'); ])->exec('CGO_ENABLED=0 go install github.com/caddyserver/xcaddy/cmd/xcaddy@master');
GlobalEnvManager::addPathIfNotExists("{$target_path}/bin"); GlobalEnvManager::addPathIfNotExists("{$target_path}/bin");
} }
} }

View File

@@ -17,7 +17,9 @@ class bzip2
#[PatchBeforeBuild] #[PatchBeforeBuild]
public function patchBeforeBuild(LibraryPackage $lib): void public function patchBeforeBuild(LibraryPackage $lib): void
{ {
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', 'CFLAGS=-fPIC -Wall'); // Inject SPC_DEFAULT_CFLAGS into the Makefile
$extra = deduplicate_flags(trim((string) getenv('SPC_DEFAULT_CFLAGS')) . ' -Wall');
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', "CFLAGS={$extra}");
} }
#[BuildFor('Windows')] #[BuildFor('Windows')]

View File

@@ -18,9 +18,11 @@ class fastlz
{ {
$cc = getenv('CC') ?: 'cc'; $cc = getenv('CC') ?: 'cc';
$ar = getenv('AR') ?: 'ar'; $ar = getenv('AR') ?: 'ar';
$extra = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
$extra = $extra !== '' ? $extra . ' -fPIC' : '-O3 -fPIC';
shell()->cd($lib->getSourceDir())->initializeEnv($lib) shell()->cd($lib->getSourceDir())->initializeEnv($lib)
->exec("{$cc} -c -O3 -fPIC fastlz.c -o fastlz.o") ->exec("{$cc} -c {$extra} fastlz.c -o fastlz.o")
->exec("{$ar} rcs libfastlz.a fastlz.o"); ->exec("{$ar} rcs libfastlz.a fastlz.o");
// Copy header file // Copy header file

View File

@@ -24,9 +24,12 @@ class icu
#[BuildFor('Linux')] #[BuildFor('Linux')]
public function buildLinux(LibraryPackage $lib, ToolchainInterface $toolchain, PackageBuilder $builder): void public function buildLinux(LibraryPackage $lib, ToolchainInterface $toolchain, PackageBuilder $builder): void
{ {
// runConfigureICU bakes CXXFLAGS/LDFLAGS, apply user flags too
$userCxxFlags = trim((string) getenv('SPC_DEFAULT_CXXFLAGS'));
$userLdFlags = trim((string) getenv('SPC_DEFAULT_LDFLAGS'));
$cppflags = 'CPPFLAGS="-DU_CHARSET_IS_UTF8=1 -DU_USING_ICU_NAMESPACE=1 -DU_STATIC_IMPLEMENTATION=1 -DPIC -fPIC"'; $cppflags = 'CPPFLAGS="-DU_CHARSET_IS_UTF8=1 -DU_USING_ICU_NAMESPACE=1 -DU_STATIC_IMPLEMENTATION=1 -DPIC -fPIC"';
$cxxflags = 'CXXFLAGS="-std=c++17 -DPIC -fPIC -fno-ident"'; $cxxflags = "CXXFLAGS=\"-std=c++17 -DPIC -fPIC -fno-ident {$userCxxFlags}\"";
$ldflags = $toolchain->isStatic() ? 'LDFLAGS="-static"' : ''; $ldflags = $toolchain->isStatic() ? "LDFLAGS=\"-static {$userLdFlags}\"" : "LDFLAGS=\"{$userLdFlags}\"";
shell()->cd($lib->getSourceDir() . '/source')->initializeEnv($lib) shell()->cd($lib->getSourceDir() . '/source')->initializeEnv($lib)
->exec( ->exec(
"{$cppflags} {$cxxflags} {$ldflags} " . "{$cppflags} {$cxxflags} {$ldflags} " .

View File

@@ -17,7 +17,9 @@ class jbig
#[PatchBeforeBuild] #[PatchBeforeBuild]
public function patchBeforeBuild(LibraryPackage $lib): void public function patchBeforeBuild(LibraryPackage $lib): void
{ {
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS = -O2 -W -Wno-unused-result', 'CFLAGS = -O2 -W -Wno-unused-result -fPIC'); $extra = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
$cflags = ($extra !== '' ? $extra : '-O2') . ' -W -Wno-unused-result -fPIC';
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS = -O2 -W -Wno-unused-result', "CFLAGS = {$cflags}");
} }
#[BuildFor('Darwin')] #[BuildFor('Darwin')]

View File

@@ -9,8 +9,10 @@ use StaticPHP\Attribute\Package\Library;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixCMakeExecutor; use StaticPHP\Runtime\Executor\UnixCMakeExecutor;
use StaticPHP\Runtime\Executor\WindowsCMakeExecutor; use StaticPHP\Runtime\Executor\WindowsCMakeExecutor;
use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\Interface\ToolchainInterface; use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ZigToolchain; use StaticPHP\Toolchain\ZigToolchain;
use StaticPHP\Util\System\UnixUtil;
#[Library('libaom')] #[Library('libaom')]
class libaom extends LibraryPackage class libaom extends LibraryPackage
@@ -39,9 +41,27 @@ class libaom extends LibraryPackage
$new = trim($extra . ' -D_GNU_SOURCE'); $new = trim($extra . ' -D_GNU_SOURCE');
f_putenv("SPC_COMPILER_EXTRA={$new}"); f_putenv("SPC_COMPILER_EXTRA={$new}");
} }
$targetCpu = SystemTarget::getTargetArch();
if (str_starts_with($targetCpu, 'aarch')) {
$targetCpu = str_replace('aarch', 'arm', $targetCpu);
}
if (
in_array($targetCpu, ['x86', 'x86_64'], true)
&& !UnixUtil::findCommand('nasm')
&& !UnixUtil::findCommand('yasm')
) {
$targetCpu = 'generic';
}
UnixCMakeExecutor::create($this) UnixCMakeExecutor::create($this)
->setBuildDir("{$this->getSourceDir()}/builddir") ->setBuildDir("{$this->getSourceDir()}/builddir")
->addConfigureArgs('-DAOM_TARGET_CPU=generic') ->addConfigureArgs(
"-DAOM_TARGET_CPU={$targetCpu}",
'-DCONFIG_RUNTIME_CPU_DETECT=1',
'-DENABLE_EXAMPLES=OFF',
'-DENABLE_TESTS=OFF',
'-DENABLE_TOOLS=OFF',
'-DENABLE_DOCS=OFF',
)
->build(); ->build();
f_putenv("SPC_COMPILER_EXTRA={$extra}"); f_putenv("SPC_COMPILER_EXTRA={$extra}");
$this->patchPkgconfPrefix(['aom.pc']); $this->patchPkgconfPrefix(['aom.pc']);

View File

@@ -8,6 +8,7 @@ use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Library; use StaticPHP\Attribute\Package\Library;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor; use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Runtime\SystemTarget;
#[Library('libffi')] #[Library('libffi')]
class libffi extends LibraryPackage class libffi extends LibraryPackage
@@ -28,7 +29,7 @@ class libffi extends LibraryPackage
#[BuildFor('Darwin')] #[BuildFor('Darwin')]
public function buildDarwin(): void public function buildDarwin(): void
{ {
$arch = getenv('SPC_ARCH'); $arch = SystemTarget::getTargetArch();
UnixAutoconfExecutor::create($this) UnixAutoconfExecutor::create($this)
->configure( ->configure(
"--host={$arch}-apple-darwin", "--host={$arch}-apple-darwin",

View File

@@ -24,6 +24,17 @@ class libheif
'list(APPEND REQUIRES_PRIVATE "libbrotlidec")' . "\n" . ' list(APPEND REQUIRES_PRIVATE "libbrotlienc")' 'list(APPEND REQUIRES_PRIVATE "libbrotlidec")' . "\n" . ' list(APPEND REQUIRES_PRIVATE "libbrotlienc")'
); );
} }
// libheif 1.22+ ships a C-incompatible header: `struct heif_bad_pixel`
$heif_properties = $lib->getSourceDir() . '/libheif/api/libheif/heif_properties.h';
if (file_exists($heif_properties)
&& str_contains(file_get_contents($heif_properties), 'struct heif_bad_pixel { uint32_t row; uint32_t column; };')
) {
FileSystem::replaceFileStr(
$heif_properties,
'struct heif_bad_pixel { uint32_t row; uint32_t column; };',
'typedef struct heif_bad_pixel { uint32_t row; uint32_t column; } heif_bad_pixel;'
);
}
} }
#[BuildFor('Darwin')] #[BuildFor('Darwin')]

View File

@@ -6,6 +6,8 @@ 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\PatchBeforeBuild;
use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor; use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Toolchain\Interface\ToolchainInterface; use StaticPHP\Toolchain\Interface\ToolchainInterface;
@@ -16,6 +18,24 @@ use StaticPHP\Util\FileSystem;
#[Library('ncursesw')] #[Library('ncursesw')]
class ncurses class ncurses
{ {
#[PatchBeforeBuild]
#[PatchDescription('Filter clang/zig "N warning(s) generated." line out of MKlib_gen.sh preprocessor pipe')]
public function patchBeforeBuild(LibraryPackage $lib): void
{
// MKlib_gen.sh feeds the C preprocessor's stdout through a sed/awk
// pipeline into lib_gen.c. zig-cc/clang emits "N warning(s) generated."
// on stdout (not stderr), and that line ends up as invalid C in the
// generated source. Filter it out of the pipe before sed sees it.
$mklibGen = $lib->getSourceDir() . '/ncurses/base/MKlib_gen.sh';
if (is_file($mklibGen) && !str_contains((string) file_get_contents($mklibGen), "| grep -v ' generated")) {
FileSystem::replaceFileStr(
$mklibGen,
'$preprocessor $TMP 2>/dev/null \\',
"\$preprocessor \$TMP 2>/dev/null \\\n| grep -v ' generated\\.\$' \\",
);
}
}
#[BuildFor('Darwin')] #[BuildFor('Darwin')]
#[BuildFor('Linux')] #[BuildFor('Linux')]
public function build(LibraryPackage $package, ToolchainInterface $toolchain): void public function build(LibraryPackage $package, ToolchainInterface $toolchain): void
@@ -45,6 +65,7 @@ class ncurses
'--without-tests', '--without-tests',
'--without-dlsym', '--without-dlsym',
'--without-debug', '--without-debug',
'--disable-stripping',
'--enable-symlinks', '--enable-symlinks',
"--with-terminfo-dirs={$terminfo_dirs}", "--with-terminfo-dirs={$terminfo_dirs}",
"--bindir={$package->getBinDir()}", "--bindir={$package->getBinDir()}",

View File

@@ -11,6 +11,7 @@ use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\ToolPackage; use StaticPHP\Package\ToolPackage;
use StaticPHP\Registry\PackageLoader; use StaticPHP\Registry\PackageLoader;
use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\System\LinuxUtil; use StaticPHP\Util\System\LinuxUtil;
@@ -57,7 +58,11 @@ class openssl
public function buildForDarwin(LibraryPackage $pkg): void public function buildForDarwin(LibraryPackage $pkg): void
{ {
$zlib_libs = $pkg->getInstaller()->getLibraryPackage('zlib')->getStaticLibFiles(); $zlib_libs = $pkg->getInstaller()->getLibraryPackage('zlib')->getStaticLibFiles();
$arch = getenv('SPC_ARCH'); $targetArch = SystemTarget::getTargetArch();
$arch = match ($targetArch) {
'aarch64' => 'arm64',
default => $targetArch,
};
shell()->cd($pkg->getSourceDir())->initializeEnv($pkg) shell()->cd($pkg->getSourceDir())->initializeEnv($pkg)
->exec( ->exec(
@@ -76,12 +81,7 @@ class openssl
#[BuildFor('Linux')] #[BuildFor('Linux')]
public function build(LibraryPackage $lib): void public function build(LibraryPackage $lib): void
{ {
$arch = getenv('SPC_ARCH'); $arch = SystemTarget::getTargetArch();
$env = "CC='" . getenv('CC') . ' -idirafter ' . BUILD_INCLUDE_PATH .
' -idirafter /usr/include/ ' .
' -idirafter /usr/include/' . getenv('SPC_ARCH') . '-linux-gnu/ ' .
"' ";
$ex_lib = trim($lib->getInstaller()->getLibraryPackage('zlib')->getStaticLibFiles()) . ' -ldl -pthread'; $ex_lib = trim($lib->getInstaller()->getLibraryPackage('zlib')->getStaticLibFiles()) . ' -ldl -pthread';
$zlib_extra = $zlib_extra =
@@ -92,9 +92,15 @@ class openssl
$openssl_dir ??= LinuxUtil::getOSRelease()['dist'] === 'redhat' ? '/etc/pki/tls' : '/etc/ssl'; $openssl_dir ??= LinuxUtil::getOSRelease()['dist'] === 'redhat' ? '/etc/pki/tls' : '/etc/ssl';
$ex_lib = trim($ex_lib); $ex_lib = trim($ex_lib);
// anything we want included (PGO -fprofile-*, LTO, custom hardening)
// has to be appended on the command line *after* the target name.
$userCFlags = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
$userLdFlags = trim((string) getenv('SPC_DEFAULT_LDFLAGS'));
$userExtra = trim($userCFlags . ' ' . $userLdFlags);
shell()->cd($lib->getSourceDir())->initializeEnv($lib) shell()->cd($lib->getSourceDir())->initializeEnv($lib)
->exec( ->exec(
"{$env} ./Configure no-shared zlib " . './Configure no-shared zlib ' .
"--prefix={$lib->getBuildRootPath()} " . "--prefix={$lib->getBuildRootPath()} " .
"--libdir={$lib->getLibDir()} " . "--libdir={$lib->getLibDir()} " .
"--openssldir={$openssl_dir} " . "--openssldir={$openssl_dir} " .
@@ -102,7 +108,8 @@ class openssl
'enable-pie ' . 'enable-pie ' .
'no-legacy ' . 'no-legacy ' .
'no-tests ' . 'no-tests ' .
"linux-{$arch}" "linux-{$arch} " .
$userExtra
) )
->exec('make clean') ->exec('make clean')
->exec("make -j{$lib->getBuilder()->concurrency} CNF_EX_LIBS=\"{$ex_lib}\"") ->exec("make -j{$lib->getBuilder()->concurrency} CNF_EX_LIBS=\"{$ex_lib}\"")

View File

@@ -14,17 +14,18 @@ trait GitHubTokenSetupTrait
public static function getGitHubTokenHeadersStatic(): array public static function getGitHubTokenHeadersStatic(): array
{ {
// GITHUB_TOKEN support // GITHUB_TOKEN support
if (($token = getenv('GITHUB_TOKEN')) !== false && ($user = getenv('GITHUB_USER')) !== false) { $token = getenv('GITHUB_TOKEN');
if ($token === false || $token === '') {
return [];
}
if (($user = getenv('GITHUB_USER')) !== false && $user !== '') {
logger()->debug("Using 'GITHUB_TOKEN' with user {$user} for authentication"); logger()->debug("Using 'GITHUB_TOKEN' with user {$user} for authentication");
$encoded = base64_encode("{$user}:{$token}"); $encoded = base64_encode("{$user}:{$token}");
spc_add_log_filter([$user, $token, $encoded]); spc_add_log_filter([$user, $token, $encoded]);
return ["Authorization: Basic {$encoded}"]; return ["Authorization: Basic {$encoded}"];
} }
if (($token = getenv('GITHUB_TOKEN')) !== false) { logger()->debug("Using 'GITHUB_TOKEN' for authentication");
logger()->debug("Using 'GITHUB_TOKEN' for authentication"); spc_add_log_filter($token);
spc_add_log_filter($token); return ["Authorization: Bearer {$token}"];
return ["Authorization: Bearer {$token}"];
}
return [];
} }
} }

View File

@@ -1,115 +0,0 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Doctor\Item;
use StaticPHP\Artifact\ArtifactCache;
use StaticPHP\Artifact\ArtifactDownloader;
use StaticPHP\Artifact\ArtifactExtractor;
use StaticPHP\Attribute\Doctor\CheckItem;
use StaticPHP\Attribute\Doctor\FixItem;
use StaticPHP\Attribute\Doctor\OptionalCheck;
use StaticPHP\DI\ApplicationContext;
use StaticPHP\Doctor\CheckResult;
use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\MuslToolchain;
use StaticPHP\Toolchain\ZigToolchain;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm;
use StaticPHP\Util\SourcePatcher;
use StaticPHP\Util\System\LinuxUtil;
#[OptionalCheck([self::class, 'optionalCheck'])]
class LinuxMuslCheck
{
public static function optionalCheck(): bool
{
$toolchain = ApplicationContext::get(ToolchainInterface::class);
return $toolchain instanceof MuslToolchain || $toolchain instanceof ZigToolchain && !LinuxUtil::isMuslDist() && !str_contains(getenv('SPC_TARGET') ?: '', 'gnu');
}
/** @noinspection PhpUnused */
#[CheckItem('if musl-wrapper is installed', limit_os: 'Linux', level: 800)]
public function checkMusl(): ?CheckResult
{
$musl_wrapper_lib = sprintf('/lib/ld-musl-%s.so.1', php_uname('m'));
if (file_exists($musl_wrapper_lib) && (file_exists('/usr/local/musl/lib/libc.a') || getenv('SPC_TOOLCHAIN') === ZigToolchain::class)) {
return null;
}
return CheckResult::fail('musl-wrapper is not installed on your system', 'fix-musl-wrapper');
}
#[CheckItem('if musl-cross-make is installed', limit_os: 'Linux', level: 799)]
public function checkMuslCrossMake(): ?CheckResult
{
if (getenv('SPC_TOOLCHAIN') === ZigToolchain::class && !LinuxUtil::isMuslDist()) {
return null;
}
$arch = arch2gnu(php_uname('m'));
$cross_compile_lib = "/usr/local/musl/{$arch}-linux-musl/lib/libc.a";
$cross_compile_gcc = "/usr/local/musl/bin/{$arch}-linux-musl-gcc";
if (file_exists($cross_compile_lib) && file_exists($cross_compile_gcc)) {
return CheckResult::ok();
}
return CheckResult::fail('musl-cross-make is not installed on your system', 'fix-musl-cross-make');
}
#[FixItem('fix-musl-wrapper')]
public function fixMusl(): bool
{
$downloader = new ArtifactDownloader(interactive: false);
$downloader->add('musl-wrapper')->download();
$extractor = new ArtifactExtractor(ApplicationContext::get(ArtifactCache::class));
$extractor->extract('musl-wrapper');
// Apply CVE-2025-26519 patch and install musl wrapper
SourcePatcher::patchFile('musl-1.2.5_CVE-2025-26519_0001.patch', SOURCE_PATH . '/musl-wrapper');
SourcePatcher::patchFile('musl-1.2.5_CVE-2025-26519_0002.patch', SOURCE_PATH . '/musl-wrapper');
$prefix = '';
if (get_current_user() !== 'root') {
$prefix = 'sudo ';
logger()->warning('Current user is not root, using sudo for running command');
}
$sysEnv = ['CC' => 'gcc', 'CXX' => 'g++', 'AR' => 'ar', 'LD' => 'ld', 'RANLIB' => 'ranlib'];
$envFlags = '';
foreach ($sysEnv as $k => $v) {
$envFlags .= "{$k}={$v} ";
}
$envFlags = rtrim($envFlags);
$shell = shell()->cd(SOURCE_PATH . '/musl-wrapper')
->setEnv($sysEnv)
->exec('./configure --disable-gcc-wrapper')
->exec('make -j');
if ($prefix !== '') {
f_passthru('cd ' . SOURCE_PATH . "/musl-wrapper && {$envFlags} {$prefix}make install");
} else {
$shell->exec("{$prefix}make install");
}
return true;
}
#[FixItem('fix-musl-cross-make')]
public function fixMuslCrossMake(): bool
{
// sudo
$prefix = '';
if (get_current_user() !== 'root') {
$prefix = 'sudo ';
logger()->warning('Current user is not root, using sudo for running command');
}
Shell::passthruCallback(function () {
InteractiveTerm::advance();
});
$downloader = new ArtifactDownloader(interactive: false);
$extractor = new ArtifactExtractor(ApplicationContext::get(ArtifactCache::class));
$downloader->add('musl-toolchain')->download();
$extractor->extract('musl-toolchain');
$pkg_root = PKG_ROOT_PATH . '/musl-toolchain';
f_passthru("{$prefix}cp -rf {$pkg_root}/* /usr/local/musl");
FileSystem::removeDir($pkg_root);
return true;
}
}

View File

@@ -173,6 +173,9 @@ class SourcePatcher
*/ */
public static function patchMicroPhar(int $version_id): void public static function patchMicroPhar(int $version_id): void
{ {
if (file_exists(SOURCE_PATH . '/php-src/ext/phar/phar.c.bak')) {
return;
}
FileSystem::backupFile(SOURCE_PATH . '/php-src/ext/phar/phar.c'); FileSystem::backupFile(SOURCE_PATH . '/php-src/ext/phar/phar.c');
FileSystem::replaceFileStr( FileSystem::replaceFileStr(
SOURCE_PATH . '/php-src/ext/phar/phar.c', SOURCE_PATH . '/php-src/ext/phar/phar.c',
@@ -198,6 +201,12 @@ class SourcePatcher
public static function unpatchMicroPhar(): void public static function unpatchMicroPhar(): void
{ {
// Tolerate a missing .bak: both drivers call this, and the first restore
// consumes the backup. Without this guard the second call throws
// "Cannot find bak file". No .bak means the source is already pristine.
if (!file_exists(SOURCE_PATH . '/php-src/ext/phar/phar.c.bak')) {
return;
}
FileSystem::restoreBackupFile(SOURCE_PATH . '/php-src/ext/phar/phar.c'); FileSystem::restoreBackupFile(SOURCE_PATH . '/php-src/ext/phar/phar.c');
} }

1620
yarn.lock

File diff suppressed because it is too large Load Diff