mirror of
https://github.com/crazywhalecc/static-php-cli.git
synced 2026-07-09 01:45:36 +08:00
Compare commits
40 Commits
4b19f4ec95
...
v3c/artifa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a1fd1f388 | ||
|
|
48d6e9ebc2 | ||
|
|
6cab47db67 | ||
|
|
ec3fd0f4b0 | ||
|
|
e72f9aa623 | ||
|
|
91cf4f83b5 | ||
|
|
c666cd6cd0 | ||
|
|
b8dd508148 | ||
|
|
582a88ef60 | ||
|
|
153003b75c | ||
|
|
899555a964 | ||
|
|
891a222c39 | ||
|
|
39beb68024 | ||
|
|
0807e9e253 | ||
|
|
1a779be028 | ||
|
|
bdfd3eb269 | ||
|
|
7ae5d742c2 | ||
|
|
95be291a84 | ||
|
|
d89add106a | ||
|
|
a36129c6cd | ||
|
|
3f3edd62a1 | ||
|
|
82b77af317 | ||
|
|
df26b93e58 | ||
|
|
d1b4c05381 | ||
|
|
e1658bc0e6 | ||
|
|
5053620b61 | ||
|
|
9366cbacd9 | ||
|
|
b8ce9f7787 | ||
|
|
6772403d81 | ||
|
|
60a91a82e1 | ||
|
|
4a274b69ac | ||
|
|
e4edd0a00f | ||
|
|
ae26ef3bdb | ||
|
|
049ecfe0a5 | ||
|
|
01a4d872ad | ||
|
|
a9e54bb725 | ||
|
|
ad9b9ec69f | ||
|
|
8a37303925 | ||
|
|
52d234f1f4 | ||
|
|
a3c39576df |
@@ -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,7 +100,6 @@ 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"
|
||||
@@ -126,8 +125,6 @@ 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
|
||||
@@ -143,10 +140,9 @@ 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
|
||||
@@ -167,7 +163,5 @@ 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ StaticPHP 支持将 FrankenPHP 连同所需扩展一起静态编译,
|
||||
|
||||
## 社区
|
||||
|
||||
加入我们的 [Discord 服务器](https://discord.gg/nrSRbpMJ),提问、分享构建成果,与其他 StaticPHP 用户交流。
|
||||
加入我们的 [Discord 服务器](https://discord.gg/xf6Rd4pEAk),提问、分享构建成果,与其他 StaticPHP 用户交流。
|
||||
|
||||
## 接下来
|
||||
|
||||
|
||||
@@ -15,6 +15,23 @@ use StaticPHP\Util\GlobalEnvManager;
|
||||
|
||||
class go_win
|
||||
{
|
||||
/** GOROOT for the Windows Go toolchain. */
|
||||
public static function path(): string
|
||||
{
|
||||
return PKG_ROOT_PATH . '/go-win';
|
||||
}
|
||||
|
||||
/** Path to a binary inside go-win's bin/ (go.exe, gofmt.exe, …). */
|
||||
public static function binary(string $name = 'go.exe'): string
|
||||
{
|
||||
return self::path() . '/bin/' . $name;
|
||||
}
|
||||
|
||||
public static function isInstalled(): bool
|
||||
{
|
||||
return is_file(self::binary());
|
||||
}
|
||||
|
||||
#[CustomBinary('go-win', [
|
||||
'windows-x86_64',
|
||||
])]
|
||||
|
||||
@@ -17,6 +17,23 @@ use StaticPHP\Util\System\LinuxUtil;
|
||||
|
||||
class go_xcaddy
|
||||
{
|
||||
/** GOROOT for the bundled Go toolchain used to build xcaddy. */
|
||||
public static function path(): string
|
||||
{
|
||||
return PKG_ROOT_PATH . '/go-xcaddy';
|
||||
}
|
||||
|
||||
/** Path to a binary inside go-xcaddy's bin/ (xcaddy, go, …). */
|
||||
public static function binary(string $name = 'xcaddy'): string
|
||||
{
|
||||
return self::path() . '/bin/' . $name;
|
||||
}
|
||||
|
||||
public static function isInstalled(): bool
|
||||
{
|
||||
return is_file(self::binary());
|
||||
}
|
||||
|
||||
#[CustomBinary('go-xcaddy', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
@@ -25,6 +42,7 @@ class go_xcaddy
|
||||
])]
|
||||
public function downBinary(ArtifactDownloader $downloader): DownloadResult
|
||||
{
|
||||
$pkgroot = PKG_ROOT_PATH;
|
||||
$name = SystemTarget::getCurrentPlatformString();
|
||||
$arch = match (explode('-', $name)[1]) {
|
||||
'x86_64' => 'amd64',
|
||||
@@ -63,7 +81,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: '{pkg_root_path}/go-xcaddy', verified: true, version: $version);
|
||||
return DownloadResult::archive(basename($path), ['url' => $url, 'version' => $version], extract: "{$pkgroot}/go-xcaddy", verified: true, version: $version);
|
||||
}
|
||||
|
||||
#[CustomBinaryCheckUpdate('go-xcaddy', [
|
||||
@@ -108,7 +126,7 @@ class go_xcaddy
|
||||
'GOROOT' => "{$target_path}",
|
||||
'GOBIN' => "{$target_path}/bin",
|
||||
'GOPATH' => "{$target_path}/go",
|
||||
])->exec('CGO_ENABLED=0 go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest');
|
||||
])->exec('CC=cc go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest');
|
||||
GlobalEnvManager::addPathIfNotExists("{$target_path}/bin");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,23 @@ use StaticPHP\Util\System\LinuxUtil;
|
||||
|
||||
class rust
|
||||
{
|
||||
/** Install prefix the rust tarball's install.sh writes into. */
|
||||
public static function path(): string
|
||||
{
|
||||
return PKG_ROOT_PATH . '/rust';
|
||||
}
|
||||
|
||||
/** Path to a binary inside the rust install dir (cargo, rustc, rustup, …). */
|
||||
public static function binary(string $name = 'cargo'): string
|
||||
{
|
||||
return self::path() . '/bin/' . $name;
|
||||
}
|
||||
|
||||
public static function isInstalled(): bool
|
||||
{
|
||||
return is_file(self::binary());
|
||||
}
|
||||
|
||||
#[CustomBinary('rust', [
|
||||
'linux-x86_64',
|
||||
'linux-aarch64',
|
||||
|
||||
@@ -12,10 +12,26 @@ use StaticPHP\Attribute\Artifact\CustomBinary;
|
||||
use StaticPHP\Attribute\Artifact\CustomBinaryCheckUpdate;
|
||||
use StaticPHP\Exception\DownloaderException;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
|
||||
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',
|
||||
@@ -62,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', [
|
||||
@@ -132,151 +148,5 @@ class zig
|
||||
chmod("{$target_path}/zig-ld.lld", 0755);
|
||||
chmod("{$target_path}/zig-ranlib", 0755);
|
||||
chmod("{$target_path}/zig-objcopy", 0755);
|
||||
|
||||
// Build the clang runtime bits zig 0.15+ doesn't ship: profile runtime
|
||||
// (so -fprofile-generate actually emits .profraw) and crtbegin/crtend
|
||||
// (so shared libs get __dso_handle and the __cxa_finalize atexit hook).
|
||||
// These get auto-linked by the zig-cc wrapper when the right flags fly past.
|
||||
$this->buildClangRuntimeBits($target_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the bundled clang version and build the missing clang runtime
|
||||
* archives into `<zig>/lib/`. Compiles from a 2 MB compiler-rt-<llvm>.src
|
||||
* tarball — far cheaper than fetching the 2 GB prebuilt LLVM tarball.
|
||||
*/
|
||||
private function buildClangRuntimeBits(string $zig_bin_dir): void
|
||||
{
|
||||
if (PHP_OS_FAMILY !== 'Linux') {
|
||||
return;
|
||||
}
|
||||
$libDir = "{$zig_bin_dir}/lib";
|
||||
$profileLib = "{$libDir}/libclang_rt.profile.a";
|
||||
$crtBegin = "{$libDir}/clang_rt.crtbegin.o";
|
||||
$crtEnd = "{$libDir}/clang_rt.crtend.o";
|
||||
if (file_exists($profileLib) && file_exists($crtBegin) && file_exists($crtEnd)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$zig = "{$zig_bin_dir}/zig";
|
||||
$verLine = trim((string) shell_exec(escapeshellarg($zig) . ' cc --version 2>/dev/null'));
|
||||
if (!preg_match('/clang version (\d+\.\d+\.\d+)/', $verLine, $m)) {
|
||||
logger()->warning('[zig] could not detect bundled clang version; skipping runtime bit build (PGO + shared libs without __dso_handle will fail to link)');
|
||||
return;
|
||||
}
|
||||
$llvmVersion = $m[1];
|
||||
logger()->info("Building clang runtime bits for LLVM {$llvmVersion} (zig's bundled clang)");
|
||||
|
||||
$srcRoot = $this->fetchCompilerRtSource($llvmVersion);
|
||||
if ($srcRoot === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
f_mkdir($libDir, recursive: true);
|
||||
if (!file_exists($profileLib)) {
|
||||
$this->buildProfileRuntime($zig, $srcRoot, $profileLib);
|
||||
}
|
||||
if (!file_exists($crtBegin) || !file_exists($crtEnd)) {
|
||||
$this->buildCrtObjects($zig, $srcRoot, $crtBegin, $crtEnd);
|
||||
}
|
||||
FileSystem::removeDir($srcRoot);
|
||||
}
|
||||
|
||||
private function fetchCompilerRtSource(string $llvmVersion): ?string
|
||||
{
|
||||
$tarball = "compiler-rt-{$llvmVersion}.src.tar.xz";
|
||||
$url = "https://github.com/llvm/llvm-project/releases/download/llvmorg-{$llvmVersion}/{$tarball}";
|
||||
$tarballPath = DOWNLOAD_PATH . '/' . $tarball;
|
||||
if (!file_exists($tarballPath)) {
|
||||
try {
|
||||
default_shell()->executeCurlDownload($url, $tarballPath);
|
||||
} catch (\Throwable $e) {
|
||||
logger()->warning("[zig] failed to download {$tarball}: {$e->getMessage()}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
$srcRoot = PKG_ROOT_PATH . "/compiler-rt-src-{$llvmVersion}";
|
||||
FileSystem::removeDir($srcRoot);
|
||||
FileSystem::createDir($srcRoot);
|
||||
try {
|
||||
default_shell()->executeTarExtract($tarballPath, $srcRoot, 'xz');
|
||||
} catch (\Throwable $e) {
|
||||
logger()->warning("[zig] failed to extract {$tarball}: {$e->getMessage()}");
|
||||
return null;
|
||||
}
|
||||
return $srcRoot;
|
||||
}
|
||||
|
||||
private function buildProfileRuntime(string $zig, string $srcRoot, string $libPath): void
|
||||
{
|
||||
$profileSrc = "{$srcRoot}/lib/profile";
|
||||
$profileInc = "{$srcRoot}/include";
|
||||
if (!is_dir($profileSrc)) {
|
||||
logger()->warning("[zig] profile src dir missing at {$profileSrc} — PGO will not work");
|
||||
return;
|
||||
}
|
||||
$sources = array_merge(
|
||||
glob("{$profileSrc}/*.c") ?: [],
|
||||
glob("{$profileSrc}/*.cpp") ?: []
|
||||
);
|
||||
// Keep Linux-only compilation units; the others bring in OS-specific headers
|
||||
// we can't satisfy without their respective SDKs.
|
||||
$skip = ['/PlatformAIX', '/PlatformDarwin', '/PlatformFuchsia', '/PlatformOther', '/PlatformWindows', '/WindowsMMap'];
|
||||
$sources = array_filter($sources, function ($f) use ($skip) {
|
||||
foreach ($skip as $s) {
|
||||
if (str_contains($f, $s)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
$objDir = "{$srcRoot}/obj-profile";
|
||||
f_mkdir($objDir, recursive: true);
|
||||
$cflags = '-c -O2 -fPIC -fvisibility=hidden ' .
|
||||
'-I' . escapeshellarg($profileInc) . ' ' .
|
||||
'-DCOMPILER_RT_HAS_ATOMICS=1 -DCOMPILER_RT_HAS_FCNTL_LCK=1 -DCOMPILER_RT_HAS_UNAME=1';
|
||||
$objs = [];
|
||||
foreach ($sources as $src) {
|
||||
$obj = $objDir . '/' . pathinfo($src, PATHINFO_FILENAME) . '.o';
|
||||
$cmd = escapeshellarg($zig) . ' cc ' . $cflags . ' -o ' . escapeshellarg($obj) . ' ' . escapeshellarg($src) . ' 2>&1';
|
||||
if (!$this->runZigCmd($cmd, $obj, "failed to compile {$src}")) {
|
||||
return;
|
||||
}
|
||||
$objs[] = $obj;
|
||||
}
|
||||
$arCmd = escapeshellarg($zig) . ' ar rcs ' . escapeshellarg($libPath) . ' ' . implode(' ', array_map('escapeshellarg', $objs)) . ' 2>&1';
|
||||
if (!$this->runZigCmd($arCmd, $libPath, 'zig ar failed')) {
|
||||
return;
|
||||
}
|
||||
logger()->info('[zig] libclang_rt.profile.a installed (' . filesize($libPath) . ' bytes)');
|
||||
}
|
||||
|
||||
private function buildCrtObjects(string $zig, string $srcRoot, string $crtBegin, string $crtEnd): void
|
||||
{
|
||||
$beginSrc = "{$srcRoot}/lib/builtins/crtbegin.c";
|
||||
$endSrc = "{$srcRoot}/lib/builtins/crtend.c";
|
||||
if (!is_file($beginSrc) || !is_file($endSrc)) {
|
||||
logger()->error("[zig] crtbegin/crtend source missing under {$srcRoot}/lib/builtins — shared libs will lack __dso_handle");
|
||||
return;
|
||||
}
|
||||
$cflags = '-c -O2 -fPIC -fvisibility=hidden -DCRT_HAS_INITFINI_ARRAY';
|
||||
foreach ([[$beginSrc, $crtBegin], [$endSrc, $crtEnd]] as [$src, $dst]) {
|
||||
$cmd = escapeshellarg($zig) . ' cc ' . $cflags . ' -o ' . escapeshellarg($dst) . ' ' . escapeshellarg($src) . ' 2>&1';
|
||||
if (!$this->runZigCmd($cmd, $dst, "failed to compile {$src}")) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
logger()->info('[zig] clang_rt.crtbegin.o + clang_rt.crtend.o installed (' . filesize($crtBegin) . ' + ' . filesize($crtEnd) . ' bytes)');
|
||||
}
|
||||
|
||||
private function runZigCmd(string $cmd, string $dst, string $errPrefix): bool
|
||||
{
|
||||
exec($cmd, $out, $rc);
|
||||
if ($rc !== 0 || !is_file($dst)) {
|
||||
logger()->warning("[zig] {$errPrefix}: " . implode("\n", $out));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,29 +4,14 @@ declare(strict_types=1);
|
||||
|
||||
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('clickhouse')]
|
||||
class clickhouse extends PhpExtensionPackage
|
||||
{
|
||||
#[BeforeStage('php', [php::class, 'buildconfForUnix'], 'ext-clickhouse')]
|
||||
#[PatchDescription('Replace THIS_DIR=`dirname $0` with PHP_EXT_SRCDIR() in config.m4 so include paths resolve to the ext source dir during PHP main configure (dirname $0 returns "." when run from php-src root).')]
|
||||
public function patchBeforeBuildconfUnix(): void
|
||||
{
|
||||
FileSystem::replaceFileRegex(
|
||||
"{$this->getSourceDir()}/config.m4",
|
||||
'/^(\s*)THIS_DIR=.*/m',
|
||||
'$1THIS_DIR=PHP_EXT_SRCDIR()',
|
||||
);
|
||||
}
|
||||
|
||||
#[CustomPhpConfigureArg('Darwin')]
|
||||
#[CustomPhpConfigureArg('Linux')]
|
||||
public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -27,7 +27,7 @@ class password_argon2 extends PhpExtensionPackage
|
||||
#[CustomPhpConfigureArg('Darwin')]
|
||||
public function getConfigureArg(PackageInstaller $installer, PackageBuilder $builder): string
|
||||
{
|
||||
if ($installer->getPhpExtensionPackage('openssl')?->isBuildStatic() || $this->isBuildShared()) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ use StaticPHP\Attribute\Package\Extension;
|
||||
use StaticPHP\Attribute\PatchDescription;
|
||||
use StaticPHP\Package\PackageInstaller;
|
||||
use StaticPHP\Package\PhpExtensionPackage;
|
||||
use StaticPHP\Util\GlobalEnvManager;
|
||||
use StaticPHP\Util\SourcePatcher;
|
||||
|
||||
#[Extension('xlswriter')]
|
||||
@@ -21,20 +20,14 @@ class xlswriter extends PhpExtensionPackage
|
||||
#[CustomPhpConfigureArg('Linux')]
|
||||
public function getUnixConfigureArg(bool $shared, PackageInstaller $installer): string
|
||||
{
|
||||
$arg = '--with-xlswriter --enable-reader';
|
||||
$shared = $shared ? '=shared' : '';
|
||||
$arg = "--with-xlswriter{$shared} --enable-reader";
|
||||
if ($installer->getLibraryPackage('openssl')) {
|
||||
$arg .= ' --with-openssl=' . $installer->getLibraryPackage('openssl')->getBuildRootPath();
|
||||
}
|
||||
return $arg;
|
||||
}
|
||||
|
||||
#[BeforeStage('php', [php::class, 'makeForUnix'], 'ext-xlswriter')]
|
||||
#[PatchDescription('Fix Unix build: add -std=gnu17 to CFLAGS to fix build errors on older GCC versions')]
|
||||
public function patchBeforeUnixMake(): void
|
||||
{
|
||||
GlobalEnvManager::putenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS=' . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS') . ' -std=gnu17');
|
||||
}
|
||||
|
||||
#[BeforeStage('php', [php::class, 'makeForWindows'], 'ext-xlswriter')]
|
||||
#[PatchDescription('Fix Windows build: apply win32 patch and add UTF-8 BOM to theme.c')]
|
||||
public function patchBeforeMakeForWindows(): void
|
||||
@@ -47,11 +40,4 @@ class xlswriter extends PhpExtensionPackage
|
||||
file_put_contents($this->getSourceDir() . '/library/libxlsxwriter/src/theme.c', $bom . $content);
|
||||
}
|
||||
}
|
||||
|
||||
public function getSharedExtensionEnv(): array
|
||||
{
|
||||
$parent = parent::getSharedExtensionEnv();
|
||||
$parent['CFLAGS'] .= ' -std=gnu17';
|
||||
return $parent;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,9 +17,7 @@ class bzip2
|
||||
#[PatchBeforeBuild]
|
||||
public function patchBeforeBuild(LibraryPackage $lib): void
|
||||
{
|
||||
// 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}");
|
||||
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', 'CFLAGS=-fPIC -Wall');
|
||||
}
|
||||
|
||||
#[BuildFor('Windows')]
|
||||
|
||||
@@ -18,11 +18,9 @@ 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 {$extra} fastlz.c -o fastlz.o")
|
||||
->exec("{$cc} -c -O3 -fPIC fastlz.c -o fastlz.o")
|
||||
->exec("{$ar} rcs libfastlz.a fastlz.o");
|
||||
|
||||
// Copy header file
|
||||
|
||||
@@ -24,12 +24,9 @@ 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 {$userCxxFlags}\"";
|
||||
$ldflags = $toolchain->isStatic() ? "LDFLAGS=\"-static {$userLdFlags}\"" : "LDFLAGS=\"{$userLdFlags}\"";
|
||||
$cxxflags = 'CXXFLAGS="-std=c++17 -DPIC -fPIC -fno-ident"';
|
||||
$ldflags = $toolchain->isStatic() ? 'LDFLAGS="-static"' : '';
|
||||
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,9 +17,7 @@ class jbig
|
||||
#[PatchBeforeBuild]
|
||||
public function patchBeforeBuild(LibraryPackage $lib): void
|
||||
{
|
||||
$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}");
|
||||
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS = -O2 -W -Wno-unused-result', 'CFLAGS = -O2 -W -Wno-unused-result -fPIC');
|
||||
}
|
||||
|
||||
#[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);
|
||||
$config = $spc->getPackageDepsConfig($lib->getName(), $resolved, include_suggests: true);
|
||||
$extraEnv = [
|
||||
'CFLAGS' => '-fcommon',
|
||||
'LIBS' => $config['libs'],
|
||||
|
||||
@@ -17,17 +17,10 @@ use StaticPHP\Util\FileSystem;
|
||||
class liblz4
|
||||
{
|
||||
#[PatchBeforeBuild]
|
||||
#[PatchDescription('Compile lib sources individually so -flto -c with multiple inputs works under zig-cc/clang')]
|
||||
#[PatchDescription('Fix Makefile install target for static liblz4')]
|
||||
public function patchBeforeBuild(LibraryPackage $lib): void
|
||||
{
|
||||
// `-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"
|
||||
);
|
||||
FileSystem::replaceFileStr($lib->getSourceDir() . '/programs/Makefile', 'install: lz4', "install: lz4\n\ninstallewfwef: lz4");
|
||||
}
|
||||
|
||||
#[BuildFor('Windows')]
|
||||
|
||||
@@ -6,8 +6,6 @@ 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;
|
||||
@@ -18,24 +16,6 @@ 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
|
||||
|
||||
@@ -111,12 +111,6 @@ 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 " .
|
||||
@@ -127,8 +121,7 @@ class openssl
|
||||
'enable-pie ' .
|
||||
'no-legacy ' .
|
||||
'no-tests ' .
|
||||
"linux-{$arch} " .
|
||||
$userExtra
|
||||
"linux-{$arch}"
|
||||
)
|
||||
->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()));
|
||||
$config = $spc_config->getPackageDepsConfig('postgresql', array_keys($installer->getResolvedPackages()), include_suggests: $builder->getOption('with-suggests', false));
|
||||
|
||||
$env_vars = [
|
||||
'CFLAGS' => $config['cflags'] . ' -std=c17',
|
||||
|
||||
@@ -20,11 +20,6 @@ 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,20 +27,7 @@ class unixodbc extends LibraryPackage
|
||||
'Linux' => '/etc',
|
||||
default => throw new WrongUsageException("Unsupported OS: {$os}"),
|
||||
};
|
||||
|
||||
// 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,
|
||||
])
|
||||
UnixAutoconfExecutor::create($this)
|
||||
->configure(
|
||||
'--disable-debug',
|
||||
'--disable-dependency-tracking',
|
||||
@@ -48,15 +35,8 @@ class unixodbc extends LibraryPackage
|
||||
'--with-included-ltdl',
|
||||
"--sysconfdir={$sysconf_selector}",
|
||||
'--enable-gui=no',
|
||||
);
|
||||
|
||||
// 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();
|
||||
)
|
||||
->make();
|
||||
$this->patchPkgconfPrefix(['odbc.pc', 'odbccr.pc', 'odbcinst.pc']);
|
||||
$this->patchLaDependencyPrefix();
|
||||
}
|
||||
|
||||
@@ -93,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,7 +5,6 @@ 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;
|
||||
@@ -49,7 +48,6 @@ 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'];
|
||||
|
||||
@@ -88,13 +88,10 @@ 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' => 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-.*',
|
||||
'CGO_LDFLAGS' => "{$package->getLibExtraLdFlags()} {$staticFlags} {$config['ldflags']} {$libs}",
|
||||
'XCADDY_GO_BUILD_FLAGS' => '-buildmode=pie ' .
|
||||
'-ldflags \"-linkmode=external ' . $extLdFlags . ' ' .
|
||||
'-X \'github.com/caddyserver/caddy/v2/modules/caddyhttp.ServerHeader=FrankenPHP Caddy\' ' .
|
||||
@@ -107,7 +104,6 @@ trait frankenphp
|
||||
InteractiveTerm::setMessage('Building frankenphp: ' . ConsoleColor::yellow('building with xcaddy'));
|
||||
shell()->cd(BUILD_LIB_PATH)
|
||||
->setEnv($env)
|
||||
->exec('go clean -cache') // fix stale include evaluation
|
||||
->exec("xcaddy build --output frankenphp {$xcaddy_modules}");
|
||||
|
||||
$builder->deployBinary(BUILD_LIB_PATH . '/frankenphp', BUILD_BIN_PATH . '/frankenphp');
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
<?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,7 +20,6 @@ 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;
|
||||
@@ -60,7 +59,7 @@ trait unix
|
||||
}
|
||||
|
||||
if (self::getPHPVersionID() >= 80300 && self::getPHPVersionID() < 80400) {
|
||||
SourcePatcher::patchFile('spc_fix_avx512_cache_before_80400.patch', SOURCE_PATH . '/php-src');
|
||||
SourcePatcher::patchFile('spc_fix_avx512_cache_before_80400.patch', $this->getSourceDir());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,10 +92,12 @@ trait unix
|
||||
$args = [];
|
||||
$version_id = self::getPHPVersionID();
|
||||
|
||||
// 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'));
|
||||
// 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')) {
|
||||
$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) {
|
||||
@@ -140,7 +141,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()}",
|
||||
'LDFLAGS' => "-L{$package->getLibDir()} " . getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS'),
|
||||
'LIBS' => $vars['EXTRA_LIBS'] ?? '',
|
||||
])->exec("{$cmd} {$args} {$static_extension_str}"), $package->getSourceDir());
|
||||
}
|
||||
@@ -167,7 +168,7 @@ trait unix
|
||||
|
||||
#[BeforeStage('php', [self::class, 'makeForUnix'], 'php')]
|
||||
#[PatchDescription('Patch Makefile to fix //lib path for Linux builds')]
|
||||
#[PatchDescription('Under CI: patch BUILD_CC to system cc — zig-cc-built minilua segfaults there for reasons we cannot reproduce locally')]
|
||||
#[PatchDescription('Patch BUILD_CC to use system cc instead of zig-cc (prevents minilua crash)')]
|
||||
public function tryPatchMakefileUnix(TargetPackage $package, ToolchainInterface $toolchain): void
|
||||
{
|
||||
if (SystemTarget::getTargetOS() !== 'Linux') {
|
||||
@@ -177,8 +178,7 @@ trait unix
|
||||
// replace //lib with /lib in 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')) {
|
||||
if ($toolchain instanceof ZigToolchain) {
|
||||
$makefile = "{$package->getSourceDir()}/Makefile";
|
||||
FileSystem::replaceFileRegex($makefile, '/^BUILD_CC\s*=\s*zig-cc\s*$/m', 'BUILD_CC = cc');
|
||||
}
|
||||
@@ -229,7 +229,6 @@ 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);
|
||||
@@ -240,13 +239,11 @@ 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);
|
||||
@@ -257,13 +254,11 @@ 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);
|
||||
@@ -274,58 +269,43 @@ 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
|
||||
{
|
||||
$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");
|
||||
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');
|
||||
}
|
||||
$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();
|
||||
$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);
|
||||
}
|
||||
|
||||
#[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(),
|
||||
@@ -339,43 +319,22 @@ 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($vars)
|
||||
->setEnv($this->makeVars($installer))
|
||||
->exec("{$sed_prefix} \"s|^EXTENSION_DIR = .*|EXTENSION_DIR = /" . basename(BUILD_MODULES_PATH) . '|" Makefile')
|
||||
->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);
|
||||
}
|
||||
}
|
||||
}
|
||||
->exec("make -j{$builder->concurrency} INSTALL_ROOT={$root} install-sapi {$install_modules} install-build install-headers install-programs");
|
||||
|
||||
// ------------- SPC_CMD_VAR_PHP_EMBED_TYPE=shared -------------
|
||||
|
||||
// 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.)
|
||||
// process libphp.so for shared embed
|
||||
$suffix = SystemTarget::getTargetOS() === 'Darwin' ? 'dylib' : 'so';
|
||||
$libphp_so = "{$package->getLibDir()}/libphp.{$suffix}";
|
||||
if (file_exists($libphp_so)) {
|
||||
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;
|
||||
// rename libphp.so if -release is set
|
||||
if (SystemTarget::getTargetOS() === 'Linux') {
|
||||
$this->processLibphpSoFile($libphp_so, $installer);
|
||||
}
|
||||
// deploy
|
||||
$builder->deployBinary($libphp_so, $libphp_so, false);
|
||||
$package->setOutput('Library path for embed SAPI', $libphp_so);
|
||||
}
|
||||
@@ -384,9 +343,6 @@ 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);
|
||||
}
|
||||
@@ -394,11 +350,6 @@ 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 (only when present)
|
||||
@@ -408,6 +359,9 @@ trait unix
|
||||
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]
|
||||
@@ -440,15 +394,8 @@ trait unix
|
||||
try {
|
||||
logger()->debug('Building shared extensions...');
|
||||
foreach ($shared_extensions as $extension) {
|
||||
$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);
|
||||
InteractiveTerm::setMessage('Building shared PHP extension: ' . ConsoleColor::yellow($extension->getName()));
|
||||
$extension->buildShared();
|
||||
}
|
||||
} finally {
|
||||
// restore php-config
|
||||
@@ -733,6 +680,77 @@ 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.
|
||||
@@ -742,28 +760,16 @@ trait unix
|
||||
$config = new SPCConfigUtil(['libs_only_deps' => true])->config($installer->getAvailableResolvedPackageNames());
|
||||
$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' => $extra_ldflags,
|
||||
'EXTRA_LDFLAGS_PROGRAM' => $extra_ldflags_program,
|
||||
'EXTRA_LDFLAGS_PROGRAM' => deduplicate_flags(getenv('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS') . " {$config['ldflags']} {$static} {$pie}"),
|
||||
'EXTRA_LDFLAGS' => $config['ldflags'],
|
||||
'EXTRA_LIBS' => $libs,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -285,19 +285,15 @@ class Artifact
|
||||
* Get source extraction directory.
|
||||
*
|
||||
* Rules:
|
||||
* 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)
|
||||
* 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)
|
||||
*/
|
||||
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);
|
||||
@@ -331,7 +327,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();
|
||||
}
|
||||
|
||||
@@ -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']}"),
|
||||
};
|
||||
|
||||
@@ -731,16 +731,6 @@ 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')];
|
||||
|
||||
|
||||
@@ -136,12 +136,6 @@ 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();
|
||||
|
||||
@@ -177,12 +171,8 @@ class ArtifactExtractor
|
||||
return SPC_STATUS_ALREADY_EXTRACTED;
|
||||
}
|
||||
|
||||
// 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)) {
|
||||
// Remove old directory if hash mismatch
|
||||
if (is_dir($target_path)) {
|
||||
logger()->notice("Source [{$name}] hash mismatch, re-extracting...");
|
||||
FileSystem::removeDir($target_path);
|
||||
}
|
||||
|
||||
@@ -16,8 +16,9 @@ trait GitHubTokenSetupTrait
|
||||
// GITHUB_TOKEN support
|
||||
if (($token = getenv('GITHUB_TOKEN')) !== false && ($user = getenv('GITHUB_USER')) !== false) {
|
||||
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");
|
||||
|
||||
@@ -9,10 +9,7 @@ use StaticPHP\Doctor\Doctor;
|
||||
use StaticPHP\Exception\ValidationException;
|
||||
use StaticPHP\Package\PackageBuilder;
|
||||
use StaticPHP\Package\PackageInstaller;
|
||||
use StaticPHP\Registry\PackageLoader;
|
||||
use StaticPHP\Util\DependencyResolver;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
use StaticPHP\Util\Pgo\PgoContext;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Yaml\Exception\ParseException;
|
||||
@@ -24,8 +21,6 @@ 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
|
||||
@@ -44,9 +39,6 @@ class CraftCommand extends BaseCommand
|
||||
// apply env
|
||||
array_walk($craft['extra-env'], fn ($v, $k) => f_putenv("{$k}={$v}"));
|
||||
|
||||
// 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);
|
||||
@@ -91,67 +83,23 @@ 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']));
|
||||
|
||||
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->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{$tag} ({$usedtime} s)</info>");
|
||||
$this->output->writeln("<info>✔ BUILD SUCCESSFUL ({$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.
|
||||
*
|
||||
|
||||
@@ -98,25 +98,6 @@ 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.
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ class ZigCheck
|
||||
public function checkZig(): CheckResult
|
||||
{
|
||||
if (new PackageInstaller()->addInstallPackage('zig')->isPackageInstalled('zig')) {
|
||||
return CheckResult::ok(PKG_ROOT_PATH . '/zig/zig');
|
||||
return CheckResult::ok();
|
||||
}
|
||||
return CheckResult::fail('zig is not installed', 'install-zig');
|
||||
}
|
||||
|
||||
@@ -154,8 +154,6 @@ class PackageInstaller
|
||||
$this->resolvePackages();
|
||||
}
|
||||
|
||||
$this->reconcilePhpSrcVersion();
|
||||
|
||||
if ($this->interactive && !$disable_delay_msg) {
|
||||
// show install or build options in terminal with beautiful output
|
||||
$this->printInstallerInfo();
|
||||
@@ -217,7 +215,7 @@ class PackageInstaller
|
||||
if (!$is_to_build && $should_use_binary) {
|
||||
// install binary
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::indicateProgress('Installing ' . $this->kindLabel($package) . ': ' . ConsoleColor::yellow($package->getName()));
|
||||
InteractiveTerm::indicateProgress('Installing package: ' . ConsoleColor::yellow($package->getName()));
|
||||
}
|
||||
try {
|
||||
// Start tracking for binary installation
|
||||
@@ -229,17 +227,17 @@ class PackageInstaller
|
||||
// Stop tracking on error
|
||||
$this->tracker?->stopTracking();
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Installing ' . $this->kindLabel($package) . ' failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
InteractiveTerm::finish('Installing binary package failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
echo PHP_EOL;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Installed ' . $this->kindLabel($package) . ': ' . ConsoleColor::green($package->getName()) . ($status === SPC_STATUS_ALREADY_INSTALLED ? ' (already installed, skipped)' : ''));
|
||||
InteractiveTerm::finish('Installed binary 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 ' . $this->kindLabel($package) . ': ' . ConsoleColor::yellow($package->getName()));
|
||||
InteractiveTerm::indicateProgress('Building package: ' . ConsoleColor::yellow($package->getName()));
|
||||
}
|
||||
try {
|
||||
// Start tracking for build
|
||||
@@ -262,13 +260,13 @@ class PackageInstaller
|
||||
// Stop tracking on error
|
||||
$this->tracker?->stopTracking();
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Building ' . $this->kindLabel($package) . ' failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
InteractiveTerm::finish('Building package failed: ' . ConsoleColor::red($package->getName()), false);
|
||||
echo PHP_EOL;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
if ($this->interactive) {
|
||||
InteractiveTerm::finish('Built ' . $this->kindLabel($package) . ': ' . ConsoleColor::green($package->getName()) . ($status === SPC_STATUS_ALREADY_BUILT ? ' (already built, skipped)' : ''));
|
||||
InteractiveTerm::finish('Built package: ' . ConsoleColor::green($package->getName()) . ($status === SPC_STATUS_ALREADY_BUILT ? ' (already built, skipped)' : ''));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -573,77 +571,6 @@ 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
|
||||
*/
|
||||
@@ -761,7 +688,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[$frankenphp->getName()] = $frankenphp;
|
||||
$this->build_packages[$package->getName()] = $package;
|
||||
$added = true;
|
||||
}
|
||||
$this->build_packages[$package->getName()] = $package;
|
||||
|
||||
@@ -12,7 +12,6 @@ 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;
|
||||
|
||||
@@ -279,15 +278,10 @@ 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' => $ldflags,
|
||||
'LDFLAGS' => $config['ldflags'],
|
||||
'LIBS' => clean_spaces("{$preStatic} {$staticLibs} {$postStatic} {$sharedLibs}"),
|
||||
'LD_LIBRARY_PATH' => BUILD_LIB_PATH,
|
||||
];
|
||||
@@ -309,7 +303,6 @@ 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(
|
||||
@@ -325,53 +318,11 @@ 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} {$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
|
||||
);
|
||||
->exec("make -j{$builder->concurrency}")
|
||||
->exec('make install');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -382,31 +333,14 @@ 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]);
|
||||
|
||||
// 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';
|
||||
// process *.so file
|
||||
$soFile = BUILD_MODULES_PATH . '/' . $this->getExtensionName() . '.so';
|
||||
if (!file_exists($soFile)) {
|
||||
throw new ValidationException("Extension {$this->getExtensionName()} build failed: {$soFile} not found", validation_module: "Extension {$this->getExtensionName()} build");
|
||||
}
|
||||
|
||||
@@ -367,18 +367,15 @@ class PackageLoader
|
||||
|
||||
public static function getBeforeStageCallbacks(string $package_name, string $stage): iterable
|
||||
{
|
||||
// match condition; '*' is a wildcard that fires for every package's stage
|
||||
// match condition
|
||||
$installer = ApplicationContext::get(PackageInstaller::class);
|
||||
$stages = array_merge(
|
||||
self::$before_stages[$package_name][$stage] ?? [],
|
||||
$package_name === '*' ? [] : (self::$before_stages['*'][$stage] ?? []),
|
||||
);
|
||||
$stages = self::$before_stages[$package_name][$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::tryGet($class) === null) {
|
||||
if (!ApplicationContext::has($class)) {
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
@@ -388,19 +385,16 @@ class PackageLoader
|
||||
|
||||
public static function getAfterStageCallbacks(string $package_name, string $stage): array
|
||||
{
|
||||
// match condition; '*' is a wildcard that fires for every package's stage
|
||||
// match condition
|
||||
$installer = ApplicationContext::get(PackageInstaller::class);
|
||||
$stages = array_merge(
|
||||
self::$after_stages[$package_name][$stage] ?? [],
|
||||
$package_name === '*' ? [] : (self::$after_stages['*'][$stage] ?? []),
|
||||
);
|
||||
$stages = self::$after_stages[$package_name][$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::tryGet($class) === null) {
|
||||
if (!ApplicationContext::has($class)) {
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
@@ -431,20 +425,6 @@ 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(
|
||||
|
||||
@@ -89,19 +89,14 @@ class Registry
|
||||
self::$current_registry_name = $registry_name;
|
||||
|
||||
try {
|
||||
// resolve autoload manually — path-repo installs have no vendor/, FileSystem::fullpath would throw
|
||||
// Load composer autoload if specified (for external registries with their own dependencies)
|
||||
if (isset($data['autoload']) && is_string($data['autoload'])) {
|
||||
$base = dirname($registry_file);
|
||||
$autoload_path = FileSystem::isRelativePath($data['autoload'])
|
||||
? rtrim($base, '/') . DIRECTORY_SEPARATOR . $data['autoload']
|
||||
: $data['autoload'];
|
||||
$autoload_path = FileSystem::fullpath($data['autoload'], dirname($registry_file));
|
||||
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 {
|
||||
throw new RegistryException("Path does not exist: {$autoload_path}");
|
||||
logger()->warning("Autoload file not found: {$autoload_path}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -302,12 +302,9 @@ set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||
set(CMAKE_C_STANDARD_INCLUDE_DIRECTORIES "{$include}")
|
||||
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES "{$include}")
|
||||
CMAKE;
|
||||
// pin AR/RANLIB so cmake uses zig-ar/zig-ranlib instead of system /usr/bin/ranlib (zig archives need it)
|
||||
// Whoops, linux may need CMAKE_AR sometimes
|
||||
if (PHP_OS_FAMILY === 'Linux') {
|
||||
$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}\")";
|
||||
$toolchain .= "\nSET(CMAKE_AR \"ar\")";
|
||||
}
|
||||
FileSystem::writeFile(SOURCE_PATH . '/toolchain.cmake', $toolchain);
|
||||
return $created = realpath(SOURCE_PATH . '/toolchain.cmake');
|
||||
|
||||
@@ -15,7 +15,6 @@ class ClangBrewToolchain extends ClangNativeToolchain
|
||||
GlobalEnvManager::putenv("SPC_DEFAULT_CC={$homebrew_prefix}/opt/llvm/bin/clang");
|
||||
GlobalEnvManager::putenv("SPC_DEFAULT_CXX={$homebrew_prefix}/opt/llvm/bin/clang++");
|
||||
GlobalEnvManager::putenv("SPC_DEFAULT_AR={$homebrew_prefix}/opt/llvm/bin/llvm-ar");
|
||||
GlobalEnvManager::putenv("SPC_DEFAULT_RANLIB={$homebrew_prefix}/opt/llvm/bin/llvm-ranlib");
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_LD=ld');
|
||||
GlobalEnvManager::addPathIfNotExists("{$homebrew_prefix}/opt/llvm/bin");
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ class ClangNativeToolchain implements UnixToolchainInterface
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_CC=clang');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_CXX=clang++');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_AR=ar');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_RANLIB=ranlib');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_LD=ld');
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ class GccNativeToolchain implements UnixToolchainInterface
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_CC=gcc');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_CXX=g++');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_AR=ar');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_RANLIB=ranlib');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_LD=ld');
|
||||
}
|
||||
|
||||
|
||||
@@ -16,8 +16,28 @@ class ZigToolchain implements UnixToolchainInterface
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_CC=zig-cc');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_CXX=zig-c++');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_AR=zig-ar');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_RANLIB=zig-ranlib');
|
||||
GlobalEnvManager::putenv('SPC_DEFAULT_LD=zig-ld.lld');
|
||||
|
||||
// Generate additional objects needed for zig toolchain
|
||||
$paths = ['/usr/lib/gcc', '/usr/local/lib/gcc'];
|
||||
$objects = ['crtbeginS.o', 'crtendS.o'];
|
||||
$found = [];
|
||||
|
||||
foreach ($objects as $obj) {
|
||||
$located = null;
|
||||
foreach ($paths as $base) {
|
||||
$output = shell_exec("find {$base} -name {$obj} 2>/dev/null | grep -v '/32/' | head -n 1");
|
||||
$line = trim((string) $output);
|
||||
if ($line !== '') {
|
||||
$located = $line;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($located) {
|
||||
$found[] = $located;
|
||||
}
|
||||
}
|
||||
GlobalEnvManager::putenv('SPC_EXTRA_RUNTIME_OBJECTS=' . implode(' ', $found));
|
||||
}
|
||||
|
||||
public function afterInit(): void
|
||||
|
||||
@@ -244,6 +244,7 @@ class FileSystem
|
||||
*/
|
||||
public static function getClassesPsr4(string $dir, string $base_namespace, mixed $rule = null, bool|string $return_path_value = false, bool $auto_require = false): array
|
||||
{
|
||||
$base_namespace = rtrim($base_namespace, '\\');
|
||||
$classes = [];
|
||||
$files = FileSystem::scanDirFiles($dir, true, true);
|
||||
if ($files === false) {
|
||||
|
||||
@@ -5,7 +5,6 @@ declare(strict_types=1);
|
||||
namespace StaticPHP\Util;
|
||||
|
||||
use StaticPHP\DI\ApplicationContext;
|
||||
use Symfony\Component\Console\Helper\Helper;
|
||||
use Symfony\Component\Console\Helper\ProgressIndicator;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\ConsoleOutput;
|
||||
@@ -28,19 +27,14 @@ class InteractiveTerm
|
||||
}
|
||||
}
|
||||
|
||||
public static function success(string $message, bool $indent = false, ?float $start_time = null): void
|
||||
public static function success(string $message, bool $indent = false): void
|
||||
{
|
||||
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
|
||||
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
|
||||
if ($start_time !== null) {
|
||||
$message .= ' (' . Helper::formatTime(microtime(true) - $start_time) . ')';
|
||||
}
|
||||
if ($output->isVerbose()) {
|
||||
logger()->info(strip_ansi_colors($message));
|
||||
} else {
|
||||
// wipe the current indicator line so our persistent ✔ line doesn't get appended to a spinner
|
||||
$clear = (self::$indicator !== null && $output->isDecorated() && !$no_ansi) ? "\x0D\x1B[2K" : '';
|
||||
$output->writeln($clear . ($no_ansi ? 'strip_ansi_colors' : 'strval')(ConsoleColor::green(($indent ? ' ' : '') . '✔ ') . $message));
|
||||
$output->writeln(($no_ansi ? 'strip_ansi_colors' : 'strval')(ConsoleColor::green(($indent ? ' ' : '') . '✔ ') . $message));
|
||||
logger()->debug(strip_ansi_colors($message));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,267 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace StaticPHP\Util\Pgo;
|
||||
|
||||
use StaticPHP\Command\BaseCommand;
|
||||
use StaticPHP\DI\ApplicationContext;
|
||||
use StaticPHP\Exception\WrongUsageException;
|
||||
use StaticPHP\Util\FileSystem;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
|
||||
final class PgoContext
|
||||
{
|
||||
public const string MODE_INSTRUMENT = 'instrument';
|
||||
|
||||
public const string MODE_CS_INSTRUMENT = 'cs-instrument';
|
||||
|
||||
public const string MODE_USE = 'use';
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const array TRAINABLE = [
|
||||
'cli' => 'build-cli',
|
||||
'micro' => 'build-micro',
|
||||
'cgi' => 'build-cgi',
|
||||
'fpm' => 'build-fpm',
|
||||
'embed' => 'build-embed',
|
||||
'frankenphp' => 'build-frankenphp',
|
||||
];
|
||||
|
||||
public const array SHUTDOWN_PATCHES = [
|
||||
'php-src' => 'spc_pgo_flush_php_main.patch',
|
||||
'frankenphp' => 'spc_pgo_flush_frankenphp.patch',
|
||||
];
|
||||
|
||||
/** @var list<string> */
|
||||
private array $trainableSapis = [];
|
||||
|
||||
public function __construct(
|
||||
public readonly string $mode,
|
||||
public readonly string $profileRoot,
|
||||
) {
|
||||
if (!in_array($mode, [self::MODE_INSTRUMENT, self::MODE_CS_INSTRUMENT, self::MODE_USE], true)) {
|
||||
throw new WrongUsageException("PgoContext: unknown mode '{$mode}'");
|
||||
}
|
||||
}
|
||||
|
||||
public static function registerOptions(BaseCommand $cmd): void
|
||||
{
|
||||
$cmd->addOption('pgi', null, null, 'PGO instrument pass: build with -fprofile-generate so the resulting binary writes .profraw on shutdown.');
|
||||
$cmd->addOption('cs-pgi', null, null, 'PGO context-sensitive instrument pass: -fprofile-use=<existing.profdata> + -fcs-profile-generate. Requires a prior --pgi/--pgo cycle.');
|
||||
$cmd->addOption('pgo', null, null, 'PGO use pass: merge the collected .profraw into .profdata, then rebuild with -fprofile-use.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string> $sapis
|
||||
* @param array<string, mixed> $build_options
|
||||
*/
|
||||
public static function tryFromInput(InputInterface $input, array $sapis, array &$build_options): ?self
|
||||
{
|
||||
$modes = array_filter(['pgi', 'cs-pgi', 'pgo'], fn ($m) => (bool) $input->getOption($m));
|
||||
if (count($modes) > 1) {
|
||||
throw new WrongUsageException('--pgi, --cs-pgi, and --pgo are mutually exclusive');
|
||||
}
|
||||
$picked = array_values($modes)[0] ?? null;
|
||||
if ($picked === null) {
|
||||
return null;
|
||||
}
|
||||
$mode = match ($picked) {
|
||||
'pgi' => self::MODE_INSTRUMENT,
|
||||
'cs-pgi' => self::MODE_CS_INSTRUMENT,
|
||||
'pgo' => self::MODE_USE,
|
||||
};
|
||||
$ctx = new self($mode, BUILD_ROOT_PATH . '/pgo-data');
|
||||
$ctx->setTrainableSapis($sapis);
|
||||
|
||||
match ($mode) {
|
||||
self::MODE_INSTRUMENT => $ctx->setupInstrument(),
|
||||
self::MODE_CS_INSTRUMENT => $ctx->setupCsInstrument(),
|
||||
self::MODE_USE => $ctx->mergeProfiles(),
|
||||
};
|
||||
|
||||
if ($ctx->isInstrument() || $ctx->isCsInstrument()) {
|
||||
$build_options['no-strip'] = true;
|
||||
}
|
||||
ApplicationContext::set(self::class, $ctx);
|
||||
return $ctx;
|
||||
}
|
||||
|
||||
public function isInstrument(): bool
|
||||
{
|
||||
return $this->mode === self::MODE_INSTRUMENT;
|
||||
}
|
||||
|
||||
public function isCsInstrument(): bool
|
||||
{
|
||||
return $this->mode === self::MODE_CS_INSTRUMENT;
|
||||
}
|
||||
|
||||
public function isUse(): bool
|
||||
{
|
||||
return $this->mode === self::MODE_USE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $sapis
|
||||
*/
|
||||
public function setTrainableSapis(array $sapis): void
|
||||
{
|
||||
$resolved = [];
|
||||
foreach ($sapis as $sapi) {
|
||||
$r = $this->resolveSapi($sapi);
|
||||
if (!in_array($r, $resolved, true)) {
|
||||
$resolved[] = $r;
|
||||
}
|
||||
}
|
||||
if ($resolved === []) {
|
||||
throw new WrongUsageException(
|
||||
'PGO: no trainable SAPI selected; supply one of ' . implode(', ', array_keys(self::TRAINABLE))
|
||||
);
|
||||
}
|
||||
$this->trainableSapis = $resolved;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function trainableSapis(): array
|
||||
{
|
||||
return $this->trainableSapis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static-embed mode links libphp.a into frankenphp, sharing a single binary
|
||||
* and profdata. Shared-embed keeps them separate.
|
||||
*/
|
||||
public function resolveSapi(string $sapi): string
|
||||
{
|
||||
if ($sapi === 'embed' && getenv('SPC_CMD_VAR_PHP_EMBED_TYPE') === 'static') {
|
||||
return 'frankenphp';
|
||||
}
|
||||
return $sapi;
|
||||
}
|
||||
|
||||
public function rawDir(string $sapi): string
|
||||
{
|
||||
return $this->profileRoot . '/' . $sapi;
|
||||
}
|
||||
|
||||
public function csRawDir(string $sapi): string
|
||||
{
|
||||
return $this->profileRoot . '/cs-' . $sapi;
|
||||
}
|
||||
|
||||
public function profDataFile(string $sapi): string
|
||||
{
|
||||
return $this->profileRoot . '/' . $sapi . '.profdata';
|
||||
}
|
||||
|
||||
public function cflagsFor(string $sapi): string
|
||||
{
|
||||
$sapi = $this->resolveSapi($sapi);
|
||||
if ($this->mode === self::MODE_USE && !is_file($this->profDataFile($sapi))) {
|
||||
return '';
|
||||
}
|
||||
return match ($this->mode) {
|
||||
self::MODE_INSTRUMENT => '-fprofile-generate=' . $this->rawDir($sapi)
|
||||
. ' -fprofile-update=atomic',
|
||||
self::MODE_CS_INSTRUMENT => '-fprofile-use=' . $this->profDataFile($sapi)
|
||||
. ' -fcs-profile-generate=' . $this->csRawDir($sapi)
|
||||
. ' -fprofile-update=atomic'
|
||||
. ' -Wno-error=profile-instr-unprofiled'
|
||||
. ' -Wno-error=profile-instr-out-of-date'
|
||||
. ' -Wno-backend-plugin',
|
||||
self::MODE_USE => '-fprofile-use=' . $this->profDataFile($sapi)
|
||||
. ' -Wno-error=profile-instr-unprofiled'
|
||||
. ' -Wno-error=profile-instr-out-of-date'
|
||||
. ' -Wno-backend-plugin',
|
||||
default => throw new WrongUsageException("PgoContext: unreachable mode '{$this->mode}'"),
|
||||
};
|
||||
}
|
||||
|
||||
public function ldflagsFor(string $sapi): string
|
||||
{
|
||||
$resolved = $this->resolveSapi($sapi);
|
||||
$flags = $this->cflagsFor($sapi);
|
||||
$patterns = ['/\s*-Wno-error=\S+/', '/\s*-Wno-backend-plugin/'];
|
||||
if ($resolved === 'frankenphp') {
|
||||
$patterns[] = '/\s*-fprofile-use=\S+/';
|
||||
$patterns[] = '/\s*-fcs-profile-generate=\S+/';
|
||||
}
|
||||
return trim((string) preg_replace($patterns, '', $flags));
|
||||
}
|
||||
|
||||
public function applyEnvFor(string $sapi): void
|
||||
{
|
||||
self::overwritePgoFlags('SPC_CMD_VAR_PHP_MAKE_EXTRA_CFLAGS', $this->cflagsFor($sapi));
|
||||
self::overwritePgoFlags('SPC_CMD_VAR_PHP_MAKE_EXTRA_LDFLAGS_PROGRAM', $this->ldflagsFor($sapi));
|
||||
}
|
||||
|
||||
public function setupInstrument(): void
|
||||
{
|
||||
FileSystem::removeDir($this->profileRoot);
|
||||
FileSystem::createDir($this->profileRoot);
|
||||
foreach ($this->trainableSapis as $sapi) {
|
||||
FileSystem::createDir($this->rawDir($sapi));
|
||||
}
|
||||
}
|
||||
|
||||
public function setupCsInstrument(): void
|
||||
{
|
||||
foreach ($this->trainableSapis as $sapi) {
|
||||
if (!is_file($this->profDataFile($sapi))) {
|
||||
throw new WrongUsageException(
|
||||
"PGO --phase=cs-instrument: missing {$sapi}.profdata; run --phase=instrument and --phase=use first"
|
||||
);
|
||||
}
|
||||
FileSystem::createDir($this->csRawDir($sapi));
|
||||
}
|
||||
}
|
||||
|
||||
public function mergeProfiles(): void
|
||||
{
|
||||
if (trim((string) shell_exec('command -v llvm-profdata 2>/dev/null')) === '') {
|
||||
throw new WrongUsageException('PGO --phase=use: llvm-profdata not on PATH');
|
||||
}
|
||||
foreach ($this->trainableSapis as $sapi) {
|
||||
$this->mergeSapi($sapi);
|
||||
}
|
||||
}
|
||||
|
||||
private function mergeSapi(string $sapi): void
|
||||
{
|
||||
$raws = glob($this->rawDir($sapi) . '/*.profraw') ?: [];
|
||||
$csRaws = glob($this->csRawDir($sapi) . '/*.profraw') ?: [];
|
||||
if ($raws === [] && $csRaws === []) {
|
||||
if ($sapi === 'frankenphp') {
|
||||
logger()->warning(
|
||||
'PGO --phase=use: no .profraw for frankenphp (cgo-glue PGO will be skipped); ' .
|
||||
'run --phase=instrument, exercise frankenphp longer, then re-run --phase=use'
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw new WrongUsageException(
|
||||
"PGO --phase=use: no .profraw for {$sapi}; run --phase=instrument, exercise the binary, then re-run --phase=use"
|
||||
);
|
||||
}
|
||||
$out = $this->profDataFile($sapi);
|
||||
$inputs = array_merge($raws, $csRaws);
|
||||
$argv = implode(' ', array_map('escapeshellarg', $inputs));
|
||||
shell()->exec('llvm-profdata merge --failure-mode=warn -output=' . escapeshellarg($out) . ' ' . $argv);
|
||||
if (!is_file($out) || filesize($out) === 0) {
|
||||
throw new WrongUsageException("PGO --phase=use: empty merge output for {$sapi}");
|
||||
}
|
||||
logger()->info("PGO merged {$sapi}: " . filesize($out) . ' bytes');
|
||||
}
|
||||
|
||||
private static function overwritePgoFlags(string $var, string $append): void
|
||||
{
|
||||
$cur = (string) getenv($var);
|
||||
$cur = preg_replace('/\s*-f(cs-)?profile-(generate|use)=\S+/', '', $cur) ?? $cur;
|
||||
$cur = preg_replace('/\s*-fprofile-update=atomic/', '', $cur) ?? $cur;
|
||||
$cur = preg_replace('/\s*-Wno-error=profile-instr-\S+/', '', $cur) ?? $cur;
|
||||
$cur = preg_replace('/\s*-Wno-backend-plugin/', '', $cur) ?? $cur;
|
||||
f_putenv($var . '=' . trim(trim($cur) . ' ' . $append));
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,7 @@ class PkgConfigUtil
|
||||
public static function getCflags(string $pkg_config_str): string
|
||||
{
|
||||
// get other things
|
||||
$result = self::execWithResult("pkg-config --static --cflags {$pkg_config_str}");
|
||||
$result = self::execWithResult("pkg-config --static --cflags-only-other {$pkg_config_str}");
|
||||
return trim($result);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,8 @@ declare(strict_types=1);
|
||||
namespace StaticPHP\Util;
|
||||
|
||||
use StaticPHP\Config\PackageConfig;
|
||||
use StaticPHP\DI\ApplicationContext;
|
||||
use StaticPHP\Exception\WrongUsageException;
|
||||
use StaticPHP\Package\LibraryPackage;
|
||||
use StaticPHP\Package\PackageInstaller;
|
||||
use StaticPHP\Package\PhpExtensionPackage;
|
||||
use StaticPHP\Runtime\SystemTarget;
|
||||
|
||||
@@ -120,10 +118,6 @@ class SPCConfigUtil
|
||||
* [Helper function]
|
||||
* Get configuration for a specific extension(s) dependencies.
|
||||
*
|
||||
* Uses the installer's resolved package set as the source of truth — only libraries that
|
||||
* are actually enabled in this build appear in the result. The resolved set already
|
||||
* reflects the user's `--with-suggests` choice.
|
||||
*
|
||||
* @param array|PhpExtensionPackage $extension_packages Extension instance or list
|
||||
* @return array{
|
||||
* cflags: string,
|
||||
@@ -131,30 +125,30 @@ class SPCConfigUtil
|
||||
* libs: string
|
||||
* }
|
||||
*/
|
||||
public function getExtensionConfig(array|PhpExtensionPackage $extension_packages): array
|
||||
public function getExtensionConfig(array|PhpExtensionPackage $extension_packages, bool $include_suggests = false): array
|
||||
{
|
||||
if (!is_array($extension_packages)) {
|
||||
$extension_packages = [$extension_packages];
|
||||
}
|
||||
$names = array_map(fn ($y) => $y->getName(), $extension_packages);
|
||||
return $this->configWithResolvedPackages($this->collectEnabledLinkPackages($names));
|
||||
return $this->config(
|
||||
packages: array_map(fn ($y) => $y->getName(), $extension_packages),
|
||||
include_suggests: $include_suggests,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* [Helper function]
|
||||
* Get configuration for a specific library(s) dependencies.
|
||||
*
|
||||
* Like {@see getExtensionConfig()}, draws from the resolved package set so we never
|
||||
* link against a library that wasn't built.
|
||||
*
|
||||
* @param array|LibraryPackage $lib Library instance or list
|
||||
* @param array|LibraryPackage $lib Library instance or list
|
||||
* @param bool $include_suggests Whether to include suggested libraries
|
||||
* @return array{
|
||||
* cflags: string,
|
||||
* ldflags: string,
|
||||
* libs: string
|
||||
* }
|
||||
*/
|
||||
public function getLibraryConfig(array|LibraryPackage $lib): array
|
||||
public function getLibraryConfig(array|LibraryPackage $lib, bool $include_suggests = false): array
|
||||
{
|
||||
if (!is_array($lib)) {
|
||||
$lib = [$lib];
|
||||
@@ -163,31 +157,35 @@ class SPCConfigUtil
|
||||
$this->no_php = true;
|
||||
$save_libs_only_deps = $this->libs_only_deps;
|
||||
$this->libs_only_deps = true;
|
||||
$names = array_map(fn ($y) => $y->getName(), $lib);
|
||||
$ret = $this->configWithResolvedPackages($this->collectEnabledLinkPackages($names));
|
||||
$ret = $this->config(
|
||||
packages: array_map(fn ($y) => $y->getName(), $lib),
|
||||
include_suggests: $include_suggests,
|
||||
);
|
||||
$this->no_php = $save_no_php;
|
||||
$this->libs_only_deps = $save_libs_only_deps;
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get build configuration for a package's sub-dependencies within a resolved set.
|
||||
* Get build configuration for a package and its sub-dependencies within a resolved set.
|
||||
*
|
||||
* Walks both depends and suggests edges — the resolved set is the filter, so anything
|
||||
* reachable but unbuilt is naturally excluded. No `include_suggests` knob is needed.
|
||||
* This is useful when you need to statically link something against a specific
|
||||
* library and all its transitive dependencies. It properly handles optional
|
||||
* dependencies by only including those that were actually resolved.
|
||||
*
|
||||
* @param string $package_name The package to get config for
|
||||
* @param string[] $resolved_packages The full resolved package list
|
||||
* @param bool $include_suggests Whether to include resolved suggests
|
||||
* @return array{
|
||||
* cflags: string,
|
||||
* ldflags: string,
|
||||
* libs: string
|
||||
* }
|
||||
*/
|
||||
public function getPackageDepsConfig(string $package_name, array $resolved_packages): array
|
||||
public function getPackageDepsConfig(string $package_name, array $resolved_packages, bool $include_suggests = false): array
|
||||
{
|
||||
// Get sub-dependencies within the resolved set
|
||||
$sub_deps = DependencyResolver::getSubDependencies($package_name, $resolved_packages, include_suggests: true);
|
||||
$sub_deps = DependencyResolver::getSubDependencies($package_name, $resolved_packages, $include_suggests);
|
||||
|
||||
if (empty($sub_deps)) {
|
||||
return [
|
||||
@@ -301,24 +299,6 @@ class SPCConfigUtil
|
||||
return implode(' ', $list);
|
||||
}
|
||||
|
||||
/**
|
||||
* For each input package name, gather its transitive deps within the installer's resolved
|
||||
* set (walking depends + suggests edges), plus the package itself, deduped and in build order.
|
||||
*
|
||||
* @param string[] $package_names Input package names
|
||||
* @return string[] Resolved packages to link against
|
||||
*/
|
||||
private function collectEnabledLinkPackages(array $package_names): array
|
||||
{
|
||||
$resolved = array_keys(ApplicationContext::get(PackageInstaller::class)->getResolvedPackages());
|
||||
$out = [];
|
||||
foreach ($package_names as $name) {
|
||||
$sub = DependencyResolver::getSubDependencies($name, $resolved, include_suggests: true);
|
||||
$out = [...$out, ...$sub, $name];
|
||||
}
|
||||
return array_values(array_unique($out));
|
||||
}
|
||||
|
||||
private function hasCpp(array $packages): bool
|
||||
{
|
||||
foreach ($packages as $package) {
|
||||
|
||||
@@ -54,6 +54,7 @@ class WindowsUtil
|
||||
}
|
||||
$args = [
|
||||
'-latest',
|
||||
'-products', '*',
|
||||
'-format', 'json',
|
||||
'-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
|
||||
];
|
||||
|
||||
@@ -33,6 +33,23 @@ ConsoleLogger::$date_format = 'H:i:s';
|
||||
ConsoleLogger::$format = '[%date% %level_long%] %body%';
|
||||
$ob_logger = new ConsoleLogger(LogLevel::WARNING);
|
||||
|
||||
$ob_logger->addLogCallback(function ($level, &$output, &$message, &$context, bool $shouldLog) {
|
||||
global $spc_log_filters;
|
||||
if (!is_array($spc_log_filters)) {
|
||||
$spc_log_filters = [];
|
||||
}
|
||||
// filter message and context
|
||||
$output = str_replace($spc_log_filters, '***', $output);
|
||||
$message = str_replace($spc_log_filters, '***', $message);
|
||||
$context = array_map(function ($item) use ($spc_log_filters) {
|
||||
if (is_string($item)) {
|
||||
return str_replace($spc_log_filters, '***', $item);
|
||||
}
|
||||
return $item;
|
||||
}, $context);
|
||||
return true;
|
||||
});
|
||||
|
||||
// setup log file
|
||||
if (filter_var(getenv('SPC_ENABLE_LOG_FILE'), FILTER_VALIDATE_BOOLEAN)) {
|
||||
// init spc log files
|
||||
@@ -60,5 +77,9 @@ if (filter_var(getenv('SPC_ENABLE_LOG_FILE'), FILTER_VALIDATE_BOOLEAN)) {
|
||||
|
||||
// load core registry
|
||||
Registry::loadRegistry(ROOT_DIR . '/spc.registry.yml');
|
||||
// in vendor mode, auto-load the local working directory registry if it exists
|
||||
if (spc_mode(SPC_MODE_VENDOR) && file_exists(WORKING_DIR . '/spc.registry.yml')) {
|
||||
Registry::loadRegistry(WORKING_DIR . '/spc.registry.yml');
|
||||
}
|
||||
// load registries from environment variable SPC_REGISTRIES
|
||||
Registry::loadFromEnvOrOption();
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
--- a/frankenphp.c
|
||||
+++ b/frankenphp.c
|
||||
@@ -1254,6 +1254,12 @@
|
||||
|
||||
go_frankenphp_shutdown_main_thread();
|
||||
|
||||
+ /* spc-pgo: explicit profile flush so the cgo-instrumented frankenphp
|
||||
+ * still writes .profraw on Go-runtime exit (which bypasses libc atexit).
|
||||
+ * Weak symbol → no-op in non-PGO builds. */
|
||||
+ { extern int __llvm_profile_write_file(void) __attribute__((weak));
|
||||
+ if (__llvm_profile_write_file) __llvm_profile_write_file(); }
|
||||
+
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
--- a/main/main.c
|
||||
+++ b/main/main.c
|
||||
@@ -2563,6 +2563,9 @@
|
||||
#endif
|
||||
|
||||
zend_observer_shutdown();
|
||||
+
|
||||
+ { extern int __llvm_profile_write_file(void) __attribute__((weak));
|
||||
+ if (__llvm_profile_write_file) __llvm_profile_write_file(); }
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")"
|
||||
BUILDROOT_INC="${BUILD_INCLUDE_PATH:-$SCRIPT_DIR/../../../buildroot/include}"
|
||||
BUILDROOT_ABS="$(realpath "$BUILDROOT_INC" 2>/dev/null || true)"
|
||||
BUILDROOT_ABS="${BUILD_ROOT_PATH:-$(realpath "$SCRIPT_DIR/../../../buildroot/include" 2>/dev/null || true)}"
|
||||
PARSED_ARGS=()
|
||||
|
||||
is_buildroot_inc() {
|
||||
[[ -n "$BUILDROOT_ABS" && "$1" == "$BUILDROOT_ABS" ]]
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-isystem)
|
||||
@@ -16,13 +11,13 @@ while [[ $# -gt 0 ]]; do
|
||||
ARG="$1"
|
||||
shift
|
||||
ARG_ABS="$(realpath "$ARG" 2>/dev/null || true)"
|
||||
is_buildroot_inc "$ARG_ABS" && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem" "$ARG")
|
||||
[[ "$ARG_ABS" == "$BUILDROOT_ABS" ]] && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem" "$ARG")
|
||||
;;
|
||||
-isystem*)
|
||||
ARG="${1#-isystem}"
|
||||
shift
|
||||
ARG_ABS="$(realpath "$ARG" 2>/dev/null || true)"
|
||||
is_buildroot_inc "$ARG_ABS" && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem$ARG")
|
||||
[[ "$ARG_ABS" == "$BUILDROOT_ABS" ]] && PARSED_ARGS+=("-I$ARG") || PARSED_ARGS+=("-isystem$ARG")
|
||||
;;
|
||||
-march=*|-mcpu=*)
|
||||
OPT_NAME="${1%%=*}"
|
||||
@@ -37,10 +32,6 @@ while [[ $# -gt 0 ]]; do
|
||||
PARSED_ARGS+=("${OPT_NAME}=${OPT_VALUE}")
|
||||
shift
|
||||
;;
|
||||
-Wlogical-op|-Wduplicated-cond|-Wduplicated-branches|-Wno-clobbered|-Wjump-misses-init|-Wformat-truncation|-Warray-bounds=*|-Wimplicit-fallthrough=*)
|
||||
# GCC-only warning flags that clang/zig doesn't recognize; drop to silence -Wunknown-warning-option noise
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
PARSED_ARGS+=("$1")
|
||||
shift
|
||||
@@ -48,24 +39,6 @@ while [[ $# -gt 0 ]]; do
|
||||
esac
|
||||
done
|
||||
|
||||
IS_LINK=1
|
||||
NEED_PROFILE_RT=0 # https://codeberg.org/ziglang/zig/issues/32066
|
||||
NEED_CRT=0 # https://codeberg.org/ziglang/zig/issues/32064
|
||||
for _a in "${PARSED_ARGS[@]}"; do
|
||||
case "$_a" in
|
||||
-c|-S|-E|-M|-MM) IS_LINK=0 ;;
|
||||
-fprofile-generate*|-fprofile-instr-generate*|-fcs-profile-generate*) NEED_PROFILE_RT=1 ;;
|
||||
-shared) NEED_CRT=1 ;;
|
||||
esac
|
||||
done
|
||||
[[ "$SPC_COMPILER_EXTRA" == *-fprofile-generate* || "$SPC_COMPILER_EXTRA" == *-fcs-profile-generate* ]] && NEED_PROFILE_RT=1
|
||||
if [[ $IS_LINK -eq 1 && $NEED_PROFILE_RT -eq 1 && -f "$SCRIPT_DIR/lib/libclang_rt.profile.a" ]]; then
|
||||
PARSED_ARGS+=("$SCRIPT_DIR/lib/libclang_rt.profile.a" "-Wl,-u,__llvm_profile_runtime")
|
||||
fi
|
||||
if [[ $IS_LINK -eq 1 && $NEED_CRT -eq 1 && -f "$SCRIPT_DIR/lib/clang_rt.crtbegin.o" && -f "$SCRIPT_DIR/lib/clang_rt.crtend.o" ]]; then
|
||||
PARSED_ARGS+=("$SCRIPT_DIR/lib/clang_rt.crtbegin.o" "$SCRIPT_DIR/lib/clang_rt.crtend.o")
|
||||
fi
|
||||
|
||||
[[ -n "$SPC_TARGET" ]] && TARGET="-target $SPC_TARGET" || TARGET=""
|
||||
|
||||
if [[ "$SPC_TARGET" =~ \.[0-9]+\.[0-9]+ ]]; then
|
||||
|
||||
104
tests/GlobalsFunctionsTest.php
Normal file
104
tests/GlobalsFunctionsTest.php
Normal file
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LogLevel;
|
||||
use ZM\Logger\ConsoleLogger;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
class GlobalsFunctionsTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
$GLOBALS['spc_log_filters'] = null;
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$GLOBALS['spc_log_filters'] = null;
|
||||
}
|
||||
|
||||
public function testAddLogFilterDeduplicates(): void
|
||||
{
|
||||
spc_add_log_filter('secret-value');
|
||||
spc_add_log_filter('secret-value');
|
||||
spc_add_log_filter(['secret-value', 'other']);
|
||||
|
||||
$this->assertSame(['secret-value', 'other'], $GLOBALS['spc_log_filters']);
|
||||
}
|
||||
|
||||
public function testWriteLogMasksRegisteredValues(): void
|
||||
{
|
||||
spc_add_log_filter(['octocat', 'ghp_abcdef1234567890']);
|
||||
|
||||
$stream = fopen('php://memory', 'r+');
|
||||
spc_write_log($stream, 'user=octocat token=ghp_abcdef1234567890');
|
||||
rewind($stream);
|
||||
$written = stream_get_contents($stream);
|
||||
fclose($stream);
|
||||
|
||||
$this->assertSame('user=*** token=***', $written);
|
||||
}
|
||||
|
||||
public function testLoggerCallbackMasksOutput(): void
|
||||
{
|
||||
$token = 'ghp_abcdef1234567890';
|
||||
spc_add_log_filter($token);
|
||||
|
||||
$stream = fopen('php://memory', 'r+');
|
||||
$logger = new ConsoleLogger(LogLevel::DEBUG, $stream, false);
|
||||
$logger->addLogCallback(function ($level, &$output, &$message, &$context, bool $shouldLog) {
|
||||
global $spc_log_filters;
|
||||
if (!is_array($spc_log_filters)) {
|
||||
$spc_log_filters = [];
|
||||
}
|
||||
$output = str_replace($spc_log_filters, '***', $output);
|
||||
$message = str_replace($spc_log_filters, '***', $message);
|
||||
$context = array_map(function ($item) use ($spc_log_filters) {
|
||||
if (is_string($item)) {
|
||||
return str_replace($spc_log_filters, '***', $item);
|
||||
}
|
||||
return $item;
|
||||
}, $context);
|
||||
return true;
|
||||
});
|
||||
|
||||
$logger->debug("[PASSTHRU] curl -H\"Authorization: Bearer {$token}\" https://api.github.com/x");
|
||||
|
||||
rewind($stream);
|
||||
$written = stream_get_contents($stream);
|
||||
fclose($stream);
|
||||
|
||||
$this->assertStringNotContainsString($token, $written);
|
||||
$this->assertStringContainsString('***', $written);
|
||||
}
|
||||
|
||||
public function testGitHubTokenTraitRegistersEncodedBasicAuthBlob(): void
|
||||
{
|
||||
$user = 'octocat';
|
||||
$token = 'ghp_abcdef1234567890';
|
||||
$original_token = getenv('GITHUB_TOKEN');
|
||||
$original_user = getenv('GITHUB_USER');
|
||||
|
||||
putenv("GITHUB_TOKEN={$token}");
|
||||
putenv("GITHUB_USER={$user}");
|
||||
|
||||
try {
|
||||
$headers = \StaticPHP\Artifact\Downloader\Type\GitHubRelease::getGitHubTokenHeadersStatic();
|
||||
|
||||
$encoded = base64_encode("{$user}:{$token}");
|
||||
$this->assertSame(["Authorization: Basic {$encoded}"], $headers);
|
||||
$this->assertContains($user, $GLOBALS['spc_log_filters']);
|
||||
$this->assertContains($token, $GLOBALS['spc_log_filters']);
|
||||
$this->assertContains($encoded, $GLOBALS['spc_log_filters']);
|
||||
} finally {
|
||||
$original_token === false ? putenv('GITHUB_TOKEN') : putenv("GITHUB_TOKEN={$original_token}");
|
||||
$original_user === false ? putenv('GITHUB_USER') : putenv("GITHUB_USER={$original_user}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -254,11 +254,16 @@ class ArtifactTest extends TestCase
|
||||
ApplicationContext::initialize();
|
||||
ApplicationContext::set(ArtifactCache::class, $cache);
|
||||
|
||||
// Use a platform-appropriate absolute path: a Unix-style /tmp/... isn't
|
||||
// absolute on Windows (no drive letter), so the test would otherwise
|
||||
// fall through into the SOURCE_PATH-prefixed branch on Windows.
|
||||
$extract = DIRECTORY_SEPARATOR === '\\' ? 'C:\tmp\my-pkg-extract' : '/tmp/my-pkg-extract';
|
||||
|
||||
$artifact = new Artifact('my-pkg', [
|
||||
'source' => ['type' => 'url', 'url' => 'https://example.com/file.tar.gz', 'extract' => '/tmp/my-pkg-extract'],
|
||||
'source' => ['type' => 'url', 'url' => 'https://example.com/file.tar.gz', 'extract' => $extract],
|
||||
]);
|
||||
|
||||
$expected = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, '/tmp/my-pkg-extract');
|
||||
$expected = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $extract);
|
||||
$this->assertSame($expected, $artifact->getSourceDir());
|
||||
}
|
||||
|
||||
@@ -703,11 +708,7 @@ class ArtifactTest extends TestCase
|
||||
'Windows' => 'windows',
|
||||
default => 'linux',
|
||||
};
|
||||
$arch = php_uname('m');
|
||||
if ($arch === 'arm64') {
|
||||
$arch = 'aarch64';
|
||||
}
|
||||
return "{$os}-{$arch}";
|
||||
return "{$os}-" . arch2gnu(php_uname('m'));
|
||||
}
|
||||
|
||||
private function injectArtifactConfig(string $name, array $config): void
|
||||
|
||||
Reference in New Issue
Block a user