diff --git a/.gitignore b/.gitignore index c10dea46..1c29a550 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ for_test/ test.exe dist/ build/ +sbom-work/ libs/ # These are artifacts when using editable builds local/lib diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e5995b8..34d29c3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## OpenBLAS v0.3.34 (v0.3.34) +### 0.3.34.481.7 (2026-12-04) + +- Add a sbom cdx.json attestation file + ### 0.3.34.481.6 (2026-11-30) - Use the correct lapack headers for windows builds (function names with diff --git a/ci-repair-wheel.sh b/ci-repair-wheel.sh index 05f3bce2..1a30a453 100755 --- a/ci-repair-wheel.sh +++ b/ci-repair-wheel.sh @@ -23,3 +23,7 @@ else # copy libs/openblas*.tar.gz to dist/ cp libs/openblas*.tar.gz /output/ fi + +# PEP 770 SBOM, from what tools/build_steps.sh recorded during the build. +# On Linux this sits next to the one auditwheel writes for anything it grafts. +$(command -v python3 || command -v python) tools/make_sbom.py inject sbom-work/sbom-build.json "$1"/*.whl diff --git a/pyproject.toml b/pyproject.toml index 772f6c7e..99201604 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ build-backend = "setuptools.build_meta" [project] name = "scipy-openblas64" # 0.3.34-481-g5137bb62 -version = "0.3.34.481.6" +version = "0.3.34.481.7" requires-python = ">=3.7" description = "Provides OpenBLAS for python packaging" readme = "README.md" @@ -51,12 +51,23 @@ environment-pass = [ # On emulated architectures, RUNNER_ARCH makes manylinux-install-clang install a # compiler for the native architecture, which will be much faster. "RUNNER_ARCH", + + # Recorded in the wheel's SBOM by tools/make_sbom.py + "GITHUB_SHA", + "GITHUB_REPOSITORY", + "GITHUB_SERVER_URL", + "GITHUB_RUN_ID", + "GITHUB_RUN_ATTEMPT", + "GITHUB_WORKFLOW_REF", ] [tool.cibuildwheel.android] # The Linux code in ci-repair-wheel.sh isn't relevant to Android, so use the default # repair command from the cibuildwheel documentation. -repair-wheel-command = "auditwheel repair --ldpaths {ldpaths} -w {dest_dir} {wheel}" +repair-wheel-command = [ + "auditwheel repair --ldpaths {ldpaths} -w {dest_dir} {wheel}", + "python tools/make_sbom.py inject sbom-work/sbom-build.json {dest_dir}/*.whl", +] # Mobile platforms only support Python test-commands, not shell scripts. test-command = """python -c ' diff --git a/tools/build_steps.sh b/tools/build_steps.sh index 60ca84a7..d863dac3 100644 --- a/tools/build_steps.sh +++ b/tools/build_steps.sh @@ -80,10 +80,15 @@ function clean_code { function patch_source { # Runs inside OpenBLAS directory # Make the patches by git format-patch + # tools/make_sbom.py reads the list of what was applied + local applied="$ROOT_DIR/sbom-work/applied-patches.txt" + mkdir -p "$(dirname "$applied")" + : > "$applied" for f in ../patches-common/*.patch ../patches/*.patch; do [ -e "$f" ] || continue echo applying patch $f git apply "$f" + echo "$f" >> "$applied" done } @@ -213,6 +218,10 @@ function build_lib { echo "the utest samin/damin have been temporarily disabled." echo "QEMU does not support the 'lper' /'lpdr' instructions used" fi + # The tree is final now: patched, and edited above. Save its diff for the + # SBOM before compiling (tools/make_sbom.py). + $(command -v python3 || command -v python) "$ROOT_DIR/tools/make_sbom.py" \ + snapshot --out "$ROOT_DIR/sbom-work/openblas-source.diff" if [ -n "$dynamic_list" ]; then CFLAGS="$CFLAGS -fvisibility=protected -Wno-uninitialized" \ make BUFFERSIZE=20 QUIET_MAKE=1 \ @@ -259,6 +268,9 @@ function build_lib { $BUILD_PREFIX/lib/libscipy_openblas*.dylib fi + record_sbom_build "$plat" "$interface64" "$target" "$dynamic_list" \ + "$interface_flags" "$compat_lib" + local out_name="openblas.tar.gz" pushd $BUILD_PREFIX tar zcvf $ROOT_DIR/libs/$out_name \ @@ -269,3 +281,48 @@ function build_lib { lib/cmake/openblas popd } + +function record_sbom_build { + # Write sbom-work/sbom-build.json, from which ci-repair-wheel.sh puts an SBOM + # into the wheel (tools/make_sbom.py). It has to run here, in the build + # environment: this is the only place that knows which compiler and which + # libgfortran.a went into the library. + local plat=$1 interface64=$2 target=$3 dynamic_list=$4 flags=$5 + local compat_lib=$6 + local py + py=$(command -v python3 || command -v python) + local args=( + --out "$ROOT_DIR/sbom-work/sbom-build.json" + --config "MB_ML_LIBC=$MB_ML_LIBC" --config "PLAT=$plat" + --config "INTERFACE64=$interface64" --config "TARGET=$target" + --config "DYNAMIC_LIST=$dynamic_list" --config "make_flags=$flags" + --config "CFLAGS=$CFLAGS" --config "NIGHTLY=${NIGHTLY:-false}" + --tool "cc=${CC:-cc}" --tool "ld=${LD:-ld}" + ) + if [ "$MB_ML_LIBC" != "android" ]; then + args+=(--tool "fc=${FC:-gfortran}") + fi + if [ -n "$compat_lib" ]; then + local compat_dir=$(dirname "$compat_lib") + args+=(--static "gfortran_compat=$ROOT_DIR/tools/gfortran_compat.c,license=BSD-3-Clause") + # Only INTERFACE64 builds take objects out of libgfortran.a + if [ -s "$compat_dir/members.txt" ]; then + local gcc_ver=$(${FC:-gfortran} -dumpfullversion 2>/dev/null \ + || ${FC:-gfortran} -dumpversion) + local spec="libgfortran=$(cat "$compat_dir/archive.txt"),version=$gcc_ver" + spec+=",members_file=$compat_dir/members.txt" + if [ "$MB_ML_LIBC" == "macosx" ]; then + # Not from a system package; from the pinned conda-forge one + local pkg sha + read -r pkg sha < <(macos_libgfortran_pkg "$plat") + local file=$(basename "$pkg" .tar.bz2) + local subdir=${pkg%%/*} + local name=${file%-*-*} build=${file##*-} + spec+=",purl=pkg:conda/conda-forge/$name@$gcc_ver?build=$build&subdir=$subdir" + spec+=",url=https://conda.anaconda.org/conda-forge/$pkg" + fi + args+=(--static "$spec") + fi + fi + "$py" "$ROOT_DIR/tools/make_sbom.py" collect "${args[@]}" +} diff --git a/tools/build_steps_win.bat b/tools/build_steps_win.bat index 107cda9e..c09bc052 100755 --- a/tools/build_steps_win.bat +++ b/tools/build_steps_win.bat @@ -92,11 +92,20 @@ if "%NIGHTLY%"=="true" ( ) if errorlevel 1 exit /b 1 -REM Patch +REM Patch, logging what was applied for tools\make_sbom.py. Its records go +REM in sbom-work, not build: a build directory in the repo root would shadow +REM the PyPA build package in the `python -m build` below. +if not exist ..\sbom-work mkdir ..\sbom-work +if exist ..\sbom-work\applied-patches.txt del ..\sbom-work\applied-patches.txt +type nul > ..\sbom-work\applied-patches.txt set patch_rc=0 for %%f in (..\patches-common\*.patch ..\patches\*.patch ..\patches-windows\*.patch) do ( git apply --ignore-whitespace %%f - if errorlevel 1 set patch_rc=1 + if errorlevel 1 ( + set patch_rc=1 + ) else ( + >>..\sbom-work\applied-patches.txt echo %%f + ) ) if not "%patch_rc%"=="0" exit /b 1 @@ -134,6 +143,11 @@ if "%if_bits%"=="64" ( REM Create build directory and navigate to it if exist build (rmdir /S /Q build || exit /b 1) + +REM The tree is final now: patched, and CMakeLists.txt edited above. Save its +REM diff for the SBOM before compiling (tools\make_sbom.py). +python ..\tools\make_sbom.py snapshot --out ..\sbom-work\openblas-source.diff +if errorlevel 1 exit /b 1 mkdir build || exit /b 1 & cd build || exit /b 1 echo Setting up %vcvars_arch% Developer Command Prompt and running CMake... @@ -269,6 +283,16 @@ if errorlevel 1 exit /b 1 echo Build complete. Returning to Batch. cd ../.. + +REM Record the toolchain for the wheel's SBOM (tools/make_sbom.py). The flang +REM runtime is the one third-party archive linked into the DLL. +python tools\make_sbom.py collect --out sbom-work\sbom-build.json ^ + --config "PLAT=%PLAT%" --config "INTERFACE_BITS=%if_bits%" ^ + --config "cmake_flags=%arch_flags% %interface_flags%" ^ + --config "C_FLAGS_RELEASE=%release_flags%" --config "NIGHTLY=%NIGHTLY%" ^ + --tool cc=clang-cl --tool fc=flang --tool ld=lld-link ^ + --static "flang-rt=%FLANG_RT_DIR%\flang_rt.runtime.dynamic.lib,version=%LLVM_VERSION%,purl=pkg:github/llvm/llvm-project@llvmorg-%LLVM_VERSION%,url=https://github.com/llvm/llvm-project/releases/tag/llvmorg-%LLVM_VERSION%" +if errorlevel 1 exit /b 1 if "%if_bits%"=="32" ( echo Rewrite to scipy_openblas32 set out_pyproject=pyproject_64_32.toml @@ -392,6 +416,9 @@ if not defined WHEEL_FILE ( exit /b 1 ) +python tools\make_sbom.py inject sbom-work\sbom-build.json %WHEEL_FILE% +if errorlevel 1 exit /b 1 + echo Installing wheel: %WHEEL_FILE% pip install "%WHEEL_FILE%" if errorlevel 1 exit /b 1 diff --git a/tools/gfortran_compat.sh b/tools/gfortran_compat.sh index 3ab4b2c0..fff50708 100644 --- a/tools/gfortran_compat.sh +++ b/tools/gfortran_compat.sh @@ -195,6 +195,11 @@ function build_gfortran_compat { wanted="_gfortran_pow_r4_i8 _gfortran_pow_r8_i8" fi + # tools/make_sbom.py reads these to list the libgfortran objects that + # end up inside the library: " " per line. + : > members.txt + echo "$archive" > archive.txt + local sym member for sym in $wanted; do # `|| true`: grep exits 1 when the member is absent, and under @@ -227,6 +232,7 @@ function build_gfortran_compat { echo "gfortran_compat: $member is not self-contained: $undef" >&2 cd "$here"; return 1 fi + echo "$member $sym" >> members.txt echo "gfortran_compat: took $member for $sym" >&2 done diff --git a/tools/make_sbom.py b/tools/make_sbom.py new file mode 100644 index 00000000..052651b5 --- /dev/null +++ b/tools/make_sbom.py @@ -0,0 +1,569 @@ +#!/usr/bin/env python3 +"""Write a CycloneDX SBOM into a scipy_openblas wheel (PEP 770). + +Three steps, because what went into the build is only knowable while +building, and the final wheel only exists after auditwheel/delocate have run: + + snapshot run after the OpenBLAS tree has been patched and edited, just + before compiling. Saves the complete diff of the tree against its + commit -- patch files plus any edits the build scripts make -- so + the SBOM carries the exact source that was compiled, not a pointer + to patch files that may have changed or gone by the time anyone + needs to look. + + collect run right after OpenBLAS is built, in the build environment. + Records the OpenBLAS commit, the patches the build applied (from + sbom-work/applied-patches.txt, written by the patch loops) and the + snapshot diff, the build configuration, + the toolchain, and every third-party archive linked statically + into the library, together with the distribution package (rpm, + apk, conda, LLVM release) it came from. Writes a JSON file. + + inject run on the finished wheel. Turns that JSON into a CycloneDX 1.6 + document, adds the sha256 of the shipped shared library, and stores + it as .dist-info/sboms/scipy-openblas.cdx.json, updating + RECORD. An SBOM auditwheel already put there is left alone. + +Only the standard library is used, since this runs in the manylinux +containers, on macOS and Windows, and in the Android build venv. +""" + +import argparse +import base64 +import csv +import datetime +import glob +import hashlib +import io +import json +import os +import platform +import re +import shutil +import subprocess +import sys +import tempfile +import uuid +import zipfile + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SBOM_NAME = "scipy-openblas.cdx.json" +# Where the build leaves its records for this script. Not "build/": on +# Windows the wheel is made with `python -m build` from the repo root, +# and a build/ directory there shadows the PyPA build package. +WORK_DIR = os.path.join(REPO_ROOT, "sbom-work") + +LICENSES = { + "openblas": "BSD-3-Clause", + "libgfortran": "GPL-3.0-or-later WITH GCC-exception-3.1", + "flang-rt": "Apache-2.0 WITH LLVM-exception", +} + + +# -------------------------------------------------------------------------- +# helpers + +def run(*cmd, cwd=None): + """Return stripped stdout of cmd, or None if it cannot be run.""" + try: + out = subprocess.run(cmd, cwd=cwd, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=True, + universal_newlines=True) + except (OSError, subprocess.CalledProcessError): + return None + return out.stdout.strip() + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def which(prog): + """Resolve a compiler given as a name or a path (possibly with args).""" + if not prog: + return None + prog = prog.split()[0] + path = shutil.which(prog) + return os.path.realpath(path) if path else None + + +def os_release(): + info = {} + try: + with open("/etc/os-release") as f: + for line in f: + key, sep, val = line.strip().partition("=") + if sep: + info[key] = val.strip('"') + except OSError: + pass + return info + + +def owning_package(path): + """The distribution package that installed path, as a dict, or None.""" + if not path or not os.path.exists(path): + return None + osr = os_release() + distro = osr.get("ID") + distro_ver = osr.get("VERSION_ID") + out = run("rpm", "-qf", "--qf", + "%{NAME}\t%{EPOCH}\t%{VERSION}\t%{RELEASE}\t%{ARCH}\n", path) + if out: + name, epoch, ver, rel, arch = out.splitlines()[0].split("\t") + evr = "%s-%s" % (ver, rel) + qual = "arch=%s" % arch + if epoch not in ("", "(none)"): + qual += "&epoch=%s" % epoch + if distro: + qual += "&distro=%s-%s" % (distro, distro_ver) + return {"name": name, "version": evr, + "purl": "pkg:rpm/%s/%s@%s?%s" % (distro or "unknown", name, + evr, qual)} + out = run("apk", "info", "--who-owns", path) + if out: + # " is owned by gfortran-14.2.0-r6" + m = re.search(r"is owned by (\S+)-(\d\S*-r\d+)$", out) + if m: + name, ver = m.groups() + arch = run("apk", "--print-arch") or platform.machine() + return {"name": name, "version": ver, + "purl": "pkg:apk/alpine/%s@%s?arch=%s&distro=alpine-%s" + % (name, ver, arch, distro_ver)} + return None + + +def tool_info(role, prog, version_args=("--version",)): + path = which(prog) + if not path: + return None + out = run(path, *version_args) or "" + info = {"role": role, "path": path, + "version": out.splitlines()[0] if out else None} + pkg = owning_package(path) + if pkg: + info["package"] = pkg + return info + + +# -------------------------------------------------------------------------- +# snapshot + +def snapshot(args): + """Write `git diff HEAD` of OpenBLAS, including files the patches added. + + New files only show up in a diff once git knows about them, so they are + marked intent-to-add in a throwaway copy of the index; the real index, + and so the tree the build uses, is left untouched. + """ + ob = os.path.join(REPO_ROOT, "OpenBLAS") + git_index = run("git", "rev-parse", "--git-path", "index", cwd=ob) + if git_index is None: + sys.exit("make_sbom: %s is not a git checkout" % ob) + git_index = os.path.join(ob, git_index) + fd, tmp_index = tempfile.mkstemp(prefix="sbom-index-") + os.close(fd) + try: + shutil.copyfile(git_index, tmp_index) + env = dict(os.environ, GIT_INDEX_FILE=tmp_index) + untracked = subprocess.run( + ["git", "ls-files", "-z", "--others", "--exclude-standard"], + cwd=ob, env=env, check=True, stdout=subprocess.PIPE).stdout + paths = [p for p in untracked.decode().split("\0") if p] + if paths: + subprocess.run(["git", "add", "--intent-to-add", "--"] + paths, + cwd=ob, env=env, check=True) + diff = subprocess.run( + ["git", "-c", "core.quotePath=false", "diff", "--binary", + "--ignore-submodules", "HEAD"], + cwd=ob, env=env, check=True, stdout=subprocess.PIPE).stdout + finally: + os.unlink(tmp_index) + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "wb") as f: + f.write(diff) + print("make_sbom: OpenBLAS source diff, %d bytes, in %s" + % (len(diff), args.out)) + + +# -------------------------------------------------------------------------- +# collect + +def collect(args): + ob = os.path.join(REPO_ROOT, "OpenBLAS") + data = { + "openblas": { + "commit": run("git", "rev-parse", "HEAD", cwd=ob), + "describe": run("git", "describe", "--tags", "--abbrev=8", cwd=ob), + "patches": [], + }, + "repo": { + "commit": os.environ.get("GITHUB_SHA") + or run("git", "rev-parse", "HEAD", cwd=REPO_ROOT), + "describe": run("git", "describe", "--tags", "--always", + cwd=REPO_ROOT), + "url": "https://github.com/%s" % os.environ.get( + "GITHUB_REPOSITORY", "MacPython/openblas-libs"), + }, + "ci": {}, + "build": {}, + "host": {"system": platform.system(), "machine": platform.machine(), + "release": platform.release()}, + "tools": [], + "static": [], + } + + if os.environ.get("GITHUB_RUN_ID"): + data["ci"] = { + "run_url": "%s/%s/actions/runs/%s" % ( + os.environ.get("GITHUB_SERVER_URL", "https://github.com"), + os.environ.get("GITHUB_REPOSITORY"), + os.environ["GITHUB_RUN_ID"]), + "run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"), + "workflow": os.environ.get("GITHUB_WORKFLOW_REF"), + } + + # Both files are written earlier in the build; a missing one means the + # build changed shape, and an SBOM without them would be silently wrong. + with open(args.applied_patches) as f: + for line in f: + # The patch loops run inside OpenBLAS/ and log "../patches/x" + # (posix) or "..\\patches\\x" (Windows). + name = line.strip().replace("\\", "/") + if not name: + continue + path = os.path.normpath(os.path.join(REPO_ROOT, "OpenBLAS", name)) + data["openblas"]["patches"].append( + {"name": os.path.relpath(path, REPO_ROOT).replace(os.sep, "/"), + "sha256": sha256_file(path)}) + with open(args.source_diff, "rb") as f: + diff = f.read() + data["openblas"]["source_diff"] = diff.decode("utf-8", "replace") + data["openblas"]["source_diff_sha256"] = hashlib.sha256(diff).hexdigest() + + for kv in args.config: + key, _, val = kv.partition("=") + data["build"][key] = val + + osr = os_release() + if osr: + data["host"]["os"] = osr.get("PRETTY_NAME") + for var in ("AUDITWHEEL_PLAT", "MACOSX_DEPLOYMENT_TARGET", + "ANDROID_API_LEVEL", "VCToolsVersion", "WindowsSDKVersion", + "VSCMD_VER"): + if os.environ.get(var): + data["host"][var] = os.environ[var] + if platform.system() == "Darwin": + data["host"]["os"] = "macOS " + (run("sw_vers", "-productVersion") or "") + data["host"]["sdk"] = run("xcrun", "--show-sdk-version") + + for spec in args.tool: + role, _, prog = spec.partition("=") + info = tool_info(role, prog) + if info: + data["tools"].append(info) + + for spec in args.static: + # name=path[,key=value...] + name, _, rest = spec.partition("=") + fields = rest.split(",") + path = fields[0] + entry = {"name": name, "path": path} + if os.path.exists(path): + entry["sha256"] = sha256_file(path) + pkg = owning_package(os.path.realpath(path)) + if pkg: + entry["package"] = pkg + for f in fields[1:]: + k, _, v = f.partition("=") + entry[k] = v + if "members_file" in entry: + with open(entry.pop("members_file")) as f: + entry["members"] = [ln.split() for ln in f if ln.strip()] + data["static"].append(entry) + + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as f: + json.dump(data, f, indent=2) + print("make_sbom: wrote build record %s" % args.out) + + +# -------------------------------------------------------------------------- +# inject + +def props(d, prefix): + return [{"name": prefix + k, "value": str(v)} + for k, v in sorted(d.items()) if v not in (None, "")] + + +def make_bom(data, dist_name, dist_version, libs): + ob = data["openblas"] + wheel_ref = "pkg:pypi/%s@%s" % (dist_name, dist_version) + ob_ref = "openblas" + + ob_component = { + "type": "library", + "bom-ref": ob_ref, + "name": "OpenBLAS", + "version": ob.get("describe") or "unknown", + "licenses": [{"expression": LICENSES["openblas"]}], + "externalReferences": [ + {"type": "vcs", + "url": "https://github.com/OpenMathLib/OpenBLAS"}], + "description": "OpenBLAS including its bundled reference LAPACK, " + "built as a single shared library", + } + if ob.get("commit"): + ob_component["purl"] = ( + "pkg:github/OpenMathLib/OpenBLAS@%s" % ob["commit"]) + if ob["source_diff"]: + # One combined diff rather than one entry per patch file: it is what + # was compiled, including edits the build scripts make that are not + # patch files. To rebuild the source, check out the commit in the + # purl and `git apply` this text. The individual patch files and + # their hashes are listed in the notes and the metadata properties. + repo_blob = "%s/blob/%s/" % (data["repo"]["url"], + data["repo"].get("commit") or "main") + notes = ("Source as compiled: the OpenBLAS commit in the purl plus " + "the diff below (sha256 %s). Patch files applied, in " + "order: %s. Any other changes in the diff were made by the " + "build scripts." % ( + ob["source_diff_sha256"], + ", ".join(repo_blob + p["name"] for p in ob["patches"]) + or "none")) + ob_component["pedigree"] = { + "patches": [{"type": "unofficial", "diff": {"text": { + "contentType": "text/x-diff", + "content": ob["source_diff"]}}}], + "notes": notes, + } + + components = [ob_component] + depends = [ob_ref] + + for lib in libs: + components.append({ + "type": "file", + "bom-ref": "file:" + lib["path"], + "name": lib["path"], + "hashes": [{"alg": "SHA-256", "content": lib["sha256"]}], + "description": "the shipped OpenBLAS shared library", + }) + depends.append("file:" + lib["path"]) + + for st in data["static"]: + ref = "static:" + st["name"] + c = { + "type": "library", + "bom-ref": ref, + "name": st["name"], + "scope": "required", + "description": "linked statically into the OpenBLAS shared " + "library", + } + if st.get("version"): + c["version"] = st["version"] + if st.get("license") or st["name"] in LICENSES: + c["licenses"] = [{"expression": st.get("license") + or LICENSES[st["name"]]}] + if st.get("sha256"): + c["hashes"] = [{"alg": "SHA-256", "content": st["sha256"]}] + pkg = st.get("package") + if pkg: + c["purl"] = pkg["purl"] + c.setdefault("version", pkg["version"]) + elif st.get("purl"): + c["purl"] = st["purl"] + if st.get("url"): + c["externalReferences"] = [{"type": "distribution", + "url": st["url"]}] + path = st["path"] + if os.path.abspath(path).startswith(REPO_ROOT + os.sep): + path = os.path.relpath(path, REPO_ROOT).replace(os.sep, "/") + p = [{"name": "scipy-openblas:path", "value": path}] + for member, symbol in st.get("members", []): + p.append({"name": "scipy-openblas:object", + "value": "%s (%s)" % (member, symbol)}) + c["properties"] = p + components.append(c) + depends.append(ref) + + for t in data["tools"]: + c = { + "type": "application", + "bom-ref": "tool:" + t["role"], + "name": t["role"], + "scope": "excluded", + "description": "build tool, not shipped: " + (t["version"] or ""), + "properties": [{"name": "scipy-openblas:path", + "value": t["path"]}], + } + if t.get("package"): + c["version"] = t["package"]["version"] + c["purl"] = t["package"]["purl"] + elif t["version"]: + m = re.search(r"(\d+\.\d+[\w.\-]*)", t["version"]) + if m: + c["version"] = m.group(1) + components.append(c) + + metadata_props = (props(data["repo"], "scipy-openblas:repo:") + + props(data["ci"], "scipy-openblas:ci:") + + props(data["host"], "scipy-openblas:host:") + + props(data["build"], "scipy-openblas:build:") + + [{"name": "scipy-openblas:openblas:patch", + "value": "%s sha256:%s" % (p["name"], p["sha256"])} + for p in ob["patches"]] + + [{"name": "scipy-openblas:openblas:source-diff-sha256", + "value": ob["source_diff_sha256"]}]) + + epoch = os.environ.get("SOURCE_DATE_EPOCH") + now = (datetime.datetime.fromtimestamp(int(epoch), datetime.timezone.utc) + if epoch else datetime.datetime.now(datetime.timezone.utc)) + return { + "bomFormat": "CycloneDX", + "specVersion": "1.6", + "serialNumber": "urn:uuid:%s" % uuid.uuid4(), + "version": 1, + "metadata": { + "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"), + "tools": {"components": [{ + "type": "application", "name": "make_sbom.py", + "externalReferences": [{ + "type": "vcs", + "url": data["repo"]["url"] + "/blob/main/tools/make_sbom.py"}], + }]}, + "component": { + "type": "library", + "bom-ref": wheel_ref, + "name": dist_name, + "version": dist_version, + "purl": wheel_ref, + "externalReferences": [ + {"type": "vcs", "url": data["repo"]["url"]}] + + ([{"type": "build-system", + "url": data["ci"]["run_url"]}] + if data["ci"].get("run_url") else []), + }, + "properties": metadata_props, + }, + "components": components, + "dependencies": [{"ref": wheel_ref, "dependsOn": depends}], + } + + +def record_hash(content): + digest = hashlib.sha256(content).digest() + return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + + +def inject(args): + with open(args.record) as f: + data = json.load(f) + wheels = [] + for w in args.wheels: + wheels.extend(glob.glob(w) or [w]) + if not wheels: + sys.exit("make_sbom: no wheel given") + for wheel in wheels: + inject_one(wheel, data) + + +def inject_one(wheel, data): + with zipfile.ZipFile(wheel) as zin: + names = zin.namelist() + dist_info = next(n.split("/")[0] for n in names + if n.split("/")[0].endswith(".dist-info")) + dist_name, dist_version = dist_info[:-len(".dist-info")].rsplit("-", 1) + dist_name = dist_name.replace("_", "-") + libs = [] + for n in names: + base = n.rsplit("/", 1)[-1] + # libscipy_openblas64_.so / .dylib, scipy_openblas_64.dll + if re.match(r"(lib)?scipy_openblas.*\.(so|dylib|dll)$", base) or \ + re.match(r"libscipy_openblas.*\.so\.", base): + libs.append({"path": n, + "sha256": hashlib.sha256(zin.read(n)).hexdigest()}) + if not libs: + sys.exit("make_sbom: no scipy_openblas library in %s" % wheel) + + bom = make_bom(data, dist_name, dist_version, libs) + sbom_path = "%s/sboms/%s" % (dist_info, SBOM_NAME) + sbom_bytes = (json.dumps(bom, indent=2) + "\n").encode() + record_path = dist_info + "/RECORD" + + rows = list(csv.reader(io.StringIO(zin.read(record_path).decode()))) + rows = [r for r in rows if r and r[0] not in (sbom_path, record_path)] + rows.append([sbom_path, record_hash(sbom_bytes), str(len(sbom_bytes))]) + rows.append([record_path, "", ""]) + buf = io.StringIO() + csv.writer(buf, lineterminator="\n").writerows(rows) + record_bytes = buf.getvalue().encode() + + fd, tmp = tempfile.mkstemp(suffix=".whl", + dir=os.path.dirname(os.path.abspath(wheel))) + os.close(fd) + try: + with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout: + for info in zin.infolist(): + if info.filename in (sbom_path, record_path): + continue + zout.writestr(info, zin.read(info.filename)) + zout.writestr(sbom_path, sbom_bytes) + # RECORD goes last, as the wheel spec recommends + zout.writestr(record_path, record_bytes) + except BaseException: + os.unlink(tmp) + raise + os.replace(tmp, wheel) + print("make_sbom: added %s to %s" % (sbom_path, os.path.basename(wheel))) + + +# -------------------------------------------------------------------------- + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawTextHelpFormatter) + sub = p.add_subparsers(dest="cmd") + sub.required = True + + c = sub.add_parser("collect", help="record the build environment") + c.add_argument("--out", required=True) + c.add_argument("--tool", action="append", default=[], + metavar="ROLE=PROGRAM", + help="a build tool, e.g. cc=$CC (repeatable)") + c.add_argument("--static", action="append", default=[], + metavar="NAME=PATH[,KEY=VAL...]", + help="a third-party archive linked in statically; keys: " + "version, license, purl, url, members_file " + "(repeatable)") + c.add_argument("--config", action="append", default=[], + metavar="KEY=VALUE", help="a build setting (repeatable)") + c.add_argument("--applied-patches", metavar="FILE", + default=os.path.join(WORK_DIR, "applied-patches.txt"), + help="list of patch files the build applied, one per line") + c.add_argument("--source-diff", metavar="FILE", + default=os.path.join(WORK_DIR, "openblas-source.diff"), + help="the diff written by snapshot") + c.set_defaults(func=collect) + + s = sub.add_parser("snapshot", help="save the diff of the OpenBLAS tree") + s.add_argument("--out", default=os.path.join(WORK_DIR, + "openblas-source.diff")) + s.set_defaults(func=snapshot) + + i = sub.add_parser("inject", help="add the SBOM to wheel(s)") + i.add_argument("record", help="the JSON written by collect") + i.add_argument("wheels", nargs="+") + i.set_defaults(func=inject) + + args = p.parse_args(argv) + args.func(args) + + +if __name__ == "__main__": + main()