-
-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathBuilderBase.php
More file actions
551 lines (500 loc) · 18.4 KB
/
BuilderBase.php
File metadata and controls
551 lines (500 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
<?php
declare(strict_types=1);
namespace SPC\builder;
use SPC\exception\BuildFailureException;
use SPC\exception\InterruptException;
use SPC\exception\WrongUsageException;
use SPC\store\Config;
use SPC\store\FileSystem;
use SPC\store\LockFile;
use SPC\store\pkg\GoXcaddy;
use SPC\store\SourceManager;
use SPC\store\SourcePatcher;
use SPC\util\AttributeMapper;
abstract class BuilderBase
{
/** @var int Concurrency */
public int $concurrency = 1;
/** @var array<string, LibraryBase> libraries */
protected array $libs = [];
/** @var array<string, Extension> extensions */
protected array $exts = [];
/** @var array<int, string> extension names */
protected array $ext_list = [];
/** @var array<int, string> library names */
protected array $lib_list = [];
/** @var bool compile libs only (just mark it) */
protected bool $libs_only = false;
/** @var array<string, mixed> compile options */
protected array $options = [];
/** @var string patch point name */
protected string $patch_point = '';
/**
* Convert libraries to class
*
* @param array<string> $sorted_libraries Libraries to build (if not empty, must sort first)
*
* @internal
*/
abstract public function proveLibs(array $sorted_libraries);
/**
* Set-Up libraries
*/
public function setupLibs(): void
{
// build all libs
foreach ($this->libs as $lib) {
$starttime = microtime(true);
$status = $lib->setup($this->getOption('rebuild', false));
match ($status) {
LIB_STATUS_OK => logger()->info('lib [' . $lib::NAME . '] setup success, took ' . round(microtime(true) - $starttime, 2) . ' s'),
LIB_STATUS_ALREADY => logger()->notice('lib [' . $lib::NAME . '] already built'),
LIB_STATUS_INSTALL_FAILED => logger()->error('lib [' . $lib::NAME . '] install failed'),
default => logger()->warning('lib [' . $lib::NAME . '] build status unknown'),
};
if (in_array($status, [LIB_STATUS_BUILD_FAILED, LIB_STATUS_INSTALL_FAILED])) {
throw new BuildFailureException('Library [' . $lib::NAME . '] setup failed.');
}
}
}
/**
* Add library to build.
*
* @param LibraryBase $library Library object
*/
public function addLib(LibraryBase $library): void
{
$this->libs[$library::NAME] = $library;
}
/**
* Get library object by name.
*/
public function getLib(string $name): ?LibraryBase
{
return $this->libs[$name] ?? null;
}
/**
* Get all library objects.
*
* @return LibraryBase[]
*/
public function getLibs(): array
{
return $this->libs;
}
/**
* Add extension to build.
*/
public function addExt(Extension $extension): void
{
$this->exts[$extension->getName()] = $extension;
}
/**
* Get extension object by name.
*/
public function getExt(string $name): ?Extension
{
return $this->exts[$name] ?? null;
}
/**
* Get all extension objects.
*
* @return Extension[]
*/
public function getExts(bool $including_shared = true): array
{
if ($including_shared) {
return $this->exts;
}
return array_filter($this->exts, fn ($ext) => $ext->isBuildStatic());
}
/**
* Set libs only mode.
*
* @internal
*/
public function setLibsOnly(bool $status = true): void
{
$this->libs_only = $status;
}
/**
* Verify the list of "ext" extensions for validity and declare an Extension object to check the dependencies of the extensions.
*
* @internal
*/
public function proveExts(array $static_extensions, array $shared_extensions = [], bool $skip_check_deps = false, bool $skip_extract = false): void
{
// judge ext
foreach ($static_extensions as $ext) {
// if extension does not support static build, throw exception
if (!in_array('static', Config::getExtTarget($ext))) {
throw new WrongUsageException('Extension [' . $ext . '] does not support static build!');
}
}
foreach ($shared_extensions as $ext) {
// if extension does not support shared build, throw exception
if (!in_array('shared', Config::getExtTarget($ext)) && !in_array($ext, $shared_extensions)) {
throw new WrongUsageException('Extension [' . $ext . '] does not support shared build!');
}
}
if (!$skip_extract) {
$this->emitPatchPoint('before-php-extract');
SourceManager::initSource(sources: [$this->getPhpSrcName()], source_only: true);
$this->emitPatchPoint('after-php-extract');
if ($this->getPHPVersionID() >= 80000) {
$this->emitPatchPoint('before-micro-extract');
SourceManager::initSource(sources: ['micro'], source_only: true);
$this->emitPatchPoint('after-micro-extract');
}
$this->emitPatchPoint('before-exts-extract');
SourceManager::initSource(exts: [...$static_extensions, ...$shared_extensions]);
$this->emitPatchPoint('after-exts-extract');
// patch micro
SourcePatcher::patchMicro();
}
foreach ([...$static_extensions, ...$shared_extensions] as $extension) {
$class = AttributeMapper::getExtensionClassByName($extension) ?? Extension::class;
/** @var Extension $ext */
$ext = new $class($extension, $this);
if (in_array($extension, $static_extensions)) {
$ext->setBuildStatic();
}
if (in_array($extension, $shared_extensions)) {
$ext->setBuildShared();
}
$this->addExt($ext);
}
if ($skip_check_deps) {
return;
}
foreach ($this->getExts() as $ext) {
$ext->checkDependency();
}
$this->ext_list = [...$static_extensions, ...$shared_extensions];
}
/**
* Start to build PHP
*
* @param int $build_target Build target, see BUILD_TARGET_*
*/
abstract public function buildPHP(int $build_target = BUILD_TARGET_NONE);
/**
* Test PHP
*/
abstract public function testPHP(int $build_target = BUILD_TARGET_NONE);
/**
* Build shared extensions.
*/
public function buildSharedExts(): void
{
$lines = file(BUILD_BIN_PATH . '/php-config');
$extension_dir_line = null;
foreach ($lines as $key => $value) {
if (str_starts_with($value, 'extension_dir=')) {
$lines[$key] = 'extension_dir="' . BUILD_MODULES_PATH . '"' . PHP_EOL;
$extension_dir_line = $value;
break;
}
}
file_put_contents(BUILD_BIN_PATH . '/php-config', implode('', $lines));
FileSystem::replaceFileStr(BUILD_LIB_PATH . '/php/build/phpize.m4', 'test "[$]$1" = "no" && $1=yes', '# test "[$]$1" = "no" && $1=yes');
FileSystem::createDir(BUILD_MODULES_PATH);
try {
foreach ($this->getExts() as $ext) {
if (!$ext->isBuildShared()) {
continue;
}
$ext->buildShared();
}
} finally {
FileSystem::replaceFileLineContainsString(BUILD_BIN_PATH . '/php-config', 'extension_dir=', $extension_dir_line);
}
FileSystem::replaceFileLineContainsString(BUILD_BIN_PATH . '/php-config', 'extension_dir=', $extension_dir_line);
FileSystem::replaceFileStr(BUILD_LIB_PATH . '/php/build/phpize.m4', '# test "[$]$1" = "no" && $1=yes', 'test "[$]$1" = "no" && $1=yes');
}
/**
* Generate extension enable arguments for configure.
* e.g. --enable-mbstring
*/
public function makeStaticExtensionArgs(): string
{
$ret = [];
foreach ($this->getExts() as $ext) {
$arg = null;
if ($ext->isBuildShared() && !$ext->isBuildStatic()) {
if (
(Config::getExt($ext->getName(), 'type') === 'builtin' &&
!file_exists(SOURCE_PATH . '/php-src/ext/' . $ext->getName() . '/config.m4')) ||
Config::getExt($ext->getName(), 'build-with-php') === true
) {
$arg = $ext->getConfigureArg(true);
} else {
continue;
}
}
$arg ??= $ext->getConfigureArg();
logger()->info($ext->getName() . ' is using ' . $arg);
$ret[] = trim($arg);
}
logger()->debug('Using configure: ' . implode(' ', $ret));
return implode(' ', $ret);
}
/**
* Get libs only mode.
*/
public function isLibsOnly(): bool
{
return $this->libs_only;
}
/**
* Get PHP Version ID from php-src/main/php_version.h
*/
public function getPHPVersionID(): int
{
if (!file_exists(SOURCE_PATH . '/php-src/main/php_version.h')) {
throw new WrongUsageException('PHP source files are not available, you need to download them first');
}
$file = file_get_contents(SOURCE_PATH . '/php-src/main/php_version.h');
if (preg_match('/PHP_VERSION_ID (\d+)/', $file, $match) !== 0) {
return intval($match[1]);
}
throw new WrongUsageException('PHP version file format is malformed, please remove "./source/php-src" dir and download/extract again');
}
public function getPHPVersion(bool $exception_on_failure = true): string
{
if (!file_exists(SOURCE_PATH . '/php-src/main/php_version.h')) {
if (!$exception_on_failure) {
return 'unknown';
}
throw new WrongUsageException('PHP source files are not available, you need to download them first');
}
$file = file_get_contents(SOURCE_PATH . '/php-src/main/php_version.h');
if (preg_match('/PHP_VERSION "(.*)"/', $file, $match) !== 0) {
return $match[1];
}
if (!$exception_on_failure) {
return 'unknown';
}
throw new WrongUsageException('PHP version file format is malformed, please remove it and download again');
}
/**
* Get PHP version from archive file name.
*
* @param null|string $file php-*.*.*.tar.gz filename, read from lockfile if empty
*/
public function getPHPVersionFromArchive(?string $file = null): false|string
{
if ($file === null) {
$lock = LockFile::get($this->getPhpSrcName());
if ($lock === null) {
return false;
}
$file = LockFile::getLockFullPath($lock);
}
if (preg_match('/php-(\d+\.\d+\.\d+(?:RC\d+|alpha\d+|beta\d+)?)\.tar\.(?:gz|bz2|xz)/', $file, $match)) {
return $match[1];
}
return false;
}
public function getMicroVersion(): false|string
{
$file = FileSystem::convertPath(SOURCE_PATH . '/php-src/sapi/micro/php_micro.h');
if (!file_exists($file)) {
return false;
}
$content = file_get_contents($file);
$ver = '';
preg_match('/#define PHP_MICRO_VER_MAJ (\d)/m', $content, $match);
$ver .= $match[1] . '.';
preg_match('/#define PHP_MICRO_VER_MIN (\d)/m', $content, $match);
$ver .= $match[1] . '.';
preg_match('/#define PHP_MICRO_VER_PAT (\d)/m', $content, $match);
$ver .= $match[1];
return $ver;
}
/**
* Get build type name string to display.
*
* @param int $type Build target type
*/
public function getBuildTypeName(int $type): string
{
$ls = [];
if (($type & BUILD_TARGET_CLI) === BUILD_TARGET_CLI) {
$ls[] = 'cli';
}
if (($type & BUILD_TARGET_MICRO) === BUILD_TARGET_MICRO) {
$ls[] = 'micro';
}
if (($type & BUILD_TARGET_FPM) === BUILD_TARGET_FPM) {
$ls[] = 'fpm';
}
if (($type & BUILD_TARGET_EMBED) === BUILD_TARGET_EMBED) {
$ls[] = 'embed';
}
if (($type & BUILD_TARGET_FRANKENPHP) === BUILD_TARGET_FRANKENPHP) {
$ls[] = 'frankenphp';
}
if (($type & BUILD_TARGET_CGI) === BUILD_TARGET_CGI) {
$ls[] = 'cgi';
}
return implode(', ', $ls);
}
/**
* Get builder options (maybe changed by user)
*
* @param string $key Option key
* @param mixed $default If not exists, return this value
*/
public function getOption(string $key, mixed $default = null): mixed
{
return $this->options[$key] ?? $default;
}
/**
* Get all builder options
*/
public function getOptions(): array
{
return $this->options;
}
/**
* Set builder options if not exists.
*/
public function setOptionIfNotExist(string $key, mixed $value): void
{
if (!isset($this->options[$key])) {
$this->options[$key] = $value;
}
}
/**
* Set builder options.
*/
public function setOption(string $key, mixed $value): void
{
$this->options[$key] = $value;
}
public function getEnvString(array $vars = ['cc', 'cxx', 'ar', 'ld']): string
{
$env = [];
foreach ($vars as $var) {
$var = strtoupper($var);
if (getenv($var) !== false) {
$env[] = "{$var}=" . getenv($var);
}
}
return implode(' ', $env);
}
/**
* Get builder patch point name.
*/
public function getPatchPoint(): string
{
return $this->patch_point;
}
/**
* Validate libs and exts can be compiled successfully in current environment
*/
public function validateLibsAndExts(): void
{
foreach ($this->libs as $lib) {
$lib->validate();
}
foreach ($this->getExts() as $ext) {
$ext->validate();
}
}
public function emitPatchPoint(string $point_name): void
{
$this->patch_point = $point_name;
if (($patches = $this->getOption('with-added-patch', [])) === []) {
return;
}
foreach ($patches as $patch) {
try {
if (!file_exists($patch)) {
throw new WrongUsageException("Additional patch script file {$patch} not found!");
}
logger()->debug('Running additional patch script: ' . $patch);
require $patch;
} catch (InterruptException $e) {
if ($e->getCode() === 0) {
logger()->notice('Patch script ' . $patch . ' interrupted' . ($e->getMessage() ? (': ' . $e->getMessage()) : '.'));
} else {
logger()->error('Patch script ' . $patch . ' interrupted with error code [' . $e->getCode() . ']' . ($e->getMessage() ? (': ' . $e->getMessage()) : '.'));
}
exit($e->getCode());
} catch (\Throwable $e) {
logger()->critical('Patch script ' . $patch . ' failed to run.');
throw $e;
}
}
}
public function checkBeforeBuildPHP(int $rule): void
{
if (($rule & BUILD_TARGET_FRANKENPHP) === BUILD_TARGET_FRANKENPHP) {
if (!$this->getOption('enable-zts')) {
throw new WrongUsageException('FrankenPHP SAPI requires ZTS enabled PHP, build with `--enable-zts`!');
}
// frankenphp doesn't support windows, BSD is currently not supported by static-php-cli
if (!in_array(PHP_OS_FAMILY, ['Linux', 'Darwin'])) {
throw new WrongUsageException('FrankenPHP SAPI is only available on Linux and macOS!');
}
// frankenphp needs package go-xcaddy installed
if (!GoXcaddy::isInstalled()) {
global $argv;
throw new WrongUsageException("FrankenPHP SAPI requires the go-xcaddy package, please install it first: {$argv[0]} install-pkg go-xcaddy");
}
// frankenphp needs libxml2 lib on macos, see: https://github.com/php/frankenphp/blob/main/frankenphp.go#L17
if (PHP_OS_FAMILY === 'Darwin' && !$this->getLib('libxml2')) {
throw new WrongUsageException('FrankenPHP SAPI for macOS requires libxml2 library, please include the `xml` extension in your build.');
}
}
}
/**
* Get the php-src name to use for lock file lookups (supports version-specific names like php-src-8.2)
*/
protected function getPhpSrcName(): string
{
return getenv('SPC_PHP_SRC_NAME') ?: 'php-src';
}
/**
* Generate micro extension test php code.
*/
protected function generateMicroExtTests(): string
{
$php = "<?php\n\necho '[micro-test-start]' . PHP_EOL;\n";
foreach ($this->getExts(false) as $ext) {
$ext_name = $ext->getDistName();
if (!empty($ext_name)) {
$php .= "echo 'Running micro with {$ext_name} test' . PHP_EOL;\n";
$php .= "assert(extension_loaded('{$ext_name}'));\n\n";
}
}
$php .= "echo '[micro-test-end]';\n";
return $php;
}
protected function getMicroTestTasks(): array
{
return [
'micro_ext_test' => [
'content' => ($this->getOption('without-micro-ext-test') ? '<?php echo "[micro-test-start][micro-test-end]";' : $this->generateMicroExtTests()),
'conditions' => [
// program success
function ($ret) { return $ret === 0; },
// program returns expected output
function ($ret, $out) {
$raw_out = trim(implode('', $out));
return str_starts_with($raw_out, '[micro-test-start]') && str_ends_with($raw_out, '[micro-test-end]');
},
],
],
'micro_zend_bug_test' => [
'content' => ($this->getOption('without-micro-ext-test') ? '<?php echo "hello";' : file_get_contents(ROOT_DIR . '/src/globals/common-tests/micro_zend_mm_heap_corrupted.txt')),
'conditions' => [
// program success
function ($ret) { return $ret === 0; },
],
],
];
}
}