From 7d5806f33b0c7e19857ab06bf2585ca5b6702b23 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 4 Nov 2026 18:10:27 -0300 Subject: [PATCH] tools/openssl: publish headers without truncating active readers --- CODING-GUIDELINES.md | 6 ++ doc/releases/0.1.0.adoc | 1 + tools/openssl/build.py | 42 ++++++++-- tools/openssl/build_test.py | 148 +++++++++++++++++++++++++++++++++++- 4 files changed, 189 insertions(+), 8 deletions(-) diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index e529601d..3df9ef61 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -627,6 +627,12 @@ with the same source verification, compiler properties and configuration as the archive action. Header preparation neither builds archives nor runs the upstream suite and publishes no build or test proof. Full consumers depend on those headers and still require the complete archive action, including `alltests` when requested. +The archive action leaves identical headers untouched and replaces changed files +atomically before publishing archives. A compiler may already have mapped a header +from the preparation action; truncating that file during the archive action can +invalidate the mapping and crash the compiler. After successful header preparation, +that action refreshes its output timestamps without rewriting identical bytes, so +B2 can record that changed prerequisites have been processed. The compilation database reuses each dry-run result for dependency discovery rather than repeating the same full build-graph traversal. diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 593a40bc..88d6465f 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -55,6 +55,7 @@ None. [#webcpp-0-1-0-tools-and-build] == Tools and build +* Fixed parallel builds truncating OpenSSL headers while compilers read them. * Fixed driven-test execution and descendant cleanup on Windows. * Fixed driven-test executable reuse for Windows and WASI builds. * Improved lint preparation by separating OpenSSL headers from archive builds and upstream tests. diff --git a/tools/openssl/build.py b/tools/openssl/build.py index 9b6aaea6..19ede301 100644 --- a/tools/openssl/build.py +++ b/tools/openssl/build.py @@ -269,7 +269,11 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat if args.headers_only: run([*make, *jobs, 'build_generated'], cwd=build, env=env, log=output / 'headers.log') - copy_headers(scratch / 'source', build, output / 'include/openssl', windows) + headers = copy_headers(scratch / 'source', build, output / 'include/openssl', windows) + # This is B2's header-producing action. Even unchanged headers must + # become newer than its prerequisites, without disturbing mapped bytes. + for header in headers: + header.touch() print(f'OpenSSL {pin["version"]}: {args.platform}/{args.threading} headers generated ' f'in {time.monotonic() - started:.1f}s', flush=True) return @@ -302,9 +306,11 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat shutil.copyfile(symbols, output / symbols.name) else: run([*make, 'install_dev'], cwd=build, env=env, log=output / 'install.log') - # Copy headers before archives: consumers cannot compile against a - # different configuration while the new archives are being produced. - shutil.copytree(install / 'include', output / 'include', dirs_exist_ok=True) + # Headers were already prepared with this configuration. Keep identical + # files untouched: consumers can be compiling with them during this action. + # Publish any changed headers atomically before making archives available. + shutil.copytree(install / 'include', output / 'include', dirs_exist_ok=True, + copy_function=publish_header) names = ('libssl.lib', 'libcrypto.lib') if windows else ('libssl.a', 'libcrypto.a') for name in names: staged = output / (name + '.new') @@ -323,15 +329,37 @@ def build_source(args: argparse.Namespace, output: Path, pin: dict, scratch: Pat f'in {record["seconds"]:.1f}s', flush=True) -def copy_headers(source: Path, build: Path, output: Path, windows: bool) -> None: +def copy_headers(source: Path, build: Path, output: Path, windows: bool) -> list[Path]: """Publish the public headers in upstream install_dev's source/generated order.""" output.mkdir(parents=True, exist_ok=True) + headers = {} for directory in (source / 'include/openssl', build / 'include/openssl'): for header in directory.glob('*.h'): if not header.name.startswith('__DECC_'): - shutil.copyfile(header, output / header.name) + headers[header.name] = header if windows: - shutil.copyfile(source / 'ms/applink.c', output / 'applink.c') + headers['applink.c'] = source / 'ms/applink.c' + for name, header in headers.items(): + publish_header(header, output / name) + return [output / name for name in headers] + + +def publish_header(source: str | Path, destination: str | Path) -> str: + """Replace changed headers without truncating files a compiler may have mapped.""" + source, destination = Path(source), Path(destination) + if destination.is_file() and source.read_bytes() == destination.read_bytes(): + return str(destination) + with tempfile.NamedTemporaryFile(prefix=f'.{destination.name}.', + dir=destination.parent, delete=False) as stream: + staged = Path(stream.name) + try: + # Retain source permissions, but give changed build outputs a fresh + # timestamp rather than the checkout's potentially older timestamp. + shutil.copy(source, staged) + staged.replace(destination) + finally: + staged.unlink(missing_ok=True) + return str(destination) if __name__ == '__main__': diff --git a/tools/openssl/build_test.py b/tools/openssl/build_test.py index a9bb4805..a80d758d 100644 --- a/tools/openssl/build_test.py +++ b/tools/openssl/build_test.py @@ -4,13 +4,17 @@ # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Check build orchestration at the unavailable native Windows tool boundary.""" +"""Check header publication and orchestration at unavailable tool boundaries.""" from __future__ import annotations +import argparse +import builtins import hashlib import json import os from pathlib import Path +import shutil +import stat import subprocess import sys import tempfile @@ -21,6 +25,148 @@ from source import inventory_digest +class HeaderPublicationTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix='openssl publication ') + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.source = self.root / 'source' + self.generated = self.root / 'generated' + self.output = self.root / 'output' + self.header = self.output / 'include/openssl/configuration.h' + self.original = b'/* configured header */\n' * 8192 + for directory in (self.source, self.generated, self.output): + (directory / 'include/openssl').mkdir(parents=True) + (self.source / 'include/openssl/configuration.h').write_bytes(b'/* source fallback */\n') + (self.generated / 'include/openssl/configuration.h').write_bytes(self.original) + self.header.write_bytes(self.original) + + def publish(self, full: bool) -> None: + scratch = Path(tempfile.mkdtemp(dir=self.root)) + shutil.copytree(self.source, scratch / 'source') + + def command(command: list[str], *, cwd: Path, env: dict, log: Path, + timeout: float = 600) -> None: + log.write_text('completed\n') + if command[-1] == 'build_generated': + shutil.copytree(self.generated / 'include', cwd / 'include') + if command[-1] == 'install_dev': + shutil.copytree(self.generated / 'include', scratch / 'install/include') + (scratch / 'install/lib').mkdir() + for name in ('libssl.a', 'libcrypto.a'): + (scratch / 'install/lib' / name).write_bytes(b'archive fixture\n') + + args = argparse.Namespace(cc=sys.executable, ar='ar', platform='wasi', + threading='single', variant='release', test=False, + headers_only=not full, flags=['--target=wasm32-wasip3']) + with patch.object(build, 'run', side_effect=command): + build.build_source(args, self.output, + {'version': 'fixture', 'source_date_epoch': 1700000000}, scratch) + + def test_full_build_keeps_identical_headers_inode_timestamp_and_permissions(self) -> None: + self.header.chmod(0o644) + os.utime(self.header, ns=(1700000000000000000, 1700000000000000000)) + before = self.header.stat() + self.publish(True) + after = self.header.stat() + self.assertEqual(self.header.read_bytes(), self.original) + self.assertEqual((after.st_ino, after.st_mtime_ns, after.st_mode), + (before.st_ino, before.st_mtime_ns, before.st_mode)) + + def test_header_action_refreshes_identical_headers_without_replacing_them(self) -> None: + os.utime(self.header, ns=(1700000000000000000, 1700000000000000000)) + before = self.header.stat() + self.publish(False) + after = self.header.stat() + self.assertEqual(self.header.read_bytes(), self.original) + self.assertEqual((after.st_ino, after.st_mode), (before.st_ino, before.st_mode)) + self.assertGreater(after.st_mtime_ns, before.st_mtime_ns) + + @unittest.skipIf(sys.platform == 'win32', 'POSIX permits replacement of mapped files') + def test_republication_keeps_existing_mapped_readers_valid(self) -> None: + # Pause at the real write-open boundary, before shutil copies any bytes. + # Truncating the published inode here used to kill this reader with SIGBUS. + for full, changed in ((False, False), (False, True), (True, False), (True, True)): + with self.subTest(full=full, changed=changed): + self.header.write_bytes(self.original) + replacement = b'/* updated configuration */\n' * 8192 if changed else self.original + (self.generated / 'include/openssl/configuration.h').write_bytes(replacement) + reader = subprocess.Popen( + [sys.executable, '-u', '-c', + 'import hashlib, mmap, resource, signal, sys; signal.alarm(10); ' + 'resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); ' + 'f = open(sys.argv[1], "rb"); ' + 'm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ); ' + 'print("mapped", flush=True); sys.stdin.readline(); ' + 'print(hashlib.sha256(m).hexdigest())', str(self.header)], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True) + original_open = builtins.open + result = [] + + def inspect_open(path, mode='r', *args, **kwargs): + stream = original_open(path, mode, *args, **kwargs) + if (isinstance(path, (str, Path)) and Path(path) == self.header + and mode == 'wb' and not result): + result.append(reader.communicate(input='read\n', timeout=15)) + return stream + + try: + assert reader.stdout is not None + self.assertEqual(reader.stdout.readline(), 'mapped\n') + with patch('builtins.open', side_effect=inspect_open): + self.publish(full) + if not result: + result.append(reader.communicate(input='read\n', timeout=15)) + self.assertEqual(reader.returncode, 0, result[0][1]) + self.assertEqual(result[0][0].strip(), + hashlib.sha256(self.original).hexdigest()) + self.assertEqual(self.header.read_bytes(), replacement) + finally: + if reader.poll() is None: + reader.kill() + reader.communicate(timeout=15) + + def test_changed_headers_keep_source_permissions(self) -> None: + source = self.generated / 'include/openssl/configuration.h' + source.write_bytes(b'/* updated configuration */\n') + source.chmod(0o644) + self.header.chmod(0o600) + self.publish(False) + self.assertEqual(self.header.read_bytes(), source.read_bytes()) + self.assertEqual(stat.S_IMODE(self.header.stat().st_mode), + stat.S_IMODE(source.stat().st_mode)) + + def test_changed_headers_receive_a_new_build_timestamp(self) -> None: + # Source headers can predate the recipe. Retaining their old timestamp + # would make B2 rerun header generation and rebuild archives forever. + source = self.generated / 'include/openssl/configuration.h' + source.write_bytes(b'/* updated configuration */\n') + os.utime(source, ns=(1700000000000000000, 1700000000000000000)) + self.publish(True) + self.assertGreater(self.header.stat().st_mtime_ns, source.stat().st_mtime_ns) + + def test_failed_copy_leaves_the_published_header_and_no_partial_files(self) -> None: + (self.generated / 'include/openssl/configuration.h').write_bytes(b'/* changed */\n') + original_copy = shutil.copyfile + + def fail_copy(source, destination, *, follow_symlinks=True): + if Path(destination).parent == self.header.parent: + Path(destination).write_bytes(b'partial') + raise OSError('interrupted header copy') + return original_copy(source, destination, follow_symlinks=follow_symlinks) + + for full in (False, True): + with self.subTest(full=full), patch.object(build.shutil, 'copyfile', + side_effect=fail_copy): + with self.assertRaisesRegex(OSError, 'interrupted header copy'): + self.publish(full) + self.assertEqual(self.header.read_bytes(), self.original) + self.assertEqual(list(self.header.parent.iterdir()), [self.header]) + for name in ('libssl.a', 'libcrypto.a', 'build.json'): + self.assertFalse((self.output / name).exists(), name) + + class UpstreamResultsTest(unittest.TestCase): def test_skipped_preparation_does_not_hide_the_full_suite_summary(self) -> None: log = ('00-prep_fipsmodule_cnf.t .. skipped: FIPS is disabled\n'