Add curl extension and enhance Windows build process

This commit is contained in:
crazywhalecc
2026-03-31 15:10:47 +08:00
parent 844bb69f0d
commit b96586e4d3
10 changed files with 1492 additions and 762 deletions

View File

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Package\Extension;
use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Attribute\PatchDescription;
#[Extension('curl')]
class curl
{
#[BeforeStage('php', [php::class, 'makeForWindows'], 'ext-curl')]
#[PatchDescription('Inject secur32.lib into SPC_EXTRA_LIBS for Schannel SSL support')]
public function addSecur32LibForWindows(): void
{
// curl on Windows uses Schannel (USE_WINDOWS_SSPI=ON, CURL_USE_SCHANNEL=ON),
// which requires secur32.lib for SSL/TLS functions (SslEncryptPackage, etc.).
$extra_libs = getenv('SPC_EXTRA_LIBS') ?: '';
if (!str_contains($extra_libs, 'secur32.lib')) {
putenv('SPC_EXTRA_LIBS=' . trim($extra_libs . ' secur32.lib'));
}
}
}

View File

@@ -9,6 +9,7 @@ use StaticPHP\Attribute\Package\Library;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor; use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Runtime\Executor\WindowsCMakeExecutor; use StaticPHP\Runtime\Executor\WindowsCMakeExecutor;
use StaticPHP\Util\FileSystem;
#[Library('nghttp2')] #[Library('nghttp2')]
class nghttp2 class nghttp2
@@ -26,6 +27,9 @@ class nghttp2
'-DBUILD_TESTING=OFF', '-DBUILD_TESTING=OFF',
) )
->build(); ->build();
FileSystem::replaceFileStr($lib->getIncludeDir() . '\nghttp2\nghttp2.h', '#ifdef NGHTTP2_STATICLIB', '#if 1');
} }
#[BuildFor('Linux')] #[BuildFor('Linux')]

View File

@@ -12,6 +12,7 @@ use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\Info; use StaticPHP\Attribute\Package\Info;
use StaticPHP\Attribute\Package\InitPackage; use StaticPHP\Attribute\Package\InitPackage;
use StaticPHP\Attribute\Package\ResolveBuild; use StaticPHP\Attribute\Package\ResolveBuild;
use StaticPHP\Attribute\Package\Stage;
use StaticPHP\Attribute\Package\Target; use StaticPHP\Attribute\Package\Target;
use StaticPHP\Attribute\Package\Validate; use StaticPHP\Attribute\Package\Validate;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
@@ -29,6 +30,7 @@ use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ToolchainManager; use StaticPHP\Toolchain\ToolchainManager;
use StaticPHP\Util\DependencyResolver; use StaticPHP\Util\DependencyResolver;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm;
use StaticPHP\Util\SourcePatcher; use StaticPHP\Util\SourcePatcher;
use StaticPHP\Util\V2CompatLayer; use StaticPHP\Util\V2CompatLayer;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
@@ -339,6 +341,35 @@ class php extends TargetPackage
FileSystem::removeDir(BUILD_MODULES_PATH); FileSystem::removeDir(BUILD_MODULES_PATH);
} }
#[Stage('postInstall')]
public function postInstall(TargetPackage $package, PackageInstaller $installer): void
{
if ($package->getName() === 'frankenphp') {
$package->runStage([$this, 'smokeTestFrankenphpForUnix']);
return;
}
if ($package->getName() !== 'php') {
return;
}
if (SystemTarget::isUnix()) {
if ($installer->interactive) {
InteractiveTerm::indicateProgress('Running PHP smoke tests');
}
$package->runStage([$this, 'smokeTestForUnix']);
if ($installer->interactive) {
InteractiveTerm::finish('PHP smoke tests passed');
}
} elseif (SystemTarget::getTargetOS() === 'Windows') {
if ($installer->interactive) {
InteractiveTerm::indicateProgress('Running PHP smoke tests');
}
$package->runStage([$this, 'smokeTestForWindows']);
if ($installer->interactive) {
InteractiveTerm::finish('PHP smoke tests passed');
}
}
}
private function makeStaticExtensionString(PackageInstaller $installer): string private function makeStaticExtensionString(PackageInstaller $installer): string
{ {
$arg = []; $arg = [];

View File

@@ -469,27 +469,6 @@ trait unix
$package->runStage([$this, 'unixBuildSharedExt']); $package->runStage([$this, 'unixBuildSharedExt']);
} }
#[Stage('postInstall')]
public function postInstall(TargetPackage $package, PackageInstaller $installer): void
{
if ($package->getName() === 'frankenphp') {
$package->runStage([$this, 'smokeTestFrankenphpForUnix']);
return;
}
if ($package->getName() !== 'php') {
return;
}
if (SystemTarget::isUnix()) {
if ($installer->interactive) {
InteractiveTerm::indicateProgress('Running PHP smoke tests');
}
$package->runStage([$this, 'smokeTestForUnix']);
if ($installer->interactive) {
InteractiveTerm::finish('PHP smoke tests passed');
}
}
}
/** /**
* Patch phpize and php-config if needed * Patch phpize and php-config if needed
*/ */
@@ -662,7 +641,7 @@ trait unix
/** /**
* Generate micro extension test php code. * Generate micro extension test php code.
*/ */
private function generateMicroExtTests(PackageInstaller $installer): string protected function generateMicroExtTests(PackageInstaller $installer): string
{ {
$php = "<?php\n\necho '[micro-test-start]' . PHP_EOL;\n"; $php = "<?php\n\necho '[micro-test-start]' . PHP_EOL;\n";
foreach ($installer->getResolvedPackages(PhpExtensionPackage::class) as $ext) { foreach ($installer->getResolvedPackages(PhpExtensionPackage::class) as $ext) {

File diff suppressed because it is too large Load Diff

View File

@@ -155,6 +155,43 @@ class PhpExtensionPackage extends Package
return $this->extension_config['display-name'] ?? $this->getExtensionName(); return $this->extension_config['display-name'] ?? $this->getExtensionName();
} }
/**
* Run smoke test for the extension on Unix CLI.
* Override this method in a subclass.
*/
public function runSmokeTestCliWindows(): void
{
if (($this->extension_config['smoke-test'] ?? true) === false) {
return;
}
$distName = $this->getDistName();
// empty display-name → no --ri check (e.g. password_argon2)
if ($distName === '') {
return;
}
[$ret] = cmd()->execWithResult(BUILD_BIN_PATH . '\php.exe -n --ri "' . $distName . '"', false);
if ($ret !== 0) {
throw new ValidationException(
"extension {$this->getName()} failed compile check: php-cli returned {$ret}",
validation_module: 'Extension ' . $this->getName() . ' sanity check'
);
}
$test_file = ROOT_DIR . '/src/globals/ext-tests/' . $this->getExtensionName() . '.php';
if (file_exists($test_file)) {
$test = self::escapeInlineTestWindows(file_get_contents($test_file));
[$ret, $out] = cmd()->execWithResult(BUILD_BIN_PATH . '\php.exe -n -r "' . trim($test) . '"');
if ($ret !== 0) {
throw new ValidationException(
"extension {$this->getName()} failed sanity check. Code: {$ret}, output: " . implode("\n", $out),
validation_module: 'Extension ' . $this->getName() . ' function check'
);
}
}
}
/** /**
* Run smoke test for the extension on Unix CLI. * Run smoke test for the extension on Unix CLI.
* Override this method in a subclass. * Override this method in a subclass.
@@ -394,4 +431,17 @@ class PhpExtensionPackage extends Package
$code $code
); );
} }
/**
* Escape PHP test file content for inline `-r` usage on Windows cmd.
* Strips <?php / declare, replaces newlines and special cmd characters.
*/
private static function escapeInlineTestWindows(string $code): string
{
return str_replace(
['<?php', 'declare(strict_types=1);', "\n", '"', '$'],
['', '', '', '\"', '$'],
$code
);
}
} }

