mirror of
https://github.com/crazywhalecc/static-php-cli.git
synced 2026-07-11 02:45:37 +08:00
Compare commits
123 Commits
cd803c75c5
...
feat/pgo-v
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a65441bbeb | ||
|
|
6b6a099a47 | ||
|
|
8f557aae8a | ||
|
|
3b8abda8c9 | ||
|
|
5747a5661e | ||
|
|
d52ba59edc | ||
|
|
2d5abd31c1 | ||
|
|
69d0f9b8cc | ||
|
|
d846db2ef2 | ||
|
|
f06891155c | ||
|
|
15deecd34f | ||
|
|
7ae5d742c2 | ||
|
|
95be291a84 | ||
|
|
d89add106a | ||
|
|
a36129c6cd | ||
|
|
3f3edd62a1 | ||
|
|
82b77af317 | ||
|
|
df26b93e58 | ||
|
|
d1b4c05381 | ||
|
|
e1658bc0e6 | ||
|
|
5053620b61 | ||
|
|
9366cbacd9 | ||
|
|
fe4803cfaf | ||
|
|
80d81079db | ||
|
|
6ab52a5181 | ||
|
|
5bdcd3f562 | ||
|
|
203fed65d9 | ||
|
|
1ae989df59 | ||
|
|
e7fb1e203f | ||
|
|
713f8255af | ||
|
|
3c24c92d61 | ||
|
|
d93fdd9707 | ||
|
|
c40d069b0c | ||
|
|
9d508f1d39 | ||
|
|
a23ad55fe2 | ||
|
|
735f12648e | ||
|
|
6fe55a4d6b | ||
|
|
b8ce9f7787 | ||
|
|
6772403d81 | ||
|
|
60a91a82e1 | ||
|
|
4a274b69ac | ||
|
|
e4edd0a00f | ||
|
|
ae26ef3bdb | ||
|
|
049ecfe0a5 | ||
|
|
01a4d872ad | ||
|
|
a9e54bb725 | ||
|
|
f1525c0ca7 | ||
|
|
ad9b9ec69f | ||
|
|
8a37303925 | ||
|
|
52d234f1f4 | ||
|
|
a3c39576df | ||
|
|
433043c0c8 | ||
|
|
b38c7b274f | ||
|
|
efa7946c14 | ||
|
|
7bb4a09a3c | ||
|
|
3eca044895 | ||
|
|
32da708f54 | ||
|
|
f27ec773a1 | ||
|
|
ce70c0df6a | ||
|
|
fdc75cb9fe | ||
|
|
697040b918 | ||
|
|
19d1379f7d | ||
|
|
07aae79cae | ||
|
|
4b19f4ec95 | ||
|
|
1707d21569 | ||
|
|
70e717adb6 | ||
|
|
a88e426623 | ||
|
|
6fda358c90 | ||
|
|
09de4c9c70 | ||
|
|
db794bf27b | ||
|
|
b880ef7003 | ||
|
|
9addbe2c7d | ||
|
|
445c0b36c9 | ||
|
|
4754faf43e | ||
|
|
2415b7db35 | ||
|
|
814014e122 | ||
|
|
defd50f459 | ||
|
|
57ef0423d5 | ||
|
|
8453f69eea | ||
|
|
c1c34d8c10 | ||
|
|
270e2d6471 | ||
|
|
4172508cb9 | ||
|
|
a585359b28 | ||
|
|
bfaa7ebb3a | ||
|
|
7e6e9d869e | ||
|
|
3f7bad75ec | ||
|
|
a3f135d26c | ||
|
|
0732c1f0b0 | ||
|
|
9b64ad8299 | ||
|
|
743934d1fe | ||
|
|
efdd2a74a5 | ||
|
|
4d1ae0093d | ||
|
|
db11d5a420 | ||
|
|
b20c1fa5c2 | ||
|
|
6e3267273b | ||
|
|
bf38212814 | ||
|
|
42fdc4eb87 | ||
|
|
685f5c565f | ||
|
|
4f7694267b | ||
|
|
b8ee484e81 | ||
|
|
c186038dca | ||
|
|
36e738f849 | ||
|
|
2cc3c8c9af | ||
|
|
0469b658bf | ||
|
|
7107566da7 | ||
|
|
02d8f51bb2 | ||
|
|
21c868463a | ||
|
|
079a30c5b1 | ||
|
|
64d9650f88 | ||
|
|
e63d49ec13 | ||
|
|
9dbb178bf3 | ||
|
|
3f48413281 | ||
|
|
dc6e63e1ba | ||
|
|
6ad4b6a4af | ||
|
|
270f131f54 | ||
|
|
ceade306b8 | ||
|
|
629b5b6b2d | ||
|
|
7b79767355 | ||
|
|
2ed4b10260 | ||
|
|
184a091fd9 | ||
|
|
e6642459b8 | ||
|
|
af3c6a6d08 | ||
|
|
e930873e60 |
11
.github/pull_request_template.md
vendored
11
.github/pull_request_template.md
vendored
@@ -1,17 +1,12 @@
|
||||
## What does this PR do?
|
||||
|
||||
<!-- Please describe the changes made in this PR here. -->
|
||||
|
||||
|
||||
## Checklist before merging
|
||||
|
||||
> If your PR involves the changes mentioned below and completed the action, please tick the corresponding option.
|
||||
> If a modification is not involved, please skip it directly.
|
||||
|
||||
- If you modified `*.php` or `*.json`, run them locally to ensure your changes are valid:
|
||||
- If you modified `*.php` or `*.yml`, run them locally to ensure your changes are valid:
|
||||
- [ ] `composer cs-fix`
|
||||
- [ ] `composer analyse`
|
||||
- [ ] `composer test`
|
||||
- [ ] `bin/spc dev:sort-config`
|
||||
- If it's an extension or dependency update, please ensure the following:
|
||||
- [ ] Add your test combination to `src/globals/test-extensions.php`.
|
||||
- [ ] If adding new or fixing bugs, add commit message containing `extension test` or `test extensions` to trigger full test suite.
|
||||
- [ ] `bin/spc dev:lint-config`
|
||||
|
||||
251
.github/workflows/tests.yml
vendored
251
.github/workflows/tests.yml
vendored
@@ -1,9 +1,9 @@
|
||||
name: Tests
|
||||
name: v3 Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [ "main", "v3" ]
|
||||
types: [ opened, synchronize, reopened ]
|
||||
branches: [ "v3" ]
|
||||
types: [ opened, synchronize, reopened, labeled, unlabeled ]
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'config/**'
|
||||
@@ -15,6 +15,10 @@ on:
|
||||
|
||||
permissions: read-all
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -103,114 +107,171 @@ jobs:
|
||||
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
|
||||
|
||||
- name: "Run PHPUnit Tests"
|
||||
run: SPC_LIBC=glibc vendor/bin/phpunit tests/ --no-coverage
|
||||
run: vendor/bin/phpunit tests/ --no-coverage
|
||||
|
||||
define-matrix:
|
||||
if: false # TODO: enable when refactoring workflows
|
||||
name: "Define Matrix"
|
||||
check-gate:
|
||||
name: "Check: need-test label"
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
php: ${{ steps.gendef.outputs.php }}
|
||||
os: ${{ steps.gendef.outputs.os }}
|
||||
enabled: ${{ steps.gate.outputs.enabled }}
|
||||
steps:
|
||||
- name: "Checkout"
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: "Setup PHP"
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: 8.4
|
||||
extensions: curl, openssl, mbstring
|
||||
|
||||
- name: Define
|
||||
id: gendef
|
||||
- name: Check label
|
||||
id: gate
|
||||
run: |
|
||||
PHP_VERSIONS=$(php src/globals/test-extensions.php php)
|
||||
OS_VERSIONS=$(php src/globals/test-extensions.php os)
|
||||
echo 'php='"$PHP_VERSIONS" >> "$GITHUB_OUTPUT"
|
||||
echo 'os='"$OS_VERSIONS" >> "$GITHUB_OUTPUT"
|
||||
LABELS='${{ toJSON(github.event.pull_request.labels.*.name) }}'
|
||||
if echo "$LABELS" | grep -q '"need-test"'; then
|
||||
echo "enabled=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "enabled=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
|
||||
build:
|
||||
if: false
|
||||
name: "Build PHP Test (PHP ${{ matrix.php }} ${{ matrix.os }})"
|
||||
runs-on: ${{ matrix.os }}
|
||||
needs: [define-matrix, php-cs-fixer, phpstan, phpunit]
|
||||
timeout-minutes: 120
|
||||
strategy:
|
||||
matrix:
|
||||
php: ${{ fromJSON(needs.define-matrix.outputs.php) }}
|
||||
os: ${{ fromJSON(needs.define-matrix.outputs.os) }}
|
||||
fail-fast: false
|
||||
test-bot:
|
||||
name: "Test Bot: analyze PR"
|
||||
needs: check-gate
|
||||
if: needs.check-gate.outputs.enabled == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: read
|
||||
outputs:
|
||||
need_test: ${{ steps.bot.outputs.need_test }}
|
||||
gen_matrix_args: ${{ steps.bot.outputs.gen_matrix_args }}
|
||||
gen_matrix_args_tier2: ${{ steps.bot.outputs.gen_matrix_args_tier2 }}
|
||||
php_versions: ${{ steps.bot.outputs.php_versions }}
|
||||
tier2: ${{ steps.bot.outputs.tier2 }}
|
||||
steps:
|
||||
- name: "Update runner packages"
|
||||
if: ${{ startsWith(matrix.os, 'ubuntu-') }}
|
||||
run: sudo apt-get update && sudo apt-get install -y ca-certificates
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: "Checkout"
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: "Setup PHP"
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: 8.4
|
||||
tools: pecl, composer
|
||||
php-version: '8.4'
|
||||
extensions: curl, openssl, mbstring
|
||||
ini-values: memory_limit=-1
|
||||
tools: composer
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev
|
||||
|
||||
- name: Run dev:test-bot
|
||||
id: bot
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
BOT_JSON=$(php -d opcache.enable_cli=0 bin/spc dev:test-bot \
|
||||
--pr=${{ github.event.pull_request.number }} \
|
||||
--repo=${{ github.repository }} 2>/dev/null)
|
||||
|
||||
echo "need_test=$(echo "$BOT_JSON" | jq -r '.need_test')" >> "$GITHUB_OUTPUT"
|
||||
echo "gen_matrix_args=$(echo "$BOT_JSON" | jq -r '.gen_matrix_args')" >> "$GITHUB_OUTPUT"
|
||||
echo "gen_matrix_args_tier2=$(echo "$BOT_JSON" | jq -r '.gen_matrix_args_tier2')" >> "$GITHUB_OUTPUT"
|
||||
echo "php_versions=$(echo "$BOT_JSON" | jq -c '.php_versions')" >> "$GITHUB_OUTPUT"
|
||||
echo "tier2=$(echo "$BOT_JSON" | jq -r '.tier2')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
COMMENT_BODY=$(echo "$BOT_JSON" | jq -r '.comment_body')
|
||||
MARKER="<!-- spc-test-bot -->"
|
||||
|
||||
# Find existing bot comment id
|
||||
EXISTING_ID=$(gh api \
|
||||
repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments \
|
||||
--jq "[.[] | select(.body | startswith(\"$MARKER\")) | .id] | first // empty")
|
||||
|
||||
if [ -n "$EXISTING_ID" ]; then
|
||||
gh api --method PATCH \
|
||||
repos/${{ github.repository }}/issues/comments/"$EXISTING_ID" \
|
||||
-f body="$COMMENT_BODY"
|
||||
else
|
||||
gh pr comment ${{ github.event.pull_request.number }} \
|
||||
--repo ${{ github.repository }} \
|
||||
--body "$COMMENT_BODY"
|
||||
fi
|
||||
|
||||
gen-matrix:
|
||||
name: "Generate test matrix"
|
||||
needs: test-bot
|
||||
if: needs.test-bot.outputs.need_test == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.build.outputs.matrix }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: curl, openssl, mbstring
|
||||
ini-values: memory_limit=-1
|
||||
tools: composer
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev
|
||||
|
||||
- name: Build matrix
|
||||
id: build
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GEN_MATRIX_ARGS: ${{ needs.test-bot.outputs.gen_matrix_args }}
|
||||
GEN_MATRIX_ARGS_TIER2: ${{ needs.test-bot.outputs.gen_matrix_args_tier2 }}
|
||||
PHP_VERSIONS: ${{ needs.test-bot.outputs.php_versions }}
|
||||
TIER2: ${{ needs.test-bot.outputs.tier2 }}
|
||||
run: |
|
||||
# Tier1 matrix
|
||||
MATRIX1=$(bin/spc dev:gen-ext-test-matrix $GEN_MATRIX_ARGS 2>/dev/null)
|
||||
|
||||
# Merge Tier2 if requested
|
||||
if [ "$TIER2" = "true" ] && [ -n "$GEN_MATRIX_ARGS_TIER2" ]; then
|
||||
MATRIX2=$(bin/spc dev:gen-ext-test-matrix $GEN_MATRIX_ARGS_TIER2 2>/dev/null)
|
||||
COMBINED=$(jq -n --argjson m1 "$MATRIX1" --argjson m2 "$MATRIX2" '$m1 + $m2')
|
||||
else
|
||||
COMBINED=$MATRIX1
|
||||
fi
|
||||
|
||||
# Expand PHP versions: cartesian product of entries × php_versions
|
||||
FINAL=$(echo "$COMBINED" | jq --argjson versions "$PHP_VERSIONS" \
|
||||
'[.[] | . as $entry | $versions[] | $entry + {"php-version": .}]')
|
||||
|
||||
echo "matrix=$(echo "$FINAL" | jq -c '{"combo": .}')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
ext-test:
|
||||
name: "Ext test: ${{ matrix.combo.extension }} (PHP ${{ matrix.combo.php-version }} · ${{ matrix.combo.os }}-${{ matrix.combo.arch }})"
|
||||
needs: gen-matrix
|
||||
runs-on: ${{ matrix.combo.runner }}
|
||||
timeout-minutes: 120
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.gen-matrix.outputs.matrix) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: 8.4
|
||||
extensions: curl, openssl, mbstring
|
||||
ini-values: memory_limit=-1
|
||||
tools: composer
|
||||
env:
|
||||
phpts: nts
|
||||
|
||||
- name: "Cache composer packages"
|
||||
id: composer-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: vendor
|
||||
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-php-
|
||||
- name: Install dependencies
|
||||
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-dev
|
||||
|
||||
# Cache downloaded source
|
||||
- id: cache-download
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: downloads
|
||||
key: php-dependencies-${{ matrix.os }}
|
||||
|
||||
- name: "Install Dependencies"
|
||||
run: composer update -vvv --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist --no-plugins
|
||||
|
||||
- name: "Run Build Tests (doctor)"
|
||||
run: php src/globals/test-extensions.php doctor_cmd ${{ matrix.os }} ${{ matrix.php }}
|
||||
|
||||
- name: "Prepare UPX for Windows"
|
||||
if: ${{ startsWith(matrix.os, 'windows-') }}
|
||||
- name: Build
|
||||
env:
|
||||
SPC_USE_SUDO: "yes"
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
php src/globals/test-extensions.php install_upx_cmd ${{ matrix.os }} ${{ matrix.php }}
|
||||
echo "UPX_CMD=$(php src/globals/test-extensions.php upx)" >> $env:GITHUB_ENV
|
||||
./bin/spc doctor --auto-fix
|
||||
${{ matrix.combo.build-args }} --dl-with-php=${{ matrix.combo.php-version }}
|
||||
|
||||
- name: "Prepare UPX for Linux"
|
||||
if: ${{ startsWith(matrix.os, 'ubuntu-') }}
|
||||
run: |
|
||||
php src/globals/test-extensions.php install_upx_cmd ${{ matrix.os }} ${{ matrix.php }}
|
||||
echo "UPX_CMD=$(php src/globals/test-extensions.php upx)" >> $GITHUB_ENV
|
||||
|
||||
- name: "Run Build Tests (download)"
|
||||
run: php src/globals/test-extensions.php download_cmd ${{ matrix.os }} ${{ matrix.php }}
|
||||
|
||||
- name: "Run Build Tests (build)"
|
||||
run: php src/globals/test-extensions.php build_cmd ${{ matrix.os }} ${{ matrix.php }}
|
||||
|
||||
- name: "Run Build Tests (build - embed for non-windows)"
|
||||
if: ${{ !startsWith(matrix.os, 'windows-') }}
|
||||
run: php src/globals/test-extensions.php build_embed_cmd ${{ matrix.os }} ${{ matrix.php }}
|
||||
|
||||
- name: "Upload logs"
|
||||
if: ${{ always() && hashFiles('log/**') != '' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: build-logs-${{ matrix.os }}-${{ matrix.php }}
|
||||
path: log
|
||||
|
||||
# - name: Setup tmate session
|
||||
# - name: Setup upterm session
|
||||
# if: ${{ failure() }}
|
||||
# uses: mxschmitt/action-tmate@v3
|
||||
# uses: owenthereal/action-upterm@v1
|
||||
|
||||
- name: Upload logs
|
||||
if: always() && hashFiles('log/**') != ''
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: logs-${{ matrix.combo.os }}-${{ matrix.combo.arch }}-${{ matrix.combo.extension }}-php${{ matrix.combo.php-version }}
|
||||
path: log
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
[](https://github.com/crazywhalecc/static-php-cli/releases)
|
||||
[](https://github.com/crazywhalecc/static-php-cli/actions/workflows/tests.yml)
|
||||
[](https://github.com/crazywhalecc/static-php-cli/blob/main/LICENSE)
|
||||
[](https://discord.gg/nrSRbpMJ)
|
||||
[](https://discord.gg/xf6Rd4pEAk)
|
||||
|
||||
**StaticPHP** 是一个强大的工具,用于构建可移植的可执行文件,包括 PHP、扩展等。
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
[](https://github.com/crazywhalecc/static-php-cli/releases)
|
||||
[](https://github.com/crazywhalecc/static-php-cli/actions/workflows/tests.yml)
|
||||
[](https://github.com/crazywhalecc/static-php-cli/blob/main/LICENSE)
|
||||
[](https://discord.gg/nrSRbpMJ)
|
||||
[](https://discord.gg/xf6Rd4pEAk)
|
||||
|
||||
**StaticPHP** is a powerful tool designed for building portable executables including PHP, extensions, and more.
|
||||
|
||||
|
||||
@@ -4,5 +4,5 @@ ncurses:
|
||||
- COPYING
|
||||
source:
|
||||
type: filelist
|
||||
url: 'https://ftp.gnu.org/pub/gnu/ncurses/'
|
||||
url: 'https://ftpmirror.gnu.org/gnu/ncurses/'
|
||||
regex: '/href="(?<file>ncurses-(?<version>[^"]+)\.tar\.gz)"/'
|
||||
|
||||
@@ -100,9 +100,10 @@ SPC_TARGET=${GNU_ARCH}-linux-musl
|
||||
CC=${SPC_DEFAULT_CC}
|
||||
CXX=${SPC_DEFAULT_CXX}
|
||||
AR=${SPC_DEFAULT_AR}
|
||||
RANLIB=${SPC_DEFAULT_RANLIB}
|
||||
LD=${SPC_DEFAULT_LD}
|
||||
; 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_LDFLAGS="-Wl,-z,relro -Wl,--as-needed -Wl,-z,now -Wl,-z,noexecstack -Wl,--gc-sections"
|
||||
; upx executable path
|
||||
@@ -125,6 +126,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}"
|
||||
; EXTRA_LDFLAGS for `make` php, can use -release to set a soname for libphp.so
|
||||
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.
|
||||
; default on Debian/Alpine: /etc/ssl, default on RHEL: /etc/pki/tls
|
||||
@@ -140,9 +143,10 @@ SPC_USE_LLVM=system
|
||||
CC=${SPC_DEFAULT_CC}
|
||||
CXX=${SPC_DEFAULT_CXX}
|
||||
AR=${SPC_DEFAULT_AR}
|
||||
RANLIB=${SPC_DEFAULT_RANLIB}
|
||||
LD=${SPC_DEFAULT_LD}
|
||||
; default compiler flags, used in CMake toolchain file, openssl and pkg-config build
|
||||
SPC_DEFAULT_CFLAGS="--target=${MAC_ARCH}-apple-darwin -O3 -fno-plt -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections"
|
||||
SPC_DEFAULT_CFLAGS="--target=${MAC_ARCH}-apple-darwin -O3 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -ffunction-sections -fdata-sections"
|
||||
SPC_DEFAULT_CXXFLAGS="${SPC_DEFAULT_CFLAGS}"
|
||||
SPC_DEFAULT_LDFLAGS="-Wl,-dead_strip"
|
||||
; phpmicro patches, for more info, see: https://github.com/easysoft/phpmicro/tree/master/patches
|
||||
@@ -163,5 +167,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}"
|
||||
; EXTRA_LDFLAGS for `make` php, can use -release to set a soname for libphp.dylib
|
||||
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)
|
||||
MACOSX_DEPLOYMENT_TARGET=12.0
|
||||
|
||||
@@ -186,6 +186,7 @@ ext-password-argon2:
|
||||
type: php-extension
|
||||
depends:
|
||||
- libargon2
|
||||
suggests:
|
||||
- ext-openssl
|
||||
php-extension:
|
||||
os:
|
||||
|
||||
@@ -2,12 +2,13 @@ ext-brotli:
|
||||
type: php-extension
|
||||
artifact:
|
||||
source:
|
||||
type: git
|
||||
type: ghtagtar
|
||||
repo: kjdev/php-ext-brotli
|
||||
extract: php-src/ext/brotli
|
||||
rev: master
|
||||
url: 'https://github.com/kjdev/php-ext-brotli'
|
||||
metadata:
|
||||
license-files: [LICENSE]
|
||||
license: MIT
|
||||
depends:
|
||||
- brotli
|
||||
php-extension:
|
||||
arg-type: '--enable-brotli@shared_suffix@ --with-libbrotli'
|
||||
|
||||
19
config/pkg/ext/ext-clickhouse.yml
Normal file
19
config/pkg/ext/ext-clickhouse.yml
Normal file
@@ -0,0 +1,19 @@
|
||||
ext-clickhouse:
|
||||
type: php-extension
|
||||
artifact:
|
||||
source:
|
||||
type: ghtar
|
||||
repo: iliaal/php_clickhouse
|
||||
extract: php-src/ext/clickhouse
|
||||
prefer-stable: true
|
||||
metadata:
|
||||
license-files: [LICENSE]
|
||||
license: PHP-3.01
|
||||
suggests@unix:
|
||||
- openssl
|
||||
lang: cpp
|
||||
php-extension:
|
||||
os:
|
||||
- Linux
|
||||
- Darwin
|
||||
arg-type@unix: custom
|
||||
20
config/pkg/ext/ext-fastchart.yml
Normal file
20
config/pkg/ext/ext-fastchart.yml
Normal file
@@ -0,0 +1,20 @@
|
||||
ext-fastchart:
|
||||
type: php-extension
|
||||
artifact:
|
||||
source:
|
||||
type: ghtar
|
||||
repo: iliaal/fastchart
|
||||
extract: php-src/ext/fastchart
|
||||
prefer-stable: true
|
||||
metadata:
|
||||
license-files: [LICENSE]
|
||||
depends:
|
||||
- freetype
|
||||
suggests:
|
||||
- libpng
|
||||
- libjpeg
|
||||
- libwebp
|
||||
php-extension:
|
||||
os:
|
||||
- Linux
|
||||
- Darwin
|
||||
14
config/pkg/ext/ext-fastjson.yml
Normal file
14
config/pkg/ext/ext-fastjson.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
ext-fastjson:
|
||||
type: php-extension
|
||||
artifact:
|
||||
source:
|
||||
type: ghtar
|
||||
repo: iliaal/fastjson
|
||||
extract: php-src/ext/fastjson
|
||||
prefer-stable: true
|
||||
metadata:
|
||||
license-files: [LICENSE]
|
||||
php-extension:
|
||||
os:
|
||||
- Linux
|
||||
- Darwin
|
||||
@@ -10,3 +10,5 @@ ext-gmssl:
|
||||
license: PHP-3.01
|
||||
depends:
|
||||
- gmssl
|
||||
php-extension:
|
||||
arg-type: with-path
|
||||
|
||||
@@ -14,5 +14,6 @@ ext-swow:
|
||||
- curl
|
||||
- ext-openssl
|
||||
- ext-curl
|
||||
- postgresql
|
||||
php-extension:
|
||||
arg-type: custom
|
||||
|
||||
@@ -2,9 +2,8 @@ ext-zstd:
|
||||
type: php-extension
|
||||
artifact:
|
||||
source:
|
||||
type: git
|
||||
url: 'https://github.com/kjdev/php-ext-zstd'
|
||||
rev: master
|
||||
type: ghtar
|
||||
repo: kjdev/php-ext-zstd
|
||||
extract: php-src/ext/zstd
|
||||
metadata:
|
||||
license-files: [LICENSE]
|
||||
|
||||
@@ -4,6 +4,6 @@ gettext-win:
|
||||
source:
|
||||
type: git
|
||||
url: 'https://github.com/winlibs/gettext.git'
|
||||
rev: master
|
||||
rev: '0.18'
|
||||
static-libs@windows:
|
||||
- libintl_a.lib
|
||||
|
||||
@@ -3,7 +3,7 @@ gettext:
|
||||
artifact:
|
||||
source:
|
||||
type: filelist
|
||||
url: 'https://ftp.gnu.org/pub/gnu/gettext/'
|
||||
url: 'https://ftpmirror.gnu.org/gnu/gettext/'
|
||||
regex: '/href="(?<file>gettext-(?<version>[^"]+)\.tar\.xz)"/'
|
||||
metadata:
|
||||
license-files: [gettext-runtime/intl/COPYING.LIB]
|
||||
|
||||
@@ -3,7 +3,7 @@ gmp:
|
||||
artifact:
|
||||
source:
|
||||
type: filelist
|
||||
url: 'https://ftp.gnu.org/gnu/gmp/'
|
||||
url: 'https://ftpmirror.gnu.org/gnu/gmp/'
|
||||
regex: '/href="(?<file>gmp-(?<version>[^"]+)\.tar\.xz)"/'
|
||||
source-mirror:
|
||||
type: url
|
||||
|
||||
@@ -2,8 +2,9 @@ gmssl:
|
||||
type: library
|
||||
artifact:
|
||||
source:
|
||||
type: ghtar
|
||||
repo: guanzhi/GmSSL
|
||||
type: git
|
||||
url: 'https://github.com/guanzhi/GmSSL.git'
|
||||
rev: master
|
||||
metadata:
|
||||
license-files: [LICENSE]
|
||||
license: Apache-2.0
|
||||
|
||||
@@ -3,7 +3,7 @@ idn2:
|
||||
artifact:
|
||||
source:
|
||||
type: filelist
|
||||
url: 'https://ftp.gnu.org/gnu/libidn/'
|
||||
url: 'https://ftpmirror.gnu.org/gnu/libidn/'
|
||||
regex: '/href="(?<file>libidn2-(?<version>[^"]+)\.tar\.gz)"/'
|
||||
metadata:
|
||||
license-files: [COPYING.LESSERv3]
|
||||
|
||||
@@ -3,7 +3,7 @@ libiconv:
|
||||
artifact:
|
||||
source:
|
||||
type: filelist
|
||||
url: 'https://ftp.gnu.org/gnu/libiconv/'
|
||||
url: 'https://ftpmirror.gnu.org/gnu/libiconv/'
|
||||
regex: '/href="(?<file>libiconv-(?<version>[^"]+)\.tar\.gz)"/'
|
||||
metadata:
|
||||
license-files: [COPYING.LIB]
|
||||
|
||||
@@ -3,7 +3,7 @@ libunistring:
|
||||
artifact:
|
||||
source:
|
||||
type: filelist
|
||||
url: 'https://ftp.gnu.org/gnu/libunistring/'
|
||||
url: 'https://ftpmirror.gnu.org/gnu/libunistring/'
|
||||
regex: '/href="(?<file>libunistring-(?<version>[^"]+)\.tar\.gz)"/'
|
||||
metadata:
|
||||
license-files: [COPYING.LIB]
|
||||
|
||||
@@ -3,7 +3,7 @@ readline:
|
||||
artifact:
|
||||
source:
|
||||
type: filelist
|
||||
url: 'https://ftp.gnu.org/pub/gnu/readline/'
|
||||
url: 'https://ftpmirror.gnu.org/gnu/readline/'
|
||||
regex: '/href="(?<file>readline-(?<version>[^"]+)\.tar\.gz)"/'
|
||||
metadata:
|
||||
license-files: [COPYING]
|
||||
|
||||
@@ -16,6 +16,8 @@ curl:
|
||||
- zlib
|
||||
- libssh2
|
||||
- nghttp2
|
||||
- brotli
|
||||
- zstd
|
||||
suggests@unix:
|
||||
- libssh2
|
||||
- brotli
|
||||
@@ -27,9 +29,6 @@ curl:
|
||||
- ldap
|
||||
- idn2
|
||||
- krb5
|
||||
suggests@windows:
|
||||
- brotli
|
||||
- zstd
|
||||
frameworks:
|
||||
- CoreFoundation
|
||||
- CoreServices
|
||||
|
||||
6
config/pkg/target/llvm-compiler-rt.yml
Normal file
6
config/pkg/target/llvm-compiler-rt.yml
Normal file
@@ -0,0 +1,6 @@
|
||||
llvm-compiler-rt:
|
||||
type: target
|
||||
artifact:
|
||||
binary: custom
|
||||
depends:
|
||||
- zig
|
||||
6
config/pkg/target/llvm-tools.yml
Normal file
6
config/pkg/target/llvm-tools.yml
Normal file
@@ -0,0 +1,6 @@
|
||||
llvm-tools:
|
||||
type: target
|
||||
artifact:
|
||||
binary: custom
|
||||
depends:
|
||||
- zig
|
||||
@@ -29,7 +29,7 @@ spc download [artifacts] [options]
|
||||
| `--for-packages=<list>` | | Download artifacts needed by the given packages |
|
||||
| `--without-suggests` | | Skip suggested packages when using `--for-extensions` |
|
||||
| `--clean` | | Delete existing download cache before fetching |
|
||||
| `--with-php=<ver>` | | PHP version in `major.minor` format (default: `8.4`) |
|
||||
| `--with-php=<ver>` | | PHP version in `major.minor` format (default: `8.5`) |
|
||||
| `--prefer-binary` | `-p` | Prefer pre-built binaries over source archives |
|
||||
| `--prefer-source` | | Prefer source archives over pre-built binaries |
|
||||
| `--source-only` | | Only download source artifacts |
|
||||
@@ -47,7 +47,7 @@ spc download [artifacts] [options]
|
||||
|
||||
```bash
|
||||
# Download only what the chosen extensions need
|
||||
spc download --for-extensions="bcmath,openssl,curl" --with-php=8.4
|
||||
spc download --for-extensions="bcmath,openssl,curl" --with-php=8.5
|
||||
|
||||
# Download specific artifacts
|
||||
spc download "php-src,openssl"
|
||||
@@ -136,7 +136,7 @@ All downloader options are available with the `--dl-` prefix:
|
||||
|
||||
| Option | Description |
|
||||
|------------------------------------|--------------------------------------------|
|
||||
| `--dl-with-php=<ver>` | PHP version to download (default: `8.4`) |
|
||||
| `--dl-with-php=<ver>` | PHP version to download (default: `8.5`) |
|
||||
| `--dl-prefer-binary` | Prefer pre-built binaries for dependencies |
|
||||
| `--dl-parallel=<n>` | Number of parallel downloads |
|
||||
| `--dl-retry=<n>` | Number of retries on failure |
|
||||
@@ -265,12 +265,12 @@ spc check-update [artifact] [options]
|
||||
|
||||
### Options
|
||||
|
||||
| Option | Short | Description |
|
||||
|---|---|---|
|
||||
| `--json` | | Output results in JSON format |
|
||||
| Option | Short | Description |
|
||||
|---|---|------------------------------------------------------------------------------------------|
|
||||
| `--json` | | Output results in JSON format |
|
||||
| `--bare` | | Check without requiring the artifact to be downloaded first (old version will be `null`) |
|
||||
| `--parallel=<n>` | `-p` | Number of parallel update checks (default: `10`) |
|
||||
| `--with-php=<ver>` | | PHP version context in `major.minor` format (default: `8.4`) |
|
||||
| `--parallel=<n>` | `-p` | Number of parallel update checks (default: `10`) |
|
||||
| `--with-php=<ver>` | | PHP version context in `major.minor` format (default: `8.5`) |
|
||||
|
||||
### Examples
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ The `craft` command reads a `craft.yml` file and handles everything automaticall
|
||||
Create a `craft.yml` in your working directory and declare the PHP version, extensions, and target SAPIs:
|
||||
|
||||
```yaml
|
||||
php-version: 8.4
|
||||
php-version: 8.5
|
||||
extensions: bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer
|
||||
sapi:
|
||||
- cli
|
||||
@@ -80,10 +80,10 @@ If you want to pre-download ahead of time, or if you're working in a slow-networ
|
||||
|
||||
```bash
|
||||
# Download only what the chosen extensions need (recommended)
|
||||
spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.4
|
||||
spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.5
|
||||
|
||||
# Download by specific package names
|
||||
spc download "curl,openssl" --with-php=8.4
|
||||
spc download "curl,openssl" --with-php=8.5
|
||||
```
|
||||
|
||||
Downloads are cached in `downloads/` and reused across builds automatically.
|
||||
|
||||
@@ -47,7 +47,7 @@ Build your CLI with [symfony/console](https://symfony.com/doc/current/components
|
||||
|
||||
## Community
|
||||
|
||||
Join our [Discord server](https://discord.gg/nrSRbpMJ) to ask questions, share your builds, and connect with other StaticPHP users.
|
||||
Join our [Discord server](https://discord.gg/xf6Rd4pEAk) to ask questions, share your builds, and connect with other StaticPHP users.
|
||||
|
||||
## Next steps
|
||||
|
||||
|
||||
@@ -22,32 +22,32 @@ spc download [artifacts] [options]
|
||||
|
||||
### 选项
|
||||
|
||||
| 选项 | 缩写 | 说明 |
|
||||
|---|------|---|
|
||||
| `--for-extensions=<list>` | `-e` | 按扩展名下载其所需的制品 |
|
||||
| `--for-libs=<list>` | `-l` | 按库名下载其所需的制品 |
|
||||
| `--for-packages=<list>` | | 按包名下载其所需的制品 |
|
||||
| `--without-suggests` | | 使用 `--for-extensions` 时跳过建议包 |
|
||||
| `--clean` | | 下载前删除旧的下载缓存 |
|
||||
| `--with-php=<ver>` | | PHP 版本,格式为 `major.minor`(默认 `8.4`)|
|
||||
| `--prefer-binary` | `-p` | 优先使用预编译二进制 |
|
||||
| `--prefer-source` | | 优先使用源码包 |
|
||||
| `--source-only` | | 仅下载源码制品 |
|
||||
| `--binary-only` | | 仅下载二进制制品 |
|
||||
| `--parallel=<n>` | `-P` | 并行下载数(默认 `1`)|
|
||||
| `--retry=<n>` | `-R` | 失败重试次数(默认 `0`)|
|
||||
| `--ignore-cache=<list>` | `-i` | 强制重新下载指定制品 |
|
||||
| `--no-alt` | | 不使用镜像站 |
|
||||
| `--no-shallow-clone` | | 不使用浅层克隆 |
|
||||
| `--custom-url=<src:url>` | `-U` | 覆盖指定源的下载地址 |
|
||||
| `--custom-git=<src:branch:url>` | `-G` | 覆盖为自定义 git 仓库 |
|
||||
| `--custom-local=<src:path>` | `-L` | 使用本地路径作为制品来源 |
|
||||
| 选项 | 缩写 | 说明 |
|
||||
|---|------|------------------------------------|
|
||||
| `--for-extensions=<list>` | `-e` | 按扩展名下载其所需的制品 |
|
||||
| `--for-libs=<list>` | `-l` | 按库名下载其所需的制品 |
|
||||
| `--for-packages=<list>` | | 按包名下载其所需的制品 |
|
||||
| `--without-suggests` | | 使用 `--for-extensions` 时跳过建议包 |
|
||||
| `--clean` | | 下载前删除旧的下载缓存 |
|
||||
| `--with-php=<ver>` | | PHP 版本,格式为 `major.minor`(默认 `8.5`) |
|
||||
| `--prefer-binary` | `-p` | 优先使用预编译二进制 |
|
||||
| `--prefer-source` | | 优先使用源码包 |
|
||||
| `--source-only` | | 仅下载源码制品 |
|
||||
| `--binary-only` | | 仅下载二进制制品 |
|
||||
| `--parallel=<n>` | `-P` | 并行下载数(默认 `1`) |
|
||||
| `--retry=<n>` | `-R` | 失败重试次数(默认 `0`) |
|
||||
| `--ignore-cache=<list>` | `-i` | 强制重新下载指定制品 |
|
||||
| `--no-alt` | | 不使用镜像站 |
|
||||
| `--no-shallow-clone` | | 不使用浅层克隆 |
|
||||
| `--custom-url=<src:url>` | `-U` | 覆盖指定源的下载地址 |
|
||||
| `--custom-git=<src:branch:url>` | `-G` | 覆盖为自定义 git 仓库 |
|
||||
| `--custom-local=<src:path>` | `-L` | 使用本地路径作为制品来源 |
|
||||
|
||||
### 示例
|
||||
|
||||
```bash
|
||||
# 按扩展名下载(推荐)
|
||||
spc download --for-extensions="bcmath,openssl,curl" --with-php=8.4
|
||||
spc download --for-extensions="bcmath,openssl,curl" --with-php=8.5
|
||||
|
||||
# 下载指定制品
|
||||
spc download "php-src,openssl"
|
||||
@@ -134,14 +134,14 @@ spc build:php <extensions> [options]
|
||||
|
||||
所有下载器选项均可加 `--dl-` 前缀使用:
|
||||
|
||||
| 选项 | 说明 |
|
||||
|---|---|
|
||||
| `--dl-with-php=<ver>` | 指定下载的 PHP 版本(默认 `8.4`)|
|
||||
| `--dl-prefer-binary` | 优先使用预编译二进制依赖 |
|
||||
| `--dl-parallel=<n>` | 并行下载数 |
|
||||
| `--dl-retry=<n>` | 失败重试次数 |
|
||||
| `--dl-custom-url=<src:url>` | 覆盖指定源的下载地址 |
|
||||
| `--dl-custom-git=<src:branch:url>` | 覆盖为自定义 git 仓库 |
|
||||
| 选项 | 说明 |
|
||||
|---|------------------------|
|
||||
| `--dl-with-php=<ver>` | 指定下载的 PHP 版本(默认 `8.5`) |
|
||||
| `--dl-prefer-binary` | 优先使用预编译二进制依赖 |
|
||||
| `--dl-parallel=<n>` | 并行下载数 |
|
||||
| `--dl-retry=<n>` | 失败重试次数 |
|
||||
| `--dl-custom-url=<src:url>` | 覆盖指定源的下载地址 |
|
||||
| `--dl-custom-git=<src:branch:url>` | 覆盖为自定义 git 仓库 |
|
||||
|
||||
Downloader 选项传递给 `build:php` 命令时,会被自动下载器在构建前使用。
|
||||
这样你就可以直接通过构建命令控制下载行为,无需单独执行 `spc download` 命令。
|
||||
@@ -265,12 +265,12 @@ spc check-update [artifact] [options]
|
||||
|
||||
### 选项
|
||||
|
||||
| 选项 | 缩写 | 说明 |
|
||||
|---|---|---|
|
||||
| `--json` | | 以 JSON 格式输出结果 |
|
||||
| `--bare` | | 检查时不要求制品已下载(旧版本显示为 null)|
|
||||
| `--parallel=<n>` | `-p` | 并行检查数(默认 `10`)|
|
||||
| `--with-php=<ver>` | | PHP 版本上下文,格式为 `major.minor`(默认 `8.4`)|
|
||||
| 选项 | 缩写 | 说明 |
|
||||
|---|---|---------------------------------------|
|
||||
| `--json` | | 以 JSON 格式输出结果 |
|
||||
| `--bare` | | 检查时不要求制品已下载(旧版本显示为 null) |
|
||||
| `--parallel=<n>` | `-p` | 并行检查数(默认 `10`) |
|
||||
| `--with-php=<ver>` | | PHP 版本上下文,格式为 `major.minor`(默认 `8.5`) |
|
||||
|
||||
### 示例
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ StaticPHP 提供两种构建方式,根据使用场景选择:
|
||||
在当前目录创建 `craft.yml`,声明要编译的 PHP 版本、扩展和目标 SAPI:
|
||||
|
||||
```yaml
|
||||
php-version: 8.4
|
||||
php-version: 8.5
|
||||
extensions: bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer
|
||||
sapi:
|
||||
- cli
|
||||
@@ -80,10 +80,10 @@ v3 版本中,你可以省略这一步骤,直接构建想要的内容,Stati
|
||||
|
||||
```bash
|
||||
# 按扩展列表下载(推荐,只下载实际需要的内容)
|
||||
spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.4
|
||||
spc download --for-extensions="bcmath,posix,phar,zlib,openssl,curl,fileinfo,tokenizer" --with-php=8.5
|
||||
|
||||
# 按依赖包列表下载
|
||||
spc download "curl,openssl" --with-php=8.4
|
||||
spc download "curl,openssl" --with-php=8.5
|
||||
```
|
||||
|
||||
下载内容缓存在 `downloads/` 目录,重复构建时会直接复用。
|
||||
|
||||
@@ -55,7 +55,7 @@ StaticPHP 支持将 FrankenPHP 连同所需扩展一起静态编译,
|
||||
|
||||
## 社区
|
||||
|
||||
加入我们的 [Discord 服务器](https://discord.gg/nrSRbpMJ),提问、分享构建成果,与其他 StaticPHP 用户交流。
|
||||
加入我们的 [Discord 服务器](https://discord.gg/xf6Rd4pEAk),提问、分享构建成果,与其他 StaticPHP 用户交流。
|
||||
|
||||
## 接下来
|
||||
|
||||
|
||||
@@ -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', '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(');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,16 +20,14 @@ class go_win
|
||||
])]
|
||||
public function downBinary(ArtifactDownloader $downloader): DownloadResult
|
||||
{
|
||||
$pkgroot = PKG_ROOT_PATH;
|
||||
|
||||
// get version
|
||||
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text') ?: '');
|
||||
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text', retries: $downloader->getRetry()) ?: '');
|
||||
if ($version === '') {
|
||||
throw new DownloaderException('Failed to get latest Go version from https://go.dev/VERSION?m=text');
|
||||
}
|
||||
|
||||
// find SHA256 hash from download page
|
||||
$page = default_shell()->executeCurl('https://go.dev/dl/');
|
||||
$page = default_shell()->executeCurl('https://go.dev/dl/', retries: $downloader->getRetry());
|
||||
if ($page === '' || $page === false) {
|
||||
throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/');
|
||||
}
|
||||
@@ -52,7 +50,7 @@ class go_win
|
||||
throw new DownloaderException("Hash mismatch for downloaded go-win binary. Expected {$hash}, got {$file_hash}");
|
||||
}
|
||||
|
||||
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: "{$pkgroot}/go-win", verified: true, version: $version);
|
||||
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: '{pkg_root_path}/go-win', verified: true, version: $version);
|
||||
}
|
||||
|
||||
#[CustomBinaryCheckUpdate('go-win', ['windows-x86_64'])]
|
||||
|
||||
@@ -25,7 +25,6 @@ class go_xcaddy
|
||||
])]
|
||||
public function downBinary(ArtifactDownloader $downloader): DownloadResult
|
||||
{
|
||||
$pkgroot = PKG_ROOT_PATH;
|
||||
$name = SystemTarget::getCurrentPlatformString();
|
||||
$arch = match (explode('-', $name)[1]) {
|
||||
'x86_64' => 'amd64',
|
||||
@@ -39,11 +38,11 @@ class go_xcaddy
|
||||
};
|
||||
|
||||
// get version and hash
|
||||
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text') ?: '');
|
||||
[$version] = explode("\n", default_shell()->executeCurl('https://go.dev/VERSION?m=text', retries: $downloader->getRetry()) ?: '');
|
||||
if ($version === '') {
|
||||
throw new DownloaderException('Failed to get latest Go version from https://go.dev/VERSION?m=text');
|
||||
}
|
||||
$page = default_shell()->executeCurl('https://go.dev/dl/');
|
||||
$page = default_shell()->executeCurl('https://go.dev/dl/', retries: $downloader->getRetry());
|
||||
if ($page === '' || $page === false) {
|
||||
throw new DownloaderException('Failed to get Go download page from https://go.dev/dl/');
|
||||
}
|
||||
@@ -64,7 +63,7 @@ class go_xcaddy
|
||||
if ($file_hash !== $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', [
|
||||
@@ -109,7 +108,7 @@ class go_xcaddy
|
||||
'GOROOT' => "{$target_path}",
|
||||
'GOBIN' => "{$target_path}/bin",
|
||||
'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");
|
||||
}
|
||||
}
|
||||
|
||||
193
src/Package/Artifact/llvm_compiler_rt.php
Normal file
193
src/Package/Artifact/llvm_compiler_rt.php
Normal file
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Package\Artifact;
|
||||
|
||||
use StaticPHP\Artifact\ArtifactDownloader;
|
||||
use StaticPHP\Artifact\Downloader\DownloadResult;
|
||||
use StaticPHP\Artifact\Downloader\Type\CheckUpdateResult;
|
||||
use StaticPHP\Artifact\Downloader\Type\GitHubTokenSetupTrait;
|
||||
use StaticPHP\Attribute\Artifact\AfterBinaryExtract;
|
||||
use StaticPHP\Attribute\Artifact\CustomBinary;
|
||||
use StaticPHP\Attribute\Artifact\CustomBinaryCheckUpdate;
|
||||
use StaticPHP\Exception\BuildFailureException;
|
||||
use StaticPHP\Exception\DownloaderException;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
|
||||
/**
|
||||
* Builds the compiler-rt bits zig ships without — libclang_rt.profile.a (PGO instrumentation)
|
||||
* and clang_rt.crtbegin.o/crtend.o (__dso_handle for shared libs). Target-arch specific:
|
||||
* libs land in PKG_ROOT_PATH/zig/lib/{triple}.
|
||||
* Also builds libclang_rt.cpu_model.a (__cpu_model / __cpu_indicator_init, the libgcc-compatible
|
||||
* globals that __builtin_cpu_supports()/__builtin_cpu_init() reference) for arches that have it.
|
||||
*/
|
||||
class llvm_compiler_rt
|
||||
{
|
||||
use GitHubTokenSetupTrait;
|
||||
|
||||
#[CustomBinary('llvm-compiler-rt', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
'macos-x86_64',
|
||||
'macos-aarch64',
|
||||
])]
|
||||
public function downBinary(ArtifactDownloader $downloader): DownloadResult
|
||||
{
|
||||
$llvmVersion = $this->detectZigLlvmVersion()
|
||||
?? throw new DownloaderException('llvm-compiler-rt: could not detect bundled clang version from zig cc --version');
|
||||
$tarball = "compiler-rt-{$llvmVersion}.src.tar.xz";
|
||||
$url = "https://github.com/llvm/llvm-project/releases/download/llvmorg-{$llvmVersion}/{$tarball}";
|
||||
$tarballPath = DOWNLOAD_PATH . '/' . $tarball;
|
||||
default_shell()->executeCurlDownload($url, $tarballPath, headers: $this->getGitHubTokenHeaders(), retries: $downloader->getRetry());
|
||||
return DownloadResult::archive($tarball, ['url' => $url, 'version' => $llvmVersion], extract: '{source_path}/llvm-compiler-rt', verified: false, version: $llvmVersion);
|
||||
}
|
||||
|
||||
#[CustomBinaryCheckUpdate('llvm-compiler-rt', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
'macos-x86_64',
|
||||
'macos-aarch64',
|
||||
])]
|
||||
public function checkUpdateBinary(?string $old_version, ArtifactDownloader $downloader): CheckUpdateResult
|
||||
{
|
||||
$llvmVersion = $this->detectZigLlvmVersion()
|
||||
?? throw new DownloaderException('llvm-compiler-rt: could not detect bundled clang version from zig cc --version');
|
||||
return new CheckUpdateResult(
|
||||
old: $old_version,
|
||||
new: $llvmVersion,
|
||||
needUpdate: $old_version === null || $llvmVersion !== $old_version,
|
||||
);
|
||||
}
|
||||
|
||||
#[AfterBinaryExtract('llvm-compiler-rt', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
'macos-x86_64',
|
||||
'macos-aarch64',
|
||||
])]
|
||||
public function postExtract(string $target_path): void
|
||||
{
|
||||
$this->buildForTriple($target_path);
|
||||
}
|
||||
|
||||
public function buildForTriple(?string $sourceDir = null, ?string $triple = null): void
|
||||
{
|
||||
$sourceDir ??= SOURCE_PATH . '/llvm-compiler-rt';
|
||||
$triple ??= SystemTarget::getCanonicalTriple();
|
||||
$libDir = zig::path() . '/lib/' . $triple;
|
||||
if ($this->isBuilt($libDir)) {
|
||||
return;
|
||||
}
|
||||
if (!is_dir($sourceDir) || !is_dir("{$sourceDir}/lib/profile")) {
|
||||
throw new BuildFailureException("llvm-compiler-rt: missing source at {$sourceDir} (extraction layout changed?)");
|
||||
}
|
||||
f_mkdir($libDir, recursive: true);
|
||||
$profileLib = "{$libDir}/libclang_rt.profile.a";
|
||||
$crtBegin = "{$libDir}/clang_rt.crtbegin.o";
|
||||
$crtEnd = "{$libDir}/clang_rt.crtend.o";
|
||||
if (!file_exists($profileLib)) {
|
||||
$this->buildProfileRuntime($sourceDir, $profileLib, $triple);
|
||||
}
|
||||
if (!file_exists($crtBegin) || !file_exists($crtEnd)) {
|
||||
$this->buildCrtObjects($sourceDir, $crtBegin, $crtEnd, $triple);
|
||||
}
|
||||
$cpuModelLib = "{$libDir}/libclang_rt.cpu_model.a";
|
||||
if (self::cpuModelArch($triple) !== null && !file_exists($cpuModelLib)) {
|
||||
$this->buildCpuModelBuiltins($sourceDir, $cpuModelLib, $triple);
|
||||
}
|
||||
}
|
||||
|
||||
public function isBuilt(string $libDir): bool
|
||||
{
|
||||
return file_exists("{$libDir}/libclang_rt.profile.a")
|
||||
&& file_exists("{$libDir}/clang_rt.crtbegin.o")
|
||||
&& file_exists("{$libDir}/clang_rt.crtend.o")
|
||||
&& (self::cpuModelArch(basename($libDir)) === null || file_exists("{$libDir}/libclang_rt.cpu_model.a"));
|
||||
}
|
||||
|
||||
private function detectZigLlvmVersion(): ?string
|
||||
{
|
||||
if (!zig::isInstalled()) {
|
||||
return null;
|
||||
}
|
||||
[$rc, $out] = shell()->execWithResult(escapeshellarg(zig::binary()) . ' cc --version', false);
|
||||
if ($rc !== 0) {
|
||||
return null;
|
||||
}
|
||||
return preg_match('/clang version (\d+\.\d+\.\d+)/', implode("\n", $out), $m) ? $m[1] : null;
|
||||
}
|
||||
|
||||
private function buildProfileRuntime(string $srcRoot, string $libPath, string $triple): void
|
||||
{
|
||||
$profileSrc = "{$srcRoot}/lib/profile";
|
||||
$profileInc = "{$srcRoot}/include";
|
||||
// Skip OS-specific sources we can't satisfy without their SDKs.
|
||||
$skip = ['/PlatformAIX', '/PlatformDarwin', '/PlatformFuchsia', '/PlatformOther', '/PlatformWindows', '/WindowsMMap'];
|
||||
$sources = array_filter(
|
||||
array_merge(glob("{$profileSrc}/*.c") ?: [], glob("{$profileSrc}/*.cpp") ?: []),
|
||||
fn ($f) => !array_any($skip, fn ($s) => str_contains($f, $s)),
|
||||
);
|
||||
|
||||
$objDir = "{$srcRoot}/obj-profile-{$triple}";
|
||||
f_mkdir($objDir, recursive: true);
|
||||
$cflags = "-target {$triple} -c -O2 -fPIC -fvisibility=hidden "
|
||||
. '-I' . escapeshellarg($profileInc) . ' '
|
||||
. '-DCOMPILER_RT_HAS_ATOMICS=1 -DCOMPILER_RT_HAS_FCNTL_LCK=1 -DCOMPILER_RT_HAS_UNAME=1';
|
||||
$srcArgs = implode(' ', array_map('escapeshellarg', $sources));
|
||||
shell()->cd($objDir)->exec("zig cc {$cflags} {$srcArgs}");
|
||||
shell()->cd($objDir)->exec('zig ar rcs ' . escapeshellarg($libPath) . ' *.o');
|
||||
}
|
||||
|
||||
private function buildCrtObjects(string $srcRoot, string $crtBegin, string $crtEnd, string $triple): void
|
||||
{
|
||||
$beginSrc = "{$srcRoot}/lib/builtins/crtbegin.c";
|
||||
$endSrc = "{$srcRoot}/lib/builtins/crtend.c";
|
||||
if (!is_file($beginSrc) || !is_file($endSrc)) {
|
||||
throw new BuildFailureException("llvm-compiler-rt: crtbegin/crtend source missing under {$srcRoot}/lib/builtins");
|
||||
}
|
||||
$cflags = "-target {$triple} -c -O2 -fPIC -fvisibility=hidden -DCRT_HAS_INITFINI_ARRAY";
|
||||
foreach ([[$beginSrc, $crtBegin], [$endSrc, $crtEnd]] as [$src, $dst]) {
|
||||
shell()->exec("zig cc {$cflags} -o " . escapeshellarg($dst) . ' ' . escapeshellarg($src));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build libclang_rt.cpu_model.a, provides
|
||||
* the globals that __builtin_cpu_supports() reference.
|
||||
*/
|
||||
private function buildCpuModelBuiltins(string $srcRoot, string $libPath, string $triple): void
|
||||
{
|
||||
$builtins = "{$srcRoot}/lib/builtins";
|
||||
$family = self::cpuModelArch($triple);
|
||||
$cpuModelDir = "{$builtins}/cpu_model";
|
||||
if (is_dir($cpuModelDir)) {
|
||||
$src = "{$cpuModelDir}/{$family}.c";
|
||||
$includes = '-I' . escapeshellarg($builtins) . ' -I' . escapeshellarg($cpuModelDir);
|
||||
} else {
|
||||
$src = "{$builtins}/cpu_model.c";
|
||||
$includes = '-I' . escapeshellarg($builtins);
|
||||
}
|
||||
if (!is_file($src)) {
|
||||
throw new BuildFailureException("llvm-compiler-rt: cpu_model source not found for {$triple} under {$builtins}");
|
||||
}
|
||||
|
||||
$objDir = "{$srcRoot}/obj-cpu-model-{$triple}";
|
||||
f_mkdir($objDir, recursive: true);
|
||||
$obj = "{$objDir}/cpu_model.o";
|
||||
$cflags = "-target {$triple} -c -O2 -fPIC {$includes}";
|
||||
shell()->exec('zig cc ' . $cflags . ' -o ' . escapeshellarg($obj) . ' ' . escapeshellarg($src));
|
||||
shell()->exec('zig ar rcs ' . escapeshellarg($libPath) . ' ' . escapeshellarg($obj));
|
||||
}
|
||||
|
||||
private static function cpuModelArch(string $triple): ?string
|
||||
{
|
||||
$arch = explode('-', $triple)[0];
|
||||
return match (true) {
|
||||
in_array($arch, ['x86_64', 'amd64', 'i386', 'i686', 'x86'], true) => 'x86',
|
||||
in_array($arch, ['aarch64', 'arm64'], true) => 'aarch64',
|
||||
str_starts_with($arch, 'riscv') => 'riscv',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
149
src/Package/Artifact/llvm_tools.php
Normal file
149
src/Package/Artifact/llvm_tools.php
Normal file
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Package\Artifact;
|
||||
|
||||
use StaticPHP\Artifact\ArtifactDownloader;
|
||||
use StaticPHP\Artifact\Downloader\DownloadResult;
|
||||
use StaticPHP\Artifact\Downloader\Type\CheckUpdateResult;
|
||||
use StaticPHP\Artifact\Downloader\Type\GitHubTokenSetupTrait;
|
||||
use StaticPHP\Attribute\Artifact\AfterBinaryExtract;
|
||||
use StaticPHP\Attribute\Artifact\CustomBinary;
|
||||
use StaticPHP\Attribute\Artifact\CustomBinaryCheckUpdate;
|
||||
use StaticPHP\DI\ApplicationContext;
|
||||
use StaticPHP\Exception\BuildFailureException;
|
||||
use StaticPHP\Exception\DownloaderException;
|
||||
use StaticPHP\Package\PackageBuilder;
|
||||
|
||||
class llvm_tools
|
||||
{
|
||||
use GitHubTokenSetupTrait;
|
||||
|
||||
public const array TOOLS = ['llvm-objcopy', 'llvm-strip', 'llvm-profdata'];
|
||||
|
||||
#[CustomBinary('llvm-tools', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
'macos-x86_64',
|
||||
'macos-aarch64',
|
||||
])]
|
||||
public function downBinary(ArtifactDownloader $downloader): DownloadResult
|
||||
{
|
||||
$llvmVersion = $this->detectLlvmVersion()
|
||||
?? throw new DownloaderException('Could not detect a clang version on host; install zig or clang first');
|
||||
$tarball = "llvm-project-{$llvmVersion}.src.tar.xz";
|
||||
$url = "https://github.com/llvm/llvm-project/releases/download/llvmorg-{$llvmVersion}/{$tarball}";
|
||||
$tarballPath = DOWNLOAD_PATH . '/' . $tarball;
|
||||
default_shell()->executeCurlDownload($url, $tarballPath, headers: $this->getGitHubTokenHeaders(), retries: $downloader->getRetry());
|
||||
return DownloadResult::archive($tarball, ['url' => $url, 'version' => $llvmVersion], extract: '{source_path}/llvm-tools', verified: false, version: $llvmVersion);
|
||||
}
|
||||
|
||||
#[CustomBinaryCheckUpdate('llvm-tools', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
'macos-x86_64',
|
||||
'macos-aarch64',
|
||||
])]
|
||||
public function checkUpdateBinary(?string $old_version, ArtifactDownloader $downloader): CheckUpdateResult
|
||||
{
|
||||
$llvmVersion = $this->detectLlvmVersion()
|
||||
?? throw new DownloaderException('Could not detect a clang version on host; install zig or clang first');
|
||||
return new CheckUpdateResult(
|
||||
old: $old_version,
|
||||
new: $llvmVersion,
|
||||
needUpdate: $old_version === null || $llvmVersion !== $old_version,
|
||||
);
|
||||
}
|
||||
|
||||
#[AfterBinaryExtract('llvm-tools', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
'macos-x86_64',
|
||||
'macos-aarch64',
|
||||
])]
|
||||
public function postExtract(string $target_path): void
|
||||
{
|
||||
$this->buildForHost($target_path);
|
||||
}
|
||||
|
||||
public function buildForHost(?string $sourceRoot = null): void
|
||||
{
|
||||
$sourceRoot ??= SOURCE_PATH . '/llvm-tools';
|
||||
$binDir = PKG_ROOT_PATH . '/llvm-tools/bin';
|
||||
if ($this->allBuilt($binDir)) {
|
||||
return;
|
||||
}
|
||||
$llvmDir = "{$sourceRoot}/llvm";
|
||||
if (!is_dir($llvmDir)) {
|
||||
throw new BuildFailureException("llvm-tools: missing source at {$llvmDir} (extraction layout changed?)");
|
||||
}
|
||||
$buildDir = "{$sourceRoot}/build";
|
||||
$installDir = PKG_ROOT_PATH . '/llvm-tools';
|
||||
f_mkdir($buildDir, recursive: true);
|
||||
f_mkdir($binDir, recursive: true);
|
||||
|
||||
$cmakeArgs = implode(' ', array_map('escapeshellarg', [
|
||||
'-S', $llvmDir,
|
||||
'-B', $buildDir,
|
||||
'-DCMAKE_BUILD_TYPE=Release',
|
||||
'-DLLVM_ENABLE_PROJECTS=',
|
||||
'-DLLVM_TARGETS_TO_BUILD=',
|
||||
'-DLLVM_INCLUDE_BENCHMARKS=OFF',
|
||||
'-DLLVM_INCLUDE_TESTS=OFF',
|
||||
'-DLLVM_INCLUDE_EXAMPLES=OFF',
|
||||
'-DLLVM_INCLUDE_DOCS=OFF',
|
||||
'-DLLVM_ENABLE_ZLIB=OFF',
|
||||
'-DLLVM_ENABLE_ZSTD=OFF',
|
||||
'-DLLVM_ENABLE_LIBXML2=OFF',
|
||||
'-DLLVM_ENABLE_TERMINFO=OFF',
|
||||
'-DLLVM_ENABLE_LIBEDIT=OFF',
|
||||
'-DLLVM_ENABLE_LIBPFM=OFF',
|
||||
'-DLLVM_BUILD_LLVM_DYLIB=OFF',
|
||||
'-DLLVM_LINK_LLVM_DYLIB=OFF',
|
||||
'-DBUILD_SHARED_LIBS=OFF',
|
||||
'-DCMAKE_C_COMPILER=' . zig::binary('zig-cc'),
|
||||
'-DCMAKE_CXX_COMPILER=' . zig::binary('zig-c++'),
|
||||
'-DCMAKE_INSTALL_PREFIX=' . $installDir,
|
||||
]));
|
||||
$jobs = ApplicationContext::get(PackageBuilder::class)->concurrency;
|
||||
$targetArgs = implode(' ', array_map(fn ($t) => '--target ' . escapeshellarg($t), self::TOOLS));
|
||||
|
||||
shell()
|
||||
->setEnv(['SPC_TARGET' => GNU_ARCH . '-linux-musl'])
|
||||
->exec('cmake ' . $cmakeArgs)
|
||||
->exec('cmake --build ' . escapeshellarg($buildDir) . ' ' . $targetArgs . " -j {$jobs}");
|
||||
|
||||
foreach (self::TOOLS as $t) {
|
||||
$built = "{$buildDir}/bin/{$t}";
|
||||
if (!is_file($built)) {
|
||||
throw new BuildFailureException("llvm-tools: missing build output {$built}");
|
||||
}
|
||||
copy($built, "{$binDir}/{$t}");
|
||||
chmod("{$binDir}/{$t}", 0755);
|
||||
}
|
||||
}
|
||||
|
||||
public function allBuilt(string $binDir): bool
|
||||
{
|
||||
foreach (self::TOOLS as $t) {
|
||||
$p = "{$binDir}/{$t}";
|
||||
if (!is_file($p) || !is_executable($p)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private function detectLlvmVersion(): ?string
|
||||
{
|
||||
if (!zig::isInstalled()) {
|
||||
return null;
|
||||
}
|
||||
[$rc, $out] = shell()->execWithResult(escapeshellarg(zig::binary()) . ' cc --version', false);
|
||||
if ($rc !== 0) {
|
||||
return null;
|
||||
}
|
||||
return preg_match('/clang version (\d+\.\d+\.\d+)/', implode("\n", $out), $m) ? $m[1] : null;
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ class rust
|
||||
$download_url = "https://static.rust-lang.org/dist/rust-{$latest_version}-{$arch}-unknown-linux-{$distro}.tar.xz";
|
||||
$path = DOWNLOAD_PATH . DIRECTORY_SEPARATOR . basename($download_url);
|
||||
default_shell()->executeCurlDownload($download_url, $path, retries: $downloader->getRetry());
|
||||
return DownloadResult::archive(basename($path), ['url' => $download_url, 'version' => $latest_version], extract: PKG_ROOT_PATH . '/rust-install', verified: false, version: $latest_version);
|
||||
return DownloadResult::archive(basename($path), ['url' => $download_url, 'version' => $latest_version], extract: '{pkg_root_path}/rust-install', verified: false, version: $latest_version);
|
||||
}
|
||||
|
||||
#[CustomBinaryCheckUpdate('rust', [
|
||||
|
||||
@@ -15,6 +15,23 @@ use StaticPHP\Runtime\SystemTarget;
|
||||
|
||||
class zig
|
||||
{
|
||||
/** Directory zig extracts into. */
|
||||
public static function path(): string
|
||||
{
|
||||
return PKG_ROOT_PATH . '/zig';
|
||||
}
|
||||
|
||||
/** Path to a binary inside the zig install dir (zig, zig-cc, zig-c++, zig-ar, …). */
|
||||
public static function binary(string $name = 'zig'): string
|
||||
{
|
||||
return self::path() . '/' . $name;
|
||||
}
|
||||
|
||||
public static function isInstalled(): bool
|
||||
{
|
||||
return is_file(self::binary());
|
||||
}
|
||||
|
||||
#[CustomBinary('zig', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
@@ -61,7 +78,7 @@ class zig
|
||||
if ($file_hash !== $sha256) {
|
||||
throw new DownloaderException("Hash mismatch for downloaded Zig binary. Expected {$sha256}, got {$file_hash}");
|
||||
}
|
||||
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $latest_version], extract: PKG_ROOT_PATH . '/zig', verified: true, version: $latest_version);
|
||||
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $latest_version], extract: '{pkg_root_path}/zig', verified: true, version: $latest_version);
|
||||
}
|
||||
|
||||
#[CustomBinaryCheckUpdate('zig', [
|
||||
@@ -110,26 +127,24 @@ class zig
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($all_exist) {
|
||||
return;
|
||||
if (!$all_exist) {
|
||||
$script_path = ROOT_DIR . '/src/globals/scripts/zig-cc.sh';
|
||||
$script_content = file_get_contents($script_path);
|
||||
|
||||
file_put_contents("{$target_path}/zig-cc", $script_content);
|
||||
chmod("{$target_path}/zig-cc", 0755);
|
||||
|
||||
$script_content = str_replace('zig cc', 'zig c++', $script_content);
|
||||
file_put_contents("{$target_path}/zig-c++", $script_content);
|
||||
file_put_contents("{$target_path}/zig-ar", "#!/usr/bin/env bash\nexec zig ar $@");
|
||||
file_put_contents("{$target_path}/zig-ld.lld", "#!/usr/bin/env bash\nexec zig ld.lld $@");
|
||||
file_put_contents("{$target_path}/zig-ranlib", "#!/usr/bin/env bash\nexec zig ranlib $@");
|
||||
file_put_contents("{$target_path}/zig-objcopy", "#!/usr/bin/env bash\nexec zig objcopy $@");
|
||||
chmod("{$target_path}/zig-c++", 0755);
|
||||
chmod("{$target_path}/zig-ar", 0755);
|
||||
chmod("{$target_path}/zig-ld.lld", 0755);
|
||||
chmod("{$target_path}/zig-ranlib", 0755);
|
||||
chmod("{$target_path}/zig-objcopy", 0755);
|
||||
}
|
||||
|
||||
$script_path = ROOT_DIR . '/src/globals/scripts/zig-cc.sh';
|
||||
$script_content = file_get_contents($script_path);
|
||||
|
||||
file_put_contents("{$target_path}/zig-cc", $script_content);
|
||||
chmod("{$target_path}/zig-cc", 0755);
|
||||
|
||||
$script_content = str_replace('zig cc', 'zig c++', $script_content);
|
||||
file_put_contents("{$target_path}/zig-c++", $script_content);
|
||||
file_put_contents("{$target_path}/zig-ar", "#!/usr/bin/env bash\nexec zig ar $@");
|
||||
file_put_contents("{$target_path}/zig-ld.lld", "#!/usr/bin/env bash\nexec zig ld.lld $@");
|
||||
file_put_contents("{$target_path}/zig-ranlib", "#!/usr/bin/env bash\nexec zig ranlib $@");
|
||||
file_put_contents("{$target_path}/zig-objcopy", "#!/usr/bin/env bash\nexec zig objcopy $@");
|
||||
chmod("{$target_path}/zig-c++", 0755);
|
||||
chmod("{$target_path}/zig-ar", 0755);
|
||||
chmod("{$target_path}/zig-ld.lld", 0755);
|
||||
chmod("{$target_path}/zig-ranlib", 0755);
|
||||
chmod("{$target_path}/zig-objcopy", 0755);
|
||||
}
|
||||
}
|
||||
|
||||
25
src/Package/Extension/clickhouse.php
Normal file
25
src/Package/Extension/clickhouse.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Package\Extension;
|
||||
|
||||
use StaticPHP\Attribute\Package\CustomPhpConfigureArg;
|
||||
use StaticPHP\Attribute\Package\Extension;
|
||||
use StaticPHP\Package\PackageInstaller;
|
||||
use StaticPHP\Package\PhpExtensionPackage;
|
||||
|
||||
#[Extension('clickhouse')]
|
||||
class clickhouse extends PhpExtensionPackage
|
||||
{
|
||||
#[CustomPhpConfigureArg('Darwin')]
|
||||
#[CustomPhpConfigureArg('Linux')]
|
||||
public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string
|
||||
{
|
||||
$arg = '--enable-clickhouse' . ($shared ? '=shared' : '');
|
||||
if ($installer->getLibraryPackage('openssl')) {
|
||||
$arg .= ' --enable-clickhouse-openssl';
|
||||
}
|
||||
return $arg;
|
||||
}
|
||||
}
|
||||
@@ -35,12 +35,37 @@ class event extends PhpExtensionPackage
|
||||
|
||||
#[BeforeStage('php', [php::class, 'makeForUnix'], 'ext-event')]
|
||||
#[PatchDescription('Prevent event extension compile error on macOS')]
|
||||
#[PatchDescription('Patch libevent http_connection.c to use a const peer address')]
|
||||
public function patchBeforeMake(PackageInstaller $installer): void
|
||||
{
|
||||
$php_src = $installer->getTargetPackage('php')->getSourceDir();
|
||||
// Prevent event extension compile error on macOS
|
||||
if (SystemTarget::getTargetOS() === 'Darwin') {
|
||||
$php_src = $installer->getTargetPackage('php')->getSourceDir();
|
||||
FileSystem::replaceFileRegex("{$php_src}/main/php_config.h", '/^#define HAVE_OPENPTY 1$/m', '');
|
||||
}
|
||||
$this->patchLibeventConstPeer("{$php_src}/ext/event");
|
||||
}
|
||||
|
||||
#[BeforeStage('ext-event', [PhpExtensionPackage::class, 'makeForUnix'])]
|
||||
#[PatchDescription('Patch libevent http_connection.c to use a const peer address')]
|
||||
public function patchBeforeSharedMake(PhpExtensionPackage $pkg): void
|
||||
{
|
||||
$this->patchLibeventConstPeer($pkg->getSourceDir());
|
||||
}
|
||||
|
||||
private function patchLibeventConstPeer(string $event_source_dir): bool
|
||||
{
|
||||
$file = "{$event_source_dir}/php8/classes/http_connection.c";
|
||||
if (!is_file($file)) {
|
||||
return false;
|
||||
}
|
||||
// libevent >= 2.2 changed evhttp_connection_get_peer()'s
|
||||
// address arg to `const char **`
|
||||
$header = $this->getBuilder()->getBuildRootPath() . '/include/event2/http.h';
|
||||
$isConst = is_file($header)
|
||||
&& preg_match('/evhttp_connection_get_peer\s*\([^;]*\bconst\s+char\s*\*\*\s*address/s', file_get_contents($header)) === 1;
|
||||
return (bool) ($isConst
|
||||
? FileSystem::replaceFileRegex($file, '/^\tchar \*address;$/m', "\tconst char *address;")
|
||||
: FileSystem::replaceFileRegex($file, '/^\tconst char \*address;$/m', "\tchar *address;"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,14 @@ use StaticPHP\Util\FileSystem;
|
||||
#[Extension('mongodb')]
|
||||
class mongodb extends PhpExtensionPackage
|
||||
{
|
||||
#[BeforeStage('php', [php::class, 'configureForUnix'], 'ext-mongodb')]
|
||||
#[PatchDescription('Export PHP_VERSION_ID so mongo-php-driver >= 2.3.3 skips its php-config lookup (in-tree builds have no php-config).')]
|
||||
public function exportPhpVersionIdForUnix(): void
|
||||
{
|
||||
$id = php::getPHPVersionID();
|
||||
f_putenv("PHP_VERSION_ID={$id}");
|
||||
}
|
||||
|
||||
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-mongodb')]
|
||||
#[PatchDescription('Add /utf-8 flag to CFLAGS_MONGODB for Windows build to fix compilation error on non-English Windows.')]
|
||||
public function patchBeforeBuild(): void
|
||||
|
||||
@@ -72,6 +72,10 @@ class opcache extends PhpExtensionPackage
|
||||
) {
|
||||
$opcache_jit = ' --disable-opcache-jit';
|
||||
}
|
||||
return '--enable-opcache' . ($shared ? '=shared' : '') . $opcache_jit;
|
||||
// PHP 8.5+ has opcache built-in
|
||||
if ($phpVersionID < 80500) {
|
||||
return '--enable-opcache' . ($shared ? '=shared' : '') . $opcache_jit;
|
||||
}
|
||||
return trim($opcache_jit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,15 +7,21 @@ namespace Package\Extension;
|
||||
use Package\Target\php;
|
||||
use StaticPHP\Attribute\Package\BeforeStage;
|
||||
use StaticPHP\Attribute\Package\Extension;
|
||||
use StaticPHP\Toolchain\Interface\ToolchainInterface;
|
||||
use StaticPHP\Toolchain\ZigToolchain;
|
||||
use StaticPHP\Util\GlobalEnvManager;
|
||||
|
||||
#[Extension('opentelemetry')]
|
||||
class opentelemetry
|
||||
{
|
||||
#[BeforeStage('php', [php::class, 'makeForUnix'], 'ext-opentelemetry')]
|
||||
public function patchBeforeMake(): void
|
||||
public function patchBeforeMake(ToolchainInterface $toolchain): void
|
||||
{
|
||||
// add -Wno-strict-prototypes
|
||||
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') . ' -Wno-strict-prototypes');
|
||||
$extra_cflags = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') ?: '';
|
||||
$extra_cflags .= ' -Wno-strict-prototypes';
|
||||
if ($toolchain instanceof ZigToolchain) {
|
||||
$extra_cflags .= ' -Wno-unknown-warning-option';
|
||||
}
|
||||
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . trim($extra_cflags));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ class password_argon2 extends PhpExtensionPackage
|
||||
#[CustomPhpConfigureArg('Darwin')]
|
||||
public function getConfigureArg(PackageInstaller $installer, PackageBuilder $builder): string
|
||||
{
|
||||
if ($installer->getLibraryPackage('openssl') !== null) {
|
||||
if ($installer->getPhpExtensionPackage('openssl')?->isBuildStatic()) {
|
||||
if (php::getPHPVersionID() >= 80500 || (php::getPHPVersionID() >= 80400 && !$builder->getOption('enable-zts'))) {
|
||||
return '--without-password-argon2'; // use --with-openssl-argon2 in openssl extension instead
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ class pgsql extends PhpExtensionPackage
|
||||
public function getUnixConfigureArg(bool $shared, PackageBuilder $builder, PackageInstaller $installer): string
|
||||
{
|
||||
if (php::getPHPVersionID() >= 80400) {
|
||||
$libfiles = new SPCConfigUtil(['libs_only_deps' => true, 'absolute_libs' => true])->getPackageDepsConfig('postgresql', array_keys($installer->getResolvedPackages()), $builder->getOption('with-suggests'))['libs'];
|
||||
$libfiles = new SPCConfigUtil(['libs_only_deps' => true, 'absolute_libs' => true])->getPackageDepsConfig('postgresql', array_keys($installer->getResolvedPackages()))['libs'];
|
||||
$libfiles = str_replace("{$builder->getLibDir()}/lib", '-l', $libfiles);
|
||||
$libfiles = str_replace('.a', '', $libfiles);
|
||||
return '--with-pgsql' . ($shared ? '=shared' : '') .
|
||||
|
||||
@@ -6,14 +6,27 @@ namespace Package\Extension;
|
||||
|
||||
use Package\Target\php;
|
||||
use StaticPHP\Attribute\Package\BeforeStage;
|
||||
use StaticPHP\Attribute\Package\CustomPhpConfigureArg;
|
||||
use StaticPHP\Attribute\Package\Extension;
|
||||
use StaticPHP\Attribute\PatchDescription;
|
||||
use StaticPHP\Package\PackageInstaller;
|
||||
use StaticPHP\Package\PhpExtensionPackage;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
|
||||
#[Extension('spx')]
|
||||
class spx extends PhpExtensionPackage
|
||||
{
|
||||
#[CustomPhpConfigureArg('Linux')]
|
||||
#[CustomPhpConfigureArg('Darwin')]
|
||||
public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string
|
||||
{
|
||||
$arg = '--enable-SPX' . ($shared ? '=shared' : '');
|
||||
if ($installer->getLibraryPackage('zlib') !== null) {
|
||||
$arg .= ' --with-zlib-dir=' . BUILD_ROOT_PATH;
|
||||
}
|
||||
return $arg;
|
||||
}
|
||||
|
||||
#[BeforeStage('php', [php::class, 'buildconfForUnix'], 'ext-spx')]
|
||||
#[PatchDescription('Fix spx extension compile error when building as static')]
|
||||
public function patchBeforeBuildconf(): bool
|
||||
|
||||
@@ -20,7 +20,7 @@ class swow extends PhpExtensionPackage
|
||||
#[CustomPhpConfigureArg('Windows')]
|
||||
public function configureArg(PackageInstaller $installer): string
|
||||
{
|
||||
$arg = '--enable-swow';
|
||||
$arg = '--enable-swow --disable-swow-pdo-pgsql';
|
||||
$arg .= $installer->getLibraryPackage('openssl') ? ' --enable-swow-ssl' : ' --disable-swow-ssl';
|
||||
$arg .= $installer->getLibraryPackage('curl') ? ' --enable-swow-curl' : ' --disable-swow-curl';
|
||||
return $arg;
|
||||
|
||||
@@ -17,7 +17,9 @@ class bzip2
|
||||
#[PatchBeforeBuild]
|
||||
public function patchBeforeBuild(LibraryPackage $lib): void
|
||||
{
|
||||
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', 'CFLAGS=-fPIC -Wall');
|
||||
// Makefile pins -O2 -fPIC; inject SPC_DEFAULT_CFLAGS
|
||||
$extra = deduplicate_flags(trim((string) getenv('SPC_DEFAULT_CFLAGS')) . ' -fPIC -Wall');
|
||||
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', "CFLAGS={$extra}");
|
||||
}
|
||||
|
||||
#[BuildFor('Windows')]
|
||||
|
||||
@@ -18,9 +18,11 @@ class fastlz
|
||||
{
|
||||
$cc = getenv('CC') ?: 'cc';
|
||||
$ar = getenv('AR') ?: 'ar';
|
||||
$extra = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
|
||||
$extra = $extra !== '' ? $extra . ' -fPIC' : '-O3 -fPIC';
|
||||
|
||||
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");
|
||||
|
||||
// Copy header file
|
||||
|
||||
@@ -24,9 +24,12 @@ class icu
|
||||
#[BuildFor('Linux')]
|
||||
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"';
|
||||
$cxxflags = 'CXXFLAGS="-std=c++17 -DPIC -fPIC -fno-ident"';
|
||||
$ldflags = $toolchain->isStatic() ? 'LDFLAGS="-static"' : '';
|
||||
$cxxflags = "CXXFLAGS=\"-std=c++17 -DPIC -fPIC -fno-ident {$userCxxFlags}\"";
|
||||
$ldflags = $toolchain->isStatic() ? "LDFLAGS=\"-static {$userLdFlags}\"" : "LDFLAGS=\"{$userLdFlags}\"";
|
||||
shell()->cd($lib->getSourceDir() . '/source')->initializeEnv($lib)
|
||||
->exec(
|
||||
"{$cppflags} {$cxxflags} {$ldflags} " .
|
||||
|
||||
@@ -42,6 +42,9 @@ class imagemagick
|
||||
->addConfigureArgs(
|
||||
'--disable-openmp',
|
||||
'--without-x',
|
||||
// implicit --with-gcc-arch
|
||||
// bleeds host cpu features into built binaries
|
||||
'--without-gcc-arch',
|
||||
);
|
||||
|
||||
// special: linux-static target needs `-static`
|
||||
|
||||
@@ -17,7 +17,9 @@ class jbig
|
||||
#[PatchBeforeBuild]
|
||||
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')]
|
||||
|
||||
@@ -27,7 +27,7 @@ class krb5
|
||||
|
||||
$resolved = array_keys($installer->getResolvedPackages());
|
||||
$spc = new SPCConfigUtil(['no_php' => true, 'libs_only_deps' => true]);
|
||||
$config = $spc->getPackageDepsConfig($lib->getName(), $resolved, include_suggests: true);
|
||||
$config = $spc->getPackageDepsConfig($lib->getName(), $resolved);
|
||||
$extraEnv = [
|
||||
'CFLAGS' => '-fcommon',
|
||||
'LIBS' => $config['libs'],
|
||||
|
||||
@@ -9,8 +9,10 @@ use StaticPHP\Attribute\Package\Library;
|
||||
use StaticPHP\Package\LibraryPackage;
|
||||
use StaticPHP\Runtime\Executor\UnixCMakeExecutor;
|
||||
use StaticPHP\Runtime\Executor\WindowsCMakeExecutor;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Toolchain\Interface\ToolchainInterface;
|
||||
use StaticPHP\Toolchain\ZigToolchain;
|
||||
use StaticPHP\Util\System\UnixUtil;
|
||||
|
||||
#[Library('libaom')]
|
||||
class libaom extends LibraryPackage
|
||||
@@ -39,9 +41,23 @@ class libaom extends LibraryPackage
|
||||
$new = trim($extra . ' -D_GNU_SOURCE');
|
||||
f_putenv("SPC_COMPILER_EXTRA={$new}");
|
||||
}
|
||||
$targetCpu = SystemTarget::getTargetArch();
|
||||
if (str_starts_with($targetCpu, 'aarch')) {
|
||||
$targetCpu = str_replace('aarch', 'arm', $targetCpu);
|
||||
}
|
||||
if (!UnixUtil::findCommand('nasm') && !UnixUtil::findCommand('yasm')) {
|
||||
$targetCpu = 'generic';
|
||||
}
|
||||
UnixCMakeExecutor::create($this)
|
||||
->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();
|
||||
f_putenv("SPC_COMPILER_EXTRA={$extra}");
|
||||
$this->patchPkgconfPrefix(['aom.pc']);
|
||||
|
||||
@@ -8,6 +8,7 @@ use StaticPHP\Attribute\Package\BuildFor;
|
||||
use StaticPHP\Attribute\Package\Library;
|
||||
use StaticPHP\Package\LibraryPackage;
|
||||
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
|
||||
#[Library('libffi')]
|
||||
class libffi extends LibraryPackage
|
||||
@@ -28,7 +29,7 @@ class libffi extends LibraryPackage
|
||||
#[BuildFor('Darwin')]
|
||||
public function buildDarwin(): void
|
||||
{
|
||||
$arch = getenv('SPC_ARCH');
|
||||
$arch = SystemTarget::getTargetArch();
|
||||
UnixAutoconfExecutor::create($this)
|
||||
->configure(
|
||||
"--host={$arch}-apple-darwin",
|
||||
|
||||
@@ -24,6 +24,17 @@ class libheif
|
||||
'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')]
|
||||
|
||||
@@ -17,10 +17,17 @@ use StaticPHP\Util\FileSystem;
|
||||
class liblz4
|
||||
{
|
||||
#[PatchBeforeBuild]
|
||||
#[PatchDescription('Fix Makefile install target for static liblz4')]
|
||||
#[PatchDescription('Compile lib sources individually so -flto -c with multiple inputs works under zig-cc/clang')]
|
||||
public function patchBeforeBuild(LibraryPackage $lib): void
|
||||
{
|
||||
FileSystem::replaceFileStr($lib->getSourceDir() . '/programs/Makefile', 'install: lz4', "install: lz4\n\ninstallewfwef: lz4");
|
||||
// `-flto -c` with multiple input files only writes a .o for the
|
||||
// first source — the others are silently dropped, leaving liblz4.a with a
|
||||
// single object. Compile each source individually so all .o files exist.
|
||||
FileSystem::replaceFileStr(
|
||||
$lib->getSourceDir() . '/lib/Makefile',
|
||||
"liblz4.a: \$(SRCFILES)\nifeq (\$(BUILD_STATIC),yes) # can be disabled on command line\n\t@echo compiling static library\n\t\$(COMPILE.c) \$^\n\t\$(AR) rcs \$@ *.o\nendif",
|
||||
"liblz4.a: \$(SRCFILES:.c=.o)\nifeq (\$(BUILD_STATIC),yes) # can be disabled on command line\n\t@echo compiling static library\n\t\$(AR) rcs \$@ \$^\nendif"
|
||||
);
|
||||
}
|
||||
|
||||
#[BuildFor('Windows')]
|
||||
|
||||
@@ -9,6 +9,7 @@ use StaticPHP\Attribute\Package\Library;
|
||||
use StaticPHP\Package\LibraryPackage;
|
||||
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
|
||||
use StaticPHP\Runtime\Executor\WindowsCMakeExecutor;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
|
||||
#[Library('libpng')]
|
||||
@@ -24,7 +25,7 @@ class libpng
|
||||
];
|
||||
|
||||
// Enable architecture-specific optimizations
|
||||
match (getenv('SPC_ARCH')) {
|
||||
match (SystemTarget::getTargetArch()) {
|
||||
'x86_64' => $args[] = '--enable-intel-sse',
|
||||
'aarch64' => $args[] = '--enable-arm-neon',
|
||||
default => null,
|
||||
|
||||
@@ -6,6 +6,8 @@ namespace Package\Library;
|
||||
|
||||
use StaticPHP\Attribute\Package\BuildFor;
|
||||
use StaticPHP\Attribute\Package\Library;
|
||||
use StaticPHP\Attribute\Package\PatchBeforeBuild;
|
||||
use StaticPHP\Attribute\PatchDescription;
|
||||
use StaticPHP\Package\LibraryPackage;
|
||||
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
|
||||
use StaticPHP\Toolchain\Interface\ToolchainInterface;
|
||||
@@ -16,6 +18,24 @@ use StaticPHP\Util\FileSystem;
|
||||
#[Library('ncursesw')]
|
||||
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('Linux')]
|
||||
public function build(LibraryPackage $package, ToolchainInterface $toolchain): void
|
||||
@@ -45,6 +65,7 @@ class ncurses
|
||||
'--without-tests',
|
||||
'--without-dlsym',
|
||||
'--without-debug',
|
||||
'--disable-stripping',
|
||||
'--enable-symlinks',
|
||||
"--with-terminfo-dirs={$terminfo_dirs}",
|
||||
"--bindir={$package->getBinDir()}",
|
||||
|
||||
@@ -76,7 +76,7 @@ class openssl
|
||||
public function buildForDarwin(LibraryPackage $pkg): void
|
||||
{
|
||||
$zlib_libs = $pkg->getInstaller()->getLibraryPackage('zlib')->getStaticLibFiles();
|
||||
$arch = getenv('SPC_ARCH');
|
||||
$arch = SystemTarget::getTargetArch();
|
||||
|
||||
shell()->cd($pkg->getSourceDir())->initializeEnv($pkg)
|
||||
->exec(
|
||||
@@ -95,12 +95,7 @@ class openssl
|
||||
#[BuildFor('Linux')]
|
||||
public function build(LibraryPackage $lib): void
|
||||
{
|
||||
$arch = getenv('SPC_ARCH');
|
||||
|
||||
$env = "CC='" . getenv('CC') . ' -idirafter ' . BUILD_INCLUDE_PATH .
|
||||
' -idirafter /usr/include/ ' .
|
||||
' -idirafter /usr/include/' . getenv('SPC_ARCH') . '-linux-gnu/ ' .
|
||||
"' ";
|
||||
$arch = SystemTarget::getTargetArch();
|
||||
|
||||
$ex_lib = trim($lib->getInstaller()->getLibraryPackage('zlib')->getStaticLibFiles()) . ' -ldl -pthread';
|
||||
$zlib_extra =
|
||||
@@ -111,9 +106,15 @@ class openssl
|
||||
$openssl_dir ??= LinuxUtil::getOSRelease()['dist'] === 'redhat' ? '/etc/pki/tls' : '/etc/ssl';
|
||||
$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)
|
||||
->exec(
|
||||
"{$env} ./Configure no-shared zlib " .
|
||||
'./Configure no-shared zlib ' .
|
||||
"--prefix={$lib->getBuildRootPath()} " .
|
||||
"--libdir={$lib->getLibDir()} " .
|
||||
"--openssldir={$openssl_dir} " .
|
||||
@@ -121,7 +122,8 @@ class openssl
|
||||
'enable-pie ' .
|
||||
'no-legacy ' .
|
||||
'no-tests ' .
|
||||
"linux-{$arch}"
|
||||
"linux-{$arch} " .
|
||||
$userExtra
|
||||
)
|
||||
->exec('make clean')
|
||||
->exec("make -j{$lib->getBuilder()->concurrency} CNF_EX_LIBS=\"{$ex_lib}\"")
|
||||
|
||||
@@ -58,7 +58,7 @@ class postgresql extends LibraryPackage
|
||||
public function buildUnix(PackageInstaller $installer, PackageBuilder $builder): void
|
||||
{
|
||||
$spc_config = new SPCConfigUtil(['no_php' => true, 'libs_only_deps' => true]);
|
||||
$config = $spc_config->getPackageDepsConfig('postgresql', array_keys($installer->getResolvedPackages()), include_suggests: $builder->getOption('with-suggests', false));
|
||||
$config = $spc_config->getPackageDepsConfig('postgresql', array_keys($installer->getResolvedPackages()));
|
||||
|
||||
$env_vars = [
|
||||
'CFLAGS' => $config['cflags'] . ' -std=c17',
|
||||
|
||||
@@ -20,6 +20,11 @@ class qdbm
|
||||
{
|
||||
$ac = UnixAutoconfExecutor::create($lib)->configure();
|
||||
FileSystem::replaceFileRegex($lib->getSourceDir() . '/Makefile', '/MYLIBS = libqdbm.a.*/m', 'MYLIBS = libqdbm.a');
|
||||
// Makefile pins -O3, replace with SPC_DEFAULT_CFLAGS
|
||||
$extra = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
|
||||
if ($extra !== '') {
|
||||
FileSystem::replaceFileRegex($lib->getSourceDir() . '/Makefile', '/^CFLAGS = .*$/m', "CFLAGS = -Wall {$extra}");
|
||||
}
|
||||
$ac->make(SystemTarget::getTargetOS() === 'Darwin' ? 'mac' : '');
|
||||
$lib->patchPkgconfPrefix(['qdbm.pc']);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,20 @@ class unixodbc extends LibraryPackage
|
||||
'Linux' => '/etc',
|
||||
default => throw new WrongUsageException("Unsupported OS: {$os}"),
|
||||
};
|
||||
UnixAutoconfExecutor::create($this)
|
||||
|
||||
// unixodbc bundles libltdl; libltdl is incompatible with -flto
|
||||
// (https://bugs.gentoo.org/532672).
|
||||
$stripLto = static fn (string $s): string => clean_spaces((string) preg_replace('/(^|\s)-flto(=\S+)?(?=\s|$)/', ' ', $s));
|
||||
$cflags = $stripLto((string) getenv('SPC_DEFAULT_CFLAGS'));
|
||||
$cxxflags = $stripLto((string) getenv('SPC_DEFAULT_CXXFLAGS'));
|
||||
$ldflags = $stripLto((string) getenv('SPC_DEFAULT_LDFLAGS'));
|
||||
|
||||
$make = UnixAutoconfExecutor::create($this)
|
||||
->setEnv([
|
||||
'CFLAGS' => $cflags,
|
||||
'CXXFLAGS' => $cxxflags,
|
||||
'LDFLAGS' => $ldflags,
|
||||
])
|
||||
->configure(
|
||||
'--disable-debug',
|
||||
'--disable-dependency-tracking',
|
||||
@@ -35,8 +48,15 @@ class unixodbc extends LibraryPackage
|
||||
'--with-included-ltdl',
|
||||
"--sysconfdir={$sysconf_selector}",
|
||||
'--enable-gui=no',
|
||||
)
|
||||
->make();
|
||||
);
|
||||
|
||||
// The exe/ subdirectory builds odbcinst/iusql/etc, turn it into a no-op
|
||||
file_put_contents(
|
||||
"{$this->getSourceDir()}/exe/Makefile",
|
||||
".PHONY: all install clean check distclean install-strip\nall install clean check distclean install-strip:\n\t@true\n",
|
||||
);
|
||||
|
||||
$make->make();
|
||||
$this->patchPkgconfPrefix(['odbc.pc', 'odbccr.pc', 'odbcinst.pc']);
|
||||
$this->patchLaDependencyPrefix();
|
||||
}
|
||||
|
||||
@@ -20,9 +20,8 @@ class watcher extends LibraryPackage
|
||||
if (stripos($cflags, '-fpic') === false) {
|
||||
$cflags .= ' -fPIC';
|
||||
}
|
||||
$ldflags = $this->getLibExtraLdFlags() ? ' ' . $this->getLibExtraLdFlags() : '';
|
||||
shell()->cd("{$this->getSourceDir()}/watcher-c")
|
||||
->exec(getenv('CXX') . " -c -o libwatcher-c.o ./src/watcher-c.cpp -I ./include -I ../include -std=c++17 -Wall -Wextra {$cflags}{$ldflags}")
|
||||
->exec(getenv('CXX') . " -c -o libwatcher-c.o ./src/watcher-c.cpp -I ./include -I ../include -std=c++17 -Wall -Wextra {$cflags}")
|
||||
->exec(getenv('AR') . ' rcs libwatcher-c.a libwatcher-c.o');
|
||||
|
||||
copy("{$this->getSourceDir()}/watcher-c/libwatcher-c.a", "{$this->getLibDir()}/libwatcher-c.a");
|
||||
|
||||
@@ -39,7 +39,7 @@ class curl
|
||||
->optionalPackage('zstd', ...cmake_boolean_args('CURL_ZSTD'))
|
||||
->optionalPackage('brotli', ...cmake_boolean_args('CURL_BROTLI'))
|
||||
->addConfigureArgs(
|
||||
'-DBUILD_CURL_EXE=OFF',
|
||||
'-DBUILD_CURL_EXE=ON',
|
||||
'-DZSTD_LIBRARY=zstd_static.lib',
|
||||
'-DBUILD_TESTING=OFF',
|
||||
'-DBUILD_EXAMPLES=OFF',
|
||||
@@ -81,6 +81,7 @@ class curl
|
||||
->addConfigureArgs(
|
||||
'-DBUILD_CURL_EXE=ON',
|
||||
'-DBUILD_LIBCURL_DOCS=OFF',
|
||||
'-DOPENSSL_ROOT_DIR=' . BUILD_ROOT_PATH,
|
||||
)
|
||||
->build();
|
||||
|
||||
@@ -92,6 +93,9 @@ class curl
|
||||
if (str_contains(FileSystem::readFile($pc_path), '-lgssapi_krb5')) {
|
||||
FileSystem::replaceFileRegex($pc_path, '/-lcom_err$/m', '-lcom_err -lkrb5support');
|
||||
}
|
||||
// FindThreads can put '-lpthread' into INTERFACE_LINK_LIBRARIES; curl's pc generator
|
||||
// prepends '-l' to each entry, producing '-l-lpthread'. Strip the extra '-l'.
|
||||
FileSystem::replaceFileRegex($pc_path, '/-l(-l\S+)/', '$1');
|
||||
shell()->cd("{$lib->getLibDir()}/cmake/CURL/")
|
||||
->exec("sed -ie 's|\"/lib/libcurl.a\"|\"{$lib->getLibDir()}/libcurl.a\"|g' CURLTargets-release.cmake");
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Package\Target;
|
||||
|
||||
use Package\Target\php\frankenphp;
|
||||
use Package\Target\php\pgo;
|
||||
use Package\Target\php\unix;
|
||||
use Package\Target\php\windows;
|
||||
use StaticPHP\Artifact\ArtifactCache;
|
||||
@@ -48,6 +49,7 @@ class php extends TargetPackage
|
||||
use unix;
|
||||
use windows;
|
||||
use frankenphp;
|
||||
use pgo;
|
||||
|
||||
/** @var string[] Supported major PHP versions */
|
||||
public const array SUPPORTED_MAJOR_VERSIONS = ['7.4', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5'];
|
||||
@@ -141,6 +143,7 @@ class php extends TargetPackage
|
||||
$package->addBuildOption('disable-opcache-jit', null, null, 'Disable opcache jit');
|
||||
$package->addBuildOption('with-config-file-path', null, InputOption::VALUE_REQUIRED, 'Set the path in which to look for php.ini', PHP_OS_FAMILY === 'Windows' ? null : '/usr/local/etc/php');
|
||||
$package->addBuildOption('with-config-file-scan-dir', null, InputOption::VALUE_REQUIRED, 'Set the directory to scan for .ini files after reading php.ini', PHP_OS_FAMILY === 'Windows' ? null : '/usr/local/etc/php/conf.d');
|
||||
$package->addBuildOption('with-sysconfdir', null, InputOption::VALUE_REQUIRED, 'Set the sysconfdir (e.g. /etc/php-zts) used by configure (not available on Windows)');
|
||||
$package->addBuildOption('with-hardcoded-ini', 'I', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Patch PHP source code, inject hardcoded INI');
|
||||
$package->addBuildOption('enable-zts', null, null, 'Enable thread safe support');
|
||||
$package->addBuildOption('no-smoke-test', null, InputOption::VALUE_OPTIONAL, 'Disable smoke test for specific SAPIs, or all if no value provided', false);
|
||||
@@ -268,12 +271,14 @@ class php extends TargetPackage
|
||||
}
|
||||
}
|
||||
// linux does not support loading shared libraries when target is pure static
|
||||
$embed_type = getenv('SPC_CMD_VAR_PHP_EMBED_TYPE') ?: 'static';
|
||||
if (SystemTarget::getTargetOS() === 'Linux' && ApplicationContext::get(ToolchainInterface::class)->isStatic() && $embed_type === 'shared') {
|
||||
throw new WrongUsageException(
|
||||
'Linux does not support loading shared libraries when linking libc statically. ' .
|
||||
'Change SPC_CMD_VAR_PHP_EMBED_TYPE to static.'
|
||||
);
|
||||
if ($package->getName() === 'php-embed') {
|
||||
$embed_type = getenv('SPC_CMD_VAR_PHP_EMBED_TYPE') ?: 'static';
|
||||
if (SystemTarget::getTargetOS() === 'Linux' && ApplicationContext::get(ToolchainInterface::class)->isStatic() && $embed_type === 'shared') {
|
||||
throw new WrongUsageException(
|
||||
'Linux does not support loading shared libraries when linking libc statically. ' .
|
||||
'Change SPC_CMD_VAR_PHP_EMBED_TYPE to static.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +337,7 @@ class php extends TargetPackage
|
||||
logger()->info("Adding hardcoded INI [{$source_name} = {$ini_value}]");
|
||||
}
|
||||
if (!empty($custom_ini)) {
|
||||
ApplicationContext::invoke([SourcePatcher::class, 'patchHardcodedINI'], [$package->getSourceDir(), $custom_ini]);
|
||||
ApplicationContext::invoke([SourcePatcher::class, 'patchHardcodedINI'], ['php_source_dir' => $package->getSourceDir(), 'ini' => $custom_ini]);
|
||||
}
|
||||
|
||||
// Patch StaticPHP version
|
||||
|
||||
@@ -73,10 +73,7 @@ trait frankenphp
|
||||
$staticFlags = '';
|
||||
}
|
||||
|
||||
$resolved = array_keys($installer->getResolvedPackages());
|
||||
// remove self from deps
|
||||
$resolved = array_filter($resolved, fn ($pkg_name) => $pkg_name !== $package->getName());
|
||||
$config = new SPCConfigUtil()->config($resolved);
|
||||
$config = new SPCConfigUtil()->config(['frankenphp']);
|
||||
$cflags = "{$package->getLibExtraCFlags()} {$config['cflags']} " . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') . " -DFRANKENPHP_VERSION={$frankenphp_version}";
|
||||
$libs = $config['libs'];
|
||||
|
||||
@@ -88,10 +85,13 @@ trait frankenphp
|
||||
$libs .= ' -lgcov';
|
||||
}
|
||||
|
||||
$extraLdProgram = clean_spaces((string) getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS_PROGRAM'));
|
||||
$env = [
|
||||
'CGO_ENABLED' => '1',
|
||||
'CGO_CFLAGS' => clean_spaces($cflags),
|
||||
'CGO_LDFLAGS' => "{$package->getLibExtraLdFlags()} {$staticFlags} {$config['ldflags']} {$libs}",
|
||||
'CGO_LDFLAGS' => clean_spaces("{$package->getLibExtraLdFlags()} {$staticFlags} {$config['ldflags']} {$libs} {$extraLdProgram}"),
|
||||
// cgo strips flags not on its safe allowlist; widen it
|
||||
'CGO_LDFLAGS_ALLOW' => '-Wl,-z,.*|-Wl,--.*|-flto.*|-fprofile-.*',
|
||||
'XCADDY_GO_BUILD_FLAGS' => '-buildmode=pie ' .
|
||||
'-ldflags \"-linkmode=external ' . $extLdFlags . ' ' .
|
||||
'-X \'github.com/caddyserver/caddy/v2/modules/caddyhttp.ServerHeader=FrankenPHP Caddy\' ' .
|
||||
@@ -101,10 +101,12 @@ trait frankenphp
|
||||
"-tags={$muslTags}nobadger,nomysql,nopgx{$no_brotli}{$no_watcher}",
|
||||
'LD_LIBRARY_PATH' => BUILD_LIB_PATH,
|
||||
];
|
||||
$pgo = file_exists("{$source_dir}/caddy/frankenphp/default.pgo") ? "--pgo {$source_dir}/caddy/frankenphp/default.pgo " : '';
|
||||
InteractiveTerm::setMessage('Building frankenphp: ' . ConsoleColor::yellow('building with xcaddy'));
|
||||
shell()->cd(BUILD_LIB_PATH)
|
||||
->setEnv($env)
|
||||
->exec("xcaddy build --output frankenphp {$xcaddy_modules}");
|
||||
->exec('go clean -cache') // fix stale include evaluation
|
||||
->exec("xcaddy build --output frankenphp {$pgo}{$xcaddy_modules}");
|
||||
|
||||
$builder->deployBinary(BUILD_LIB_PATH . '/frankenphp', BUILD_BIN_PATH . '/frankenphp');
|
||||
$package->setOutput('Binary path for FrankenPHP SAPI', BUILD_BIN_PATH . '/frankenphp');
|
||||
|
||||
127
src/Package/Target/php/pgo.php
Normal file
127
src/Package/Target/php/pgo.php
Normal file
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Package\Target\php;
|
||||
|
||||
use StaticPHP\Attribute\Package\AfterStage;
|
||||
use StaticPHP\Attribute\Package\BeforeStage;
|
||||
use StaticPHP\Attribute\Package\ConditionalOn;
|
||||
use StaticPHP\Attribute\PatchDescription;
|
||||
use StaticPHP\Exception\WrongUsageException;
|
||||
use StaticPHP\Package\TargetPackage;
|
||||
use StaticPHP\Util\Pgo\PgoContext;
|
||||
use StaticPHP\Util\SourcePatcher;
|
||||
|
||||
trait pgo
|
||||
{
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'buildconfForUnix'], 'php')]
|
||||
#[PatchDescription('Inject __llvm_profile_write_file() flush at php/frankenphp shutdown for instrumented builds')]
|
||||
public function pgoApplyShutdownPatches(PgoContext $pgo): void
|
||||
{
|
||||
if (!$pgo->isInstrument() && !$pgo->isCsInstrument()) {
|
||||
return;
|
||||
}
|
||||
foreach (PgoContext::SHUTDOWN_PATCHES as $dir => $patch) {
|
||||
$cwd = SOURCE_PATH . '/' . $dir;
|
||||
if (!is_dir($cwd)) {
|
||||
continue;
|
||||
}
|
||||
if (!SourcePatcher::patchFile($patch, $cwd)) {
|
||||
throw new WrongUsageException("PGO --phase=instrument: patch {$patch} failed to apply in {$cwd}");
|
||||
}
|
||||
logger()->info("PGO --phase=instrument: applied {$patch}");
|
||||
}
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[AfterStage('php', [self::class, 'configureForUnix'], 'php')]
|
||||
#[PatchDescription('Patch libtool to passthrough -fcs-profile-* for context-sensitive PGO')]
|
||||
public function pgoPatchLibtoolForCsInstrument(PgoContext $pgo): void
|
||||
{
|
||||
if (!$pgo->isCsInstrument()) {
|
||||
return;
|
||||
}
|
||||
$libtool = SOURCE_PATH . '/php-src/libtool';
|
||||
if (!is_file($libtool)) {
|
||||
return;
|
||||
}
|
||||
$contents = (string) file_get_contents($libtool);
|
||||
if (str_contains($contents, '-fcs-profile-*')) {
|
||||
return;
|
||||
}
|
||||
$patched = str_replace('-fprofile-*|-F*', '-fprofile-*|-fcs-profile-*|-F*', $contents);
|
||||
if ($patched === $contents) {
|
||||
logger()->warning('PGO --phase=cs-instrument: could not patch libtool for -fcs-profile-* passthrough');
|
||||
return;
|
||||
}
|
||||
file_put_contents($libtool, $patched);
|
||||
logger()->info('PGO --phase=cs-instrument: patched libtool for -fcs-profile-* passthrough');
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'configureForUnix'], 'php')]
|
||||
public function pgoApplyConfigureFlags(PgoContext $pgo): void
|
||||
{
|
||||
$sapis = $pgo->trainableSapis();
|
||||
if ($sapis === []) {
|
||||
return;
|
||||
}
|
||||
$pgo->applyEnvFor($sapis[0]);
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'makeCliForUnix'], 'php')]
|
||||
public function pgoBeforeMakeCli(PgoContext $pgo, TargetPackage $package): void
|
||||
{
|
||||
$this->pgoBeforeSapiMake($pgo, $package, 'cli');
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'makeCgiForUnix'], 'php')]
|
||||
public function pgoBeforeMakeCgi(PgoContext $pgo, TargetPackage $package): void
|
||||
{
|
||||
$this->pgoBeforeSapiMake($pgo, $package, 'cgi');
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'makeFpmForUnix'], 'php')]
|
||||
public function pgoBeforeMakeFpm(PgoContext $pgo, TargetPackage $package): void
|
||||
{
|
||||
$this->pgoBeforeSapiMake($pgo, $package, 'fpm');
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'makeMicroForUnix'], 'php')]
|
||||
public function pgoBeforeMakeMicro(PgoContext $pgo, TargetPackage $package): void
|
||||
{
|
||||
$this->pgoBeforeSapiMake($pgo, $package, 'micro');
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'makeEmbedForUnix'], 'php')]
|
||||
public function pgoBeforeMakeEmbed(PgoContext $pgo, TargetPackage $package): void
|
||||
{
|
||||
$this->pgoBeforeSapiMake($pgo, $package, 'embed');
|
||||
}
|
||||
|
||||
#[ConditionalOn(PgoContext::class)]
|
||||
#[BeforeStage('php', [self::class, 'buildFrankenphpForUnix'], 'php')]
|
||||
public function pgoBeforeBuildFrankenphp(PgoContext $pgo): void
|
||||
{
|
||||
$pgo->applyEnvFor('frankenphp');
|
||||
logger()->info("PGO {$pgo->mode}: applying flags for frankenphp");
|
||||
}
|
||||
|
||||
private function pgoBeforeSapiMake(PgoContext $pgo, TargetPackage $package, string $sapi): void
|
||||
{
|
||||
$resolved = $pgo->resolveSapi($sapi);
|
||||
if (!in_array($resolved, $pgo->trainableSapis(), true)) {
|
||||
return;
|
||||
}
|
||||
shell()->cd($package->getSourceDir())->exec('make clean');
|
||||
$pgo->applyEnvFor($sapi);
|
||||
logger()->info("PGO {$pgo->mode}: applying flags for {$sapi}");
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,11 @@ use StaticPHP\Package\PhpExtensionPackage;
|
||||
use StaticPHP\Package\TargetPackage;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Toolchain\Interface\ToolchainInterface;
|
||||
use StaticPHP\Toolchain\ToolchainManager;
|
||||
use StaticPHP\Toolchain\ZigToolchain;
|
||||
use StaticPHP\Util\DirDiff;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
use StaticPHP\Util\GlobalEnvManager;
|
||||
use StaticPHP\Util\InteractiveTerm;
|
||||
use StaticPHP\Util\SourcePatcher;
|
||||
use StaticPHP\Util\SPCConfigUtil;
|
||||
@@ -39,6 +42,15 @@ trait unix
|
||||
// php-src patches from micro (reads SPC_MICRO_PATCHES env var)
|
||||
SourcePatcher::patchPhpSrc();
|
||||
|
||||
$microFileinfo = "{$package->getSourceDir()}/sapi/micro/php_micro_fileinfo.c";
|
||||
if (is_file($microFileinfo) && !str_contains((string) file_get_contents($microFileinfo), 'Elf32_Shdr')) {
|
||||
FileSystem::replaceFileStr(
|
||||
$microFileinfo,
|
||||
'typedef Elf32_Ehdr Elf_Ehdr;',
|
||||
'typedef Elf32_Ehdr Elf_Ehdr; typedef Elf32_Shdr Elf_Shdr;',
|
||||
);
|
||||
}
|
||||
|
||||
// patch configure.ac for musl and musl-toolchain
|
||||
$musl = SystemTarget::getTargetOS() === 'Linux' && SystemTarget::getLibc() === 'musl';
|
||||
FileSystem::backupFile(SOURCE_PATH . '/php-src/configure.ac');
|
||||
@@ -57,12 +69,13 @@ trait unix
|
||||
}
|
||||
|
||||
if (self::getPHPVersionID() >= 80300 && self::getPHPVersionID() < 80400) {
|
||||
SourcePatcher::patchFile('spc_fix_avx512_cache_before_80400.patch', $this->getSourceDir());
|
||||
SourcePatcher::patchFile('spc_fix_avx512_cache_before_80400.patch', SOURCE_PATH . '/php-src');
|
||||
}
|
||||
}
|
||||
|
||||
#[BeforeStage('php', [self::class, 'configureForUnix'], 'php')]
|
||||
#[PatchDescription('Patch configure to use -std=gnu17 instead of -std=gnu23 for PHP <= 8.2')]
|
||||
#[PatchDescription('Strip build-time env vars from phpinfo\'s "Configure Command"')]
|
||||
public function patchBeforeConfigure(TargetPackage $package): void
|
||||
{
|
||||
if (SystemTarget::isUnix() && self::getPHPVersionID() < 80300) {
|
||||
@@ -72,6 +85,22 @@ trait unix
|
||||
"for ac_arg in '' -std=gnu17",
|
||||
);
|
||||
}
|
||||
|
||||
// strip our build-time env vars from phpinfo's "Configure Command" ('|' delimiter: PHP_BUILD_PROVIDER may contain '#')
|
||||
if (SystemTarget::isUnix()) {
|
||||
FileSystem::replaceFileStr(
|
||||
"{$package->getSourceDir()}/configure",
|
||||
'for var in CFLAGS CXXFLAGS CPPFLAGS LDFLAGS EXTRA_LDFLAGS_PROGRAM LIBS CC CXX; do',
|
||||
'for var in CFLAGS CXXFLAGS CPPFLAGS LDFLAGS EXTRA_LDFLAGS_PROGRAM LIBS CC CXX '
|
||||
. 'PKG_CONFIG PKG_CONFIG_PATH EXTENSION_DIR OPENSSL_LIBS '
|
||||
. 'PHP_BUILD_SYSTEM PHP_BUILD_PROVIDER PHP_BUILD_COMPILER PHP_BUILD_ARCH; do',
|
||||
);
|
||||
FileSystem::replaceFileStr(
|
||||
"{$package->getSourceDir()}/configure",
|
||||
'clean_configure_args=$(echo $clean_configure_args | $SED -e "s#\'$var=$val\'##")',
|
||||
'clean_configure_args=$(echo $clean_configure_args | $SED -e "s|\'$var=$val\'||")',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[Stage]
|
||||
@@ -90,11 +119,10 @@ trait unix
|
||||
$args = [];
|
||||
$version_id = self::getPHPVersionID();
|
||||
|
||||
// disable undefined behavior sanitizer when opcache JIT is enabled (Linux only)
|
||||
if (SystemTarget::getTargetOS() === 'Linux' && !$package->getBuildOption('disable-opcache-jit', false)) {
|
||||
if ($version_id >= 80500 || $installer->isPackageResolved('ext-opcache')) {
|
||||
f_putenv('SPC_COMPILER_EXTRA=-fno-sanitize=undefined');
|
||||
}
|
||||
// disable undefined behavior sanitizer for zig, trips up on lua minijit and opcache-jit
|
||||
if (SystemTarget::getTargetOS() === 'Linux' && ToolchainManager::getToolchainClass() === ZigToolchain::class) {
|
||||
$compiler_extra = getenv('SPC_COMPILER_EXTRA') ?: '';
|
||||
GlobalEnvManager::putenv('SPC_COMPILER_EXTRA=' . trim($compiler_extra . ' -fno-sanitize=undefined'));
|
||||
}
|
||||
// PHP JSON extension is built-in since PHP 8.0
|
||||
if ($version_id < 80000) {
|
||||
@@ -114,6 +142,9 @@ trait unix
|
||||
if ($option = $package->getBuildOption('with-config-file-scan-dir', false)) {
|
||||
$args[] = "--with-config-file-scan-dir={$option}";
|
||||
}
|
||||
if ($option = $package->getBuildOption('with-sysconfdir', false)) {
|
||||
$args[] = "--sysconfdir={$option}";
|
||||
}
|
||||
// perform enable cli options
|
||||
$args[] = $installer->isPackageResolved('php-cli') ? '--enable-cli' : '--disable-cli';
|
||||
$args[] = $installer->isPackageResolved('php-fpm')
|
||||
@@ -126,6 +157,10 @@ trait unix
|
||||
$args[] = $installer->isPackageResolved('php-cgi') ? '--enable-cgi' : '--disable-cgi';
|
||||
$embed_type = getenv('SPC_CMD_VAR_PHP_EMBED_TYPE') ?: 'static';
|
||||
$args[] = $installer->isPackageResolved('php-embed') ? "--enable-embed={$embed_type}" : '--disable-embed';
|
||||
// Cross-compile: pass --host so configure picks the correct fiber asm file and host_cpu logic
|
||||
if ($host_triple = SystemTarget::getAutoconfHostTriple()) {
|
||||
$args[] = "--host={$host_triple}";
|
||||
}
|
||||
$args[] = getenv('SPC_EXTRA_PHP_VARS') ?: null;
|
||||
$args = implode(' ', array_filter($args));
|
||||
|
||||
@@ -138,7 +173,7 @@ trait unix
|
||||
$this->seekPhpSrcLogFileOnException(fn () => shell()->cd($package->getSourceDir())->setEnv([
|
||||
'CFLAGS' => getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS'),
|
||||
'CPPFLAGS' => "-I{$package->getIncludeDir()}",
|
||||
'LDFLAGS' => "-L{$package->getLibDir()} " . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS'),
|
||||
'LDFLAGS' => "-L{$package->getLibDir()}",
|
||||
'LIBS' => $vars['EXTRA_LIBS'] ?? '',
|
||||
])->exec("{$cmd} {$args} {$static_extension_str}"), $package->getSourceDir());
|
||||
}
|
||||
@@ -165,14 +200,21 @@ trait unix
|
||||
|
||||
#[BeforeStage('php', [self::class, 'makeForUnix'], 'php')]
|
||||
#[PatchDescription('Patch Makefile to fix //lib path for Linux builds')]
|
||||
public function tryPatchMakefileUnix(): void
|
||||
#[PatchDescription('Under CI: patch BUILD_CC to system cc — zig-cc-built minilua segfaults there for reasons we cannot reproduce locally')]
|
||||
public function tryPatchMakefileUnix(TargetPackage $package, ToolchainInterface $toolchain): void
|
||||
{
|
||||
if (SystemTarget::getTargetOS() !== 'Linux') {
|
||||
return;
|
||||
}
|
||||
|
||||
// replace //lib with /lib in Makefile
|
||||
shell()->cd(SOURCE_PATH . '/php-src')->exec('sed -i "s|//lib|/lib|g" Makefile');
|
||||
shell()->cd($package->getSourceDir())->exec('sed -i "s|//lib|/lib|g" Makefile');
|
||||
|
||||
// CI escape hatch: in CI, zig-cc-built minilua segfaults
|
||||
if ($toolchain instanceof ZigToolchain && getenv('CI')) {
|
||||
$makefile = "{$package->getSourceDir()}/Makefile";
|
||||
FileSystem::replaceFileRegex($makefile, '/^BUILD_CC\s*=\s*zig-cc\s*$/m', 'BUILD_CC = cc');
|
||||
}
|
||||
}
|
||||
|
||||
#[BeforeStage('php', [self::class, 'makeForUnix'], 'php')]
|
||||
@@ -220,6 +262,7 @@ trait unix
|
||||
#[Stage]
|
||||
public function makeCliForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
|
||||
{
|
||||
$start = microtime(true);
|
||||
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make cli'));
|
||||
$concurrency = $builder->concurrency;
|
||||
$vars = $this->makeVars($installer);
|
||||
@@ -230,11 +273,13 @@ trait unix
|
||||
|
||||
$builder->deployBinary("{$package->getSourceDir()}/sapi/cli/php", BUILD_BIN_PATH . '/php');
|
||||
$package->setOutput('Binary path for cli SAPI', BUILD_BIN_PATH . '/php');
|
||||
InteractiveTerm::success('Built SAPI: ' . ConsoleColor::green('php-cli'), true, $start);
|
||||
}
|
||||
|
||||
#[Stage]
|
||||
public function makeCgiForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
|
||||
{
|
||||
$start = microtime(true);
|
||||
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make cgi'));
|
||||
$concurrency = $builder->concurrency;
|
||||
$vars = $this->makeVars($installer);
|
||||
@@ -245,11 +290,13 @@ trait unix
|
||||
|
||||
$builder->deployBinary("{$package->getSourceDir()}/sapi/cgi/php-cgi", BUILD_BIN_PATH . '/php-cgi');
|
||||
$package->setOutput('Binary path for cgi SAPI', BUILD_BIN_PATH . '/php-cgi');
|
||||
InteractiveTerm::success('Built SAPI: ' . ConsoleColor::green('php-cgi'), true, $start);
|
||||
}
|
||||
|
||||
#[Stage]
|
||||
public function makeFpmForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
|
||||
{
|
||||
$start = microtime(true);
|
||||
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make fpm'));
|
||||
$concurrency = $builder->concurrency;
|
||||
$vars = $this->makeVars($installer);
|
||||
@@ -260,43 +307,58 @@ trait unix
|
||||
|
||||
$builder->deployBinary("{$package->getSourceDir()}/sapi/fpm/php-fpm", BUILD_BIN_PATH . '/php-fpm');
|
||||
$package->setOutput('Binary path for fpm SAPI', BUILD_BIN_PATH . '/php-fpm');
|
||||
InteractiveTerm::success('Built SAPI: ' . ConsoleColor::green('php-fpm'), true, $start);
|
||||
}
|
||||
|
||||
#[Stage]
|
||||
#[PatchDescription('Patch phar extension for micro SAPI to support compressed phar')]
|
||||
public function makeMicroForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
|
||||
{
|
||||
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make micro'));
|
||||
// apply --with-micro-fake-cli option
|
||||
$vars = $this->makeVars($installer);
|
||||
$vars['EXTRA_CFLAGS'] .= $package->getBuildOption('with-micro-fake-cli', false) ? ' -DPHP_MICRO_FAKE_CLI' : '';
|
||||
$makeArgs = $this->makeVarsToArgs($vars);
|
||||
// build
|
||||
shell()->cd($package->getSourceDir())
|
||||
->setEnv($vars)
|
||||
->exec("make -j{$builder->concurrency} {$makeArgs} micro");
|
||||
$start = microtime(true);
|
||||
$phar_patched = false;
|
||||
try {
|
||||
if ($installer->isPackageResolved('ext-phar')) {
|
||||
$phar_patched = true;
|
||||
SourcePatcher::patchMicroPhar(self::getPHPVersionID());
|
||||
}
|
||||
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make micro'));
|
||||
// apply --with-micro-fake-cli option
|
||||
$vars = $this->makeVars($installer);
|
||||
$vars['EXTRA_CFLAGS'] .= $package->getBuildOption('with-micro-fake-cli', false) ? ' -DPHP_MICRO_FAKE_CLI' : '';
|
||||
$makeArgs = $this->makeVarsToArgs($vars);
|
||||
// build
|
||||
shell()->cd($package->getSourceDir())
|
||||
->setEnv($vars)
|
||||
->exec("make -j{$builder->concurrency} {$makeArgs} micro");
|
||||
|
||||
$dst = BUILD_BIN_PATH . '/micro.sfx';
|
||||
$builder->deployBinary($package->getSourceDir() . '/sapi/micro/micro.sfx', $dst);
|
||||
// patch after UPX-ed micro.sfx (Linux only)
|
||||
if (SystemTarget::getTargetOS() === 'Linux' && $builder->getOption('with-upx-pack')) {
|
||||
// cut binary with readelf to remove UPX extra segment
|
||||
[$ret, $out] = shell()->execWithResult("readelf -l {$dst} | awk '/LOAD|GNU_STACK/ {getline; print \\$1, \\$2, \\$3, \\$4, \\$6, \\$7}'");
|
||||
$out[1] = explode(' ', $out[1]);
|
||||
$offset = $out[1][0];
|
||||
if ($ret !== 0 || !str_starts_with($offset, '0x')) {
|
||||
throw new PatchException('phpmicro UPX patcher', 'Cannot find offset in readelf output');
|
||||
$dst = BUILD_BIN_PATH . '/micro.sfx';
|
||||
$builder->deployBinary($package->getSourceDir() . '/sapi/micro/micro.sfx', $dst);
|
||||
// patch after UPX-ed micro.sfx (Linux only)
|
||||
if (SystemTarget::getTargetOS() === 'Linux' && $builder->getOption('with-upx-pack')) {
|
||||
// cut binary with readelf to remove UPX extra segment
|
||||
[$ret, $out] = shell()->execWithResult("readelf -l {$dst} | awk '/LOAD|GNU_STACK/ {getline; print \\$1, \\$2, \\$3, \\$4, \\$6, \\$7}'");
|
||||
$out[1] = explode(' ', $out[1]);
|
||||
$offset = $out[1][0];
|
||||
if ($ret !== 0 || !str_starts_with($offset, '0x')) {
|
||||
throw new PatchException('phpmicro UPX patcher', 'Cannot find offset in readelf output');
|
||||
}
|
||||
$offset = hexdec($offset);
|
||||
// remove upx extra wastes
|
||||
file_put_contents($dst, substr(file_get_contents($dst), 0, $offset));
|
||||
}
|
||||
$package->setOutput('Binary path for micro SAPI', $dst);
|
||||
InteractiveTerm::success('Built SAPI: ' . ConsoleColor::green('php-micro'), true, $start);
|
||||
} finally {
|
||||
if ($phar_patched) {
|
||||
SourcePatcher::unpatchMicroPhar();
|
||||
}
|
||||
$offset = hexdec($offset);
|
||||
// remove upx extra wastes
|
||||
file_put_contents($dst, substr(file_get_contents($dst), 0, $offset));
|
||||
}
|
||||
$package->setOutput('Binary path for micro SAPI', $dst);
|
||||
}
|
||||
|
||||
#[Stage]
|
||||
public function makeEmbedForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
|
||||
{
|
||||
$start = microtime(true);
|
||||
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make embed'));
|
||||
$shared_exts = array_filter(
|
||||
$installer->getResolvedPackages(),
|
||||
@@ -310,22 +372,43 @@ trait unix
|
||||
$root = BUILD_ROOT_PATH;
|
||||
$sed_prefix = SystemTarget::getTargetOS() === 'Darwin' ? 'sed -i ""' : 'sed -i';
|
||||
|
||||
$vars = $this->makeVars($installer);
|
||||
$makeArgs = $this->makeVarsToArgs($vars);
|
||||
shell()->cd($package->getSourceDir())
|
||||
->setEnv($this->makeVars($installer))
|
||||
->setEnv($vars)
|
||||
->exec("{$sed_prefix} \"s|^EXTENSION_DIR = .*|EXTENSION_DIR = /" . basename(BUILD_MODULES_PATH) . '|" Makefile')
|
||||
->exec("make -j{$builder->concurrency} INSTALL_ROOT={$root} install-sapi {$install_modules} install-build install-headers install-programs");
|
||||
->exec("make -j{$builder->concurrency} {$makeArgs} INSTALL_ROOT={$root} install-sapi {$install_modules} install-build install-headers install-programs");
|
||||
|
||||
// install-modules deref'd libtool's `$ext.so → $ext-X.so` symlink for each built-with-php ext; restore them.
|
||||
$release = null;
|
||||
if (preg_match('/-release\s+(\S+)/', (string) getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS'), $m)) {
|
||||
$release = $m[1];
|
||||
foreach ($shared_exts as $ext) {
|
||||
$name = $ext->getExtensionName();
|
||||
$u = BUILD_MODULES_PATH . "/{$name}.so";
|
||||
$v = BUILD_MODULES_PATH . "/{$name}-{$release}.so";
|
||||
if (file_exists($v) && file_exists($u) && !is_link($u)) {
|
||||
unlink($u);
|
||||
symlink(basename($v), $u);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------- SPC_CMD_VAR_PHP_EMBED_TYPE=shared -------------
|
||||
|
||||
// process libphp.so for shared embed
|
||||
// INSTALL_IT for embed copies through libtool's symlink, leaving only unversioned libphp.{so,dylib} — rename and symlink back so shared exts can `-lphp`. (static libphp.a is never versioned, even with -release.)
|
||||
$suffix = SystemTarget::getTargetOS() === 'Darwin' ? 'dylib' : 'so';
|
||||
$libphp_so = "{$package->getLibDir()}/libphp.{$suffix}";
|
||||
if (file_exists($libphp_so)) {
|
||||
// rename libphp.so if -release is set
|
||||
if (SystemTarget::getTargetOS() === 'Linux') {
|
||||
$this->processLibphpSoFile($libphp_so, $installer);
|
||||
if ($release !== null) {
|
||||
$versioned = "{$package->getLibDir()}/libphp-{$release}.{$suffix}";
|
||||
if (file_exists($versioned)) {
|
||||
@unlink($versioned);
|
||||
}
|
||||
rename($libphp_so, $versioned);
|
||||
symlink(basename($versioned), $libphp_so);
|
||||
$libphp_so = $versioned;
|
||||
}
|
||||
// deploy
|
||||
$builder->deployBinary($libphp_so, $libphp_so, false);
|
||||
$package->setOutput('Library path for embed SAPI', $libphp_so);
|
||||
}
|
||||
@@ -334,6 +417,9 @@ trait unix
|
||||
$increment_files = $diff->getChangedFiles();
|
||||
$files = [];
|
||||
foreach ($increment_files as $increment_file) {
|
||||
if (is_link($increment_file) || !file_exists($increment_file)) {
|
||||
continue;
|
||||
}
|
||||
$builder->deployBinary($increment_file, $increment_file, false);
|
||||
$files[] = basename($increment_file);
|
||||
}
|
||||
@@ -341,19 +427,20 @@ trait unix
|
||||
$package->setOutput('Built shared extensions', implode(', ', $files));
|
||||
}
|
||||
|
||||
// phpize needs prefix patched whether libphp is .a or .so
|
||||
$package->runStage([$this, 'patchUnixEmbedScripts']);
|
||||
|
||||
InteractiveTerm::success('Built SAPI: ' . ConsoleColor::green('php-embed'), true, $start);
|
||||
|
||||
// ------------- SPC_CMD_VAR_PHP_EMBED_TYPE=static -------------
|
||||
|
||||
// process libphp.a for static embed
|
||||
if (!file_exists("{$package->getLibDir()}/libphp.a")) {
|
||||
return;
|
||||
// process libphp.a for static embed (only when present)
|
||||
if (file_exists("{$package->getLibDir()}/libphp.a")) {
|
||||
$ar = getenv('AR') ?: 'ar';
|
||||
$libphp_a = "{$package->getLibDir()}/libphp.a";
|
||||
shell()->exec("{$ar} -t {$libphp_a} | grep '\\.a$' | xargs -n1 {$ar} d {$libphp_a}");
|
||||
UnixUtil::exportDynamicSymbols($libphp_a);
|
||||
}
|
||||
$ar = getenv('AR') ?: 'ar';
|
||||
$libphp_a = "{$package->getLibDir()}/libphp.a";
|
||||
shell()->exec("{$ar} -t {$libphp_a} | grep '\\.a$' | xargs -n1 {$ar} d {$libphp_a}");
|
||||
UnixUtil::exportDynamicSymbols($libphp_a);
|
||||
|
||||
// deploy embed php scripts
|
||||
$package->runStage([$this, 'patchUnixEmbedScripts']);
|
||||
}
|
||||
|
||||
#[Stage]
|
||||
@@ -386,8 +473,15 @@ trait unix
|
||||
try {
|
||||
logger()->debug('Building shared extensions...');
|
||||
foreach ($shared_extensions as $extension) {
|
||||
InteractiveTerm::setMessage('Building shared PHP extension: ' . ConsoleColor::yellow($extension->getName()));
|
||||
$extension->buildShared();
|
||||
$ext_start = microtime(true);
|
||||
InteractiveTerm::setMessage('Building shared extension: ' . ConsoleColor::yellow($extension->getName()));
|
||||
try {
|
||||
$extension->buildShared();
|
||||
} catch (\Throwable $e) {
|
||||
InteractiveTerm::error('Building shared extension failed: ' . ConsoleColor::red($extension->getName()));
|
||||
throw $e;
|
||||
}
|
||||
InteractiveTerm::success('Built shared extension: ' . ConsoleColor::green($extension->getName()), true, $ext_start);
|
||||
}
|
||||
} finally {
|
||||
// restore php-config
|
||||
@@ -479,6 +573,8 @@ trait unix
|
||||
$package->runStage([$this, 'makeForUnix']);
|
||||
}
|
||||
|
||||
// shared extensions build before frankenphp so their undefined references are
|
||||
// collected into libphp's exported dynamic-symbol list.
|
||||
$package->runStage([$this, 'unixBuildSharedExt']);
|
||||
}
|
||||
|
||||
@@ -499,7 +595,8 @@ trait unix
|
||||
if (file_exists(BUILD_BIN_PATH . '/php-config')) {
|
||||
logger()->debug('Patching php-config prefix and libs order');
|
||||
$php_config_str = FileSystem::readFile(BUILD_BIN_PATH . '/php-config');
|
||||
$php_config_str = str_replace('prefix=""', 'prefix="' . BUILD_ROOT_PATH . '"', $php_config_str);
|
||||
// anchor to start-of-line so we don't also match `program_prefix=""`
|
||||
$php_config_str = preg_replace('/^prefix=""/m', 'prefix="' . BUILD_ROOT_PATH . '"', $php_config_str);
|
||||
// move mimalloc to the beginning of libs
|
||||
$php_config_str = preg_replace('/(libs=")(.*?)\s*(' . preg_quote(BUILD_LIB_PATH, '/') . '\/mimalloc\.o)\s*(.*?)"/', '$1$3 $2 $4"', $php_config_str);
|
||||
// move lstdc++ to the end of libs
|
||||
@@ -590,7 +687,7 @@ trait unix
|
||||
copy(ROOT_DIR . '/src/globals/common-tests/embed.c', $sample_file_path . '/embed.c');
|
||||
copy(ROOT_DIR . '/src/globals/common-tests/embed.php', $sample_file_path . '/embed.php');
|
||||
|
||||
$config = new SPCConfigUtil()->config($installer->getAvailableResolvedPackageNames());
|
||||
$config = new SPCConfigUtil()->config(['php']);
|
||||
$lens = "{$config['cflags']} {$config['ldflags']} {$config['libs']}";
|
||||
if ($toolchain->isStatic()) {
|
||||
$lens .= ' -static';
|
||||
@@ -671,96 +768,37 @@ trait unix
|
||||
return $php;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename libphp.so to libphp-<release>.so if -release is set in LDFLAGS.
|
||||
*/
|
||||
private function processLibphpSoFile(string $libphpSo, PackageInstaller $installer): void
|
||||
{
|
||||
$ldflags = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS') ?: '';
|
||||
$libDir = BUILD_LIB_PATH;
|
||||
$modulesDir = BUILD_MODULES_PATH;
|
||||
$realLibName = 'libphp.so';
|
||||
$cwd = getcwd();
|
||||
|
||||
if (preg_match('/-release\s+(\S+)/', $ldflags, $matches)) {
|
||||
$release = $matches[1];
|
||||
$realLibName = "libphp-{$release}.so";
|
||||
$libphpRelease = "{$libDir}/{$realLibName}";
|
||||
if (!file_exists($libphpRelease) && file_exists($libphpSo)) {
|
||||
rename($libphpSo, $libphpRelease);
|
||||
}
|
||||
if (file_exists($libphpRelease)) {
|
||||
chdir($libDir);
|
||||
if (file_exists($libphpSo)) {
|
||||
unlink($libphpSo);
|
||||
}
|
||||
symlink($realLibName, 'libphp.so');
|
||||
shell()->exec(sprintf(
|
||||
'patchelf --set-soname %s %s',
|
||||
escapeshellarg($realLibName),
|
||||
escapeshellarg($libphpRelease)
|
||||
));
|
||||
}
|
||||
if (is_dir($modulesDir)) {
|
||||
chdir($modulesDir);
|
||||
foreach ($installer->getResolvedPackages(PhpExtensionPackage::class) as $ext) {
|
||||
if (!$ext->isBuildShared()) {
|
||||
continue;
|
||||
}
|
||||
$name = $ext->getName();
|
||||
$versioned = "{$name}-{$release}.so";
|
||||
$unversioned = "{$name}.so";
|
||||
$src = "{$modulesDir}/{$versioned}";
|
||||
$dst = "{$modulesDir}/{$unversioned}";
|
||||
if (is_file($src)) {
|
||||
rename($src, $dst);
|
||||
shell()->exec(sprintf(
|
||||
'patchelf --set-soname %s %s',
|
||||
escapeshellarg($unversioned),
|
||||
escapeshellarg($dst)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
chdir($cwd);
|
||||
}
|
||||
|
||||
$target = "{$libDir}/{$realLibName}";
|
||||
if (file_exists($target)) {
|
||||
[, $output] = shell()->execWithResult('readelf -d ' . escapeshellarg($target));
|
||||
$output = implode("\n", $output);
|
||||
if (preg_match('/SONAME.*\[(.+)]/', $output, $sonameMatch)) {
|
||||
$currentSoname = $sonameMatch[1];
|
||||
if ($currentSoname !== basename($target)) {
|
||||
shell()->exec(sprintf(
|
||||
'patchelf --set-soname %s %s',
|
||||
escapeshellarg(basename($target)),
|
||||
escapeshellarg($target)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make environment variables for php make.
|
||||
* This will call SPCConfigUtil to generate proper LDFLAGS and LIBS for static linking.
|
||||
*/
|
||||
private function makeVars(PackageInstaller $installer): array
|
||||
{
|
||||
$config = new SPCConfigUtil(['libs_only_deps' => true])->config($installer->getAvailableResolvedPackageNames());
|
||||
$config = new SPCConfigUtil(['libs_only_deps' => true])->config(['php']);
|
||||
$static = ApplicationContext::get(ToolchainInterface::class)->isStatic() ? '-all-static' : '';
|
||||
$pie = SystemTarget::getTargetOS() === 'Linux' ? '-pie' : '';
|
||||
$lib = BUILD_LIB_PATH;
|
||||
|
||||
// Append SPC_EXTRA_LIBS to libs for dynamic linking support (e.g., X11)
|
||||
$extra_libs = getenv('SPC_EXTRA_LIBS') ?: '';
|
||||
$libs = trim($config['libs'] . ' ' . $extra_libs);
|
||||
|
||||
// libtool input (libphp.la). `make EXTRA_LDFLAGS=…` cmdline overrides fully replace the Makefile value, so re-include $config['ldflags'] for -L paths.
|
||||
$extra_ldflags = clean_spaces($config['ldflags'] . ' ' . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS'));
|
||||
if (getenv('SPC_CMD_VAR_PHP_EMBED_TYPE') === 'shared'
|
||||
&& !str_contains($extra_ldflags, '-avoid-version')
|
||||
&& !preg_match('/-release\s+\S+/', $extra_ldflags)) {
|
||||
$extra_ldflags = trim($extra_ldflags . ' -avoid-version -module');
|
||||
}
|
||||
|
||||
$extra_ldflags_program_env = getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS_PROGRAM') ?: '';
|
||||
$extra_ldflags_program = clean_spaces("-L{$lib} {$static} {$pie} {$extra_ldflags_program_env}");
|
||||
|
||||
return array_filter([
|
||||
'EXTRA_CFLAGS' => getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS'),
|
||||
'EXTRA_CXXFLAGS' => getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CXXFLAGS'),
|
||||
'EXTRA_LDFLAGS_PROGRAM' => deduplicate_flags(getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS') . " {$config['ldflags']} {$static} {$pie}"),
|
||||
'EXTRA_LDFLAGS' => $config['ldflags'],
|
||||
'EXTRA_LDFLAGS' => $extra_ldflags,
|
||||
'EXTRA_LDFLAGS_PROGRAM' => $extra_ldflags_program,
|
||||
'EXTRA_LIBS' => $libs,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -27,12 +27,18 @@ class Artifact
|
||||
/** @var null|callable Bind custom source fetcher callback */
|
||||
protected mixed $custom_source_callback = null;
|
||||
|
||||
/** @var null|string Display label describing where the custom source callback came from */
|
||||
protected ?string $custom_source_callback_origin = null;
|
||||
|
||||
/** @var null|callable Bind custom source check-update callback */
|
||||
protected mixed $custom_source_check_update_callback = null;
|
||||
|
||||
/** @var array<string, callable> Bind custom binary fetcher callbacks */
|
||||
protected mixed $custom_binary_callbacks = [];
|
||||
|
||||
/** @var array<string, string> Display label per platform describing where the custom binary callback came from */
|
||||
protected array $custom_binary_callback_origins = [];
|
||||
|
||||
/** @var array<string, callable> Bind custom binary check-update callbacks */
|
||||
protected array $custom_binary_check_update_callbacks = [];
|
||||
|
||||
@@ -285,15 +291,19 @@ class Artifact
|
||||
* Get source extraction directory.
|
||||
*
|
||||
* Rules:
|
||||
* 1. If extract is not specified: SOURCE_PATH/{artifact_name}
|
||||
* 2. If extract is relative path: SOURCE_PATH/{value}
|
||||
* 3. If extract is absolute path: {value}
|
||||
* 4. If extract is array (dict): handled by extractor (selective extraction)
|
||||
* 1. If cache_type is 'local': use the absolute dirname recorded at download time (no symlink/copy).
|
||||
* 2. If extract is not specified: SOURCE_PATH/{artifact_name}
|
||||
* 3. If extract is relative path: SOURCE_PATH/{value}
|
||||
* 4. If extract is absolute path: {value}
|
||||
* 5. If extract is array (dict): handled by extractor (selective extraction)
|
||||
*/
|
||||
public function getSourceDir(): string
|
||||
{
|
||||
// Prefer cache extract path, fall back to config
|
||||
$cache_info = ApplicationContext::get(ArtifactCache::class)->getSourceInfo($this->name);
|
||||
if (($cache_info['cache_type'] ?? null) === 'local' && isset($cache_info['dirname'])) {
|
||||
return FileSystem::convertPath($cache_info['dirname']);
|
||||
}
|
||||
$extract = is_string($cache_info['extract'] ?? null)
|
||||
? $cache_info['extract']
|
||||
: ($this->config['source']['extract'] ?? null);
|
||||
@@ -327,7 +337,7 @@ class Artifact
|
||||
public function getSourceRoot(): string
|
||||
{
|
||||
if (isset($this->config['metadata']['source-root'])) {
|
||||
return $this->getSourceDir() . '/' . ltrim($this->config['metadata']['source-root'], '/');
|
||||
return FileSystem::convertPath($this->getSourceDir() . '/' . ltrim($this->config['metadata']['source-root'], '/'));
|
||||
}
|
||||
return $this->getSourceDir();
|
||||
}
|
||||
@@ -407,10 +417,13 @@ class Artifact
|
||||
|
||||
/**
|
||||
* Set custom source fetcher callback.
|
||||
*
|
||||
* @param string $origin Short label shown in progress output (e.g. 'package downloader', 'custom url')
|
||||
*/
|
||||
public function setCustomSourceCallback(callable $callback): void
|
||||
public function setCustomSourceCallback(callable $callback, string $origin = 'package downloader'): void
|
||||
{
|
||||
$this->custom_source_callback = $callback;
|
||||
$this->custom_source_callback_origin = $origin;
|
||||
}
|
||||
|
||||
public function getCustomSourceCallback(): ?callable
|
||||
@@ -418,6 +431,11 @@ class Artifact
|
||||
return $this->custom_source_callback ?? null;
|
||||
}
|
||||
|
||||
public function getCustomSourceCallbackOrigin(): ?string
|
||||
{
|
||||
return $this->custom_source_callback_origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set custom source check-update callback.
|
||||
*/
|
||||
@@ -452,11 +470,19 @@ class Artifact
|
||||
*
|
||||
* @param string $target_os Target OS platform string (e.g. linux-x86_64)
|
||||
* @param callable $callback Custom binary fetcher callback
|
||||
* @param string $origin Short label shown in progress output (e.g. 'package downloader')
|
||||
*/
|
||||
public function setCustomBinaryCallback(string $target_os, callable $callback): void
|
||||
public function setCustomBinaryCallback(string $target_os, callable $callback, string $origin = 'package downloader'): void
|
||||
{
|
||||
ConfigValidator::validatePlatformString($target_os);
|
||||
$this->custom_binary_callbacks[$target_os] = $callback;
|
||||
$this->custom_binary_callback_origins[$target_os] = $origin;
|
||||
}
|
||||
|
||||
public function getCustomBinaryCallbackOrigin(): ?string
|
||||
{
|
||||
$current_platform = SystemTarget::getCurrentPlatformString();
|
||||
return $this->custom_binary_callback_origins[$current_platform] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -223,8 +223,8 @@ class ArtifactCache
|
||||
public function getCacheFullPath(array $cache_info): string
|
||||
{
|
||||
return match ($cache_info['cache_type']) {
|
||||
'archive', 'file' => DOWNLOAD_PATH . '/' . $cache_info['filename'],
|
||||
'git' => DOWNLOAD_PATH . '/' . $cache_info['dirname'],
|
||||
'archive', 'file' => FileSystem::convertPath(DOWNLOAD_PATH . '/' . $cache_info['filename']),
|
||||
'git' => FileSystem::convertPath(DOWNLOAD_PATH . '/' . $cache_info['dirname']),
|
||||
'local' => $cache_info['dirname'], // local dirname is absolute path
|
||||
default => throw new SPCInternalException("Unknown cache type: {$cache_info['cache_type']}"),
|
||||
};
|
||||
|
||||
@@ -317,7 +317,10 @@ class ArtifactDownloader
|
||||
if (!is_dir(DOWNLOAD_PATH)) {
|
||||
FileSystem::createDir(DOWNLOAD_PATH);
|
||||
}
|
||||
logger()->info('Downloading' . implode(', ', array_map(fn ($x) => " '{$x->getName()}'", $this->artifacts)) . " with concurrency {$this->parallel} ...");
|
||||
$pending = array_values(array_filter($this->artifacts, fn ($a) => $this->generateQueue($a) !== []));
|
||||
if ($pending !== []) {
|
||||
logger()->info('Downloading' . implode(', ', array_map(fn ($x) => " '{$x->getName()}'", $pending)) . " with concurrency {$this->parallel} ...");
|
||||
}
|
||||
// Download artifacts parallelly
|
||||
if ($this->parallel > 1) {
|
||||
$this->downloadWithConcurrency();
|
||||
@@ -551,8 +554,8 @@ class ArtifactDownloader
|
||||
$instance = null;
|
||||
$call = $this->downloaders[$item['config']['type']] ?? null;
|
||||
$type_display_name = match (true) {
|
||||
$item['lock'] === 'source' && ($callback = $artifact->getCustomSourceCallback()) !== null => 'user defined source downloader',
|
||||
$item['lock'] === 'binary' && ($callback = $artifact->getCustomBinaryCallback()) !== null => 'user defined binary downloader',
|
||||
$item['lock'] === 'source' && $artifact->getCustomSourceCallback() !== null => $artifact->getCustomSourceCallbackOrigin() ?? 'source package downloader',
|
||||
$item['lock'] === 'binary' && $artifact->getCustomBinaryCallback() !== null => $artifact->getCustomBinaryCallbackOrigin() ?? 'binary package downloader',
|
||||
default => SPC_DOWNLOAD_TYPE_DISPLAY_NAME[$item['config']['type']] ?? $item['config']['type'],
|
||||
};
|
||||
$try_h = $try ? 'Try downloading' : 'Downloading';
|
||||
@@ -731,6 +734,16 @@ class ArtifactDownloader
|
||||
$binary_downloaded = $artifact->isBinaryDownloaded(compare_hash: true);
|
||||
$source_downloaded = $artifact->isSourceDownloaded(compare_hash: true);
|
||||
|
||||
if ($source_downloaded && $artifact->getName() === 'php-src' && ($requested = $this->getOption('with-php'))) {
|
||||
$info = ApplicationContext::get(ArtifactCache::class)->getSourceInfo('php-src');
|
||||
$cv = $info['version'] ?? null;
|
||||
$ct = $info['cache_type'] ?? null;
|
||||
$matches = $requested === 'git' ? $ct === 'git' : ($cv !== null && $ct !== 'git' && ($cv === $requested || str_starts_with($cv, $requested . '.')));
|
||||
if (!$matches) {
|
||||
$source_downloaded = false;
|
||||
}
|
||||
}
|
||||
|
||||
$item_source = ['display' => 'source', 'lock' => 'source', 'config' => $artifact->getDownloadConfig('source')];
|
||||
$item_source_mirror = ['display' => 'source (mirror)', 'lock' => 'source', 'config' => $artifact->getDownloadConfig('source-mirror')];
|
||||
|
||||
@@ -825,21 +838,21 @@ class ArtifactDownloader
|
||||
if (isset($this->artifacts[$artifact_name])) {
|
||||
$this->artifacts[$artifact_name]->setCustomSourceCallback(function (ArtifactDownloader $downloader) use ($artifact_name, $custom_url) {
|
||||
return (new Url())->download($artifact_name, ['url' => $custom_url], $downloader);
|
||||
});
|
||||
}, 'custom url');
|
||||
}
|
||||
}
|
||||
foreach ($this->custom_gits as $artifact_name => [$branch, $git_url]) {
|
||||
if (isset($this->artifacts[$artifact_name])) {
|
||||
$this->artifacts[$artifact_name]->setCustomSourceCallback(function (ArtifactDownloader $downloader) use ($artifact_name, $branch, $git_url) {
|
||||
return (new Git())->download($artifact_name, ['rev' => $branch, 'url' => $git_url], $downloader);
|
||||
});
|
||||
}, 'custom git');
|
||||
}
|
||||
}
|
||||
foreach ($this->custom_locals as $artifact_name => $local_path) {
|
||||
if (isset($this->artifacts[$artifact_name])) {
|
||||
$this->artifacts[$artifact_name]->setCustomSourceCallback(function (ArtifactDownloader $downloader) use ($artifact_name, $local_path) {
|
||||
return (new LocalDir())->download($artifact_name, ['dirname' => $local_path], $downloader);
|
||||
});
|
||||
}, 'custom local dir');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +136,12 @@ class ArtifactExtractor
|
||||
throw new WrongUsageException("Artifact source [{$name}] not downloaded, please download it first!");
|
||||
}
|
||||
|
||||
// Local (--custom-local): source lives in place at $cache_info['dirname'].
|
||||
if (($cache_info['cache_type'] ?? null) === 'local') {
|
||||
$artifact->emitAfterSourceExtract($artifact->getSourceDir());
|
||||
return SPC_STATUS_ALREADY_EXTRACTED;
|
||||
}
|
||||
|
||||
$source_file = $this->cache->getCacheFullPath($cache_info);
|
||||
$target_path = $artifact->getSourceDir();
|
||||
|
||||
@@ -171,8 +177,12 @@ class ArtifactExtractor
|
||||
return SPC_STATUS_ALREADY_EXTRACTED;
|
||||
}
|
||||
|
||||
// Remove old directory if hash mismatch
|
||||
if (is_dir($target_path)) {
|
||||
// Remove old directory if hash mismatch.
|
||||
// Guard: a symlink at $target_path (left over from older local-source handling) must be
|
||||
// unlinked directly — never recurse into the link target, that would wipe the user's tree.
|
||||
if (is_link($target_path)) {
|
||||
@unlink($target_path);
|
||||
} elseif (is_dir($target_path)) {
|
||||
logger()->notice("Source [{$name}] hash mismatch, re-extracting...");
|
||||
FileSystem::removeDir($target_path);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ class Git implements DownloadTypeInterface, CheckUpdateInterface
|
||||
|
||||
// direct branch clone
|
||||
if (isset($config['rev'])) {
|
||||
default_shell()->executeGitClone($config['url'], $config['rev'], $path, $shallow, $config['submodules'] ?? null);
|
||||
default_shell()->executeGitClone($config['url'], $config['rev'], $path, $shallow, $config['submodules'] ?? null, $downloader->getRetry());
|
||||
$shell = PHP_OS_FAMILY === 'Windows' ? cmd(false) : shell(false);
|
||||
$hash_result = $shell->execWithResult(SPC_GIT_EXEC . ' -C ' . escapeshellarg($path) . ' rev-parse --short HEAD');
|
||||
$hash = ($hash_result[0] === 0 && !empty($hash_result[1])) ? trim($hash_result[1][0]) : '';
|
||||
@@ -66,7 +66,7 @@ class Git implements DownloadTypeInterface, CheckUpdateInterface
|
||||
$version = array_key_first($matched_version_branch);
|
||||
$branch = $matched_version_branch[$version];
|
||||
logger()->info("Matched version {$version} from branch {$branch} for {$name}");
|
||||
default_shell()->executeGitClone($config['url'], $branch, $path, $shallow, $config['submodules'] ?? null);
|
||||
default_shell()->executeGitClone($config['url'], $branch, $path, $shallow, $config['submodules'] ?? null, $downloader->getRetry());
|
||||
return DownloadResult::git($name, $config, extract: $config['extract'] ?? null, version: $version, downloader: static::class);
|
||||
}
|
||||
throw new DownloaderException("No matching branch found for regex {$config['regex']} (checked {$matched_count} branches).");
|
||||
|
||||
@@ -21,13 +21,13 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
|
||||
|
||||
private ?string $version = null;
|
||||
|
||||
public function getGitHubReleases(string $name, string $repo, bool $prefer_stable = true, ?string $query = null): array
|
||||
public function getGitHubReleases(string $name, string $repo, bool $prefer_stable = true, ?string $query = null, int $retries = 0): array
|
||||
{
|
||||
logger()->debug("Fetching {$name} GitHub releases from {$repo}");
|
||||
$url = str_replace('{repo}', $repo, self::API_URL);
|
||||
$url .= ($query ?? '');
|
||||
$headers = $this->getGitHubTokenHeaders();
|
||||
$data2 = default_shell()->executeCurl($url, headers: $headers);
|
||||
$data2 = default_shell()->executeCurl($url, headers: $headers, retries: $retries);
|
||||
$data = json_decode($data2 ?: '', true);
|
||||
if (!is_array($data)) {
|
||||
throw new DownloaderException("Failed to get GitHub release API info for {$repo} from {$url}");
|
||||
@@ -46,17 +46,27 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
|
||||
* Get the latest GitHub release assets for a given repository.
|
||||
* match_asset is provided, only return the asset that matches the regex.
|
||||
*/
|
||||
public function getLatestGitHubRelease(string $name, string $repo, bool $prefer_stable, string $match_asset, ?string $query = null): array
|
||||
public function getLatestGitHubRelease(string $name, string $repo, bool $prefer_stable, string $match_asset, ?string $query = null, int $retries = 0): array
|
||||
{
|
||||
logger()->debug("Fetching {$name} GitHub release from {$repo}");
|
||||
$url = str_replace('{repo}', $repo, self::API_URL);
|
||||
$url .= ($query ?? '');
|
||||
$headers = $this->getGitHubTokenHeaders();
|
||||
$data2 = default_shell()->executeCurl($url, headers: $headers);
|
||||
$data2 = default_shell()->executeCurl($url, headers: $headers, retries: $retries);
|
||||
$data = json_decode($data2 ?: '', true);
|
||||
if (!is_array($data)) {
|
||||
throw new DownloaderException("Failed to get GitHub release API info for {$repo} from {$url}");
|
||||
}
|
||||
// GitHub's /releases list is ordered by publish date, so a newer-tagged prerelease
|
||||
// (e.g. 2.2.x-alpha) can precede the latest stable (2.1.x-stable). /releases/latest
|
||||
// returns the semantically latest stable release regardless of order; check it first.
|
||||
if ($prefer_stable) {
|
||||
$latest_url = str_replace('{repo}', $repo, self::API_URL) . '/latest';
|
||||
$latest = json_decode(default_shell()->executeCurl($latest_url, headers: $headers, retries: $retries) ?: '', true);
|
||||
if (is_array($latest) && isset($latest['assets'])) {
|
||||
array_unshift($data, $latest);
|
||||
}
|
||||
}
|
||||
foreach ($data as $release) {
|
||||
if ($prefer_stable && $release['prerelease'] === true) {
|
||||
continue;
|
||||
@@ -84,7 +94,7 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
|
||||
if (!isset($config['match'])) {
|
||||
throw new DownloaderException("GitHubRelease downloader requires 'match' config for {$name}");
|
||||
}
|
||||
$rel = $this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null);
|
||||
$rel = $this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null, $downloader->getRetry());
|
||||
|
||||
// download file using curl
|
||||
$asset_url = str_replace(['{repo}', '{id}'], [$config['repo'], $rel['id']], self::ASSET_URL);
|
||||
@@ -124,7 +134,7 @@ class GitHubRelease implements DownloadTypeInterface, ValidatorInterface, CheckU
|
||||
if (!isset($config['match'])) {
|
||||
throw new DownloaderException("GitHubRelease downloader requires 'match' config for {$name}");
|
||||
}
|
||||
$this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null);
|
||||
$this->getLatestGitHubRelease($name, $config['repo'], $config['prefer-stable'] ?? true, $config['match'], $config['query'] ?? null, $downloader->getRetry());
|
||||
$new_version = $this->version ?? $old_version ?? '';
|
||||
return new CheckUpdateResult(
|
||||
old: $old_version,
|
||||
|
||||
@@ -22,11 +22,11 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
|
||||
* Get the GitHub tarball URL for a given repository and release type.
|
||||
* If match_url is provided, only return the tarball that matches the regex.
|
||||
*/
|
||||
public function getGitHubTarballInfo(string $name, string $repo, string $rel_type, bool $prefer_stable = true, ?string $match_url = null, ?string $basename = null, ?string $query = null): array
|
||||
public function getGitHubTarballInfo(string $name, string $repo, string $rel_type, bool $prefer_stable = true, ?string $match_url = null, ?string $basename = null, ?string $query = null, int $retries = 0): array
|
||||
{
|
||||
if ($rel_type === 'releases' && $match_url === null && $query === null && $prefer_stable) {
|
||||
$api_url = str_replace(['{repo}', '{rel_type}'], [$repo, 'releases/latest'], self::API_URL);
|
||||
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders());
|
||||
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders(), retries: $retries);
|
||||
$data = json_decode($data ?: '', true);
|
||||
if (!is_array($data) || empty($data['tarball_url'])) {
|
||||
throw new DownloaderException("Failed to get GitHub latest release for {$repo} from {$api_url}");
|
||||
@@ -36,7 +36,7 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
|
||||
} else {
|
||||
$api_url = str_replace(['{repo}', '{rel_type}'], [$repo, $rel_type], self::API_URL);
|
||||
$api_url .= ($query ?? '');
|
||||
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders());
|
||||
$data = default_shell()->executeCurl($api_url, headers: $this->getGitHubTokenHeaders(), retries: $retries);
|
||||
$data = json_decode($data ?: '', true);
|
||||
if (!is_array($data)) {
|
||||
throw new DownloaderException("Failed to get GitHub tarball URL for {$repo} from {$api_url}");
|
||||
@@ -65,7 +65,7 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
|
||||
}
|
||||
$this->version = $version ?? null;
|
||||
}
|
||||
$head = default_shell()->executeCurl($rel_url, 'HEAD', headers: $this->getGitHubTokenHeaders()) ?: '';
|
||||
$head = default_shell()->executeCurl($rel_url, 'HEAD', headers: $this->getGitHubTokenHeaders(), retries: $retries) ?: '';
|
||||
preg_match('/^content-disposition:\s+attachment;\s*filename=("?)(?<filename>.+\.tar\.gz)\1/im', $head, $matches);
|
||||
if ($matches) {
|
||||
$filename = $matches['filename'];
|
||||
@@ -84,9 +84,9 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
|
||||
'ghtagtar' => 'tags',
|
||||
default => throw new DownloaderException("Invalid GitHubTarball type for {$name}"),
|
||||
};
|
||||
[$url, $filename] = $this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null);
|
||||
[$url, $filename] = $this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null, $downloader->getRetry());
|
||||
$path = DOWNLOAD_PATH . "/{$filename}";
|
||||
default_shell()->executeCurlDownload($url, $path, headers: $this->getGitHubTokenHeaders());
|
||||
default_shell()->executeCurlDownload($url, $path, headers: $this->getGitHubTokenHeaders(), retries: $downloader->getRetry());
|
||||
return DownloadResult::archive($filename, $config, $config['extract'] ?? null, version: $this->version, downloader: static::class);
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ class GitHubTarball implements DownloadTypeInterface, CheckUpdateInterface
|
||||
'ghtagtar' => 'tags',
|
||||
default => throw new DownloaderException("Invalid GitHubTarball type for {$name}"),
|
||||
};
|
||||
$this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null);
|
||||
$this->getGitHubTarballInfo($name, $config['repo'], $rel_type, $config['prefer-stable'] ?? true, $config['match'] ?? null, $name, $config['query'] ?? null, $downloader->getRetry());
|
||||
$new_version = $this->version ?? $old_version ?? '';
|
||||
return new CheckUpdateResult(
|
||||
old: $old_version,
|
||||
|
||||
@@ -14,16 +14,18 @@ trait GitHubTokenSetupTrait
|
||||
public static function getGitHubTokenHeadersStatic(): array
|
||||
{
|
||||
// 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");
|
||||
spc_add_log_filter([$user, $token]);
|
||||
return ['Authorization: Basic ' . base64_encode("{$user}:{$token}")];
|
||||
$encoded = base64_encode("{$user}:{$token}");
|
||||
spc_add_log_filter([$user, $token, $encoded]);
|
||||
return ["Authorization: Basic {$encoded}"];
|
||||
}
|
||||
if (($token = getenv('GITHUB_TOKEN')) !== false) {
|
||||
logger()->debug("Using 'GITHUB_TOKEN' for authentication");
|
||||
spc_add_log_filter($token);
|
||||
return ["Authorization: Bearer {$token}"];
|
||||
}
|
||||
return [];
|
||||
logger()->debug("Using 'GITHUB_TOKEN' for authentication");
|
||||
spc_add_log_filter($token);
|
||||
return ["Authorization: Bearer {$token}"];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ class PhpRelease implements DownloadTypeInterface, ValidatorInterface, CheckUpda
|
||||
|
||||
public function download(string $name, array $config, ArtifactDownloader $downloader): DownloadResult
|
||||
{
|
||||
$phpver = $downloader->getOption('with-php', '8.4');
|
||||
$phpver = $downloader->getOption('with-php', '8.5');
|
||||
// Handle 'git' version to clone from php-src repository
|
||||
if ($phpver === 'git') {
|
||||
$this->sha256 = null;
|
||||
@@ -74,7 +74,7 @@ class PhpRelease implements DownloadTypeInterface, ValidatorInterface, CheckUpda
|
||||
|
||||
public function checkUpdate(string $name, array $config, ?string $old_version, ArtifactDownloader $downloader): CheckUpdateResult
|
||||
{
|
||||
$phpver = $downloader->getOption('with-php', '8.4');
|
||||
$phpver = $downloader->getOption('with-php', '8.5');
|
||||
if ($phpver === 'git') {
|
||||
// git version: delegate to Git checkUpdate with master branch
|
||||
return (new Git())->checkUpdate($name, ['url' => 'https://github.com/php/php-src.git', 'rev' => 'master'], $old_version, $downloader);
|
||||
@@ -90,7 +90,7 @@ class PhpRelease implements DownloadTypeInterface, ValidatorInterface, CheckUpda
|
||||
|
||||
protected function fetchPhpReleaseInfo(string $name, array $config, ArtifactDownloader $downloader): array
|
||||
{
|
||||
$phpver = $downloader->getOption('with-php', '8.4');
|
||||
$phpver = $downloader->getOption('with-php', '8.5');
|
||||
// Handle 'git' version to clone from php-src repository
|
||||
if ($phpver === 'git') {
|
||||
// cannot fetch release info for git version, return empty info to skip validation
|
||||
|
||||
@@ -52,7 +52,7 @@ class DownloaderOptions
|
||||
|
||||
return [
|
||||
// php version option
|
||||
new InputOption("{$p}with-php", null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.4)', '8.4'),
|
||||
new InputOption("{$p}with-php", null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.5)', '8.5'),
|
||||
|
||||
// download preference options
|
||||
new InputOption("{$p}prefer-source", null, InputOption::VALUE_OPTIONAL, 'Prefer source downloads when both source and binary are available', false),
|
||||
|
||||
@@ -26,7 +26,7 @@ class CheckUpdateCommand extends BaseCommand
|
||||
$this->addOption('parallel', 'p', InputOption::VALUE_REQUIRED, 'Number of parallel update checks (default: 10)', 10);
|
||||
|
||||
// --with-php option for checking updates with a specific PHP version context
|
||||
$this->addOption('with-php', null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.4)', '8.4');
|
||||
$this->addOption('with-php', null, InputOption::VALUE_REQUIRED, 'PHP version in major.minor format (default 8.5)', '8.5');
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
|
||||
@@ -9,7 +9,12 @@ use StaticPHP\Doctor\Doctor;
|
||||
use StaticPHP\Exception\ValidationException;
|
||||
use StaticPHP\Package\PackageBuilder;
|
||||
use StaticPHP\Package\PackageInstaller;
|
||||
use StaticPHP\Registry\PackageLoader;
|
||||
use StaticPHP\Toolchain\ToolchainManager;
|
||||
use StaticPHP\Util\DependencyResolver;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
use StaticPHP\Util\GlobalEnvManager;
|
||||
use StaticPHP\Util\Pgo\PgoContext;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Yaml\Exception\ParseException;
|
||||
@@ -21,6 +26,8 @@ class CraftCommand extends BaseCommand
|
||||
public function configure(): void
|
||||
{
|
||||
$this->addArgument('craft', null, 'Path to craft.yml file', WORKING_DIR . '/craft.yml');
|
||||
$this->addOption('libs-only', null, null, 'Build only the libraries needed by the configured extensions (skip PHP and SAPI build).');
|
||||
PgoContext::registerOptions($this);
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
@@ -39,6 +46,13 @@ class CraftCommand extends BaseCommand
|
||||
// apply env
|
||||
array_walk($craft['extra-env'], fn ($v, $k) => f_putenv("{$k}={$v}"));
|
||||
|
||||
// re-substitute env.ini's CC=${SPC_DEFAULT_CC} bindings.
|
||||
ToolchainManager::initToolchain();
|
||||
GlobalEnvManager::reapplyOsIni();
|
||||
|
||||
// stash craft for doctor checks that depend on what's being built (e.g. frankenphp → go-xcaddy)
|
||||
ApplicationContext::set('craft', $craft);
|
||||
|
||||
// run doctor
|
||||
if ($craft['craft-options']['doctor']) {
|
||||
$doctor = new Doctor($this->output, FIX_POLICY_AUTOFIX);
|
||||
@@ -83,23 +97,67 @@ class CraftCommand extends BaseCommand
|
||||
FileSystem::resetDir(SOURCE_PATH);
|
||||
}
|
||||
|
||||
$pgo = $this->getOption('libs-only') ? null : PgoContext::tryFromInput($this->input, $craft['sapi'], $build_options);
|
||||
|
||||
$starttime = microtime(true);
|
||||
// run installer
|
||||
$installer = new PackageInstaller($build_options);
|
||||
ApplicationContext::get(PackageBuilder::class)->setArgument('extensions', implode(',', $craft['extensions']));
|
||||
$installer->addBuildPackage('php');
|
||||
|
||||
if ($this->getOption('libs-only')) {
|
||||
$with_suggests = (bool) ($craft['build-options']['with-suggests'] ?? false);
|
||||
$libs = $this->resolveLibsForExtensions($craft, $with_suggests);
|
||||
if ($libs === []) {
|
||||
$this->output->writeln('<comment>No libraries needed for the configured extensions; nothing to do.</comment>');
|
||||
return static::SUCCESS;
|
||||
}
|
||||
foreach ($libs as $lib) {
|
||||
$installer->addBuildPackage($lib);
|
||||
}
|
||||
} else {
|
||||
$installer->addBuildPackage('php');
|
||||
}
|
||||
$installer->run(true);
|
||||
|
||||
$usedtime = round(microtime(true) - $starttime, 1);
|
||||
$tag = $pgo !== null ? " (PGO {$pgo->mode})" : '';
|
||||
$this->output->writeln("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
|
||||
$this->output->writeln("<info>✔ BUILD SUCCESSFUL ({$usedtime} s)</info>");
|
||||
$this->output->writeln("<info>✔ BUILD SUCCESSFUL{$tag} ({$usedtime} s)</info>");
|
||||
$this->output->writeln("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
|
||||
|
||||
if ($pgo !== null && $pgo->isInstrument()) {
|
||||
$this->output->writeln("<comment>Next: exercise the instrumented binary, then re-run craft with --pgo to consume {$pgo->profileRoot}.</comment>");
|
||||
}
|
||||
|
||||
$installer->printBuildPackageOutputs();
|
||||
|
||||
return static::SUCCESS;
|
||||
}
|
||||
|
||||
/** @return list<string> library package names transitively required by the configured extensions */
|
||||
private function resolveLibsForExtensions(array $craft, bool $include_suggests): array
|
||||
{
|
||||
$exts = array_merge($craft['extensions'], $craft['shared-extensions'] ?? []);
|
||||
$ext_pkgs = array_map(fn ($x) => "ext-{$x}", $exts);
|
||||
$extra = $craft['packages'] ?? [];
|
||||
|
||||
$resolved = DependencyResolver::resolve(
|
||||
array_merge($ext_pkgs, $extra),
|
||||
include_suggests: $include_suggests,
|
||||
);
|
||||
|
||||
$libs = [];
|
||||
foreach ($resolved as $pkg_name) {
|
||||
if (str_starts_with($pkg_name, 'ext-') || !PackageLoader::hasPackage($pkg_name)) {
|
||||
continue;
|
||||
}
|
||||
if (PackageLoader::getPackage($pkg_name)->getType() === 'library') {
|
||||
$libs[] = $pkg_name;
|
||||
}
|
||||
}
|
||||
return $libs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and parse craft.yml file to array.
|
||||
*
|
||||
|
||||
@@ -12,7 +12,7 @@ use Symfony\Component\Console\Input\InputOption;
|
||||
#[AsCommand('dev:gen-ext-test-matrix', 'Generate GitHub Actions extension test matrix JSON', [], true)]
|
||||
class GenExtTestMatrixCommand extends BaseCommand
|
||||
{
|
||||
private const string BUILD_TARGETS = '--build-cli --build-cgi --build-micro';
|
||||
private const string BUILD_TARGETS = '--build-cli --build-cgi --build-micro --with-suggests -vvv';
|
||||
|
||||
private const array OS_RUNNERS = [
|
||||
'linux' => ['arch' => 'x86_64', 'runner' => 'ubuntu-latest', 'os_key' => 'Linux'],
|
||||
@@ -20,6 +20,14 @@ class GenExtTestMatrixCommand extends BaseCommand
|
||||
'macos' => ['arch' => 'aarch64', 'runner' => 'macos-15', 'os_key' => 'Darwin'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Tier 2 runners: Linux aarch64 + macOS x86_64, no Windows.
|
||||
*/
|
||||
private const array OS_RUNNERS_TIER2 = [
|
||||
'linux' => ['arch' => 'aarch64', 'runner' => 'ubuntu-24.04-arm', 'os_key' => 'Linux'],
|
||||
'macos' => ['arch' => 'x86_64', 'runner' => 'macos-15-intel', 'os_key' => 'Darwin'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Extensions excluded from specific OS matrix entries.
|
||||
*/
|
||||
@@ -54,6 +62,14 @@ class GenExtTestMatrixCommand extends BaseCommand
|
||||
'intl',
|
||||
];
|
||||
|
||||
/**
|
||||
* Extensions that are emitted as isolated standalone entries.
|
||||
*/
|
||||
private const array STANDALONE_ISOLATED = [
|
||||
'swow' => '',
|
||||
'swoole' => 'swoole-hook-',
|
||||
];
|
||||
|
||||
/**
|
||||
* Maximum number of orphan extensions per matrix entry.
|
||||
*/
|
||||
@@ -65,7 +81,8 @@ class GenExtTestMatrixCommand extends BaseCommand
|
||||
{
|
||||
$this->addOption('for-extensions', null, InputOption::VALUE_OPTIONAL, 'Filter by extension display names, comma-separated', '')
|
||||
->addOption('for-libs', null, InputOption::VALUE_OPTIONAL, 'Filter by lib names (depends+suggests), comma-separated', '')
|
||||
->addOption('os', null, InputOption::VALUE_OPTIONAL, 'Filter by OS (Linux/Darwin/Windows), comma-separated', '');
|
||||
->addOption('os', null, InputOption::VALUE_OPTIONAL, 'Filter by OS (Linux/Darwin/Windows), comma-separated', '')
|
||||
->addOption('tier2', null, InputOption::VALUE_NONE, 'Use Tier 2 runners (Linux aarch64 + macOS x86_64, no Windows)');
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
@@ -79,6 +96,9 @@ class GenExtTestMatrixCommand extends BaseCommand
|
||||
$filter_extensions = $parse_option('for-extensions');
|
||||
$filter_libs = $parse_option('for-libs');
|
||||
$filter_os_keys = $parse_option('os');
|
||||
$tier2 = (bool) $this->input->getOption('tier2');
|
||||
|
||||
$base_runners = $tier2 ? self::OS_RUNNERS_TIER2 : self::OS_RUNNERS;
|
||||
|
||||
$all = PackageConfig::getAll();
|
||||
|
||||
@@ -100,8 +120,8 @@ class GenExtTestMatrixCommand extends BaseCommand
|
||||
}
|
||||
|
||||
$os_runners = empty($filter_os_keys)
|
||||
? self::OS_RUNNERS
|
||||
: array_filter(self::OS_RUNNERS, fn ($info) => in_array($info['os_key'], $filter_os_keys, true));
|
||||
? $base_runners
|
||||
: array_filter($base_runners, fn ($info) => in_array($info['os_key'], $filter_os_keys, true));
|
||||
|
||||
$entries = [];
|
||||
$all_ext_lib_deps = [];
|
||||
@@ -165,13 +185,34 @@ class GenExtTestMatrixCommand extends BaseCommand
|
||||
$groups = [];
|
||||
$orphans = [];
|
||||
$standalone_set = array_fill_keys(self::STANDALONE, true);
|
||||
$standalone_isolated = self::STANDALONE_ISOLATED;
|
||||
|
||||
foreach (array_merge($roots, $non_roots) as $ext) {
|
||||
if (isset($covered[$ext])) {
|
||||
continue;
|
||||
}
|
||||
$chain = $this->dfsCollect($ext, $ext_deps, $pool_set, $covered);
|
||||
$display = $this->displayName($ext);
|
||||
|
||||
if (array_key_exists($display, $standalone_isolated)) {
|
||||
// Isolated standalone: mark only this ext + its hook virtuals as covered
|
||||
$covered[$ext] = true;
|
||||
$hook_prefix = $standalone_isolated[$display];
|
||||
$group_names = [$display];
|
||||
if ($hook_prefix !== '') {
|
||||
foreach ($os_virtual as $vpkg => $_) {
|
||||
$vdisplay = $this->displayName($vpkg);
|
||||
if (str_starts_with($vdisplay, $hook_prefix) && !isset($covered[$vpkg])) {
|
||||
$covered[$vpkg] = true;
|
||||
$group_names[] = $vdisplay;
|
||||
}
|
||||
}
|
||||
sort($group_names);
|
||||
}
|
||||
$groups[] = implode(',', $group_names);
|
||||
continue;
|
||||
}
|
||||
|
||||
$chain = $this->dfsCollect($ext, $ext_deps, $pool_set, $covered);
|
||||
if (isset($standalone_set[$display])) {
|
||||
// Always emit standalone extensions as their own single entry
|
||||
$groups[] = $display;
|
||||
@@ -198,7 +239,7 @@ class GenExtTestMatrixCommand extends BaseCommand
|
||||
'os' => $os,
|
||||
'arch' => $os_info['arch'],
|
||||
'extension' => $group,
|
||||
'build-args' => '"' . $group . '" ' . self::BUILD_TARGETS . ($extra !== '' ? ' ' . $extra : ''),
|
||||
'build-args' => './bin/spc build "' . $group . '" ' . self::BUILD_TARGETS . ($extra !== '' ? ' ' . $extra : ''),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
313
src/StaticPHP/Command/Dev/TestBotCommand.php
Normal file
313
src/StaticPHP/Command/Dev/TestBotCommand.php
Normal file
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace StaticPHP\Command\Dev;
|
||||
|
||||
use StaticPHP\Artifact\Downloader\Type\GitHubTokenSetupTrait;
|
||||
use StaticPHP\Command\BaseCommand;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
|
||||
#[AsCommand('dev:test-bot', 'Analyze PR changes and labels, output test-bot metadata JSON', [], true)]
|
||||
class TestBotCommand extends BaseCommand
|
||||
{
|
||||
use GitHubTokenSetupTrait;
|
||||
|
||||
private const string API_BASE = 'https://api.github.com';
|
||||
|
||||
/** Platform labels → os_key used by dev:gen-ext-test-matrix --os= */
|
||||
private const array PLATFORM_LABELS = [
|
||||
'test/linux' => 'Linux',
|
||||
'test/windows' => 'Windows',
|
||||
'test/macos' => 'Darwin',
|
||||
];
|
||||
|
||||
private const string TIER2_LABEL = 'test/tier2';
|
||||
|
||||
/** PHP version labels → version string (8.5 is always included as default) */
|
||||
private const array PHP_VERSION_LABELS = [
|
||||
'test/php-83' => '8.3',
|
||||
'test/php-84' => '8.4',
|
||||
];
|
||||
|
||||
private const string DEFAULT_PHP_VERSION = '8.5';
|
||||
|
||||
protected bool $no_motd = true;
|
||||
|
||||
public function configure(): void
|
||||
{
|
||||
$this->addOption('pr', null, InputOption::VALUE_REQUIRED, 'Pull request number')
|
||||
->addOption('repo', null, InputOption::VALUE_REQUIRED, 'Repository in owner/repo format (e.g. owner/repo)')
|
||||
->addOption('mock-files', null, InputOption::VALUE_REQUIRED, 'Comma-separated file paths to simulate PR changed files (skips GitHub API, for local testing)', '')
|
||||
->addOption('mock-labels', null, InputOption::VALUE_REQUIRED, 'Comma-separated labels to simulate PR labels (skips GitHub API, for local testing)', '');
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$mock_files_raw = (string) $this->input->getOption('mock-files');
|
||||
$mock_labels_raw = (string) $this->input->getOption('mock-labels');
|
||||
$is_mock = $mock_files_raw !== '' || $mock_labels_raw !== '';
|
||||
|
||||
if ($is_mock) {
|
||||
// Local testing mode: skip all GitHub API calls
|
||||
$changed_files = array_map(
|
||||
fn ($f) => ['filename' => trim($f)],
|
||||
array_filter(explode(',', $mock_files_raw))
|
||||
);
|
||||
$label_names = array_map('trim', array_filter(explode(',', $mock_labels_raw)));
|
||||
} else {
|
||||
$pr = (int) $this->input->getOption('pr');
|
||||
$repo = (string) $this->input->getOption('repo');
|
||||
|
||||
if ($pr <= 0 || $repo === '') {
|
||||
$this->output->writeln('<error>Either --mock-files/--mock-labels (local test) or --pr and --repo (live) are required.</error>');
|
||||
return static::USER_ERROR;
|
||||
}
|
||||
|
||||
$headers = array_merge(
|
||||
$this->getGitHubTokenHeaders(),
|
||||
['Accept: application/vnd.github+json', 'X-GitHub-Api-Version: 2022-11-28'],
|
||||
);
|
||||
|
||||
// Fetch changed files (paginated, up to 300)
|
||||
$changed_files = $this->fetchPaginatedFiles($repo, $pr, $headers);
|
||||
|
||||
// Fetch current labels on the PR/issue
|
||||
$labels_raw = $this->apiGet(
|
||||
sprintf('%s/repos/%s/issues/%d/labels', self::API_BASE, $repo, $pr),
|
||||
$headers
|
||||
);
|
||||
$label_names = array_column($labels_raw ?? [], 'name');
|
||||
}
|
||||
|
||||
// Analyze changed files → extensions, libs, targets
|
||||
[$extensions, $libs, $targets] = $this->analyzeChangedFiles($changed_files);
|
||||
|
||||
// Resolve active platform OS keys (used as filters, not as trigger)
|
||||
$os_keys = [];
|
||||
foreach (self::PLATFORM_LABELS as $label => $os_key) {
|
||||
if (in_array($label, $label_names, true)) {
|
||||
$os_keys[] = $os_key;
|
||||
}
|
||||
}
|
||||
$tier2 = in_array(self::TIER2_LABEL, $label_names, true);
|
||||
$need_test = in_array('need-test', $label_names, true);
|
||||
|
||||
// Resolve PHP versions (default always included)
|
||||
$php_versions = [self::DEFAULT_PHP_VERSION];
|
||||
foreach (self::PHP_VERSION_LABELS as $label => $version) {
|
||||
if (in_array($label, $label_names, true)) {
|
||||
$php_versions[] = $version;
|
||||
}
|
||||
}
|
||||
$php_versions = array_unique($php_versions);
|
||||
sort($php_versions);
|
||||
|
||||
// Build gen_matrix_args whenever need-test is set.
|
||||
// Platform labels narrow the OS scope; absent = no --os filter (all platforms).
|
||||
$gen_matrix_args = '';
|
||||
$gen_matrix_args_tier2 = '';
|
||||
if ($need_test) {
|
||||
$flag_parts = [];
|
||||
if (!empty($extensions)) {
|
||||
$flag_parts[] = '--for-extensions=' . implode(',', $extensions);
|
||||
}
|
||||
if (!empty($libs)) {
|
||||
$flag_parts[] = '--for-libs=' . implode(',', $libs);
|
||||
}
|
||||
if (!empty($os_keys)) {
|
||||
$flag_parts[] = '--os=' . implode(',', $os_keys);
|
||||
}
|
||||
$gen_matrix_args = implode(' ', $flag_parts);
|
||||
|
||||
if ($tier2) {
|
||||
// Tier2 covers Linux + macOS only (never Windows)
|
||||
$tier2_os = array_values(array_filter(
|
||||
!empty($os_keys) ? $os_keys : ['Linux', 'Darwin'],
|
||||
fn ($k) => $k !== 'Windows'
|
||||
));
|
||||
if (!empty($tier2_os)) {
|
||||
$tier2_parts = array_values(array_filter($flag_parts, fn ($f) => !str_starts_with($f, '--os=')));
|
||||
$tier2_parts[] = '--os=' . implode(',', $tier2_os);
|
||||
$tier2_parts[] = '--tier2';
|
||||
$gen_matrix_args_tier2 = implode(' ', $tier2_parts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$comment_body = $this->buildCommentBody(
|
||||
$extensions,
|
||||
$libs,
|
||||
$targets,
|
||||
$label_names,
|
||||
$os_keys,
|
||||
$tier2,
|
||||
$php_versions,
|
||||
$need_test,
|
||||
);
|
||||
|
||||
$result = [
|
||||
'need_test' => $need_test,
|
||||
'extensions' => array_values($extensions),
|
||||
'libs' => array_values($libs),
|
||||
'targets' => array_values($targets),
|
||||
'gen_matrix_args' => $gen_matrix_args,
|
||||
'gen_matrix_args_tier2' => $gen_matrix_args_tier2,
|
||||
'php_versions' => array_values($php_versions),
|
||||
'tier2' => $tier2,
|
||||
'comment_body' => $comment_body,
|
||||
];
|
||||
|
||||
$this->output->write(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
|
||||
return static::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all changed files for a PR across up to 3 pages (max 300 files).
|
||||
*/
|
||||
private function fetchPaginatedFiles(string $repo, int $pr, array $headers): array
|
||||
{
|
||||
$files = [];
|
||||
for ($page = 1; $page <= 3; ++$page) {
|
||||
$url = sprintf('%s/repos/%s/pulls/%d/files?per_page=100&page=%d', self::API_BASE, $repo, $pr, $page);
|
||||
$batch = $this->apiGet($url, $headers);
|
||||
if (empty($batch)) {
|
||||
break;
|
||||
}
|
||||
$files = array_merge($files, $batch);
|
||||
if (count($batch) < 100) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a GET request and return decoded JSON array, or null on failure.
|
||||
*/
|
||||
private function apiGet(string $url, array $headers): ?array
|
||||
{
|
||||
$data = default_shell()->executeCurl($url, headers: $headers);
|
||||
$decoded = json_decode($data ?: '', true);
|
||||
return is_array($decoded) ? $decoded : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze changed file paths and classify them into extensions, libs, and targets.
|
||||
*
|
||||
* @return array{string[], string[], string[]}
|
||||
*/
|
||||
private function analyzeChangedFiles(array $files): array
|
||||
{
|
||||
$extensions = [];
|
||||
$libs = [];
|
||||
$targets = [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
$path = $file['filename'] ?? '';
|
||||
|
||||
if (preg_match('#^src/Package/Extension/([^/]+)\.php$#', $path, $m)) {
|
||||
$name = strtolower($m[1]);
|
||||
$extensions[$name] = $name;
|
||||
} elseif (preg_match('#^config/pkg/ext/ext-([^/]+)\.yml$#', $path, $m)) {
|
||||
$extensions[$m[1]] = $m[1];
|
||||
} elseif (preg_match('#^src/Package/Library/([^/]+)\.php$#', $path, $m)) {
|
||||
$name = strtolower($m[1]);
|
||||
$libs[$name] = $name;
|
||||
} elseif (preg_match('#^config/pkg/lib/([^/]+)\.yml$#', $path, $m)) {
|
||||
$libs[$m[1]] = $m[1];
|
||||
} elseif (preg_match('#^src/Package/Target/([^/]+)\.php$#', $path, $m)) {
|
||||
$name = strtolower($m[1]);
|
||||
$targets[$name] = $name;
|
||||
} elseif (preg_match('#^config/pkg/target/([^/]+)\.yml$#', $path, $m)) {
|
||||
$targets[$m[1]] = $m[1];
|
||||
}
|
||||
}
|
||||
|
||||
sort($extensions);
|
||||
sort($libs);
|
||||
sort($targets);
|
||||
|
||||
return [$extensions, $libs, $targets];
|
||||
}
|
||||
|
||||
private function buildCommentBody(
|
||||
array $extensions,
|
||||
array $libs,
|
||||
array $targets,
|
||||
array $label_names,
|
||||
array $os_keys,
|
||||
bool $tier2,
|
||||
array $php_versions,
|
||||
bool $need_test,
|
||||
): string {
|
||||
$fmt = static fn (array $items): string => !empty($items)
|
||||
? '`' . implode('`, `', $items) . '`'
|
||||
: '_none_';
|
||||
|
||||
$detected = sprintf(
|
||||
'**Detected**: Extensions: %s | Libraries: %s | Targets: %s',
|
||||
$fmt($extensions),
|
||||
$fmt($libs),
|
||||
$fmt($targets),
|
||||
);
|
||||
|
||||
// Case 1: need-test absent → invite the author to add it
|
||||
if (!$need_test) {
|
||||
return implode("\n", [
|
||||
'<!-- spc-test-bot -->',
|
||||
'**StaticPHP Test Bot**',
|
||||
'',
|
||||
$detected,
|
||||
'',
|
||||
'To trigger extension build tests on this PR, add the `need-test` label:',
|
||||
'',
|
||||
'**Gate**: `need-test`',
|
||||
'**Platform filter** (optional, default all): `test/linux` `test/windows` `test/macos` · `test/tier2`',
|
||||
'**PHP version** (optional, default 8.5): `test/php-83` `test/php-84`',
|
||||
]);
|
||||
}
|
||||
|
||||
// Case 2: need-test present → show what will run
|
||||
// os_keys empty = no filter = all platforms
|
||||
$effective_os = !empty($os_keys)
|
||||
? $os_keys
|
||||
: array_values(self::PLATFORM_LABELS); // all OS keys
|
||||
|
||||
$platform_parts = [];
|
||||
foreach (self::PLATFORM_LABELS as $_label => $os_key) {
|
||||
if (!in_array($os_key, $effective_os, true)) {
|
||||
continue;
|
||||
}
|
||||
$platform_parts[] = match ($os_key) {
|
||||
'Linux' => 'Linux x86_64',
|
||||
'Darwin' => 'macOS arm64',
|
||||
/* @phpstan-ignore-next-line */
|
||||
'Windows' => 'Windows x86_64',
|
||||
default => $os_key,
|
||||
};
|
||||
}
|
||||
if ($tier2) {
|
||||
if (in_array('Linux', $effective_os, true)) {
|
||||
$platform_parts[] = 'Linux aarch64 (Tier2)';
|
||||
}
|
||||
if (in_array('Darwin', $effective_os, true)) {
|
||||
$platform_parts[] = 'macOS x86_64 (Tier2)';
|
||||
}
|
||||
}
|
||||
|
||||
$php_str = implode(', ', array_map(fn ($v) => "PHP {$v}", $php_versions)) . ' NTS';
|
||||
$active_test_labels = array_values(array_filter($label_names, fn ($l) => str_starts_with($l, 'test/')));
|
||||
$labels_str = !empty($active_test_labels) ? '`' . implode('`, `', $active_test_labels) . '`' : '_none_';
|
||||
|
||||
return implode("\n", [
|
||||
'<!-- spc-test-bot -->',
|
||||
'**StaticPHP Test Bot**',
|
||||
'',
|
||||
$detected,
|
||||
'**Active labels**: ' . $labels_str,
|
||||
'**Config**: ' . implode(' + ', $platform_parts) . ' | ' . $php_str,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use StaticPHP\DI\ApplicationContext;
|
||||
use StaticPHP\Registry\ArtifactLoader;
|
||||
use StaticPHP\Registry\PackageLoader;
|
||||
use StaticPHP\Util\DependencyResolver;
|
||||
use StaticPHP\Util\GlobalEnvManager;
|
||||
use StaticPHP\Util\InteractiveTerm;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
@@ -34,6 +35,7 @@ class ExtractCommand extends BaseCommand
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
GlobalEnvManager::afterInit();
|
||||
$cache = ApplicationContext::get(ArtifactCache::class);
|
||||
$extractor = new ArtifactExtractor($cache);
|
||||
$force_source = (bool) $this->getOption('source-only');
|
||||
|
||||
@@ -44,7 +44,7 @@ class SPCConfigCommand extends BaseCommand
|
||||
'absolute_libs' => (bool) $this->getOption('absolute-libs'),
|
||||
]);
|
||||
$packages = array_merge(array_map(fn ($x) => "ext-{$x}", $extensions), $libraries);
|
||||
$config = $util->config($packages, $include_suggests);
|
||||
$config = $util->config($packages);
|
||||
|
||||
$this->output->writeln(match (true) {
|
||||
$this->getOption('includes') => $config['cflags'],
|
||||
|
||||
@@ -19,6 +19,7 @@ use StaticPHP\Command\Dev\LintConfigCommand;
|
||||
use StaticPHP\Command\Dev\PackageInfoCommand;
|
||||
use StaticPHP\Command\Dev\PackLibCommand;
|
||||
use StaticPHP\Command\Dev\ShellCommand;
|
||||
use StaticPHP\Command\Dev\TestBotCommand;
|
||||
use StaticPHP\Command\DoctorCommand;
|
||||
use StaticPHP\Command\DownloadCommand;
|
||||
use StaticPHP\Command\DumpExtensionsCommand;
|
||||
@@ -87,6 +88,7 @@ class ConsoleApplication extends Application
|
||||
new GenExtDocsCommand(),
|
||||
new GenDepsDataCommand(),
|
||||
new GenExtTestMatrixCommand(),
|
||||
new TestBotCommand(),
|
||||
]);
|
||||
|
||||
// add additional commands from registries
|
||||
|
||||
@@ -98,6 +98,25 @@ class ApplicationContext
|
||||
return self::getContainer()->has($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve $id, returning null if it can't be constructed.
|
||||
* PHP-DI's has() returns true for any autowirable class even when get()
|
||||
* would throw on missing scalar args — for "is this resolvable right now"
|
||||
* semantics use this.
|
||||
*
|
||||
* @template T
|
||||
* @param class-string<T> $id
|
||||
* @return null|T
|
||||
*/
|
||||
public static function tryGet(string $id): mixed
|
||||
{
|
||||
try {
|
||||
return self::getContainer()->get($id);
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a service in the container.
|
||||
* Use sparingly - prefer configuration-based definitions.
|
||||
|
||||
44
src/StaticPHP/Doctor/Item/GoXcaddyCheck.php
Normal file
44
src/StaticPHP/Doctor/Item/GoXcaddyCheck.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace StaticPHP\Doctor\Item;
|
||||
|
||||
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\Package\PackageInstaller;
|
||||
|
||||
#[OptionalCheck([self::class, 'optionalCheck'])]
|
||||
class GoXcaddyCheck
|
||||
{
|
||||
public static function optionalCheck(): bool
|
||||
{
|
||||
if (!ApplicationContext::has('craft')) {
|
||||
return false;
|
||||
}
|
||||
/** @var null|array $craft */
|
||||
$craft = ApplicationContext::get('craft');
|
||||
return in_array('frankenphp', $craft['sapi'] ?? [], true);
|
||||
}
|
||||
|
||||
#[CheckItem('if go-xcaddy is installed', level: 800)]
|
||||
public function check(): CheckResult
|
||||
{
|
||||
if (!new PackageInstaller()->addInstallPackage('go-xcaddy')->isPackageInstalled('go-xcaddy')) {
|
||||
return CheckResult::fail('go-xcaddy is not installed', 'install-go-xcaddy');
|
||||
}
|
||||
return CheckResult::ok(PKG_ROOT_PATH . '/go-xcaddy/bin/xcaddy');
|
||||
}
|
||||
|
||||
#[FixItem('install-go-xcaddy')]
|
||||
public function installGoXcaddy(): bool
|
||||
{
|
||||
$installer = new PackageInstaller(interactive: false);
|
||||
$installer->addInstallPackage('go-xcaddy');
|
||||
$installer->run(true);
|
||||
return $installer->isPackageInstalled('go-xcaddy');
|
||||
}
|
||||
}
|
||||
@@ -73,13 +73,20 @@ class LinuxMuslCheck
|
||||
$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')
|
||||
->exec('CC=gcc CXX=g++ AR=ar LD=ld ./configure --disable-gcc-wrapper')
|
||||
->exec('CC=gcc CXX=g++ AR=ar LD=ld make -j');
|
||||
->setEnv($sysEnv)
|
||||
->exec('./configure --disable-gcc-wrapper')
|
||||
->exec('make -j');
|
||||
if ($prefix !== '') {
|
||||
f_passthru('cd ' . SOURCE_PATH . "/musl-wrapper && CC=gcc CXX=g++ AR=ar LD=ld {$prefix}make install");
|
||||
f_passthru('cd ' . SOURCE_PATH . "/musl-wrapper && {$envFlags} {$prefix}make install");
|
||||
} else {
|
||||
$shell->exec("CC=gcc CXX=g++ AR=ar LD=ld {$prefix}make install");
|
||||
$shell->exec("{$prefix}make install");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
48
src/StaticPHP/Doctor/Item/LlvmCompilerRtCheck.php
Normal file
48
src/StaticPHP/Doctor/Item/LlvmCompilerRtCheck.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace StaticPHP\Doctor\Item;
|
||||
|
||||
use Package\Artifact\llvm_compiler_rt;
|
||||
use Package\Artifact\zig;
|
||||
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\Package\PackageInstaller;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Toolchain\Interface\ToolchainInterface;
|
||||
use StaticPHP\Toolchain\ZigToolchain;
|
||||
|
||||
#[OptionalCheck([self::class, 'optionalCheck'])]
|
||||
class LlvmCompilerRtCheck
|
||||
{
|
||||
public static function optionalCheck(): bool
|
||||
{
|
||||
return ApplicationContext::get(ToolchainInterface::class) instanceof ZigToolchain;
|
||||
}
|
||||
|
||||
/** @noinspection PhpUnused */
|
||||
#[CheckItem('if llvm-compiler-rt is built for current target', level: 799)]
|
||||
public function checkLlvmCompilerRt(): CheckResult
|
||||
{
|
||||
$libDir = zig::path() . '/lib/' . SystemTarget::getCanonicalTriple();
|
||||
if (new llvm_compiler_rt()->isBuilt($libDir)) {
|
||||
return CheckResult::ok($libDir);
|
||||
}
|
||||
return CheckResult::fail('llvm-compiler-rt is not built for ' . SystemTarget::getCanonicalTriple(), 'build-llvm-compiler-rt');
|
||||
}
|
||||
|
||||
#[FixItem('build-llvm-compiler-rt')]
|
||||
public function fixLlvmCompilerRt(): bool
|
||||
{
|
||||
$installer = new PackageInstaller(interactive: false);
|
||||
$installer->addInstallPackage('llvm-compiler-rt');
|
||||
$installer->run(true);
|
||||
new llvm_compiler_rt()->buildForTriple();
|
||||
$libDir = zig::path() . '/lib/' . SystemTarget::getCanonicalTriple();
|
||||
return new llvm_compiler_rt()->isBuilt($libDir);
|
||||
}
|
||||
}
|
||||
45
src/StaticPHP/Doctor/Item/LlvmToolsCheck.php
Normal file
45
src/StaticPHP/Doctor/Item/LlvmToolsCheck.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace StaticPHP\Doctor\Item;
|
||||
|
||||
use Package\Artifact\llvm_tools;
|
||||
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\Package\PackageInstaller;
|
||||
use StaticPHP\Toolchain\Interface\ToolchainInterface;
|
||||
use StaticPHP\Toolchain\ZigToolchain;
|
||||
|
||||
#[OptionalCheck([self::class, 'optionalCheck'])]
|
||||
class LlvmToolsCheck
|
||||
{
|
||||
public static function optionalCheck(): bool
|
||||
{
|
||||
return ApplicationContext::get(ToolchainInterface::class) instanceof ZigToolchain;
|
||||
}
|
||||
|
||||
/** @noinspection PhpUnused */
|
||||
#[CheckItem('if llvm-tools (objcopy/strip/profdata) are built', level: 798)]
|
||||
public function checkLlvmTools(): CheckResult
|
||||
{
|
||||
$binDir = PKG_ROOT_PATH . '/llvm-tools/bin';
|
||||
if (new llvm_tools()->allBuilt($binDir)) {
|
||||
return CheckResult::ok($binDir);
|
||||
}
|
||||
return CheckResult::fail('llvm-tools are not built', 'build-llvm-tools');
|
||||
}
|
||||
|
||||
#[FixItem('build-llvm-tools')]
|
||||
public function fixLlvmTools(): bool
|
||||
{
|
||||
$installer = new PackageInstaller(interactive: false);
|
||||
$installer->addInstallPackage('llvm-tools');
|
||||
$installer->run(true);
|
||||
new llvm_tools()->buildForHost();
|
||||
return new llvm_tools()->allBuilt(PKG_ROOT_PATH . '/llvm-tools/bin');
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace StaticPHP\Doctor\Item;
|
||||
|
||||
use Package\Artifact\zig;
|
||||
use StaticPHP\Attribute\Doctor\CheckItem;
|
||||
use StaticPHP\Attribute\Doctor\FixItem;
|
||||
use StaticPHP\Attribute\Doctor\OptionalCheck;
|
||||
@@ -26,7 +27,7 @@ class ZigCheck
|
||||
public function checkZig(): CheckResult
|
||||
{
|
||||
if (new PackageInstaller()->addInstallPackage('zig')->isPackageInstalled('zig')) {
|
||||
return CheckResult::ok();
|
||||
return CheckResult::ok(zig::binary());
|
||||
}
|
||||
return CheckResult::fail('zig is not installed', 'install-zig');
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ use StaticPHP\Exception\SPCInternalException;
|
||||
use StaticPHP\Exception\WrongUsageException;
|
||||
use StaticPHP\Runtime\Shell\Shell;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Toolchain\Interface\ToolchainInterface;
|
||||
use StaticPHP\Toolchain\ZigToolchain;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
use StaticPHP\Util\GlobalPathTrait;
|
||||
use StaticPHP\Util\InteractiveTerm;
|
||||
@@ -178,14 +180,15 @@ class PackageBuilder
|
||||
if (SystemTarget::getTargetOS() === 'Darwin') {
|
||||
shell()->exec("dsymutil -f {$binary_path} -o {$debug_file}");
|
||||
} elseif (SystemTarget::getTargetOS() === 'Linux') {
|
||||
$objcopy = getenv('OBJCOPY') ?: 'objcopy';
|
||||
if ($eu_strip = LinuxUtil::findCommand('eu-strip')) {
|
||||
shell()
|
||||
->exec("{$eu_strip} -f {$debug_file} {$binary_path}")
|
||||
->exec("objcopy --add-gnu-debuglink={$debug_file} {$binary_path}");
|
||||
->exec("{$objcopy} --add-gnu-debuglink={$debug_file} {$binary_path}");
|
||||
} else {
|
||||
shell()
|
||||
->exec("objcopy --only-keep-debug {$binary_path} {$debug_file}")
|
||||
->exec("objcopy --add-gnu-debuglink={$debug_file} {$binary_path}");
|
||||
->exec("{$objcopy} --only-keep-debug {$binary_path} {$debug_file}")
|
||||
->exec("{$objcopy} --add-gnu-debuglink={$debug_file} {$binary_path}");
|
||||
}
|
||||
} else {
|
||||
logger()->debug('extractDebugInfo is only supported on Linux and macOS');
|
||||
@@ -199,9 +202,12 @@ class PackageBuilder
|
||||
*/
|
||||
public function stripBinary(string $binary_path): void
|
||||
{
|
||||
$strip = ApplicationContext::tryGet(ToolchainInterface::class) instanceof ZigToolchain
|
||||
? PKG_ROOT_PATH . '/llvm-tools/bin/llvm-strip'
|
||||
: 'strip';
|
||||
shell()->exec(match (SystemTarget::getTargetOS()) {
|
||||
'Darwin' => "strip -S {$binary_path}",
|
||||
'Linux' => "strip --strip-unneeded {$binary_path}",
|
||||
'Darwin' => "{$strip} -S {$binary_path}",
|
||||
'Linux' => "{$strip} --strip-unneeded {$binary_path}",
|
||||
'Windows' => 'echo "Skip strip on Windows"', // Windows strip is not available for now
|
||||
default => throw new SPCInternalException('stripBinary is only supported on Linux and macOS'),
|
||||
});
|
||||
|
||||
@@ -154,6 +154,9 @@ class PackageInstaller
|
||||
$this->resolvePackages();
|
||||
}
|
||||
|
||||
$this->reconcilePhpSrcVersion();
|
||||
$this->emitPreInstallEvents();
|
||||
|
||||
if ($this->interactive && !$disable_delay_msg) {
|
||||
// show install or build options in terminal with beautiful output
|
||||
$this->printInstallerInfo();
|
||||
@@ -215,7 +218,7 @@ class PackageInstaller
|
||||
if (!$is_to_build && $should_use_binary) {
|
||||
// install binary
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::indicateProgress('Installing package: ' . ConsoleColor::yellow($package->getName()));
|
||||
InteractiveTerm::indicateProgress('Installing ' . $this->kindLabel($package) . ': ' . ConsoleColor::yellow($package->getName()));
|
||||
}
|
||||
try {
|
||||
// Start tracking for binary installation
|
||||
@@ -227,17 +230,17 @@ class PackageInstaller
|
||||
// Stop tracking on error
|
||||
$this->tracker?->stopTracking();
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Installing binary package failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
InteractiveTerm::finish('Installing ' . $this->kindLabel($package) . ' failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
echo PHP_EOL;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Installed binary package: ' . ConsoleColor::green($package->getName()) . ($status === SPC_STATUS_ALREADY_INSTALLED ? ' (already installed, skipped)' : ''));
|
||||
InteractiveTerm::finish('Installed ' . $this->kindLabel($package) . ': ' . ConsoleColor::green($package->getName()) . ($status === SPC_STATUS_ALREADY_INSTALLED ? ' (already installed, skipped)' : ''));
|
||||
}
|
||||
} elseif ($is_to_build && $has_build_stage || $has_source && $has_build_stage) {
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::indicateProgress('Building package: ' . ConsoleColor::yellow($package->getName()));
|
||||
InteractiveTerm::indicateProgress('Building ' . $this->kindLabel($package) . ': ' . ConsoleColor::yellow($package->getName()));
|
||||
}
|
||||
try {
|
||||
// Start tracking for build
|
||||
@@ -260,13 +263,13 @@ class PackageInstaller
|
||||
// Stop tracking on error
|
||||
$this->tracker?->stopTracking();
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Building package failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
InteractiveTerm::finish('Building ' . $this->kindLabel($package) . ' failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
echo PHP_EOL;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Built package: ' . ConsoleColor::green($package->getName()) . ($status === SPC_STATUS_ALREADY_BUILT ? ' (already built, skipped)' : ''));
|
||||
InteractiveTerm::finish('Built ' . $this->kindLabel($package) . ': ' . ConsoleColor::green($package->getName()) . ($status === SPC_STATUS_ALREADY_BUILT ? ' (already built, skipped)' : ''));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -359,6 +362,15 @@ class PackageInstaller
|
||||
return false;
|
||||
}
|
||||
|
||||
public function emitPreInstallEvents(): void
|
||||
{
|
||||
foreach ($this->packages as $package) {
|
||||
if ($package->hasStage('preInstall')) {
|
||||
$package->runStage('preInstall');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function emitPostInstallEvents(): void
|
||||
{
|
||||
foreach ($this->packages as $package) {
|
||||
@@ -571,6 +583,77 @@ class PackageInstaller
|
||||
return null;
|
||||
}
|
||||
|
||||
private function reconcilePhpSrcVersion(): void
|
||||
{
|
||||
$src_dir = SOURCE_PATH . '/php-src';
|
||||
$cache = ApplicationContext::get(ArtifactCache::class);
|
||||
$requested = $this->options['dl-with-php'] ?? null;
|
||||
if ($requested !== null && $requested !== '' && $requested !== 'git') {
|
||||
$info = $cache->getSourceInfo('php-src') ?? [];
|
||||
$cv = $info['version'] ?? null;
|
||||
if (($info['cache_type'] ?? null) === 'git' || $cv === null
|
||||
|| ($cv !== $requested && !str_starts_with($cv, $requested . '.'))) {
|
||||
$resolved = null;
|
||||
$candidates = glob(DOWNLOAD_PATH . '/php-' . $requested . '.*.tar.xz') ?: [];
|
||||
if ($candidates !== []) {
|
||||
usort($candidates, 'strnatcmp');
|
||||
if (preg_match('/^php-([0-9.]+)\.tar\.xz$/', basename(end($candidates)), $vm)) {
|
||||
$resolved = $vm[1];
|
||||
}
|
||||
} elseif ($this->download) {
|
||||
$j = @file_get_contents('https://www.php.net/releases/index.php?json&version=' . urlencode($requested));
|
||||
$rel = is_string($j) ? json_decode($j, true) : null;
|
||||
$resolved = is_array($rel) ? ($rel['version'] ?? null) : null;
|
||||
} else {
|
||||
throw new WrongUsageException("Requested PHP '{$requested}' but no php-{$requested}.*.tar.xz in downloads/; drop --no-download or run 'bin/spc download php-src --with-php={$requested}' first.");
|
||||
}
|
||||
if ($resolved !== null) {
|
||||
$cf = DOWNLOAD_PATH . '/.cache.json';
|
||||
$j = json_decode(@file_get_contents($cf) ?: '{}', true) ?: [];
|
||||
$tarball = DOWNLOAD_PATH . "/php-{$resolved}.tar.xz";
|
||||
$j['php-src']['source'] = [
|
||||
'lock_type' => 'source', 'cache_type' => 'archive',
|
||||
'filename' => "php-{$resolved}.tar.xz",
|
||||
'extract' => $info['extract'] ?? null,
|
||||
'hash' => is_file($tarball) ? sha1_file($tarball) : null,
|
||||
'time' => time(), 'version' => $resolved,
|
||||
'config' => $info['config'] ?? ['type' => 'php-release', 'domain' => 'https://www.php.net'],
|
||||
'downloader' => $info['downloader'] ?? \StaticPHP\Artifact\Downloader\Type\PhpRelease::class,
|
||||
];
|
||||
$j['php-src']['binary'] ??= [];
|
||||
file_put_contents($cf, json_encode($j, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
ApplicationContext::set(ArtifactCache::class, $cache = new ArtifactCache());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_dir($src_dir) || ($info = $cache->getSourceInfo('php-src')) === null) {
|
||||
return;
|
||||
}
|
||||
if (($info['cache_type'] ?? null) === 'git') {
|
||||
if (!is_dir($src_dir . '/.git')) {
|
||||
FileSystem::removeDir($src_dir);
|
||||
}
|
||||
return;
|
||||
}
|
||||
$vh = $src_dir . '/main/php_version.h';
|
||||
if (is_file($vh)
|
||||
&& preg_match('/#define\s+PHP_VERSION\s+"([^"]+)"/', file_get_contents($vh), $m)
|
||||
&& $m[1] !== ($info['version'] ?? null)
|
||||
) {
|
||||
FileSystem::removeDir($src_dir);
|
||||
}
|
||||
}
|
||||
|
||||
private function kindLabel(Package $package): string
|
||||
{
|
||||
return match (true) {
|
||||
$package instanceof PhpExtensionPackage => 'extension',
|
||||
$package instanceof TargetPackage => 'target',
|
||||
$package instanceof LibraryPackage => 'library',
|
||||
default => 'package',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Package[] $packages
|
||||
*/
|
||||
@@ -688,7 +771,7 @@ class PackageInstaller
|
||||
if ($package->getBuildOption('build-all') || $package->getBuildOption('build-frankenphp')) {
|
||||
$frankenphp = PackageLoader::getPackage('frankenphp');
|
||||
$this->install_packages[$frankenphp->getName()] = $frankenphp;
|
||||
$this->build_packages[$package->getName()] = $package;
|
||||
$this->build_packages[$frankenphp->getName()] = $frankenphp;
|
||||
$added = true;
|
||||
}
|
||||
$this->build_packages[$package->getName()] = $package;
|
||||
|
||||
@@ -12,6 +12,7 @@ use StaticPHP\Exception\WrongUsageException;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Toolchain\ToolchainManager;
|
||||
use StaticPHP\Toolchain\ZigToolchain;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
use StaticPHP\Util\GlobalEnvManager;
|
||||
use StaticPHP\Util\SPCConfigUtil;
|
||||
|
||||
@@ -278,10 +279,15 @@ class PhpExtensionPackage extends Package
|
||||
[$staticLibs, $sharedLibs] = $this->splitLibsIntoStaticAndShared($config['libs']);
|
||||
$preStatic = PHP_OS_FAMILY === 'Darwin' ? '' : '-Wl,--start-group ';
|
||||
$postStatic = PHP_OS_FAMILY === 'Darwin' ? '' : ' -Wl,--end-group ';
|
||||
// -Wl,-Bsymbolic: bind zend_* refs to the .so's own copies, not via global lookup
|
||||
$ldflags = (string) $config['ldflags'];
|
||||
if (PHP_OS_FAMILY !== 'Darwin' && !str_contains($ldflags, '-Wl,-Bsymbolic')) {
|
||||
$ldflags = clean_spaces($ldflags . ' -Wl,-Bsymbolic');
|
||||
}
|
||||
return [
|
||||
'CFLAGS' => $config['cflags'],
|
||||
'CXXFLAGS' => $config['cflags'],
|
||||
'LDFLAGS' => $config['ldflags'],
|
||||
'CXXFLAGS' => $config['cxxflags'],
|
||||
'LDFLAGS' => $ldflags,
|
||||
'LIBS' => clean_spaces("{$preStatic} {$staticLibs} {$postStatic} {$sharedLibs}"),
|
||||
'LD_LIBRARY_PATH' => BUILD_LIB_PATH,
|
||||
];
|
||||
@@ -303,10 +309,11 @@ class PhpExtensionPackage extends Package
|
||||
public function configureForUnix(array $env, PhpExtensionPackage $package): void
|
||||
{
|
||||
$phpvars = getenv('SPC_EXTRA_PHP_VARS') ?: '';
|
||||
// CustomPhpConfigureArg keys are OS names ('Linux'/'Darwin'), not platform strings
|
||||
shell()->cd($package->getSourceDir())
|
||||
->setEnv($env)
|
||||
->exec(
|
||||
'./configure ' . $this->getPhpConfigureArg(SystemTarget::getCurrentPlatformString(), true) .
|
||||
'./configure ' . $this->getPhpConfigureArg(SystemTarget::getTargetOS(), true) .
|
||||
' --with-php-config=' . BUILD_BIN_PATH . '/php-config ' .
|
||||
"--enable-shared --disable-static {$phpvars}"
|
||||
);
|
||||
@@ -318,11 +325,53 @@ class PhpExtensionPackage extends Package
|
||||
#[Stage]
|
||||
public function makeForUnix(array $env, PhpExtensionPackage $package, PackageBuilder $builder): void
|
||||
{
|
||||
// phpize Makefile's _SHARED_LIBADD line misses our static archives — splice them in
|
||||
$package->patchSharedLibAdd();
|
||||
$extra_ldflags = (string) getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS');
|
||||
$makeArgs = $extra_ldflags !== '' ? 'EXTRA_LDFLAGS=' . escapeshellarg($extra_ldflags) : '';
|
||||
shell()->cd($package->getSourceDir())
|
||||
->setEnv($env)
|
||||
->exec('make clean')
|
||||
->exec("make -j{$builder->concurrency}")
|
||||
->exec('make install');
|
||||
->exec("make -j{$builder->concurrency} {$makeArgs}")
|
||||
->exec("make install {$makeArgs}");
|
||||
|
||||
// install-modules deref'd libtool's `$ext.so → $ext-X.so` symlink into two regular files; restore the symlink.
|
||||
if (preg_match('/-release\s+(\S+)/', $extra_ldflags, $m)) {
|
||||
$name = $package->getExtensionName();
|
||||
$unversioned = BUILD_MODULES_PATH . "/{$name}.so";
|
||||
$versioned = BUILD_MODULES_PATH . "/{$name}-{$m[1]}.so";
|
||||
if (file_exists($versioned) && file_exists($unversioned) && !is_link($unversioned)) {
|
||||
unlink($unversioned);
|
||||
symlink(basename($versioned), $unversioned);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function patchSharedLibAdd(): void
|
||||
{
|
||||
$config = new SPCConfigUtil()->getExtensionConfig($this);
|
||||
[$staticLibs, $sharedLibs] = $this->splitLibsIntoStaticAndShared($config['libs']);
|
||||
$lstdcpp = str_contains($sharedLibs, '-l:libstdc++.a')
|
||||
? '-l:libstdc++.a'
|
||||
: (str_contains($sharedLibs, '-lstdc++') ? '-lstdc++' : '');
|
||||
|
||||
$makefile = $this->getSourceDir() . '/Makefile';
|
||||
if (!is_file($makefile)) {
|
||||
return;
|
||||
}
|
||||
$content = (string) file_get_contents($makefile);
|
||||
if (!preg_match('/^(.*_SHARED_LIBADD\s*=\s*)(.*)$/m', $content, $m)) {
|
||||
return;
|
||||
}
|
||||
$prefix = $m[1];
|
||||
$current = trim($m[2]);
|
||||
$merged = clean_spaces("{$current} {$staticLibs} {$lstdcpp}");
|
||||
$merged = deduplicate_flags($merged);
|
||||
FileSystem::replaceFileRegex(
|
||||
$makefile,
|
||||
'/^(.*_SHARED_LIBADD\s*=.*)$/m',
|
||||
$prefix . $merged
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -333,14 +382,31 @@ class PhpExtensionPackage extends Package
|
||||
*/
|
||||
public function buildSharedForUnix(PackageBuilder $builder): void
|
||||
{
|
||||
// skip virtual addons (arg-type=none + display-name → owning ext); the parent ext built it
|
||||
$argType = $this->extension_config['arg-type'] ?? null;
|
||||
$displayName = $this->extension_config['display-name'] ?? null;
|
||||
if ($argType === 'none' && $displayName !== null && $displayName !== $this->getExtensionName()) {
|
||||
logger()->info("Skipping virtual extension [{$this->getName()}] — it's part of [{$displayName}].");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_dir($this->getSourceDir())) {
|
||||
throw new ValidationException(
|
||||
"Extension source directory not found: {$this->getSourceDir()}",
|
||||
validation_module: "Extension {$this->getName()} source"
|
||||
);
|
||||
}
|
||||
|
||||
$env = $this->getSharedExtensionEnv();
|
||||
|
||||
$this->runStage([$this, 'phpizeForUnix'], ['env' => $env]);
|
||||
$this->runStage([$this, 'configureForUnix'], ['env' => $env]);
|
||||
$this->runStage([$this, 'makeForUnix'], ['env' => $env]);
|
||||
|
||||
// process *.so file
|
||||
$soFile = BUILD_MODULES_PATH . '/' . $this->getExtensionName() . '.so';
|
||||
// libtool's -release X gives $name-X.so as the real file
|
||||
$soFile = BUILD_MODULES_PATH . '/' . $this->getExtensionName()
|
||||
. (preg_match('/-release\s+(\S+)/', (string) getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS'), $m) ? "-{$m[1]}" : '')
|
||||
. '.so';
|
||||
if (!file_exists($soFile)) {
|
||||
throw new ValidationException("Extension {$this->getExtensionName()} build failed: {$soFile} not found", validation_module: "Extension {$this->getExtensionName()} build");
|
||||
}
|
||||
|
||||
@@ -36,6 +36,13 @@ class ArtifactLoader
|
||||
public static function getArtifactInstance(string $artifact_name): ?Artifact
|
||||
{
|
||||
self::initArtifactInstances();
|
||||
if (!isset(self::$artifacts[$artifact_name])) {
|
||||
// Artifact may have been registered after initArtifactInstances() ran (e.g., from a vendor registry)
|
||||
$config = ArtifactConfig::get($artifact_name);
|
||||
if ($config !== null) {
|
||||
self::$artifacts[$artifact_name] = new Artifact($artifact_name, $config);
|
||||
}
|
||||
}
|
||||
return self::$artifacts[$artifact_name] ?? null;
|
||||
}
|
||||
|
||||
|
||||
@@ -367,15 +367,18 @@ class PackageLoader
|
||||
|
||||
public static function getBeforeStageCallbacks(string $package_name, string $stage): iterable
|
||||
{
|
||||
// match condition
|
||||
// match condition; '*' is a wildcard that fires for every package's stage
|
||||
$installer = ApplicationContext::get(PackageInstaller::class);
|
||||
$stages = self::$before_stages[$package_name][$stage] ?? [];
|
||||
$stages = array_merge(
|
||||
self::$before_stages[$package_name][$stage] ?? [],
|
||||
$package_name === '*' ? [] : (self::$before_stages['*'][$stage] ?? []),
|
||||
);
|
||||
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) {
|
||||
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($conditionals as $class) {
|
||||
if (!ApplicationContext::has($class)) {
|
||||
if (ApplicationContext::tryGet($class) === null) {
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
@@ -385,16 +388,19 @@ class PackageLoader
|
||||
|
||||
public static function getAfterStageCallbacks(string $package_name, string $stage): array
|
||||
{
|
||||
// match condition
|
||||
// match condition; '*' is a wildcard that fires for every package's stage
|
||||
$installer = ApplicationContext::get(PackageInstaller::class);
|
||||
$stages = self::$after_stages[$package_name][$stage] ?? [];
|
||||
$stages = array_merge(
|
||||
self::$after_stages[$package_name][$stage] ?? [],
|
||||
$package_name === '*' ? [] : (self::$after_stages['*'][$stage] ?? []),
|
||||
);
|
||||
$result = [];
|
||||
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) {
|
||||
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($conditionals as $class) {
|
||||
if (!ApplicationContext::has($class)) {
|
||||
if (ApplicationContext::tryGet($class) === null) {
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
@@ -425,6 +431,20 @@ class PackageLoader
|
||||
{
|
||||
foreach (['BeforeStage' => self::$before_stages, 'AfterStage' => self::$after_stages] as $event_name => $ev_all) {
|
||||
foreach ($ev_all as $package_name => $stages) {
|
||||
// wildcard hooks fire for every package's stage; nothing to validate against
|
||||
if ($package_name === '*') {
|
||||
foreach ($stages as $stage_name => $before_events) {
|
||||
foreach ($before_events as [$event_callable, $only_when_package_resolved, $conditionals]) {
|
||||
if ($only_when_package_resolved !== null && !self::hasPackage($only_when_package_resolved)) {
|
||||
throw new RegistryException("{$event_name} event for wildcard [*] stage [{$stage_name}] has unknown only_when_package_resolved package [{$only_when_package_resolved}].");
|
||||
}
|
||||
if (!is_callable($event_callable)) {
|
||||
throw new RegistryException("{$event_name} event for wildcard [*] stage [{$stage_name}] has invalid callable.");
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// check package exists
|
||||
if (!self::hasPackage($package_name)) {
|
||||
throw new RegistryException(
|
||||
@@ -499,6 +519,7 @@ class PackageLoader
|
||||
throw new RegistryException('Package name must not be empty when no package context is available for BeforeStage attribute.');
|
||||
}
|
||||
$package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name;
|
||||
|
||||
$conditionals = array_map(
|
||||
fn (\ReflectionAttribute $a) => $a->newInstance()->class,
|
||||
[...$method->getDeclaringClass()->getAttributes(ConditionalOn::class), ...$method->getAttributes(ConditionalOn::class)],
|
||||
@@ -529,6 +550,7 @@ class PackageLoader
|
||||
throw new RegistryException('Package name must not be empty when no package context is available for AfterStage attribute.');
|
||||
}
|
||||
$package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name;
|
||||
|
||||
$conditionals = array_map(
|
||||
fn (\ReflectionAttribute $a) => $a->newInstance()->class,
|
||||
[...$method->getDeclaringClass()->getAttributes(ConditionalOn::class), ...$method->getAttributes(ConditionalOn::class)],
|
||||
|
||||
@@ -89,14 +89,19 @@ class Registry
|
||||
self::$current_registry_name = $registry_name;
|
||||
|
||||
try {
|
||||
// Load composer autoload if specified (for external registries with their own dependencies)
|
||||
// resolve autoload manually — path-repo installs have no vendor/, FileSystem::fullpath would throw
|
||||
if (isset($data['autoload']) && is_string($data['autoload'])) {
|
||||
$autoload_path = FileSystem::fullpath($data['autoload'], dirname($registry_file));
|
||||
$base = dirname($registry_file);
|
||||
$autoload_path = FileSystem::isRelativePath($data['autoload'])
|
||||
? rtrim($base, '/') . DIRECTORY_SEPARATOR . $data['autoload']
|
||||
: $data['autoload'];
|
||||
if (file_exists($autoload_path)) {
|
||||
logger()->debug("Loading external autoload from: {$autoload_path}");
|
||||
require_once $autoload_path;
|
||||
} elseif (str_contains(rtrim(FileSystem::convertPath($base), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR)) {
|
||||
logger()->debug("Registry autoload not present, relying on consumer autoloader: {$autoload_path}");
|
||||
} else {
|
||||
logger()->warning("Autoload file not found: {$autoload_path}");
|
||||
throw new RegistryException("Path does not exist: {$autoload_path}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ use StaticPHP\Package\LibraryPackage;
|
||||
use StaticPHP\Package\PackageBuilder;
|
||||
use StaticPHP\Package\PackageInstaller;
|
||||
use StaticPHP\Runtime\Shell\UnixShell;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Util\InteractiveTerm;
|
||||
use ZM\Logger\ConsoleColor;
|
||||
|
||||
@@ -149,13 +150,17 @@ class UnixAutoconfExecutor extends Executor
|
||||
*/
|
||||
private function getDefaultConfigureArgs(): array
|
||||
{
|
||||
return [
|
||||
$args = [
|
||||
'--disable-shared',
|
||||
'--enable-static',
|
||||
"--prefix={$this->package->getBuildRootPath()}",
|
||||
'--with-pic',
|
||||
'--enable-pic',
|
||||
];
|
||||
if ($host_triple = SystemTarget::getAutoconfHostTriple()) {
|
||||
$args[] = "--host={$host_triple}";
|
||||
}
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -302,9 +302,12 @@ set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||
set(CMAKE_C_STANDARD_INCLUDE_DIRECTORIES "{$include}")
|
||||
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES "{$include}")
|
||||
CMAKE;
|
||||
// Whoops, linux may need CMAKE_AR sometimes
|
||||
// pin AR/RANLIB so cmake uses zig-ar/zig-ranlib instead of system /usr/bin/ranlib (zig archives need it)
|
||||
if (PHP_OS_FAMILY === 'Linux') {
|
||||
$toolchain .= "\nSET(CMAKE_AR \"ar\")";
|
||||
$ar = getenv('SPC_DEFAULT_AR') ?: getenv('AR') ?: 'ar';
|
||||
$ranlib = getenv('SPC_DEFAULT_RANLIB') ?: (getenv('RANLIB') ?: 'ranlib');
|
||||
$toolchain .= "\nSET(CMAKE_AR \"{$ar}\")";
|
||||
$toolchain .= "\nSET(CMAKE_RANLIB \"{$ranlib}\")";
|
||||
}
|
||||
FileSystem::writeFile(SOURCE_PATH . '/toolchain.cmake', $toolchain);
|
||||
return $created = realpath(SOURCE_PATH . '/toolchain.cmake');
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user