diff --git a/.github/workflows/library.yml b/.github/workflows/library.yml index 89c4d3da..21f867b2 100644 --- a/.github/workflows/library.yml +++ b/.github/workflows/library.yml @@ -34,7 +34,10 @@ # emscripten lane emsdk and Node, which runs its programs, and a lane whose entry # says external the libraries its libraries need, built with the lane's compilers. # GCC 14 and Clang 18 run their b2 in a container with no network but the loopback, -# whose image is prepared separately and pulled by its immutable digest. +# whose image is prepared separately and pulled by its immutable digest. A lane, an +# own lane but OpenSSL's upstream suite and the lint restore the OpenSSL and +# libdatachannel configurations they built before, which b2 -a keeps, and save +# those their cache lacks (tools/ci/actions/third-party). # own-lanes one job per own lane of a library and target it runs on, which runs the lane # in every directory that declares it there. One that names no target, as an # oracle, runs on Linux x86-64 with Clang 18, and with Node when it runs the @@ -256,6 +259,14 @@ jobs: - if: matrix.container uses: ./tools/ci/actions/container + # The configurations of OpenSSL and libdatachannel this lane built before, which its b2 -a + # keeps; it saves those it builds that its cache does not hold. + - name: Restore the third-party builds + uses: ./tools/ci/actions/third-party + with: + step: restore + job: ${{ matrix.id }} + # The lane registers its toolset in .local/user-config.jam, prints its b2 command and runs # it; Windows's Python is python. - name: Lane @@ -265,6 +276,13 @@ jobs: PYTHON: ${{ runner.os == 'Windows' && 'python' || 'python3' }} run: '"$PYTHON" tools/ci/matrix.py lane "$LANE"' + - name: Save the third-party builds + if: ${{ !cancelled() }} + uses: ./tools/ci/actions/third-party + with: + step: save + job: ${{ matrix.id }} + - name: Upload the lane's XML if: always() && steps.lane.outputs.xml != '' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -370,6 +388,15 @@ jobs: python3 libs/beast/test/applications/inventory_test.py python3 libs/beast/test/applications/driver_test.py + # As a lane's, except where the lane runs OpenSSL's upstream suite, which a configuration + # restored from the cache would not run again. + - name: Restore the third-party builds + if: ${{ !startsWith(matrix.lane, 'openssl-upstream') }} + uses: ./tools/ci/actions/third-party + with: + step: restore + job: own-${{ matrix.id || matrix.name }} + # It registers its toolset in .local/user-config.jam, prints its b2 command and runs it. - name: Own lane id: lane @@ -377,6 +404,13 @@ jobs: LANE: ${{ toJSON(matrix) }} run: python3 tools/ci/matrix.py own-lane "$LANE" + - name: Save the third-party builds + if: ${{ !cancelled() && !startsWith(matrix.lane, 'openssl-upstream') }} + uses: ./tools/ci/actions/third-party + with: + step: save + job: own-${{ matrix.id || matrix.name }} + - name: Upload the lane's XML if: always() && steps.lane.outputs.xml != '' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -554,6 +588,14 @@ jobs: # builds, with the toolset of that target: a WASI dry run generates the bindings its # commands include, and an emscripten command is analysed with the sysroot of the cache the # emsdk action restores. + # + # The configured headers of OpenSSL and libdatachannel, which each shard generates for its + # compilation database, come from the lint's cache, which the first shard saves. + - name: Restore the third-party headers + uses: ./tools/ci/actions/third-party + with: + step: restore + job: lint - name: Lint env: SHARD: ${{ matrix.shard }}/${{ strategy.job-total }} @@ -566,6 +608,12 @@ jobs: python3 tools/ci/matrix.py register "${toolsets[@]}" tools/lint/lint.sh --clang-format .local/wasi-sdk/bin/clang-format \ --clang-tidy .local/wasi-sdk/bin/clang-tidy --shard "$SHARD" + - name: Save the third-party headers + if: ${{ !cancelled() && matrix.shard == 1 }} + uses: ./tools/ci/actions/third-party + with: + step: save + job: lint tools: name: Tests of the tools (${{ matrix.shard }}/${{ strategy.job-total }}) diff --git a/AGENTS.md b/AGENTS.md index fc2f2f35..b1f66632 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -281,7 +281,10 @@ Jamroot is its build configuration, and `libs/` is its repository. - for native or WASIp2/P3 guest TLS: Python 3, Perl, Make (nmake on Windows), the selected compiler and `third_party/libs/openssl`, initialized with `git submodule update --init third_party/libs/openssl`. B2 builds the pinned - OpenSSL sources and matching generated headers. Native Trystero's + OpenSSL sources and matching generated headers, each configuration once, in + `bin/third_party/openssl/config-`, which its inputs and its command + name and `b2 -a` keeps, as it does libdatachannel's: removing the directory + builds it again (`CODING-GUIDELINES.md` chapter 15). Native Trystero's libdatachannel uses that same provider. Neither `OPENSSL_ROOT` nor `LIBDATACHANNEL_ROOT` selects a separate installed copy. Source archives contain the required sources and do not require Git for these builds. diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 43264225..1fe65f28 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -7972,6 +7972,22 @@ The closure record distinguishes the baseline CI from validation of later change archives for one configuration, two OpenSSL copies in one program. Source: `docs/superpowers/plans/2026-10-16-openssl-source-build.md`, `docs/superpowers/plans/2026-10-16-cobalt-ssl.md` (superproject). +- **Each configuration of OpenSSL and libdatachannel is built once, in + `bin/third_party//config-`, named by the bytes of its inputs + (its scripts and its pin) and by its build command, and never again, `b2 -a` + included: its outputs are `NOUPDATE`.** A directory that exists holds the + build of exactly those inputs and that command, so consumers whose + properties differ only in what the command leaves out, as + `exception-handling` for OpenSSL's C, share it, and the CI restores a lane's + directories from its cache (`tools/ci/actions/third-party`) and builds only + those the cache lacks. A consumer depends on the selection of its + configuration, `-config-.selected` in its own variant directory, + which is written when the configuration changes, to a new one or back to one + built earlier, so the consumer is built again. Removing a configuration's + directory builds it again. A checkout that differs from its pin stops b2 + before any build, by the library's own `check_checkout`. + Source: `tools/webcpp-third-party.jam`, `tools/third_party_build.py` + (superproject). - **A dated curl export of Mozilla's root certificates (2026-09-25, 121 CAs) is checked in under `third_party/ca_certificates`, with a manifest of its URL, SHA-256 and DER fingerprints and its MPL-2.0 licence, verified and diff --git a/doc/releases/0.1.0.adoc b/doc/releases/0.1.0.adoc index 008e4dda..ec939e33 100644 --- a/doc/releases/0.1.0.adoc +++ b/doc/releases/0.1.0.adoc @@ -67,7 +67,7 @@ None. == Tools and build * Fixed emscripten release programs linking unoptimized; they now link at `-O3`. -* Fixed WASI release programs carrying wasi-sdk's libc++ debug information, most of their size; they now link with `--strip-debug`. +* Fixed WASI release programs carrying wasi-sdk's `libc++` debug information, most of their size; they now link with `--strip-debug`. * Fixed clean CMake consumer audits rejecting system libraries and phony dependency rules. * Changed CI to consume verified prepared environments without rebuilding images in PR jobs. * Added verified archive caches and isolated container availability from unrelated CI lanes. @@ -105,6 +105,8 @@ None. * Added source-built OpenSSL and Cobalt SSL targets for WASIp2. * Added explicit browser pthread profiles with main-thread handoff tests. * Fixed the lint's clang-tidy stopping at Boost.Unordered on arm64 hosts. +* Changed OpenSSL and libdatachannel to build each configuration once, in a directory its inputs name, which b2 -a keeps. +* Added the CI's cache of the OpenSSL and libdatachannel builds, which a lane reuses until an input changes. * Changed lint to verify WASIp3 ABI snapshots before excluding upstream headers. * Fixed embedded CA headers using an unowned namespace and include path. * Added source-built Boost.Context for native stackful coroutine applications. diff --git a/third_party/Jamfile b/third_party/Jamfile index 142522c9..fb31922d 100644 --- a/third_party/Jamfile +++ b/third_party/Jamfile @@ -137,27 +137,33 @@ alias bips : : @bips-checked-out : : explicit bips ; # OpenSSL uses its upstream Configure/Make source manifest. The bridge emits -# static archives and matching generated headers in B2's variant directory. +# static archives and matching generated headers in the directory of their +# configuration, bin/third_party/openssl/config-, named by the bytes of +# the inputs below and the build command (tools/webcpp-third-party.jam). import webcpp-openssl ; -.openssl-headers = [ glob libs/openssl/include/openssl/*.h ] ; +# OpenSSL's VMS prologue and epilogue, __DECC_INCLUDE_*.H, are no header of the +# install (tools/openssl/build.py leaves them out). b2's glob, which ignores +# case on Windows, would declare them outputs never made, which would generate +# the headers again on every run. +.openssl-headers = [ glob libs/openssl/include/openssl/*.h + : libs/openssl/include/openssl/__DECC_* ] ; .openssl-templates = [ glob libs/openssl/include/openssl/*.h.in ] ; webcpp-openssl.declare $(WEBCPP_ROOT) : $(.openssl-headers:B).h $(.openssl-templates:B) - : ../tools/openssl/build.py ../tools/openssl/source.py ../tools/openssl/wasip3.conf - ../tools/openssl/msvc.conf - ../tools/openssl/pin.json [ glob-tree-ex libs/openssl : *.c *.h *.in *.pl *.pm *.t *.S *.s - *.conf *.num build.info Configure VERSION.dat *.tmpl : .git ] ; + : tools/openssl/build.py tools/openssl/source.py tools/openssl/wasip3.conf + tools/openssl/msvc.conf tools/openssl/pin.json ; explicit openssl ; # libdatachannel and its pinned nested dependencies use upstream CMake, with -# the exact OpenSSL archives above. Each archive reaches the program once. +# the exact OpenSSL archives above. Each archive reaches the program once. Its +# configurations are named as OpenSSL's are, by the bytes of the inputs below, +# the build command and OpenSSL's configuration. import webcpp-libdatachannel ; .libdatachannel-headers = [ glob libs/libdatachannel/include/rtc/*.hpp libs/libdatachannel/include/rtc/*.h ] ; webcpp-libdatachannel.declare $(WEBCPP_ROOT) : $(.libdatachannel-headers:BS) - : ../tools/libdatachannel/build.py ../tools/libdatachannel/source.py - ../tools/libdatachannel/pin.json ../tools/libdatachannel/msvc.cmake - [ glob-tree-ex libs/libdatachannel : *.c *.cpp *.h *.hpp *.in *.cmake CMakeLists.txt : .git ] ; + : tools/libdatachannel/build.py tools/libdatachannel/source.py + tools/libdatachannel/pin.json tools/libdatachannel/msvc.cmake ; explicit libdatachannel ; # A dated, digest-pinned Mozilla/curl data export, not third-party source code. diff --git a/tools/ci/actions/third-party/action.yml b/tools/ci/actions/third-party/action.yml new file mode 100644 index 00000000..67ba09dc --- /dev/null +++ b/tools/ci/actions/third-party/action.yml @@ -0,0 +1,71 @@ +# Copyright (c) 2026 WebCpp.org +# +# 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) + +name: Third-party builds +description: >- + Restores, before a job's b2, and saves, after it, the configurations of the source-built OpenSSL + and libdatachannel under bin/third_party, which B2 names by the bytes of their inputs and by + their build command and never builds again, b2 -a included (tools/webcpp-third-party.jam): a job + builds only the configurations its cache does not hold. The cache is the job's own, on its runner + image, and starts afresh when an input of those builds or a pinned toolchain changes. A job saves + it only when it built a configuration the cache did not hold, under the hash of the + configurations' names. + +inputs: + step: + description: restore, before the job's b2, or save, after it. + required: true + job: + description: What keys the cache, such as the lane's id. + required: true + +runs: + using: composite + steps: + - name: Cache key + id: key + shell: bash + env: + JOB: ${{ inputs.job }} + INPUTS: >- + ${{ hashFiles('tools/openssl/build.py', 'tools/openssl/source.py', + 'tools/openssl/pin.json', 'tools/openssl/msvc.conf', 'tools/openssl/wasip3.conf', + 'tools/libdatachannel/build.py', 'tools/libdatachannel/source.py', + 'tools/libdatachannel/pin.json', 'tools/libdatachannel/msvc.cmake', + 'tools/third_party_build.py', 'tools/webcpp-third-party.jam', 'tools/webcpp-openssl.jam', + 'tools/webcpp-libdatachannel.jam', 'tools/ci/actions/third-party/**', + 'tools/ci/actions/gcc/**', 'tools/ci/actions/wasi-sdk/**', 'tools/ci/actions/emsdk/**', + 'tools/ci/actions/container/**', 'tools/ci/container/**') }} + run: bash tools/ci/actions/third-party/key.sh + + - name: Restore the third-party builds + id: restore + if: inputs.step == 'restore' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + bin/third_party/openssl + bin/third_party/libdatachannel + key: ${{ steps.key.outputs.prefix }} + restore-keys: ${{ steps.key.outputs.prefix }} + + - name: Record the restored builds + if: inputs.step == 'restore' + shell: bash + env: + RESTORED: ${{ steps.restore.outputs.cache-matched-key }} + run: echo "WEBCPP_THIRD_PARTY_RESTORED=$RESTORED" >> "$GITHUB_ENV" + + - name: Save the third-party builds + if: >- + inputs.step == 'save' && steps.key.outputs.built == 'true' + && steps.key.outputs.key != env.WEBCPP_THIRD_PARTY_RESTORED + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + bin/third_party/openssl + bin/third_party/libdatachannel + key: ${{ steps.key.outputs.key }} diff --git a/tools/ci/actions/third-party/key.sh b/tools/ci/actions/third-party/key.sh new file mode 100644 index 00000000..03be2e68 --- /dev/null +++ b/tools/ci/actions/third-party/key.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Copyright (c) 2026 WebCpp.org +# +# 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) + +# The cache key of tools/ci/actions/third-party, which it computes before the job's b2, to +# restore, and after it, to save. +# +# Usage, from the superproject's root, with JOB, what keys the cache (such as the lane's id), +# INPUTS, the hash of the files the builds read, and the variables a runner sets (ImageOS, +# ImageVersion, GITHUB_OUTPUT): +# +# key.sh writes to GITHUB_OUTPUT the prefix, the job's cache on its runner image for those +# inputs, whose most recent entry a job restores; the key, the prefix and a hash of the +# names of the configurations under bin/third_party, under which a job saves them; and +# built, whether there is any. +# +# A checkout without bin/third_party, a fresh one or that of a job whose programs use neither +# library, has no configuration, and nothing to save. Bash 3.2, the macOS runners', runs it too. +set -euo pipefail + +if [ -z "${JOB-}" ] || [ -z "${INPUTS-}" ]; then + printf 'usage: key.sh, with JOB and INPUTS set\n' >&2 + exit 2 +fi + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# The functions every action shares: digest. +# shellcheck source=SCRIPTDIR/../../helpers.sh +. "${here}/../../helpers.sh" + +# The runner image's compilers, and the job's: a key holds no comma, which a job's name may. +prefix="third-party-v1-${JOB//[^A-Za-z0-9._-]/-}-${ImageOS:-image}-${ImageVersion:-0}-" +prefix="${prefix}${INPUTS:0:16}-" + +# The configurations' directories, of either library, whose own directory may not exist. +shopt -s nullglob +configurations=(bin/third_party/openssl/config-*/ bin/third_party/libdatachannel/config-*/) +# Given no file, digest hashes its standard input, as cat reads it. +# shellcheck disable=SC2119 +names="$(printf '%s\n' ${configurations[@]+"${configurations[@]}"} | digest)" +built=false +if [ "${#configurations[@]}" -gt 0 ]; then + built=true +fi + +printf 'prefix=%s\nkey=%s%s\nbuilt=%s\n' "${prefix}" "${prefix}" "${names:0:16}" "${built}" \ + >> "${GITHUB_OUTPUT}" diff --git a/tools/ci/actions_test.py b/tools/ci/actions_test.py index 55434d57..11950683 100755 --- a/tools/ci/actions_test.py +++ b/tools/ci/actions_test.py @@ -43,7 +43,10 @@ only parses (the input libraries: 'false', under the same key), the sysroot alone, a cache the action never saves. The node action keys npm's cache on the lock file of every directory a job runs npm ci in: tools/doc, tools/lint, every -library's oracle and the site. Nothing is fetched +library's oracle and the site. The third-party action's key.sh keys a job's cache of the +OpenSSL and libdatachannel configurations by the job, its runner image and the builds' inputs, +and the configurations under bin/third_party, which a fresh checkout, or either library alone, +lacks, under the Bash on PATH and /bin/bash, macOS's 3.2. Nothing is fetched from the network: the downloads are file:// URLs or a server of the test's own on the loopback, git is a stand-in, and install.sh runs against a download.sh that only says it was called, or that hands it a stand-in archive. Run with the @@ -75,6 +78,7 @@ WASI_WIT = CI / 'actions/wasi-wit/install.sh' WASI_SDK = CI / 'actions/wasi-sdk/install.sh' EMSDK = CI / 'actions/emsdk/install.sh' +THIRD_PARTY = CI / 'actions/third-party/key.sh' HELPERS = CI / 'helpers.sh' # What the stand-in download.sh prints, and its exit status: install.sh got past its guards. @@ -1475,8 +1479,8 @@ def helper(call: str, **variables: str) -> str: 'gcc-14 (stand-in) 14.2.0\ng++-14 (stand-in) 14.2.0\n') assert helper('compiler_identity', CC='gcc-14') == 'gcc-14 (stand-in) 14.2.0\n' assert helper('compiler_identity', ImageOS='win22', ImageVersion='1') == 'default win22 1\n' - # Each action sources it, and defines none of the four itself. - for script in sorted(CI.glob('actions/*/install.sh')): + # Each action's script sources it, and defines none of the four itself. + for script in sorted(CI.glob('actions/*/*.sh')): text = script.read_text() for name in ('digest', 'mixed', 'configuration', 'compiler_identity'): assert f'\n{name}() {{' not in text, (script, name) @@ -1484,8 +1488,84 @@ def helper(call: str, **variables: str) -> str: assert '. "${here}/../../helpers.sh"' in text, script +def bashes() -> list[str]: + """Each bash an action's step may run in here: the one on PATH, and /bin/bash, which is Bash + 3.2 on macOS, the one the macOS runners run a step with.""" + found = {} + for candidate in (shutil.which('bash'), '/bin/bash'): + if candidate and os.access(candidate, os.X_OK): + found.setdefault(os.path.realpath(candidate), candidate) + return list(found.values()) + + +def third_party_key(root: Path, bash: str, job: str = 'gcc-15', + **variables: str) -> tuple[subprocess.CompletedProcess, dict[str, str]]: + """Runs the third-party action's key step in root, a checkout, as the action does, and + returns what it wrote to GITHUB_OUTPUT.""" + output = root / 'github-output' + output.unlink(missing_ok=True) + environment = {**os.environ, 'JOB': job, 'INPUTS': 'fd7fb185cbfac59a' + '0' * 48, + 'ImageOS': 'ubuntu26', 'ImageVersion': '20261111.196', + 'GITHUB_OUTPUT': str(output), **variables} + result = subprocess.run([bash, str(THIRD_PARTY)], capture_output=True, text=True, + check=False, cwd=root, env=environment) + written = (dict(line.split('=', 1) for line in output.read_text().splitlines()) + if output.exists() else {}) + return result, written + + +def test_third_party_key_of_a_checkout_without_builds(scratch: Path) -> None: + # A fresh checkout has no bin/third_party, nor has a job whose programs use neither library: + # neither is an error, and neither has a configuration to save. A key holds no comma, which + # a job's name may, nor a space. + for bash in bashes(): + result, written = third_party_key(scratch, bash, 'own-Own lane (asio, tls)') + assert result.returncode == 0, (bash, result.returncode, result.stderr) + prefix = 'third-party-v1-own-Own-lane--asio--tls--ubuntu26-20261111.196-fd7fb185cbfac59a-' + assert written['prefix'] == prefix, (bash, written) + assert re.fullmatch(re.escape(prefix) + '[0-9a-f]{16}', written['key']), (bash, written) + assert written['built'] == 'false', (bash, written) + # Without the job or the inputs, the key would name no cache. + for missing in ('JOB', 'INPUTS'): + result, written = third_party_key(scratch, bashes()[0], **{missing: ''}) + assert result.returncode == 2, (missing, result.returncode, result.stderr) + assert 'usage: key.sh' in result.stderr, (missing, result.stderr) + assert written == {}, (missing, written) + # The action keys both its steps with the script, which the tests run. + action = (THIRD_PARTY.parent / 'action.yml').read_text() + steps = {step.split('\n', 1)[0]: step for step in action.split(' - name: ')[1:]} + assert 'run: bash tools/ci/actions/third-party/key.sh\n' in steps['Cache key'], ( + steps['Cache key']) + + +def test_third_party_key_names_the_configurations(scratch: Path) -> None: + # The key is the prefix and a hash of the names of the configurations, which either + # library's directory may hold alone: a job saves its cache under a new key when it built a + # configuration its restored entry did not hold. + openssl = scratch / 'bin/third_party/openssl' + libdatachannel = scratch / 'bin/third_party/libdatachannel' + for bash in bashes(): + keys = [] + shutil.rmtree(scratch / 'bin', ignore_errors=True) + for made in (openssl / 'config-1', libdatachannel / 'config-2', openssl / 'config-1'): + if made == libdatachannel / 'config-2': + shutil.rmtree(openssl) + made.mkdir(parents=True) + result, written = third_party_key(scratch, bash) + assert result.returncode == 0, (bash, made, result.returncode, result.stderr) + assert written['built'] == 'true', (bash, made, written) + assert written['key'].startswith(written['prefix']), (bash, written) + # The same configurations give the same key, and a file there is no configuration. + (made.parent / 'config-stray').write_text('stray\n') + assert third_party_key(scratch, bash)[1] == written, (bash, made) + keys.append(written['key']) + assert len(set(keys)) == 3, (bash, keys) + + CASES: list[Callable[[Path], None]] = [ test_the_shared_helpers, + test_third_party_key_of_a_checkout_without_builds, + test_third_party_key_names_the_configurations, test_a_pinned_download_is_kept, test_another_digest_leaves_no_file, test_a_failed_download_exits_1_and_leaves_no_file, diff --git a/tools/lint/compile_commands.py b/tools/lint/compile_commands.py index 491fba49..c0040378 100755 --- a/tools/lint/compile_commands.py +++ b/tools/lint/compile_commands.py @@ -583,6 +583,34 @@ def of_the_tree(root: str, source: str) -> bool: Units = dict[str, dict[str, list[list[str]]]] +# What a dry run prints for a provider configuration it builds: its archives, or, when they +# exist, which B2 keeps (tools/webcpp-third-party.jam), only its headers' generation, when they +# are missing. +PROVIDER_ACTION = re.compile( + r'webcpp-(openssl|libdatachannel)\.(?:build (.+[/\\])' + r'(?:libssl|libdatachannel|datachannel)\.(?:a|lib)' + r'|(?:generate|prepare)-headers (.+[/\\])include[/\\](?:openssl|rtc)[/\\].+)') + + +def provider_headers(root: str, lines: list[str], includes: set[Path]) -> set[str]: + """The header that stands for each provider configuration of lines, a dry run's, whose + include directory is one of includes.""" + # Select each provider by its real B2 action, preserving the exact variant + # that the consumer uses, including program-only definitions and ABI flags. + headers: set[str] = set() + for line in lines: + action = PROVIDER_ACTION.fullmatch(line) + if action: + directory = Path(root, action.group(2) or action.group(3), 'include') + # B2 aliases explicit outputs by their original spelling, even when + # the build directory is a symlink. Canonicalize only comparisons. + if directory.resolve() in includes: + header = ('openssl/configuration.h' if action.group(1) == 'openssl' + else 'rtc/datachannel.hpp') + headers.add(str(directory / header)) + return headers + + def prepare_provider_headers(root: str, request: list[str], commands: list[list[str]], lines: list[str]) -> None: """Build each program's configured provider headers without executing its test target.""" @@ -602,21 +630,7 @@ def prepare_provider_headers(root: str, request: list[str], commands: list[list[ includes.add(directory) if not includes: return - # Select each provider by its real B2 action, preserving the exact variant - # that the consumer uses, including program-only definitions and ABI flags. - headers: set[str] = set() - for line in lines: - built = re.fullmatch( - r'webcpp-(openssl|libdatachannel)\.build (.+[/\\])' - r'(?:libssl|libdatachannel|datachannel)\.(?:a|lib)', line) - if built: - directory = Path(root, built.group(2), 'include') - # B2 aliases explicit outputs by their original spelling, even when - # the build directory is a symlink. Canonicalize only comparisons. - if directory.resolve() in includes: - header = ('openssl/configuration.h' if built.group(1) == 'openssl' - else 'rtc/datachannel.hpp') - headers.add(str(directory / header)) + headers = provider_headers(root, lines, includes) if not headers: return # Resolve the original consumers inside a dedicated B2 preparation target. diff --git a/tools/lint/lint_test.py b/tools/lint/lint_test.py index 22acf3a2..5b60cb4c 100755 --- a/tools/lint/lint_test.py +++ b/tools/lint/lint_test.py @@ -507,6 +507,22 @@ def test_compile_database_prepares_generated_header_dependencies(root): assert not list((root / 'bin').rglob('*.run')) +def test_provider_headers_of_a_kept_configuration(root): + # A configuration whose archives exist is kept, b2 -a included (tools/webcpp-third-party.jam): + # a dry run prints only the generation of its headers, when they are missing, and the lint + # still prepares them, as it does those of a configuration the dry run builds. + kept = root / 'bin/third_party/openssl/config-1' + built = root / 'bin/third_party/libdatachannel/config-2' + lines = [f'webcpp-openssl.generate-headers {kept}/include/openssl/aes.h', + f'webcpp-libdatachannel.build {built}/libdatachannel.a', + f'webcpp-openssl.generate-headers {root}/bin/third_party/openssl/config-3/' + 'include/openssl/aes.h'] + includes = {(kept / 'include').resolve(), (built / 'include').resolve()} + assert compile_commands.provider_headers(str(root), lines, includes) == { + str(kept / 'include/openssl/configuration.h'), + str(built / 'include/rtc/datachannel.hpp')} + + def test_compile_database_prepares_program_openssl_variants(root): # A program-only define selects a different OpenSSL configuration than any # public header unit. Both exception modes must be analysable on a clean tree. @@ -540,7 +556,9 @@ def test_compile_database_prepares_program_openssl_variants(root): assert planned.returncode == 0, planned.stdout[-6000:] directories = re.findall(r'^webcpp-openssl\.build (.+)[/\\]libssl\.(?:a|lib)$', planned.stdout, re.MULTILINE) - assert len(directories) == 4, planned.stdout[-6000:] + # One configuration with the upstream suite and one without: OpenSSL's C is the same in + # both exception modes, which share its build. + assert len(directories) == 2, planned.stdout[-6000:] preparation = harness.run_b2( root, '-n', f'--webcpp-lint-source={request}', '--webcpp-lint-property=exception-handling=on,off', @@ -593,15 +611,12 @@ def test_compile_database_prepares_program_openssl_variants(root): tested = harness.run_b2(root, '-n', 'libs/tls_user/test/release//tls_upstream') assert tested.returncode == 0, tested.stdout[-6000:] assert 'webcpp-openssl.build ' in tested.stdout and '--test' in tested.stdout - # A missing header and an existing, stale variant must both be updated. - # Inspect B2's actual actions without rebuilding OpenSSL a third time. - # B2 roots output paths at its actual cwd. Preserve the bin symlink while - # resolving the parent's /var alias on macOS, just as its dry run does. + # A missing header is generated again, without the archives of its configuration, which + # B2 keeps (tools/webcpp-third-party.jam). B2 roots output paths at its actual cwd. Preserve + # the bin symlink while resolving the parent's /var alias on macOS, as its dry run does. headers = sorted(root.resolve() / header.relative_to(root) for header in (root / 'bin/third_party').rglob('configuration.h')) - assert len(headers) == 4, headers - changed = max(header.stat().st_mtime for header in headers) + 1 - os.utime(root / 'tools/openssl/build.py', (changed, changed)) + assert len(headers) == 2, headers headers[0].unlink() pending = harness.run_b2( root, '-n', '--webcpp-lint-source=libs/tls_user/test/release//tls-variant', @@ -609,11 +624,21 @@ def test_compile_database_prepares_program_openssl_variants(root): *(f'--webcpp-lint-header={header}' for header in headers), 'lint-provider-headers') assert pending.returncode == 0, pending.stdout[-6000:] assert len(re.findall(r'^webcpp-openssl\.generate-headers ', pending.stdout, - re.MULTILINE)) == 4, ( - pending.stdout[-6000:]) + re.MULTILINE)) == 1, pending.stdout[-6000:] assert not re.search(r'^webcpp-openssl\.build ', pending.stdout, re.MULTILINE) assert 'testing.capture-output' not in pending.stdout, pending.stdout[-6000:] assert not re.search(r'^\S+\.compile', pending.stdout, re.MULTILINE), pending.stdout[-6000:] + # A changed input names other configurations: the lint prepares their headers, and still + # builds no archive. + script = root / 'tools/openssl/build.py' + script.write_text(script.read_text() + '\n# A changed input.\n') + completed = compile_database(root) + assert completed.returncode == 0, completed.stdout[-6000:] + prepared = {header.parent.parent.parent.resolve() + for header in (root / 'bin/third_party').rglob('configuration.h')} + earlier = {header.parent.parent.parent.resolve() for header in headers} + assert len(prepared - earlier) == 2, (prepared, earlier) + assert len(list((root / 'bin/third_party').rglob('build.json'))) == 1 def test_compile_database_prepares_program_libdatachannel_variants(root): @@ -2840,6 +2865,7 @@ def test_wasip3_abi_snapshot_requires_integrity_before_style_exemption(root): test_a_user_config_the_environment_names_is_read, test_compile_database_lists_what_b2_builds, test_compile_database_prepares_generated_header_dependencies, + test_provider_headers_of_a_kept_configuration, test_compile_database_prepares_program_openssl_variants, test_compile_database_prepares_program_libdatachannel_variants, test_compile_database_reads_what_only_wasi_builds, diff --git a/tools/openssl/test/threads.cpp b/tools/openssl/test/threads.cpp index ef24ecfa..77364054 100644 --- a/tools/openssl/test/threads.cpp +++ b/tools/openssl/test/threads.cpp @@ -34,7 +34,7 @@ int main() { } std::array buffer{}; for (int round = 0; round < 16; ++round) { - if (RAND_priv_bytes(buffer.data(), buffer.size()) != 1) { + if (RAND_priv_bytes(buffer.data(), static_cast(buffer.size())) != 1) { return; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); diff --git a/tools/test/libdatachannel_test.py b/tools/test/libdatachannel_test.py index a12f021e..6d69e72e 100644 --- a/tools/test/libdatachannel_test.py +++ b/tools/test/libdatachannel_test.py @@ -64,6 +64,12 @@ def test_one_native_provider_in_a_path_with_spaces(root: Path) -> None: 'libs/datachannel_user/test') harness.expect(result, True) assert 'webcpp-libdatachannel.build ' not in result.stdout, result.stdout + # b2 -a, which the CI's lanes run, builds the program again, not the providers it uses. + result = harness.run_b2(root, '-a', '-j4', 'toolset=clang', 'variant=release', + 'libs/datachannel_user/test') + harness.expect(result, True, '**passed**') + assert 'webcpp-libdatachannel.' not in result.stdout, result.stdout + assert 'webcpp-openssl.' not in result.stdout, result.stdout # A free C++ ABI/compiler option changes the dependency's output directory. changed = harness.run_b2(root, '-n', '-a', '-d+2', 'toolset=clang', 'variant=release', 'cxxflags=-DWEBCPP_TEST_DATACHANNEL_VARIANT=1', diff --git a/tools/test/openssl_test.py b/tools/test/openssl_test.py index 90576766..4e1c4268 100644 --- a/tools/test/openssl_test.py +++ b/tools/test/openssl_test.py @@ -139,12 +139,65 @@ def test_native_source_dependency(root: Path) -> None: custom = [record for record in records if '-DWEBCPP_TEST_OPENSSL_CONFIGURATION=17' in record['flags']] assert len(custom) == 1, records - # All installed headers, not just configuration.h, are generated outputs. + # All installed headers, not just configuration.h, are generated outputs. The archives of + # their configuration exist, and are kept: only the headers are generated again. for header in (root / 'bin/third_party').rglob('include/openssl/ssl.h'): header.unlink() result = harness.run_b2(root, 'toolset=clang', 'variant=release', 'threading=single', 'libs/openssl_user/test') - harness.expect(result, True, 'webcpp-openssl.build', '**passed**') + harness.expect(result, True, 'webcpp-openssl.generate-headers', '**passed**') + assert 'webcpp-openssl.build ' not in result.stdout, result.stdout + + +def test_one_c_configuration_is_built_once(root: Path) -> None: + harness.add_library(root, 'openssl_user', JAM, {'uses_openssl.cpp': SOURCE}) + # exception-handling changes the consumer's C++, not OpenSSL's C: both consumers share + # one build of the same configuration, as they would otherwise build it twice. + result = harness.run_b2(root, '-n', '-a', '-d+2', 'toolset=clang', 'variant=release', + 'threading=single', 'exception-handling=on,off', + 'libs/openssl_user/test') + harness.expect(result, True) + builds = re.findall(r'^webcpp-openssl\.build .*$', result.stdout, re.M) + assert len(builds) == 1, builds + archives = set(re.findall(r'"([^"\n]+/config-[^"\n]+/libcrypto\.a)"', result.stdout)) + assert len(archives) == 1, archives + + +def test_a_built_configuration_is_kept_and_selected(root: Path) -> None: + harness.add_library(root, 'openssl_user', JAM, {'uses_openssl.cpp': SOURCE}) + request = ('toolset=clang', 'variant=release', 'threading=single', 'libs/openssl_user/test') + harness.expect(harness.run_b2(root, *request), True, 'webcpp-openssl.build', '**passed**') + archive = next((root / 'bin/third_party').rglob('libcrypto.a')) + built = archive.stat().st_mtime_ns + # b2 -a, which the CI's lanes run, builds the program again, not the archives it uses: a + # configuration's directory is named by its inputs, so the one that exists is theirs. + result = harness.run_b2(root, '-a', *request) + harness.expect(result, True, '**passed**') + assert 'webcpp-openssl.' not in result.stdout, result.stdout + assert archive.stat().st_mtime_ns == built + # A changed input names another configuration. + script = root / 'tools/openssl/build.py' + original = script.read_text() + script.write_text(original + '\n# A changed input.\n') + planned = harness.run_b2(root, '-n', *request) + harness.expect(planned, True) + changed = re.findall(r'^webcpp-openssl\.build (.+[/\\])libssl\.a$', planned.stdout, re.M) + assert len(changed) == 1, planned.stdout + other = root / changed[0] + assert other.resolve() != archive.parent.resolve(), other + # A program is built again when its configuration changes to one that exists, here a copy + # of the first, and when it changes back. + shutil.copytree(archive.parent, other) + result = harness.run_b2(root, *request) + harness.expect(result, True, '**passed**') + assert 'webcpp-openssl.build' not in result.stdout, result.stdout + script.write_text(original) + result = harness.run_b2(root, *request) + harness.expect(result, True, '**passed**') + assert 'webcpp-openssl.build' not in result.stdout, result.stdout + result = harness.run_b2(root, *request) + harness.expect(result, True) + assert '**passed**' not in result.stdout, result.stdout def test_wasip2_source_dependency(root: Path) -> None: @@ -421,6 +474,8 @@ def test_source_archive_without_git_and_inside_parent_checkout(root: Path) -> No for parent_checkout in (False, True): if parent_checkout: subprocess.run(['git', 'init', '--quiet', str(root)], check=True) + # b2 -a keeps a configuration that exists: build this one again, in the parent. + shutil.rmtree(root / 'bin/third_party/openssl') result = harness.run_b2(root, '-a', 'toolset=clang', 'variant=release', 'threading=single', 'libs/openssl_user/test') if result.returncode: @@ -464,7 +519,9 @@ def test_source_archive_tampering_fails_before_configuration(root: Path) -> None CASES = [test_native_upstream_suite_checks_the_consumed_archives, test_upstream_suite_rejects_wasi_by_name, test_upstream_failure_prevents_archive_publication, - test_native_source_dependency, test_wasip2_source_dependency, + test_native_source_dependency, test_one_c_configuration_is_built_once, + test_a_built_configuration_is_kept_and_selected, + test_wasip2_source_dependency, test_symlinked_compiler_without_c_sibling, test_msvc_build_commands_preserve_the_consumers_configuration, test_msvc_tls_lanes_keep_distinct_openssl_thread_profiles, diff --git a/tools/third_party_build.py b/tools/third_party_build.py new file mode 100644 index 00000000..3e9b76f0 --- /dev/null +++ b/tools/third_party_build.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# 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) + +"""The key of a source-built third-party library's inputs, and the selection of its builds. + +key ROOT NAME SOURCE INPUT... prints the SHA-256 of each INPUT's path, relative to ROOT, and +bytes: the files that make NAME's build what it is, its scripts and its pin. B2 names the +directory of each configuration of NAME by this key and its build command, so a directory that +exists holds the build of exactly those inputs, and is never built again, b2 -a included +(tools/webcpp-third-party.jam). The checkout SOURCE, relative to ROOT, is checked first with +NAME's own rules, check_checkout of tools/NAME/source.py, against tools/NAME/pin.json: a checkout +that differs from its pin has no key, as it has no build. + +select STAMP writes STAMP, /-.selected, and removes the other +selections of the library in its directory. A consumer depends on the selection of the +configuration it uses, so it is built again when that configuration changes, even to one built +earlier: its directory exists, and only the selection is new. + +Exit 0 on success; 1, with the reason on standard output, when there is no key. +""" +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import runpy +import subprocess +import sys + +USAGE = '''Usage: third_party_build.py key ROOT NAME SOURCE INPUT... + third_party_build.py select STAMP''' + + +def check(root: Path, name: str, source: str) -> None: + """Applies tools//source.py's check_checkout to source, against its pin.""" + tools = root / 'tools' / name + rules = runpy.run_path(str(tools / 'source.py')) + pin = json.loads((tools / 'pin.json').read_text()) + try: + rules['check_checkout']((root / source).resolve(), pin) + except subprocess.CalledProcessError as error: + raise RuntimeError(f'{source} differs from its pinned commit; restore its files or ' + f'update tools/{name}/pin.json') from error + + +def key(root: Path, inputs: list[str]) -> str: + """The SHA-256 of each input's path and bytes, independent of the order inputs are given.""" + digest = hashlib.sha256(b'webcpp-third-party-inputs-v1\0') + for relative in sorted(set(inputs)): + path = root / relative + if not path.is_file(): + raise RuntimeError(f'{relative} is an input of a third-party build and is missing') + content = path.read_bytes() + digest.update(f'{Path(relative).as_posix()}\0{len(content)}\0'.encode()) + digest.update(content) + return digest.hexdigest() + + +def select(stamp: Path) -> None: + """Writes stamp and removes the other selections of its library in its directory.""" + library, _, selected = stamp.name.removesuffix('.selected').rpartition('-') + for other in stamp.parent.glob(f'{library}-*.selected'): + if other.name != stamp.name and other.name.rpartition('-')[0] == library: + other.unlink() + stamp.write_text(selected + '\n') + + +def main(arguments: list[str]) -> int: + if len(arguments) >= 5 and arguments[0] == 'key': + root = Path(arguments[1]).resolve() + try: + check(root, arguments[2], arguments[3]) + print(key(root, arguments[4:])) + except RuntimeError as error: + print(error) + return 1 + return 0 + if len(arguments) == 2 and arguments[0] == 'select': + select(Path(arguments[1])) + return 0 + print(USAGE) + return 2 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/third_party_build_test.py b/tools/third_party_build_test.py new file mode 100644 index 00000000..f0c6a883 --- /dev/null +++ b/tools/third_party_build_test.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 WebCpp.org +# +# 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) + +"""A third-party build's key names its inputs, and one configuration is selected at a time.""" +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +SCRIPT = Path(__file__).with_name('third_party_build.py') + +# A library's own source checks, as tools//source.py defines them: the stand-in refuses +# a pin whose commit says so, the way the real ones refuse a checkout that differs from it. +SOURCE = '''from pathlib import Path +import subprocess + +def check_checkout(source: Path, pin: dict) -> None: + (source / 'checked').write_text(str(source.is_absolute()) + ' ' + pin['commit']) + if pin['commit'] == 'moved': + raise RuntimeError('Demo checkout differs from tools/demo/pin.json; ' + 'update the submodule') + if pin['commit'] == 'edited': + raise subprocess.CalledProcessError(1, ['git', 'diff', '--exit-code', 'HEAD', '--']) +''' + + +class ThirdPartyBuildTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix='third party ') + self.root = Path(self.temporary.name) + tools = self.root / 'tools/demo' + tools.mkdir(parents=True) + (tools / 'source.py').write_text(SOURCE) + self.pin('pinned') + (tools / 'build.py').write_text('# builds the demo\n') + (self.root / 'third_party/libs/demo').mkdir(parents=True) + + def tearDown(self): + self.temporary.cleanup() + + def pin(self, commit: str) -> None: + (self.root / 'tools/demo/pin.json').write_text('{"commit": "%s"}\n' % commit) + + def run_script(self, *arguments: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(SCRIPT), *arguments], text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60) + + def key(self, *inputs: str) -> subprocess.CompletedProcess: + return self.run_script('key', str(self.root), 'demo', 'third_party/libs/demo', *inputs) + + def test_the_key_names_each_inputs_path_and_bytes(self): + inputs = ('tools/demo/build.py', 'tools/demo/pin.json') + first = self.key(*inputs) + self.assertEqual(first.returncode, 0, first.stdout) + key = first.stdout.strip() + self.assertRegex(key, r'^[0-9a-f]{64}$') + self.assertEqual(self.key(*reversed(inputs)).stdout.strip(), key) + build = self.root / 'tools/demo/build.py' + build.write_text('# builds the demo differently\n') + changed = self.key(*inputs).stdout.strip() + self.assertNotEqual(changed, key) + build.rename(self.root / 'tools/demo/make.py') + moved = self.key('tools/demo/make.py', 'tools/demo/pin.json').stdout.strip() + self.assertNotIn(moved, (key, changed)) + + def test_the_key_checks_the_checkout_with_the_librarys_own_rules(self): + result = self.key('tools/demo/pin.json') + self.assertEqual(result.returncode, 0, result.stdout) + checked = (self.root / 'third_party/libs/demo/checked').read_text() + self.assertEqual(checked, 'True pinned') + + def test_a_checkout_that_differs_from_its_pin_has_no_key(self): + self.pin('moved') + result = self.key('tools/demo/pin.json') + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout.strip(), 'Demo checkout differs from ' + 'tools/demo/pin.json; update the submodule') + + def test_a_checkout_with_local_changes_has_no_key(self): + self.pin('edited') + result = self.key('tools/demo/pin.json') + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout.strip(), 'third_party/libs/demo differs from its ' + 'pinned commit; restore its files or update tools/demo/pin.json') + + def test_a_missing_input_has_no_key(self): + result = self.key('tools/demo/pin.json', 'tools/demo/absent.py') + self.assertNotEqual(result.returncode, 0) + self.assertIn('tools/demo/absent.py', result.stdout) + + def test_a_selection_replaces_the_previous_one_of_its_library(self): + directory = self.root / 'bin/release' + directory.mkdir(parents=True) + for name in ('demo-1111.selected', 'demo-2222.selected', 'other-3333.selected', + 'demo.txt'): + (directory / name).write_text('earlier\n') + result = self.run_script('select', str(directory / 'demo-4444.selected')) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertEqual(sorted(path.name for path in directory.iterdir()), + ['demo-4444.selected', 'demo.txt', 'other-3333.selected']) + self.assertEqual((directory / 'demo-4444.selected').read_text(), '4444\n') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/webcpp-libdatachannel.jam b/tools/webcpp-libdatachannel.jam index 173f35a5..2ac541d9 100644 --- a/tools/webcpp-libdatachannel.jam +++ b/tools/webcpp-libdatachannel.jam @@ -15,6 +15,7 @@ import targets ; import toolset ; import virtual-target ; import webcpp-lint-headers ; +import webcpp-third-party ; feature.feature webcpp-libdatachannel-openssl : : free incidental ; @@ -29,6 +30,7 @@ class libdatachannel-target : basic-target import toolset ; import unix ; import virtual-target ; + import webcpp-third-party ; rule __init__ ( name : project : sources * : requirements * : default-build * : usage-requirements * ) @@ -49,7 +51,6 @@ class libdatachannel-target : basic-target local provider-libraries ; local provider-ssl ; local provider-crypto ; - local header-sources ; for local source in $(source-targets) { if [ $(source).name ] in libssl.a libssl.lib @@ -65,10 +66,6 @@ class libdatachannel-target : basic-target { provider-libraries += $(source) ; } - else - { - header-sources += $(source) ; - } } if ! $(provider) { @@ -76,8 +73,36 @@ class libdatachannel-target : basic-target } local relevant = [ toolset.relevant webcpp-libdatachannel.build ] ; properties = [ $(properties).add $(relevant) ] ; - local fingerprint = [ modules.call-in webcpp-libdatachannel : fingerprint $(properties) ] ; properties = [ $(properties).add-raw $(provider) ] ; + # The configuration's directory is named by the key of the inputs and + # by every value of the build command, OpenSSL's configuration + # included (tools/webcpp-third-party.jam). + local directory = [ webcpp-third-party.directory $(self.project) : libdatachannel + : [ modules.call-in webcpp-libdatachannel : command-values $(properties) ] ] ; + local built = [ modules.peek webcpp-libdatachannel : .built.$(directory) ] ; + if ! $(built) + { + built = [ build-configuration $(directory) : $(source-targets) : $(provider-ssl) + : $(properties) ] ; + modules.poke webcpp-libdatachannel : .built.$(directory) : $(built) ; + } + local archives = $(built[1-4]) ; + unix.set-library-order-aux $(provider-ssl) : $(provider-crypto) ; + unix.set-library-order-aux $(archives[1]) : $(archives[2-]) ; + unix.set-library-order-aux $(archives) : $(provider-libraries) ; + local selection = [ webcpp-third-party.selection $(self.project) : libdatachannel + : $(directory) : $(properties) ] ; + # Keep the one OpenSSL target in the final link after its static users. + return [ property-set.create [ $(relevant).raw ] $(directory)/include + $(built[5-]) $(selection) ] $(archives) $(provider-libraries) ; + } + + # The four archives, then the headers and every other output, of the + # configuration that properties give, in directory, built from the OpenSSL + # archives among source-targets, provider-ssl's action's. + rule build-configuration ( directory : source-targets * : provider-ssl : properties ) + { + local os = [ $(properties).get ] ; # RTC headers are verified source files. Preparing them needs neither # OpenSSL archives nor a CMake build of the native provider. # OpenSSL also propagates proof and PDB outputs through . @@ -94,19 +119,13 @@ class libdatachannel-target : basic-target } local header-properties = [ property-set.create [ set.difference [ $(properties).raw ] : $(archive-dependencies) ] ] ; - local header-action = [ new action $(header-sources) - : webcpp-libdatachannel.prepare-headers : $(header-properties) ] ; + local header-action = [ new action : webcpp-libdatachannel.prepare-headers + : $(header-properties) ] ; local headers ; - local directory ; for local header in [ modules.peek webcpp-libdatachannel : .headers ] { local generated = [ new file-target include/rtc/$(header) exact : H : $(self.project) : $(header-action) ] ; - if ! $(directory) - { - directory = [ path.root [ path.make [ $(generated).path ] ] [ path.pwd ] ] ; - directory = $(directory)/config-$(fingerprint) ; - } $(generated).set-path $(directory) ; generated = [ virtual-target.register $(generated) ] ; headers += $(generated) ; @@ -142,21 +161,23 @@ class libdatachannel-target : basic-target headers += [ virtual-target.register $(symbols) ] ; } } - unix.set-library-order-aux $(provider-ssl) : $(provider-crypto) ; - unix.set-library-order-aux $(archives[1]) : $(archives[2-]) ; - unix.set-library-order-aux $(archives) : $(provider-libraries) ; - # Keep the one OpenSSL target in the final link after its static users. - return [ property-set.create [ $(relevant).raw ] $(directory)/include - $(headers) ] $(archives) $(provider-libraries) ; + return $(archives) $(headers) ; } } -rule declare ( root : headers * : sources * ) +# Declares the libdatachannel target of the current project, the checkout of +# third_party/libs/libdatachannel under root built with +# tools/libdatachannel/build.py over the project's openssl target, which +# installs headers, named relative to include/rtc. inputs, relative to root, +# are the files whose bytes make the build what it is, the key of its +# configurations (tools/webcpp-third-party.jam). +rule declare ( root : headers * : inputs * ) { .root = $(root) ; .headers = $(headers) ; + .inputs = $(inputs) ; targets.create-metatarget libdatachannel-target : [ project.current ] : libdatachannel - : $(sources) openssl : static off off + : openssl : static off off @webcpp-libdatachannel.configuration : : RTC_STATIC RTC_ENABLE_WEBSOCKET=0 RTC_ENABLE_MEDIA=1 linux:-pthread @@ -207,14 +228,27 @@ rule compiler-settings ( outputs * : ps ) } } -rule fingerprint ( ps ) +# The values of the build command of the configuration that ps gives, after +# the key of the inputs: what names its directory. OpenSSL's is named by its +# directory's, which names its configuration. +rule command-values ( ps ) { - if $(.fingerprint.$(ps)) { return $(.fingerprint.$(ps)) ; } + if $(.values.$(ps)) { return $(.values.$(ps)) ; } local settings = libdatachannel-settings-$(ps) ; compiler-settings $(settings) : $(ps) ; - local values = [ on $(settings) return $(DRIVER) $(C_OPTIONS) $(CXX_OPTIONS) $(DEFINES) $(.SETUP) $(.SETUP-SCRIPT) $(.SETUP-OPTIONS) ] ; - .fingerprint.$(ps) = [ MD5 "$(values:J=|)" ] ; - return $(.fingerprint.$(ps)) ; + local key = [ webcpp-third-party.inputs-key $(.root) : libdatachannel + : third_party/libs/libdatachannel : $(.inputs) ] ; + local openssl = [ $(ps).get ] ; + local named = openssl=$(openssl:D=) ; + for local feature in target-os variant debug-symbols debug-store + { + local value = [ $(ps).get <$(feature)> ] ; + named += $(feature)=$(value:E=) ; + } + .values.$(ps) = $(key) + [ on $(settings) return $(DRIVER) $(C_OPTIONS) $(CXX_OPTIONS) $(DEFINES) $(.SETUP) $(.SETUP-SCRIPT) $(.SETUP-OPTIONS) ] + $(named) ; + return $(.values.$(ps)) ; } rule build-settings ( outputs * : properties * ) @@ -235,11 +269,13 @@ rule build-settings ( outputs * : properties * ) rule build ( outputs * : inputs * : properties * ) { build-settings $(outputs) : $(properties) ; + webcpp-third-party.keep $(outputs) ; } rule prepare-headers ( outputs * : inputs * : properties * ) { build-settings $(outputs) : $(properties) ; + webcpp-third-party.keep $(outputs) ; } actions prepare-headers diff --git a/tools/webcpp-openssl.jam b/tools/webcpp-openssl.jam index 709bcbd2..15f93be8 100644 --- a/tools/webcpp-openssl.jam +++ b/tools/webcpp-openssl.jam @@ -16,6 +16,7 @@ import toolset ; import type ; import virtual-target ; import webcpp-lint-headers ; +import webcpp-third-party ; import webcpp-wasi ; feature.feature webcpp-openssl-tests : on : optional propagated ; @@ -31,6 +32,7 @@ class openssl-target : basic-target import regex ; import toolset ; import virtual-target ; + import webcpp-third-party ; rule __init__ ( name : project : sources * : requirements * : default-build * : usage-requirements * ) { @@ -60,27 +62,40 @@ class openssl-target : basic-target errors.user-error "Source-built OpenSSL supports native Clang/GCC on macOS/Linux, MSVC on Windows, clang-wasip2 and clang-wasip3." "Other targets are not supported by this recipe." ; } - # B2's normal directory omits free flags. Add the effective compiler - # configuration so changing cflags or a user-config tool cannot reuse - # archives or headers from the previous configuration. + # The configuration's directory is named by the key of the inputs and + # by every value of the build command, free flags and user-config tools + # included: consumers that differ in nothing the command uses share it + # (tools/webcpp-third-party.jam). local relevant = [ toolset.relevant webcpp-openssl.build ] ; properties = [ $(properties).add $(relevant) ] ; - local fingerprint = [ modules.call-in webcpp-openssl : fingerprint $(properties) ] ; + local directory = [ webcpp-third-party.directory $(self.project) : openssl + : [ modules.call-in webcpp-openssl : command-values $(properties) ] ] ; + local built = [ modules.peek webcpp-openssl : .built.$(directory) ] ; + if ! $(built) + { + built = [ build-configuration $(directory) : $(properties) ] ; + modules.poke webcpp-openssl : .built.$(directory) : $(built) ; + } + local selection = [ webcpp-third-party.selection $(self.project) : openssl + : $(directory) : $(properties) ] ; + return [ property-set.create [ $(relevant).raw ] $(directory)/include + $(built[3-]) $(selection) ] $(built[1-2]) ; + } + + # The archives, then the headers and every other output, of the + # configuration that properties give, in directory. + rule build-configuration ( directory : properties ) + { + local os = [ $(properties).get ] ; # Analysis needs the configured headers, but no archives or upstream # suite. Keep generation separate, under the exact same properties. - local header-action = [ new action $(source-targets) - : webcpp-openssl.generate-headers : $(properties) ] ; - local directory ; + local header-action = [ new action : webcpp-openssl.generate-headers + : $(properties) ] ; local headers ; for local header in [ modules.peek webcpp-openssl : .headers ] { local generated = [ new file-target include/openssl/$(header) exact : H : $(self.project) : $(header-action) ] ; - if ! $(directory) - { - directory = [ path.root [ path.make [ $(generated).path ] ] [ path.pwd ] ] ; - directory = $(directory)/config-$(fingerprint) ; - } $(generated).set-path $(directory) ; generated = [ virtual-target.register $(generated) ] ; headers += $(generated) ; @@ -93,8 +108,7 @@ class openssl-target : basic-target # The complete build publishes into that directory too. Its dependency # on the headers orders both writers and leaves archives/proof pending # after a lint preparation, including on an incremental build. - local action = [ new action $(source-targets) $(headers) - : webcpp-openssl.build : $(properties) ] ; + local action = [ new action $(headers) : webcpp-openssl.build : $(properties) ] ; local extension = a ; if $(os) = windows { extension = lib ; } local ssl = [ new file-target libssl.$(extension) exact : STATIC_LIB : $(self.project) : $(action) ] ; @@ -118,17 +132,22 @@ class openssl-target : basic-target $(symbols).set-path $(directory) ; headers += [ virtual-target.register $(symbols) ] ; } - return [ property-set.create [ $(relevant).raw ] $(directory)/include - $(headers) ] $(ssl) $(crypto) ; + return $(ssl) $(crypto) $(headers) ; } } -rule declare ( root : headers * : sources * ) +# Declares the openssl target of the current project, the checkout of +# third_party/libs/openssl under root built with tools/openssl/build.py, which +# installs headers, named relative to include/openssl. inputs, relative to +# root, are the files whose bytes make the build what it is, the key of its +# configurations (tools/webcpp-third-party.jam). +rule declare ( root : headers * : inputs * ) { .root = $(root) ; .headers = $(headers) ; + .inputs = $(inputs) ; targets.create-metatarget openssl-target : [ project.current ] : openssl - : $(sources) : static off off + : : static off off @webcpp-openssl.configuration : : darwin:-Wl,-dead_strip linux:-Wl,--gc-sections @@ -155,19 +174,30 @@ rule configuration ( properties * ) } } -rule fingerprint ( ps ) +# The values of the build command of the configuration that ps gives, after +# the key of the inputs: what names its directory. +rule command-values ( ps ) { # Toolset variables append to their target. Cache by immutable property set # to avoid accumulating flags or building duplicate archives on each visit. - if $(.fingerprint.$(ps)) + if $(.values.$(ps)) { - return $(.fingerprint.$(ps)) ; + return $(.values.$(ps)) ; } local settings = openssl-settings-$(ps) ; compiler-settings $(settings) : $(ps) ; - local values = [ on $(settings) return $(DRIVER) $(C_OPTIONS) $(DEFINES) $(ARCHIVER) $(.SETUP) $(.SETUP-SCRIPT) $(.SETUP-OPTIONS) ] ; - .fingerprint.$(ps) = [ MD5 "$(values:J=|)" ] ; - return $(.fingerprint.$(ps)) ; + local key = [ webcpp-third-party.inputs-key $(.root) : openssl + : third_party/libs/openssl : $(.inputs) ] ; + local named ; + for local feature in target-os threading variant debug-symbols debug-store webcpp-openssl-tests + { + local value = [ $(ps).get <$(feature)> ] ; + named += $(feature)=$(value:E=) ; + } + .values.$(ps) = $(key) + [ on $(settings) return $(DRIVER) $(C_OPTIONS) $(DEFINES) $(ARCHIVER) $(.SETUP) $(.SETUP-SCRIPT) $(.SETUP-OPTIONS) ] + $(named) ; + return $(.values.$(ps)) ; } rule compiler-settings ( outputs * : ps ) @@ -220,6 +250,7 @@ rule build-settings ( outputs * : properties * ) rule build ( outputs * : inputs * : properties * ) { build-settings $(outputs) : $(properties) ; + webcpp-third-party.keep $(outputs) ; } actions build @@ -230,6 +261,7 @@ actions build rule generate-headers ( outputs * : inputs * : properties * ) { build-settings $(outputs) : $(properties) ; + webcpp-third-party.keep $(outputs) ; } actions generate-headers diff --git a/tools/webcpp-third-party.jam b/tools/webcpp-third-party.jam new file mode 100644 index 00000000..22b3ed31 --- /dev/null +++ b/tools/webcpp-third-party.jam @@ -0,0 +1,91 @@ +# Copyright (c) 2026 WebCpp.org +# +# 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) + +# What the B2 rules of the source-built OpenSSL and libdatachannel share +# (CODING-GUIDELINES.md chapter 15): where a configuration is built, that it +# is built once, and how its consumers follow a change of configuration. +# +# A configuration's directory is bin/third_party//config-, the +# hash of the key of the library's inputs (tools/third_party_build.py key: its +# scripts and its pin) and of the build command's values. So a +# directory that exists holds the build of exactly those inputs and that +# command: its outputs are NOUPDATE, built when missing and never again, b2 -a +# included, which the CI's lanes run, and a directory the CI restores from its +# cache is used as it is. Consumers whose properties differ only in what the +# command leaves out, as exception-handling for OpenSSL's C, share one build. +# +# A consumer depends on -config-.selected in its own variant +# directory, which tools/third_party_build.py select writes when the consumer's +# configuration changes, removing the other selections of the library there: +# the consumer is built again, even when the configuration it changes to was +# built earlier and its directory, NOUPDATE, is older than the consumer. A +# variant directory holds one selection of a library: in one b2 run, its +# requests differ only in free features, and no free feature propagates, so +# each reaches the library from b2's command line alone, the same in all. + +import "class" : new ; +import errors ; +import path ; +import type ; +import virtual-target ; + +type.register WEBCPP_THIRD_PARTY_SELECTION ; + +# The key of name's inputs, files named relative to root, once per b2 run. The +# checkout source, relative to root, is first checked with name's own rules, +# tools//source.py, against tools//pin.json: one that differs from +# its pin stops b2 here, with their reason. +rule inputs-key ( root : name : source : inputs + ) +{ + if ! $(.key.$(name)) + { + .script = [ path.native $(root)/tools/third_party_build.py ] ; + local command = python3 \"$(.script)\" key \"$(root)\" $(name) $(source) + $(inputs) ; + local result = [ SHELL $(command:J=" ") : strip-eol : exit-status ] ; + if $(result[2]) != 0 + { + errors.user-error "The inputs of $(name) have no key:" $(result[1]) ; + } + .key.$(name) = $(result[1]) ; + } + return $(.key.$(name)) ; +} + +# The directory of the configuration of name that values give, under project's +# build directory. +rule directory ( project : name : values * ) +{ + local build = [ path.root [ path.make [ $(project).get build-dir ] ] [ path.pwd ] ] ; + local hash = [ MD5 "$(values:J=|)" ] ; + return $(build)/$(name)/config-$(hash) ; +} + +# The outputs of a configuration's action, which exist only as its build. +rule keep ( outputs * ) +{ + NOUPDATE $(outputs) ; +} + +# The selection of name's configuration in directory for a consumer built with +# properties, in project, which the consumer depends on. +rule selection ( project : name : directory : properties ) +{ + local action = [ new action : webcpp-third-party.select : $(properties) ] ; + local stamp = [ new file-target $(name)-$(directory:B).selected exact + : WEBCPP_THIRD_PARTY_SELECTION : $(project) : $(action) ] ; + return [ virtual-target.register $(stamp) ] ; +} + +rule select ( targets * : sources * : properties * ) +{ + SCRIPT on $(targets) = $(.script) ; +} + +actions select +{ + python3 "$(SCRIPT)" select "$(<)" +}