View File

@@ -133,7 +133,7 @@ class DefaultShell extends Shell
}; };
$mute = $this->console_putput ? '' : ' 2>/dev/null'; $mute = $this->console_putput ? '' : ' 2>/dev/null';
$tar = SystemTarget::isUnix() ? 'tar' : '"C:\\Windows\\system32\\tar.exe"'; $tar = SystemTarget::isUnix() ? 'tar' : '"C:\Windows\system32\tar.exe"';
$cmd = "{$tar} {$compression_flag}xf {$archive_arg} --strip-components {$strip} -C {$target_arg}{$mute}"; $cmd = "{$tar} {$compression_flag}xf {$archive_arg} --strip-components {$strip} -C {$target_arg}{$mute}";
$this->logCommandInfo($cmd); $this->logCommandInfo($cmd);
@@ -187,7 +187,7 @@ class DefaultShell extends Shell
}; };
$extname = FileSystem::extname($archive_path); $extname = FileSystem::extname($archive_path);
$tar = SystemTarget::isUnix() ? 'tar' : '"C:\\Windows\\system32\\tar.exe"'; $tar = SystemTarget::isUnix() ? 'tar' : '"C:\Windows\system32\tar.exe"';
match ($extname) { match ($extname) {
'tar' => $this->executeTarExtract($archive_path, $target_path, 'none'), 'tar' => $this->executeTarExtract($archive_path, $target_path, 'none'),

View File

@@ -1,62 +1,64 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace StaticPHP\Runtime\Shell; namespace StaticPHP\Runtime\Shell;
use StaticPHP\Exception\SPCInternalException; use StaticPHP\Exception\SPCInternalException;
use ZM\Logger\ConsoleColor; use ZM\Logger\ConsoleColor;
class WindowsCmd extends Shell class WindowsCmd extends Shell
{ {
public function __construct(?bool $debug = null) public function __construct(?bool $debug = null)
{ {
if (PHP_OS_FAMILY !== 'Windows') { if (PHP_OS_FAMILY !== 'Windows') {
throw new SPCInternalException('Only windows can use WindowsCmd'); throw new SPCInternalException('Only windows can use WindowsCmd');
} }
parent::__construct($debug); parent::__construct($debug);
} }
public function exec(string $cmd): static public function exec(string $cmd): static
{ {
/* @phpstan-ignore-next-line */ /* @phpstan-ignore-next-line */
logger()->info(ConsoleColor::yellow('[EXEC] ') . ConsoleColor::green($cmd)); logger()->info(ConsoleColor::yellow('[EXEC] ') . ConsoleColor::green($cmd));
$original_command = $cmd; $original_command = $cmd;
$this->logCommandInfo($original_command); $this->logCommandInfo($original_command);
$this->last_cmd = $cmd = $this->getExecString($cmd); $this->last_cmd = $cmd = $this->getExecString($cmd);
// echo $cmd . PHP_EOL; // echo $cmd . PHP_EOL;
$this->passthru($cmd, $this->console_putput, $original_command, cwd: $this->cd); $this->passthru($cmd, $this->console_putput, $original_command, cwd: $this->cd);
return $this; return $this;
} }
public function execWithWrapper(string $wrapper, string $args): WindowsCmd public function execWithWrapper(string $wrapper, string $args): WindowsCmd
{ {
return $this->exec($wrapper . ' "' . str_replace('"', '^"', $args) . '"'); return $this->exec($wrapper . ' "' . str_replace('"', '^"', $args) . '"');
} }
public function execWithResult(string $cmd, bool $with_log = true): array public function execWithResult(string $cmd, bool $with_log = true): array
{ {
if ($with_log) { if ($with_log) {
/* @phpstan-ignore-next-line */ /* @phpstan-ignore-next-line */
logger()->info(ConsoleColor::blue('[EXEC] ') . ConsoleColor::green($cmd)); logger()->info(ConsoleColor::blue('[EXEC] ') . ConsoleColor::green($cmd));
} else { } else {
logger()->debug('Running command with result: ' . $cmd); logger()->debug('Running command with result: ' . $cmd);
} }
$cmd = $this->getExecString($cmd); $original_command = $cmd;
$result = $this->passthru($cmd, $this->console_putput, $cmd, capture_output: true, throw_on_error: false, cwd: $this->cd, env: $this->env); $this->logCommandInfo($original_command);
$out = explode("\n", $result['output']); $cmd = $this->getExecString($cmd);
return [$result['code'], $out]; $result = $this->passthru($cmd, $this->console_putput, $original_command, capture_output: true, throw_on_error: false, cwd: $this->cd, env: $this->env);
} $out = explode("\n", $result['output']);
return [$result['code'], $out];
public function getLastCommand(): string }
{
return $this->last_cmd; public function getLastCommand(): string
} {
return $this->last_cmd;
private function getExecString(string $cmd): string }
{
return $cmd; private function getExecString(string $cmd): string
} {
} return $cmd;
}
}

View File

@@ -1,437 +1,509 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace StaticPHP\Util; namespace StaticPHP\Util;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Package\LibraryPackage; use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\PhpExtensionPackage; use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
class SPCConfigUtil class SPCConfigUtil
{ {
private bool $no_php; private bool $no_php;
private bool $libs_only_deps; private bool $libs_only_deps;
private bool $absolute_libs; private bool $absolute_libs;
/** /**
* @param array{ * @param array{
* no_php?: bool, * no_php?: bool,
* libs_only_deps?: bool, * libs_only_deps?: bool,
* absolute_libs?: bool * absolute_libs?: bool
* } $options Options pass to spc-config * } $options Options pass to spc-config
*/ */
public function __construct(array $options = []) public function __construct(array $options = [])
{ {
$this->no_php = $options['no_php'] ?? false; $this->no_php = $options['no_php'] ?? false;
$this->libs_only_deps = $options['libs_only_deps'] ?? false; $this->libs_only_deps = $options['libs_only_deps'] ?? false;
$this->absolute_libs = $options['absolute_libs'] ?? false; $this->absolute_libs = $options['absolute_libs'] ?? false;
} }
public function config(array $packages = [], bool $include_suggests = false): array public function config(array $packages = [], bool $include_suggests = false): array
{ {
// if have php, make php as all extension's dependency // if have php, make php as all extension's dependency
if (!$this->no_php) { if (!$this->no_php) {
$dep_override = ['php' => array_filter($packages, fn ($y) => str_starts_with($y, 'ext-'))]; $dep_override = ['php' => array_filter($packages, fn ($y) => str_starts_with($y, 'ext-'))];
} else { } else {
$dep_override = []; $dep_override = [];
} }
$resolved = DependencyResolver::resolve($packages, $dep_override, $include_suggests); $resolved = DependencyResolver::resolve($packages, $dep_override, $include_suggests);
$ldflags = $this->getLdflagsString(); $ldflags = $this->getLdflagsString();
$cflags = $this->getIncludesString($resolved); $cflags = $this->getIncludesString($resolved);
$libs = $this->getLibsString($resolved, !$this->absolute_libs); $libs = $this->getLibsString($resolved, !$this->absolute_libs);
// additional OS-specific libraries (e.g. macOS -lresolv) // additional OS-specific libraries (e.g. macOS -lresolv)
// embed // embed
if ($extra_libs = SystemTarget::getRuntimeLibs()) { if ($extra_libs = SystemTarget::getRuntimeLibs()) {
$libs .= " {$extra_libs}"; $libs .= " {$extra_libs}";
} }
$extra_env = getenv('SPC_EXTRA_LIBS'); $extra_env = getenv('SPC_EXTRA_LIBS');
if (is_string($extra_env) && !empty($extra_env)) { if (is_string($extra_env) && !empty($extra_env)) {
$libs .= " {$extra_env}"; $libs .= " {$extra_env}";
} }
// package frameworks // package frameworks
if (SystemTarget::getTargetOS() === 'Darwin') { if (SystemTarget::getTargetOS() === 'Darwin') {
$libs .= " {$this->getFrameworksString($resolved)}"; $libs .= " {$this->getFrameworksString($resolved)}";
} }
// C++ // C++
if ($this->hasCpp($resolved)) { if ($this->hasCpp($resolved)) {
$libcpp = SystemTarget::getTargetOS() === 'Darwin' ? '-lc++' : '-lstdc++'; $target_os = SystemTarget::getTargetOS();
$libs = str_replace($libcpp, '', $libs) . " {$libcpp}"; if ($target_os === 'Darwin') {
} $libcpp = '-lc++';
$libs = str_replace($libcpp, '', $libs) . " {$libcpp}";
if ($this->libs_only_deps) { } elseif ($target_os !== 'Windows') {
// mimalloc must come first // Linux and other Unix-like systems use libstdc++
if (in_array('mimalloc', $resolved) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) { $libcpp = '-lstdc++';
$libs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $libs); $libs = str_replace($libcpp, '', $libs) . " {$libcpp}";
} }
return [ // Windows (MSVC): C++ runtime is linked automatically, no explicit lib needed
'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags), }
'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags),
'libs' => clean_spaces(getenv('LIBS') . ' ' . $libs), if ($this->libs_only_deps) {
]; // mimalloc must come first
} if (in_array('mimalloc', $resolved) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) {
$libs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $libs);
// embed }
if (!$this->no_php) { return [
$libs = "-lphp {$libs} -lc"; 'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags),
} 'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags),
'libs' => clean_spaces(getenv('LIBS') . ' ' . $libs),
$allLibs = getenv('LIBS') . ' ' . $libs; ];
}
// mimalloc must come first
if (in_array('mimalloc', $resolved) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) { // embed
$allLibs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $allLibs); if (!$this->no_php) {
} if (SystemTarget::getTargetOS() === 'Windows') {
// Windows: use php8embed.lib directly (either full path or short name)
return [ $major = intdiv(PHP_VERSION_ID, 10000);
'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags), $php_lib = $this->absolute_libs ? BUILD_LIB_PATH . "\\php{$major}embed.lib" : "php{$major}embed.lib";
'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags), // Windows system libs required by PHP
'libs' => clean_spaces($allLibs), // Use same system libs as PHP Makefile: LIBS=kernel32.lib ole32.lib user32.lib advapi32.lib shell32.lib ws2_32.lib Dnsapi.lib psapi.lib bcrypt.lib
]; $libs = "{$php_lib} {$libs} kernel32.lib ole32.lib user32.lib advapi32.lib shell32.lib ws2_32.lib dnsapi.lib psapi.lib bcrypt.lib";
} } else {
$libs = "-lphp {$libs} -lc";
/** }
* [Helper function] }
* Get configuration for a specific extension(s) dependencies.
* $allLibs = getenv('LIBS') . ' ' . $libs;
* @param array|PhpExtensionPackage $extension_packages Extension instance or list
* @return array{ // mimalloc must come first
* cflags: string, if (in_array('mimalloc', $resolved) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) {
* ldflags: string, $allLibs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $allLibs);
* libs: string }
* }
*/ return [
public function getExtensionConfig(array|PhpExtensionPackage $extension_packages, bool $include_suggests = false): array 'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags),
{ 'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags),
if (!is_array($extension_packages)) { 'libs' => clean_spaces($allLibs),
$extension_packages = [$extension_packages]; ];
} }
return $this->config(
packages: array_map(fn ($y) => $y->getName(), $extension_packages), /**
include_suggests: $include_suggests, * [Helper function]
); * Get configuration for a specific extension(s) dependencies.
} *
* @param array|PhpExtensionPackage $extension_packages Extension instance or list
/** * @return array{
* [Helper function] * cflags: string,
* Get configuration for a specific library(s) dependencies. * ldflags: string,
* * libs: string
* @param array|LibraryPackage $lib Library instance or list * }
* @param bool $include_suggests Whether to include suggested libraries */
* @return array{ public function getExtensionConfig(array|PhpExtensionPackage $extension_packages, bool $include_suggests = false): array
* cflags: string, {
* ldflags: string, if (!is_array($extension_packages)) {
* libs: string $extension_packages = [$extension_packages];
* } }
*/ return $this->config(
public function getLibraryConfig(array|LibraryPackage $lib, bool $include_suggests = false): array packages: array_map(fn ($y) => $y->getName(), $extension_packages),
{ include_suggests: $include_suggests,
if (!is_array($lib)) { );
$lib = [$lib]; }
}
$save_no_php = $this->no_php; /**
$this->no_php = true; * [Helper function]
$save_libs_only_deps = $this->libs_only_deps; * Get configuration for a specific library(s) dependencies.
$this->libs_only_deps = true; *
$ret = $this->config( * @param array|LibraryPackage $lib Library instance or list
packages: array_map(fn ($y) => $y->getName(), $lib), * @param bool $include_suggests Whether to include suggested libraries
include_suggests: $include_suggests, * @return array{
); * cflags: string,
$this->no_php = $save_no_php; * ldflags: string,
$this->libs_only_deps = $save_libs_only_deps; * libs: string
return $ret; * }
} */
public function getLibraryConfig(array|LibraryPackage $lib, bool $include_suggests = false): array
/** {
* Get build configuration for a package and its sub-dependencies within a resolved set. if (!is_array($lib)) {
* $lib = [$lib];
* This is useful when you need to statically link something against a specific }
* library and all its transitive dependencies. It properly handles optional $save_no_php = $this->no_php;
* dependencies by only including those that were actually resolved. $this->no_php = true;
* $save_libs_only_deps = $this->libs_only_deps;
* @param string $package_name The package to get config for $this->libs_only_deps = true;
* @param string[] $resolved_packages The full resolved package list $ret = $this->config(
* @param bool $include_suggests Whether to include resolved suggests packages: array_map(fn ($y) => $y->getName(), $lib),
* @return array{ include_suggests: $include_suggests,
* cflags: string, );
* ldflags: string, $this->no_php = $save_no_php;
* libs: string $this->libs_only_deps = $save_libs_only_deps;
* } return $ret;
*/ }
public function getPackageDepsConfig(string $package_name, array $resolved_packages, bool $include_suggests = false): array
{ /**
// Get sub-dependencies within the resolved set * Get build configuration for a package and its sub-dependencies within a resolved set.
$sub_deps = DependencyResolver::getSubDependencies($package_name, $resolved_packages, $include_suggests); *
* This is useful when you need to statically link something against a specific
if (empty($sub_deps)) { * library and all its transitive dependencies. It properly handles optional
return [ * dependencies by only including those that were actually resolved.
'cflags' => '', *
'ldflags' => '', * @param string $package_name The package to get config for
'libs' => '', * @param string[] $resolved_packages The full resolved package list
]; * @param bool $include_suggests Whether to include resolved suggests
} * @return array{
* cflags: string,
// Use libs_only_deps mode and no_php for library linking * ldflags: string,
$save_no_php = $this->no_php; * libs: string
$save_libs_only_deps = $this->libs_only_deps; * }
$this->no_php = true; */
$this->libs_only_deps = true; public function getPackageDepsConfig(string $package_name, array $resolved_packages, bool $include_suggests = false): array
{
$ret = $this->configWithResolvedPackages($sub_deps); // Get sub-dependencies within the resolved set
$sub_deps = DependencyResolver::getSubDependencies($package_name, $resolved_packages, $include_suggests);
$this->no_php = $save_no_php;
$this->libs_only_deps = $save_libs_only_deps; if (empty($sub_deps)) {
return [
return $ret; 'cflags' => '',
} 'ldflags' => '',
'libs' => '',
/** ];
* Get configuration using already-resolved packages (skip dependency resolution). }
*
* @param string[] $resolved_packages Already resolved package names in build order // Use libs_only_deps mode and no_php for library linking
* @return array{ $save_no_php = $this->no_php;
* cflags: string, $save_libs_only_deps = $this->libs_only_deps;
* ldflags: string, $this->no_php = true;
* libs: string $this->libs_only_deps = true;
* }
*/ $ret = $this->configWithResolvedPackages($sub_deps);
public function configWithResolvedPackages(array $resolved_packages): array
{ $this->no_php = $save_no_php;
$ldflags = $this->getLdflagsString(); $this->libs_only_deps = $save_libs_only_deps;
$cflags = $this->getIncludesString($resolved_packages);
$libs = $this->getLibsString($resolved_packages, !$this->absolute_libs); return $ret;
}
// additional OS-specific libraries (e.g. macOS -lresolv)
if ($extra_libs = SystemTarget::getRuntimeLibs()) { /**
$libs .= " {$extra_libs}"; * Get configuration using already-resolved packages (skip dependency resolution).
} *
* @param string[] $resolved_packages Already resolved package names in build order
$extra_env = getenv('SPC_EXTRA_LIBS'); * @return array{
if (is_string($extra_env) && !empty($extra_env)) { * cflags: string,
$libs .= " {$extra_env}"; * ldflags: string,
} * libs: string
* }
// package frameworks */
if (SystemTarget::getTargetOS() === 'Darwin') { public function configWithResolvedPackages(array $resolved_packages): array
$libs .= " {$this->getFrameworksString($resolved_packages)}"; {
} $ldflags = $this->getLdflagsString();
$cflags = $this->getIncludesString($resolved_packages);
// C++ $libs = $this->getLibsString($resolved_packages, !$this->absolute_libs);
if ($this->hasCpp($resolved_packages)) {
$libcpp = SystemTarget::getTargetOS() === 'Darwin' ? '-lc++' : '-lstdc++'; // additional OS-specific libraries (e.g. macOS -lresolv)
$libs = str_replace($libcpp, '', $libs) . " {$libcpp}"; if ($extra_libs = SystemTarget::getRuntimeLibs()) {
} $libs .= " {$extra_libs}";
}
if ($this->libs_only_deps) {
// mimalloc must come first $extra_env = getenv('SPC_EXTRA_LIBS');
if (in_array('mimalloc', $resolved_packages) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) { if (is_string($extra_env) && !empty($extra_env)) {
$libs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $libs); $libs .= " {$extra_env}";
} }
return [
'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags), // package frameworks
'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags), if (SystemTarget::getTargetOS() === 'Darwin') {
'libs' => clean_spaces(getenv('LIBS') . ' ' . $libs), $libs .= " {$this->getFrameworksString($resolved_packages)}";
]; }
}
// C++
// embed if ($this->hasCpp($resolved_packages)) {
if (!$this->no_php) { $target_os = SystemTarget::getTargetOS();
$libs = "-lphp {$libs} -lc"; if ($target_os === 'Darwin') {
} $libcpp = '-lc++';
$libs = str_replace($libcpp, '', $libs) . " {$libcpp}";
$allLibs = getenv('LIBS') . ' ' . $libs; } elseif ($target_os !== 'Windows') {
// Linux and other Unix-like systems use libstdc++
// mimalloc must come first $libcpp = '-lstdc++';
if (in_array('mimalloc', $resolved_packages) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) { $libs = str_replace($libcpp, '', $libs) . " {$libcpp}";
$allLibs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $allLibs); }
} // Windows (MSVC): C++ runtime is linked automatically, no explicit lib needed
}
return [
'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags), if ($this->libs_only_deps) {
'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags), // mimalloc must come first
'libs' => clean_spaces($allLibs), if (in_array('mimalloc', $resolved_packages) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) {
]; $libs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $libs);
} }
return [
private function hasCpp(array $packages): bool 'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags),
{ 'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags),
foreach ($packages as $package) { 'libs' => clean_spaces(getenv('LIBS') . ' ' . $libs),
$lang = PackageConfig::get($package, 'lang', 'c'); ];
if ($lang === 'cpp') { }
return true;
} // embed
} if (!$this->no_php) {
return false; $libs = "-lphp {$libs} -lc";
} }
private function getIncludesString(array $packages): string $allLibs = getenv('LIBS') . ' ' . $libs;
{
$base = BUILD_INCLUDE_PATH; // mimalloc must come first
$includes = ["-I{$base}"]; if (in_array('mimalloc', $resolved_packages) && file_exists(BUILD_LIB_PATH . '/libmimalloc.a')) {
$allLibs = BUILD_LIB_PATH . '/libmimalloc.a ' . str_replace([BUILD_LIB_PATH . '/libmimalloc.a', '-lmimalloc'], ['', ''], $allLibs);
// link with libphp }
if (!$this->no_php) {
$includes = [ return [
...$includes, 'cflags' => clean_spaces(getenv('CFLAGS') . ' ' . $cflags),
"-I{$base}/php", 'ldflags' => clean_spaces(getenv('LDFLAGS') . ' ' . $ldflags),
"-I{$base}/php/main", 'libs' => clean_spaces($allLibs),
"-I{$base}/php/TSRM", ];
"-I{$base}/php/Zend", }
"-I{$base}/php/ext",
]; private function hasCpp(array $packages): bool
} {
foreach ($packages as $package) {
// parse pkg-configs $lang = PackageConfig::get($package, 'lang', 'c');
foreach ($packages as $package) { if ($lang === 'cpp') {
$pc = PackageConfig::get($package, 'pkg-configs', []); return true;
$pkg_config_path = getenv('PKG_CONFIG_PATH') ?: ''; }
$search_paths = array_filter(explode(SystemTarget::isUnix() ? ':' : ';', $pkg_config_path)); }
foreach ($pc as $file) { return false;
$found = false; }
foreach ($search_paths as $path) {
if (file_exists($path . "/{$file}.pc")) { private function getIncludesString(array $packages): string
$found = true; {
break; $base = BUILD_INCLUDE_PATH;
}
} // Windows MSVC uses /I flag instead of -I
if (!$found) { if (SystemTarget::getTargetOS() === 'Windows') {
throw new WrongUsageException("pkg-config file '{$file}.pc' for lib [{$package}] does not exist. Please build it first."); $includes = ["/I\"{$base}\""];
}
} // link with libphp
$pc_cflags = implode(' ', $pc); if (!$this->no_php) {
if ($pc_cflags !== '' && ($pc_cflags = PkgConfigUtil::getCflags($pc_cflags)) !== '') { $includes = [
$arr = explode(' ', $pc_cflags); ...$includes,
$arr = array_unique($arr); "/I\"{$base}\\php\"",
$arr = array_filter($arr, fn ($x) => !str_starts_with($x, 'SHELL:-Xarch_')); "/I\"{$base}\\php\\main\"",
$pc_cflags = implode(' ', $arr); "/I\"{$base}\\php\\TSRM\"",
$includes[] = $pc_cflags; "/I\"{$base}\\php\\Zend\"",
} "/I\"{$base}\\php\\ext\"",
} ];
$includes = array_unique($includes); }
return implode(' ', $includes); } else {
} $includes = ["-I{$base}"];
private function getLdflagsString(): string // link with libphp
{ if (!$this->no_php) {
return '-L' . BUILD_LIB_PATH; $includes = [
} ...$includes,
"-I{$base}/php",
private function getLibsString(array $packages, bool $use_short_libs = true): string "-I{$base}/php/main",
{ "-I{$base}/php/TSRM",
$lib_names = []; "-I{$base}/php/Zend",
$frameworks = []; "-I{$base}/php/ext",
];
foreach ($packages as $package) { }
// parse pkg-configs only for unix systems }
if (SystemTarget::isUnix()) {
// add pkg-configs libs // parse pkg-configs (only for Unix)
$pkg_configs = PackageConfig::get($package, 'pkg-configs', []); if (SystemTarget::isUnix()) {
$pkg_config_path = getenv('PKG_CONFIG_PATH') ?: ''; foreach ($packages as $package) {
$search_paths = array_filter(explode(':', $pkg_config_path)); $pc = PackageConfig::get($package, 'pkg-configs', []);
foreach ($pkg_configs as $pkg_config) { $pkg_config_path = getenv('PKG_CONFIG_PATH') ?: '';
$found = false; $search_paths = array_filter(explode(':', $pkg_config_path));
foreach ($search_paths as $path) { foreach ($pc as $file) {
if (file_exists($path . "/{$pkg_config}.pc")) { $found = false;
$found = true; foreach ($search_paths as $path) {
break; if (file_exists($path . "/{$file}.pc")) {
} $found = true;
} break;
if (!$found) { }
throw new WrongUsageException("pkg-config file '{$pkg_config}.pc' for lib [{$package}] does not exist. Please build it first."); }
} if (!$found) {
} throw new WrongUsageException("pkg-config file '{$file}.pc' for lib [{$package}] does not exist. Please build it first.");
$pkg_configs = implode(' ', $pkg_configs); }
if ($pkg_configs !== '') { }
// static libs with dependencies come in reverse order, so reverse this too $pc_cflags = implode(' ', $pc);
$pc_libs = array_reverse(PkgConfigUtil::getLibsArray($pkg_configs)); if ($pc_cflags !== '' && ($pc_cflags = PkgConfigUtil::getCflags($pc_cflags)) !== '') {
$lib_names = [...$lib_names, ...$pc_libs]; $arr = explode(' ', $pc_cflags);
} $arr = array_unique($arr);
} $arr = array_filter($arr, fn ($x) => !str_starts_with($x, 'SHELL:-Xarch_'));
// convert all static-libs to short names $pc_cflags = implode(' ', $arr);
$libs = array_reverse(PackageConfig::get($package, 'static-libs', [])); $includes[] = $pc_cflags;
foreach ($libs as $lib) { }
if (FileSystem::isRelativePath($lib)) { }
// check file existence }
if (!file_exists(BUILD_LIB_PATH . "/{$lib}")) { $includes = array_unique($includes);
throw new WrongUsageException("Library file '{$lib}' for lib [{$package}] does not exist in '" . BUILD_LIB_PATH . "'. Please build it first."); return implode(' ', $includes);
} }
$lib_names[] = $this->getShortLibName($lib);
} else { private function getLdflagsString(): string
$lib_names[] = $lib; {
} // Windows MSVC uses /LIBPATH flag instead of -L
} if (SystemTarget::getTargetOS() === 'Windows') {
// add frameworks for macOS return '/LIBPATH:"' . BUILD_LIB_PATH . '"';
if (SystemTarget::getTargetOS() === 'Darwin') { }
$frameworks = array_merge($frameworks, PackageConfig::get($package, 'frameworks', [])); return '-L' . BUILD_LIB_PATH;
} }
}
private function getLibsString(array $packages, bool $use_short_libs = true): string
// post-process {
$lib_names = array_filter($lib_names, fn ($x) => $x !== ''); $lib_names = [];
$lib_names = array_reverse(array_unique($lib_names)); $frameworks = [];
$frameworks = array_unique($frameworks);
foreach ($packages as $package) {
// process frameworks to short_name // parse pkg-configs only for unix systems
if (SystemTarget::getTargetOS() === 'Darwin') { if (SystemTarget::isUnix()) {
foreach ($frameworks as $fw) { // add pkg-configs libs
$ks = '-framework ' . $fw; $pkg_configs = PackageConfig::get($package, 'pkg-configs', []);
if (!in_array($ks, $lib_names)) { $pkg_config_path = getenv('PKG_CONFIG_PATH') ?: '';
$lib_names[] = $ks; $search_paths = array_filter(explode(':', $pkg_config_path));
} foreach ($pkg_configs as $pkg_config) {
} $found = false;
} foreach ($search_paths as $path) {
if (file_exists($path . "/{$pkg_config}.pc")) {
if (in_array('imap', $packages) && SystemTarget::getTargetOS() === 'Linux' && SystemTarget::getLibc() === 'glibc') { $found = true;
if (file_exists(BUILD_LIB_PATH . '/libcrypt.a')) { break;
$lib_names[] = '-lcrypt'; }
} }
} if (!$found) {
if (!$use_short_libs) { throw new WrongUsageException("pkg-config file '{$pkg_config}.pc' for lib [{$package}] does not exist. Please build it first.");
$lib_names = array_map(fn ($l) => $this->getFullLibName($l), $lib_names); }
} }
return implode(' ', $lib_names); $pkg_configs = implode(' ', $pkg_configs);
} if ($pkg_configs !== '') {
// static libs with dependencies come in reverse order, so reverse this too
private function getShortLibName(string $lib): string $pc_libs = array_reverse(PkgConfigUtil::getLibsArray($pkg_configs));
{ $lib_names = [...$lib_names, ...$pc_libs];
if (!str_starts_with($lib, 'lib') || !str_ends_with($lib, '.a')) { }
return BUILD_LIB_PATH . '/' . $lib; }
} // convert all static-libs to short names
// get short name $libs = array_reverse(PackageConfig::get($package, 'static-libs', []));
return '-l' . substr($lib, 3, -2); foreach ($libs as $lib) {
} if (FileSystem::isRelativePath($lib)) {
// check file existence
private function getFullLibName(string $lib): string if (!file_exists(BUILD_LIB_PATH . "/{$lib}")) {
{ throw new WrongUsageException("Library file '{$lib}' for lib [{$package}] does not exist in '" . BUILD_LIB_PATH . "'. Please build it first.");
if (!str_starts_with($lib, '-l')) { }
return $lib; $lib_names[] = $this->getShortLibName($lib);
} } else {
$libname = substr($lib, 2); $lib_names[] = $lib;
$staticLib = BUILD_LIB_PATH . '/' . "lib{$libname}.a"; }
if (file_exists($staticLib)) { }
return $staticLib; // add frameworks for macOS
} if (SystemTarget::getTargetOS() === 'Darwin') {
return $lib; $frameworks = array_merge($frameworks, PackageConfig::get($package, 'frameworks', []));
} }
}
private function getFrameworksString(array $extensions): string
{ // post-process
$list = []; $lib_names = array_filter($lib_names, fn ($x) => $x !== '');
foreach ($extensions as $extension) { $lib_names = array_reverse(array_unique($lib_names));
foreach (PackageConfig::get($extension, 'frameworks', []) as $fw) { $frameworks = array_unique($frameworks);
$ks = '-framework ' . $fw;
if (!in_array($ks, $list)) { // process frameworks to short_name
$list[] = $ks; if (SystemTarget::getTargetOS() === 'Darwin') {
} foreach ($frameworks as $fw) {
} $ks = '-framework ' . $fw;
} if (!in_array($ks, $lib_names)) {
return implode(' ', $list); $lib_names[] = $ks;
} }
} }
}
if (in_array('imap', $packages) && SystemTarget::getTargetOS() === 'Linux' && SystemTarget::getLibc() === 'glibc') {
if (file_exists(BUILD_LIB_PATH . '/libcrypt.a')) {
$lib_names[] = '-lcrypt';
}
}
if (!$use_short_libs) {
$lib_names = array_map(fn ($l) => $this->getFullLibName($l), $lib_names);
}
return implode(' ', $lib_names);
}
private function getShortLibName(string $lib): string
{
// Windows: library files are xxx.lib format (not libxxx.a)
if (SystemTarget::getTargetOS() === 'Windows') {
if (!str_ends_with($lib, '.lib')) {
return BUILD_LIB_PATH . '\\' . $lib;
}
// For Windows, return just the library filename (e.g., "libssl.lib")
return $lib;
}
// Unix: library files are libxxx.a format
if (!str_starts_with($lib, 'lib') || !str_ends_with($lib, '.a')) {
return BUILD_LIB_PATH . '/' . $lib;
}
// get short name (e.g., "libssl.a" -> "-lssl")
return '-l' . substr($lib, 3, -2);
}
private function getFullLibName(string $lib): string
{
// Windows: libraries don't use -l prefix, return as-is or with full path
if (SystemTarget::getTargetOS() === 'Windows') {
if (str_ends_with($lib, '.lib') && !str_contains($lib, '\\') && !str_contains($lib, '/')) {
// It's a short lib name like "libssl.lib", convert to full path
$fullPath = BUILD_LIB_PATH . '\\' . $lib;
if (file_exists($fullPath)) {
return $fullPath;
}
}
return $lib;
}
// Unix: convert -lxxx to full path
if (!str_starts_with($lib, '-l')) {
return $lib;
}
$libname = substr($lib, 2);
$staticLib = BUILD_LIB_PATH . '/' . "lib{$libname}.a";
if (file_exists($staticLib)) {
return $staticLib;
}
return $lib;
}
private function getFrameworksString(array $extensions): string
{
$list = [];
foreach ($extensions as $extension) {
foreach (PackageConfig::get($extension, 'frameworks', []) as $fw) {
$ks = '-framework ' . $fw;
if (!in_array($ks, $list)) {
$list[] = $ks;
}
}
}
return implode(' ', $list);
}
}

View File

@@ -138,6 +138,28 @@ CMAKE;
FileSystem::writeFile($cmake_find_dir . DIRECTORY_SEPARATOR . 'FindOpenSSL.cmake', <<<'CMAKE' FileSystem::writeFile($cmake_find_dir . DIRECTORY_SEPARATOR . 'FindOpenSSL.cmake', <<<'CMAKE'
# Custom FindOpenSSL.cmake wrapper for static-php-cli Windows builds. # Custom FindOpenSSL.cmake wrapper for static-php-cli Windows builds.
set(_spc_saved_module_path "${CMAKE_MODULE_PATH}")
list(REMOVE_ITEM CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}")
set(_spc_find_args "")
if(OpenSSL_FIND_VERSION)
list(APPEND _spc_find_args "${OpenSSL_FIND_VERSION}")
if(OpenSSL_FIND_VERSION_EXACT)
list(APPEND _spc_find_args EXACT)
endif()
endif()
if(OpenSSL_FIND_REQUIRED)
list(APPEND _spc_find_args REQUIRED)
endif()
if(OpenSSL_FIND_QUIETLY)
list(APPEND _spc_find_args QUIET)
endif()
find_package(OpenSSL ${_spc_find_args})
unset(_spc_find_args)
set(CMAKE_MODULE_PATH "${_spc_saved_module_path}")
unset(_spc_saved_module_path)
if(WIN32 AND (OpenSSL_FOUND OR OPENSSL_FOUND)) if(WIN32 AND (OpenSSL_FOUND OR OPENSSL_FOUND))
list(GET CMAKE_FIND_ROOT_PATH 0 _spc_buildroot) list(GET CMAKE_FIND_ROOT_PATH 0 _spc_buildroot)
# Normalize to forward slashes — backslash paths cause 'Invalid character # Normalize to forward slashes — backslash paths cause 'Invalid character