From a064b0e7f419032d455d47f71ca3d9c77f381528 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Wed, 11 Nov 2026 12:21:49 -0800 Subject: [PATCH 1/4] Add Linux armhf cross-build toolchain, CI, and smoke tests. Enable phaser_runtime on 32-bit ARM via Bazel platform/toolchain and QEMU-backed tests on Ubuntu CI; bump coroutines for native ARM support and use BCR cpp_toolbelt to avoid module cycles. --- .bazelrc | 14 ++ .github/workflows/ci.yml | 29 +++ MODULE.bazel | 17 +- MODULE.bazel.lock | 109 +++++++++- README.md | 17 ++ bazel/toolchains/linux_arm32/BUILD.bazel | 10 + bazel/toolchains/linux_arm32/qemu.sh | 12 ++ bazel/toolchains/linux_arm32/repo.bzl | 247 +++++++++++++++++++++++ docker/arm32/Dockerfile | 33 +++ phaser/BUILD.bazel | 12 ++ phaser/arm32_platform_test.cc | 38 ++++ platform/BUILD.bazel | 28 +++ scripts/build-armhf-colima.sh | 52 +++++ scripts/build-armhf-linux.sh | 44 ++++ 14 files changed, 650 insertions(+), 12 deletions(-) create mode 100644 bazel/toolchains/linux_arm32/BUILD.bazel create mode 100755 bazel/toolchains/linux_arm32/qemu.sh create mode 100644 bazel/toolchains/linux_arm32/repo.bzl create mode 100644 docker/arm32/Dockerfile create mode 100644 phaser/arm32_platform_test.cc create mode 100644 platform/BUILD.bazel create mode 100755 scripts/build-armhf-colima.sh create mode 100755 scripts/build-armhf-linux.sh diff --git a/.bazelrc b/.bazelrc index 0ff7adb..d759ea7 100644 --- a/.bazelrc +++ b/.bazelrc @@ -103,3 +103,17 @@ build:libc++ --action_env=BAZEL_CXXOPTS=-stdlib=libc++ build:libc++ --action_env=BAZEL_LINKLIBS=-l%:libc++.a:-l%:libc++abi.a build:libc++ --action_env=BAZEL_LINKOPTS=-lm:-pthread build:libc++ --define force_libcpp=enabled + +# Linux ARMv7 hard-float (armhf) cross-compile from a Linux x86_64 or aarch64 host. +# Install g++-arm-linux-gnueabihf and qemu-user-static (Debian/Ubuntu). +# Example: +# bazel build --config=linux_arm32 //phaser/runtime:phaser_runtime +# On macOS, use scripts/build-armhf-colima.sh (Colima + docker/arm32). +build:linux_arm32 --platforms=//platform:linux_arm32 +build:linux_arm32 --extra_toolchains=@linux_arm32_toolchain//:cc_toolchain,@linux_arm32_toolchain//:cc_toolchain_aarch64 +build:linux_arm32 --cpu=armv7 +build:linux_arm32 --features=-external_include_paths +test:linux_arm32 --run_under=//bazel/toolchains/linux_arm32:qemu +test:linux_arm32 --test_env=QEMU_LD_PREFIX=/usr/arm-linux-gnueabihf +run:linux_arm32 --run_under=//bazel/toolchains/linux_arm32:qemu +run:linux_arm32 --run_env=QEMU_LD_PREFIX=/usr/arm-linux-gnueabihf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9654afa..c74c6d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,6 +42,7 @@ jobs: - name: Test (everything except perf_test) run: | bazel test --disk_cache="$HOME/.cache/bazel-disk" $EXTRA_CONFIG \ + --test_tag_filters=-linux_arm32 \ -- //... -//phaser:perf_test # AddressSanitizer runs on macOS (Apple Silicon). @@ -63,6 +64,7 @@ jobs: run: | bazel test --disk_cache="$HOME/.cache/bazel-disk" \ --config=asan --config=apple_silicon \ + --test_tag_filters=-linux_arm32 \ -- //... -//phaser:perf_test # AddressSanitizer runs on Linux (no apple_silicon config). @@ -84,6 +86,7 @@ jobs: run: | bazel test --disk_cache="$HOME/.cache/bazel-disk" \ --config=asan \ + --test_tag_filters=-linux_arm32 \ -- //... -//phaser:perf_test # Valgrind (memcheck) runs on Linux only. @@ -109,4 +112,30 @@ jobs: - name: Test under Valgrind (everything except perf_test) run: | bazel test --disk_cache="$HOME/.cache/bazel-disk" --config=valgrind \ + --test_tag_filters=-linux_arm32 \ -- //... -//phaser:perf_test + + # Cross-build phaser_runtime for armhf and smoke-test under QEMU user emulation. + arm32: + name: arm32 (Linux armhf) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install cross toolchain and QEMU + run: | + sudo apt-get update + sudo apt-get install -y g++-arm-linux-gnueabihf qemu-user-static binutils-arm-linux-gnueabihf + + - name: Cache Bazel + uses: actions/cache@v4 + with: + path: ~/.cache/bazel-disk + key: bazel-disk-arm32-linux-${{ hashFiles('MODULE.bazel', 'MODULE.bazel.lock', '.bazelrc', '.bazelversion') }} + restore-keys: | + bazel-disk-arm32-linux- + + - name: Build and test (armhf) + run: | + chmod +x scripts/build-armhf-linux.sh + scripts/build-armhf-linux.sh --test diff --git a/MODULE.bazel b/MODULE.bazel index 844bb40..42b7316 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -20,15 +20,7 @@ bazel_dep(name = "rules_pkg", version = "1.0.1") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") bazel_dep(name = "cpp_toolbelt", version = "2.1.6") - -# Remove once cpp_toolbelt 2.1.6 is in the Bazel Central Registry. -git_override( - module_name = "cpp_toolbelt", - commit = "86b45cdd3da46a97a4476be2f2a61909677284a2", - remote = "https://github.com/dallison/cpp_toolbelt.git", -) - -bazel_dep(name = "coroutines", version = "3.3.2") +bazel_dep(name = "coroutines", version = "3.4.1") # protobuf pulls an older rules_go via gazelle; Bazel 9 needs a current rules_go. single_version_override( @@ -51,3 +43,10 @@ rust = use_extension("@rules_rust//rust:extensions.bzl", "rust") rust.toolchain(edition = "2021") use_repo(rust, "rust_toolchains") register_toolchains("@rust_toolchains//:all") + +# Fetched only when --config=linux_arm32 selects @linux_arm32_toolchain. +linux_arm32_toolchain = use_repo_rule( + "//bazel/toolchains/linux_arm32:repo.bzl", + "linux_arm32_toolchain", +) +linux_arm32_toolchain(name = "linux_arm32_toolchain") diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 97b91ce..092d7fa 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -80,8 +80,10 @@ "https://bcr.bazel.build/modules/bazel_worker_java/0.0.8/MODULE.bazel": "e76479eae70bd4e8f5f4c2dfc5d03ab971cfb18750246c7b3f3454c5c2ee6629", "https://bcr.bazel.build/modules/buildozer/8.5.1/MODULE.bazel": "a35d9561b3fc5b18797c330793e99e3b834a473d5fbd3d7d7634aafc9bdb6f8f", "https://bcr.bazel.build/modules/buildozer/8.5.1/source.json": "e3386e6ff4529f2442800dee47ad28d3e6487f36a1f75ae39ae56c70f0cd2fbd", - "https://bcr.bazel.build/modules/coroutines/3.3.2/MODULE.bazel": "ad1395ae9758ee5d113acab755b4d972c368c4dab66513bfe31423136f3ee608", - "https://bcr.bazel.build/modules/coroutines/3.3.2/source.json": "fb47a4c3e13d730a1a58ed6a34add8f6aaeef655a47d0f179427f71bf58ba150", + "https://bcr.bazel.build/modules/coroutines/3.4.1/MODULE.bazel": "ac9abd7ce43b211ec5a37c63b1bf29e4b4455a645cb5539747b2fb776b42591d", + "https://bcr.bazel.build/modules/coroutines/3.4.1/source.json": "ca2002a54d0fac44387cd8f8a6ed3c89f2df137b192ec4395b6bf67736239ca1", + "https://bcr.bazel.build/modules/cpp_toolbelt/2.1.6/MODULE.bazel": "f2963e61c86cb8c0b33a3d47f2d3ebb800245e949357451e05ef912ebea38224", + "https://bcr.bazel.build/modules/cpp_toolbelt/2.1.6/source.json": "8cce32b4fbf40e39e474ae6c812b6bb1b3f2a2490d96b97e21c17b11c0fd31de", "https://bcr.bazel.build/modules/gawk/5.3.2.bcr.1/MODULE.bazel": "cdf8cbe5ee750db04b78878c9633cc76e80dcf4416cbe982ac3a9222f80713c8", "https://bcr.bazel.build/modules/gawk/5.3.2.bcr.1/source.json": "fa7b512dfcb5eafd90ce3959cf42a2a6fe96144ebbb4b3b3928054895f2afac2", "https://bcr.bazel.build/modules/gazelle/0.45.0/MODULE.bazel": "ecd19ebe9f8e024e1ccffb6d997cc893a974bcc581f1ae08f386bdd448b10687", @@ -167,7 +169,6 @@ "https://bcr.bazel.build/modules/rules_cc/0.2.0/MODULE.bazel": "b5c17f90458caae90d2ccd114c81970062946f49f355610ed89bebf954f5783c", "https://bcr.bazel.build/modules/rules_cc/0.2.13/MODULE.bazel": "eecdd666eda6be16a8d9dc15e44b5c75133405e820f620a234acc4b1fdc5aa37", "https://bcr.bazel.build/modules/rules_cc/0.2.14/MODULE.bazel": "353c99ed148887ee89c54a17d4100ae7e7e436593d104b668476019023b58df8", - "https://bcr.bazel.build/modules/rules_cc/0.2.16/MODULE.bazel": "9242fa89f950c6ef7702801ab53922e99c69b02310c39fb6e62b2bd30df2a1d4", "https://bcr.bazel.build/modules/rules_cc/0.2.17/MODULE.bazel": "1849602c86cb60da8613d2de887f9566a6d354a6df6d7009f9d04a14402f9a84", "https://bcr.bazel.build/modules/rules_cc/0.2.17/source.json": "3832f45d145354049137c0090df04629d9c2b5493dc5c2bf46f1834040133a07", "https://bcr.bazel.build/modules/rules_cc/0.2.4/MODULE.bazel": "1ff1223dfd24f3ecf8f028446d4a27608aa43c3f41e346d22838a4223980b8cc", @@ -382,6 +383,108 @@ } } }, + "@@rules_rust+//crate_universe/private:internal_extensions.bzl%cu_nr": { + "general": { + "bzlTransitiveDigest": "sczwLqD227NV8u20G93UxqFM//eXKLmfSv9V3Y6RTz0=", + "usagesDigest": "McimNXAztVHDzspa1Kng94T+YeyY/44zx9FkNqIMn2s=", + "recordedInputs": [ + "REPO_MAPPING:apple_support+,bazel_skylib bazel_skylib+", + "REPO_MAPPING:bazel_features+,bazel_features_globals bazel_features++version_extension+bazel_features_globals", + "REPO_MAPPING:bazel_features+,bazel_features_version bazel_features++version_extension+bazel_features_version", + "REPO_MAPPING:rules_cc+,bazel_skylib bazel_skylib+", + "REPO_MAPPING:rules_cc+,bazel_tools bazel_tools", + "REPO_MAPPING:rules_cc+,cc_compatibility_proxy rules_cc++compatibility_proxy+cc_compatibility_proxy", + "REPO_MAPPING:rules_cc+,platforms platforms", + "REPO_MAPPING:rules_cc+,rules_cc rules_cc+", + "REPO_MAPPING:rules_cc++compatibility_proxy+cc_compatibility_proxy,rules_cc rules_cc+", + "REPO_MAPPING:rules_rust+,apple_support apple_support+", + "REPO_MAPPING:rules_rust+,bazel_features bazel_features+", + "REPO_MAPPING:rules_rust+,bazel_skylib bazel_skylib+", + "REPO_MAPPING:rules_rust+,bazel_tools bazel_tools", + "REPO_MAPPING:rules_rust+,cui rules_rust++cu+cui", + "REPO_MAPPING:rules_rust+,rrc rules_rust++i2+rrc", + "REPO_MAPPING:rules_rust+,rules_cc rules_cc+", + "REPO_MAPPING:rules_rust+,rules_rust rules_rust+" + ], + "generatedRepoSpecs": { + "cargo_bazel_bootstrap": { + "repoRuleId": "@@rules_rust+//cargo/private:cargo_bootstrap.bzl%cargo_bootstrap_repository", + "attributes": { + "srcs": [ + "@@rules_rust+//crate_universe:src/api.rs", + "@@rules_rust+//crate_universe:src/api/lockfile.rs", + "@@rules_rust+//crate_universe:src/cli.rs", + "@@rules_rust+//crate_universe:src/cli/generate.rs", + "@@rules_rust+//crate_universe:src/cli/query.rs", + "@@rules_rust+//crate_universe:src/cli/render.rs", + "@@rules_rust+//crate_universe:src/cli/splice.rs", + "@@rules_rust+//crate_universe:src/cli/vendor.rs", + "@@rules_rust+//crate_universe:src/config.rs", + "@@rules_rust+//crate_universe:src/config/label_injection.rs", + "@@rules_rust+//crate_universe:src/context.rs", + "@@rules_rust+//crate_universe:src/context/crate_context.rs", + "@@rules_rust+//crate_universe:src/context/platforms.rs", + "@@rules_rust+//crate_universe:src/lib.rs", + "@@rules_rust+//crate_universe:src/lockfile.rs", + "@@rules_rust+//crate_universe:src/main.rs", + "@@rules_rust+//crate_universe:src/metadata.rs", + "@@rules_rust+//crate_universe:src/metadata/cargo_bin.rs", + "@@rules_rust+//crate_universe:src/metadata/cargo_tree_resolver.rs", + "@@rules_rust+//crate_universe:src/metadata/cargo_tree_rustc_wrapper.bat", + "@@rules_rust+//crate_universe:src/metadata/cargo_tree_rustc_wrapper.sh", + "@@rules_rust+//crate_universe:src/metadata/dependency.rs", + "@@rules_rust+//crate_universe:src/metadata/metadata_annotation.rs", + "@@rules_rust+//crate_universe:src/rendering.rs", + "@@rules_rust+//crate_universe:src/rendering/template_engine.rs", + "@@rules_rust+//crate_universe:src/rendering/templates/defs_bzl_shim.j2", + "@@rules_rust+//crate_universe:src/rendering/templates/module_bzl.j2", + "@@rules_rust+//crate_universe:src/rendering/templates/partials/header.j2", + "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/aliases_map.j2", + "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/deps_map.j2", + "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/repo_git.j2", + "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/repo_http.j2", + "@@rules_rust+//crate_universe:src/rendering/verbatim/alias_rules.bzl", + "@@rules_rust+//crate_universe:src/select.rs", + "@@rules_rust+//crate_universe:src/splicing.rs", + "@@rules_rust+//crate_universe:src/splicing/cargo_config.rs", + "@@rules_rust+//crate_universe:src/splicing/crate_index_lookup.rs", + "@@rules_rust+//crate_universe:src/splicing/splicer.rs", + "@@rules_rust+//crate_universe:src/test.rs", + "@@rules_rust+//crate_universe:src/utils.rs", + "@@rules_rust+//crate_universe:src/utils/starlark.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/glob.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/label.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/select.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/select_dict.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/select_list.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/select_scalar.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/select_set.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/serialize.rs", + "@@rules_rust+//crate_universe:src/utils/starlark/target_compatible_with.rs", + "@@rules_rust+//crate_universe:src/utils/symlink.rs", + "@@rules_rust+//crate_universe:src/utils/target_triple.rs" + ], + "binary": "cargo-bazel", + "cargo_lockfile": "@@rules_rust+//crate_universe:Cargo.lock", + "cargo_toml": "@@rules_rust+//crate_universe:Cargo.toml", + "version": "1.98.0", + "rust_toolchain_cargo_template": "@rust_host_tools//:bin/{tool}", + "rust_toolchain_rustc_template": "@rust_host_tools//:bin/{tool}", + "compressed_windows_toolchain_names": false, + "timeout": 900 + } + } + }, + "moduleExtensionMetadata": { + "explicitRootModuleDirectDeps": [ + "cargo_bazel_bootstrap" + ], + "explicitRootModuleDirectDevDeps": [], + "useAllRepos": "NO", + "reproducible": false + } + } + }, "@@tar.bzl+//tar:extensions.bzl%toolchains": { "general": { "bzlTransitiveDigest": "/2afh6fPjq/rcyE/jztQDK3ierehmFFngfvmqyRv72M=", diff --git a/README.md b/README.md index 13070d6..5cbc855 100644 --- a/README.md +++ b/README.md @@ -569,6 +569,23 @@ bazelisk test --config=asan //phaser/... On Apple Silicon, the `asan` config already pulls in the native `apple_silicon` settings; see [`.bazelrc`](.bazelrc) for the available configurations. +### Linux armhf (32-bit ARM) + +Cross-compile `phaser_runtime` for 32-bit ARM Linux with `--config=linux_arm32`. CI and +native Ubuntu use [`scripts/build-armhf-linux.sh`](scripts/build-armhf-linux.sh) (requires +`g++-arm-linux-gnueabihf` and `qemu-user-static`). On macOS, [`scripts/build-armhf-colima.sh`](scripts/build-armhf-colima.sh) +builds the same target inside a Colima Docker image. The `protoc-gen-phaser` plugin is built +for the host only (not armhf). + +```bash +# Linux (or CI) +scripts/build-armhf-linux.sh +scripts/build-armhf-linux.sh --test + +# macOS (Colima + Docker) +scripts/build-armhf-colima.sh --test +``` + ### Using Phaser without Bazel Phaser is a `protoc` plugin, so any build system can drive it as long as the plugin binary diff --git a/bazel/toolchains/linux_arm32/BUILD.bazel b/bazel/toolchains/linux_arm32/BUILD.bazel new file mode 100644 index 0000000..631f49b --- /dev/null +++ b/bazel/toolchains/linux_arm32/BUILD.bazel @@ -0,0 +1,10 @@ +# The armhf C++ toolchain is generated by @linux_arm32_toolchain. This +# package exists so MODULE.bazel can load repo.bzl. +load("@rules_shell//shell:sh_binary.bzl", "sh_binary") + +package(default_visibility = ["//visibility:public"]) + +sh_binary( + name = "qemu", + srcs = ["qemu.sh"], +) diff --git a/bazel/toolchains/linux_arm32/qemu.sh b/bazel/toolchains/linux_arm32/qemu.sh new file mode 100755 index 0000000..4fbb020 --- /dev/null +++ b/bazel/toolchains/linux_arm32/qemu.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Run an armhf binary on the host. Ubuntu 24.04 names the emulator +# qemu-arm-static; Ubuntu 26.04 names it qemu-arm. +set -euo pipefail +export QEMU_LD_PREFIX="${QEMU_LD_PREFIX:-/usr/arm-linux-gnueabihf}" +if command -v qemu-arm-static >/dev/null 2>&1; then + exec qemu-arm-static "$@" +elif command -v qemu-arm >/dev/null 2>&1; then + exec qemu-arm "$@" +fi +echo "qemu-arm-static or qemu-arm is required to run armhf binaries" >&2 +exit 1 diff --git a/bazel/toolchains/linux_arm32/repo.bzl b/bazel/toolchains/linux_arm32/repo.bzl new file mode 100644 index 0000000..8cea8cb --- /dev/null +++ b/bazel/toolchains/linux_arm32/repo.bzl @@ -0,0 +1,247 @@ +"""Local ARMv7 hard-float Linux C++ toolchain. + +Uses the distro `arm-linux-gnueabihf` cross compiler +(`g++-arm-linux-gnueabihf`). The repository is fetched only when a build +selects `@linux_arm32_toolchain`, so hosts without the cross compiler can +still build for the machine they are running on. +""" + +_TOOLS = [ + "ar", + "cpp", + "dwp", + "gcov", + "ld", + "nm", + "objcopy", + "objdump", + "strip", +] + +def _include_dirs(repository_ctx, gxx): + result = repository_ctx.execute( + [gxx, "-E", "-x", "c++", "-", "-v"], + environment = {"LANG": "C"}, + ) + if result.return_code != 0: + fail("failed to query {} include paths:\n{}".format(gxx, result.stderr)) + + includes = [] + in_list = False + for line in result.stderr.splitlines(): + if line.startswith("#include <...>"): + in_list = True + continue + if line.startswith("End of search list"): + break + if not in_list: + continue + path = line.strip() + # The cross compiler also lists the host /usr/include. Those headers + # are the wrong architecture. + if path == "/usr/include" or path.startswith("/usr/include/"): + continue + resolved = repository_ctx.execute(["readlink", "-f", path]).stdout.strip() + if resolved and resolved not in includes: + includes.append(resolved) + if not includes: + fail("no target include directories reported by " + gxx) + return includes + +def _write_wrapper(repository_ctx): + repository_ctx.file( + "bin/armhf-tool.sh", + """#!/usr/bin/env bash +set -euo pipefail + +tool="$1" +shift +prefix="/usr/bin/arm-linux-gnueabihf" + +if [[ "${tool}" == "compiler" ]]; then + compiler_kind="g++" + previous="" + for arg in "$@"; do + if [[ "${previous}" == "-x" ]]; then + case "${arg}" in + c|assembler|assembler-with-cpp) compiler_kind="gcc" ;; + esac + previous="" + continue + fi + case "${arg}" in + -x) previous="-x" ;; + *.c|*.s|*.S) compiler_kind="gcc" ;; + esac + done + exec "${prefix}-${compiler_kind}" "$@" +fi + +exec "${prefix}-${tool}" "$@" +""", + executable = True, + ) + repository_ctx.file( + "bin/armhf-compiler", + """#!/usr/bin/env bash +exec "$(dirname "$0")/armhf-tool.sh" compiler "$@" +""", + executable = True, + ) + for tool in _TOOLS: + repository_ctx.file( + "bin/armhf-" + tool, + """#!/usr/bin/env bash +exec "$(dirname "$0")/armhf-tool.sh" {tool} "$@" +""".format(tool = tool), + executable = True, + ) + +def _linux_arm32_toolchain_impl(repository_ctx): + gxx = repository_ctx.which("arm-linux-gnueabihf-g++") + gcc = repository_ctx.which("arm-linux-gnueabihf-gcc") + if not gxx or not gcc: + fail( + "arm-linux-gnueabihf-g++ was not found on PATH. " + + "Install g++-arm-linux-gnueabihf (Debian/Ubuntu) and retry " + + "`bazel build --config=linux_arm32 ...`.", + ) + includes = _include_dirs(repository_ctx, str(gxx)) + _write_wrapper(repository_ctx) + # -nostdinc drops the compiler's default search path, which ends in the + # host /usr/include. Headers found there (valgrind, for example) are the + # wrong architecture and Bazel rejects the absolute include. + compile_flags = [ + "-fPIC", + "-no-canonical-prefixes", + "-fno-canonical-system-headers", + "-nostdinc", + "-march=armv7-a", + "-mfpu=vfpv3-d16", + "-mfloat-abi=hard", + ] + for inc in includes: + compile_flags.append("-isystem") + compile_flags.append(inc) + + tool_paths = { + "gcc": "bin/armhf-compiler", + "ar": "bin/armhf-ar", + "cpp": "bin/armhf-cpp", + "dwp": "bin/armhf-dwp", + "gcov": "bin/armhf-gcov", + "ld": "bin/armhf-ld", + "nm": "bin/armhf-nm", + "objcopy": "bin/armhf-objcopy", + "objdump": "bin/armhf-objdump", + "strip": "bin/armhf-strip", + } + repository_ctx.file( + "BUILD.bazel", + """load("@rules_cc//cc:defs.bzl", "cc_toolchain") +load("@rules_cc//cc/private/toolchain:unix_cc_toolchain_config.bzl", "cc_toolchain_config") + +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "all_files", + srcs = glob(["bin/**"]), +) + +filegroup( + name = "empty", + srcs = [], +) + +cc_toolchain_config( + name = "config", + abi_libc_version = "glibc", + abi_version = "gnueabihf", + compile_flags = {compile_flags}, + compiler = "gcc", + cpu = "armv7", + cxx_builtin_include_directories = {includes}, + cxx_flags = ["-std=c++17"], + dbg_compile_flags = ["-g"], + host_system_name = "local", + link_flags = [ + "-no-canonical-prefixes", + "-lstdc++", + "-lm", + "-ldl", + ], + opt_compile_flags = [ + "-g0", + "-O2", + "-DNDEBUG", + ], + opt_link_flags = ["-Wl,-S"], + supports_start_end_lib = False, + target_libc = "glibc", + target_system_name = "arm-linux-gnueabihf", + tool_paths = {tool_paths}, + toolchain_identifier = "linux-arm32-gnueabihf", + unfiltered_compile_flags = [ + "-no-canonical-prefixes", + "-fno-canonical-system-headers", + "-Wno-builtin-macro-redefined", + '-D__DATE__="redacted"', + '-D__TIMESTAMP__="redacted"', + '-D__TIME__="redacted"', + ], +) + +cc_toolchain( + name = "cc-compiler", + all_files = ":all_files", + ar_files = ":all_files", + compiler_files = ":all_files", + dwp_files = ":empty", + linker_files = ":all_files", + objcopy_files = ":all_files", + strip_files = ":all_files", + supports_param_files = 1, + toolchain_config = ":config", + toolchain_identifier = "linux-arm32-gnueabihf", +) + +toolchain( + name = "cc_toolchain", + exec_compatible_with = [ + "@platforms//cpu:x86_64", + "@platforms//os:linux", + ], + target_compatible_with = [ + "@platforms//cpu:armv7", + "@platforms//os:linux", + ], + toolchain = ":cc-compiler", + toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", +) + +toolchain( + name = "cc_toolchain_aarch64", + exec_compatible_with = [ + "@platforms//cpu:aarch64", + "@platforms//os:linux", + ], + target_compatible_with = [ + "@platforms//cpu:armv7", + "@platforms//os:linux", + ], + toolchain = ":cc-compiler", + toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", +) +""".format( + compile_flags = repr(compile_flags), + includes = repr(includes), + tool_paths = repr(tool_paths), + ), + ) + +linux_arm32_toolchain = repository_rule( + implementation = _linux_arm32_toolchain_impl, + configure = True, + local = True, + environ = ["PATH"], +) diff --git a/docker/arm32/Dockerfile b/docker/arm32/Dockerfile new file mode 100644 index 0000000..24ecfcd --- /dev/null +++ b/docker/arm32/Dockerfile @@ -0,0 +1,33 @@ +# Native aarch64/amd64 image used to cross-compile Phaser for armhf with Bazel. +# Colima on Apple Silicon runs this as linux/arm64; qemu-user-static runs the +# armhf binaries it produces when tests use --config=linux_arm32. +FROM ubuntu:24.04 + +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential \ + ca-certificates \ + curl \ + git \ + openjdk-21-jdk-headless \ + python3 \ + unzip \ + zip \ + gcc-arm-linux-gnueabihf \ + g++-arm-linux-gnueabihf \ + libc6-dev-armhf-cross \ + qemu-user-static \ + && rm -rf /var/lib/apt/lists/* + +# Bazelisk picks the version from .bazelversion in the mounted repo. +RUN arch="$(uname -m)"; \ + case "${arch}" in \ + aarch64) bazelisk_arch=arm64 ;; \ + x86_64) bazelisk_arch=amd64 ;; \ + *) echo "unsupported docker arch: ${arch}" >&2; exit 1 ;; \ + esac; \ + curl -fsSL -o /usr/local/bin/bazelisk \ + "https://github.com/bazelbuild/bazelisk/releases/download/v1.25.0/bazelisk-linux-${bazelisk_arch}" && \ + chmod +x /usr/local/bin/bazelisk && \ + ln -sf /usr/local/bin/bazelisk /usr/local/bin/bazel diff --git a/phaser/BUILD.bazel b/phaser/BUILD.bazel index 3141878..408f6ba 100644 --- a/phaser/BUILD.bazel +++ b/phaser/BUILD.bazel @@ -37,6 +37,18 @@ cc_library( ], ) +# Built and executed with --config=linux_arm32 (QEMU on CI). Skips on native hosts. +cc_test( + name = "arm32_platform_test", + srcs = ["arm32_platform_test.cc"], + copts = PHASER_COPTS, + tags = ["linux_arm32"], + deps = [ + "//phaser/runtime:phaser_runtime", + "@com_google_googletest//:gtest_main", + ], +) + cc_test( name = "columnar_test", srcs = ["columnar_test.cc"], diff --git a/phaser/arm32_platform_test.cc b/phaser/arm32_platform_test.cc new file mode 100644 index 0000000..fb89e8b --- /dev/null +++ b/phaser/arm32_platform_test.cc @@ -0,0 +1,38 @@ +// Copyright 2024-2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include + +#include "gtest/gtest.h" +#include "phaser/runtime/md5.h" + +namespace phaser { +namespace { + +bool IsArm32() { +#if defined(__arm__) && !defined(__aarch64__) + return true; +#else + return false; +#endif +} + +TEST(Arm32PlatformTest, ThirtyTwoBitPointers) { + if (!IsArm32()) { + GTEST_SKIP() << "armhf-only"; + } + EXPECT_EQ(sizeof(void*), 4u); +} + +TEST(Arm32PlatformTest, Md5Digest) { + if (!IsArm32()) { + GTEST_SKIP() << "armhf-only"; + } + const std::string digest = Md5("phaser-arm32"); + EXPECT_EQ(digest.size(), 32u); + EXPECT_EQ(digest, "6c87cfacf0231472239d82855e2a0f08"); +} + +} // namespace +} // namespace phaser diff --git a/platform/BUILD.bazel b/platform/BUILD.bazel new file mode 100644 index 0000000..03077f2 --- /dev/null +++ b/platform/BUILD.bazel @@ -0,0 +1,28 @@ +# Explicit platforms for cross-compilation and macOS Rust crate resolution. +package(default_visibility = ["//visibility:public"]) + +platform( + name = "darwin_arm64", + constraint_values = [ + "@platforms//cpu:aarch64", + "@platforms//os:osx", + ], +) + +platform( + name = "darwin_x86_64", + constraint_values = [ + "@platforms//cpu:x86_64", + "@platforms//os:osx", + ], +) + +# Cross-compilation target: 32-bit ARM Linux, hard float (armhf / ARMv7). +# Select with --config=linux_arm32. +platform( + name = "linux_arm32", + constraint_values = [ + "@platforms//cpu:armv7", + "@platforms//os:linux", + ], +) diff --git a/scripts/build-armhf-colima.sh b/scripts/build-armhf-colima.sh new file mode 100755 index 0000000..dba5300 --- /dev/null +++ b/scripts/build-armhf-colima.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Cross-build Phaser for 32-bit ARM Linux (armhf) inside Colima. +# +# Colima only hosts aarch64 and x86_64 VMs, and Bazel does not ship a 32-bit +# ARM binary, so this uses an Ubuntu container with gcc-arm-linux-gnueabihf and +# Bazel's @linux_arm32_toolchain. +# +# Usage, from the repo root: +# scripts/build-armhf-colima.sh +# scripts/build-armhf-colima.sh --test +# +set -euo pipefail + +root=$(cd "$(dirname "$0")/.." && pwd) +cd "$root" + +run_tests=0 +if [[ "${1:-}" == "--test" ]]; then + run_tests=1 +elif [[ -n "${1:-}" ]]; then + echo "usage: $0 [--test]" >&2 + exit 2 +fi + +if ! colima status >/dev/null 2>&1; then + echo "Starting Colima (aarch64)..." + colima start --profile default --arch aarch64 --cpu 6 --memory 12 --disk 80 --vm-type vz +fi + +docker build -t phaser-arm32-builder -f docker/arm32/Dockerfile docker/arm32 + +# Cross-compile the runtime for the device. The phaser protoc plugin stays on the +# host (build without --config=linux_arm32). +build_targets="//phaser/runtime:phaser_runtime" +test_targets="//phaser:arm32_platform_test //phaser/runtime:payload_buffer_test //phaser/runtime:md5_test" + +docker run --rm \ + --user "$(id -u):$(id -g)" \ + -e HOME=/tmp \ + -e USER=builder \ + -v "$root:/src" \ + -w /src \ + phaser-arm32-builder \ + bash -eo pipefail -c " + set -euo pipefail + export PATH=/usr/local/bin:\$PATH + bazel build --config=linux_arm32 ${build_targets} + readelf -h bazel-bin/phaser/runtime/libphaser_runtime.so | grep -E 'Class:|Machine:' + if [[ ${run_tests} -eq 1 ]]; then + bazel test --config=linux_arm32 ${test_targets} + fi + " diff --git a/scripts/build-armhf-linux.sh b/scripts/build-armhf-linux.sh new file mode 100755 index 0000000..8f537ef --- /dev/null +++ b/scripts/build-armhf-linux.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Cross-build Phaser for 32-bit ARM Linux (armhf) on Linux (CI or native Ubuntu). +# +# Requires: g++-arm-linux-gnueabihf, qemu-user-static (Debian/Ubuntu). +# +# Usage: +# scripts/build-armhf-linux.sh +# scripts/build-armhf-linux.sh --test +# +set -euo pipefail + +root=$(cd "$(dirname "$0")/.." && pwd) +cd "$root" + +run_tests=0 +if [[ "${1:-}" == "--test" ]]; then + run_tests=1 +elif [[ -n "${1:-}" ]]; then + echo "usage: $0 [--test]" >&2 + exit 2 +fi + +if ! command -v arm-linux-gnueabihf-g++ >/dev/null 2>&1; then + echo "arm-linux-gnueabihf-g++ not found; install g++-arm-linux-gnueabihf" >&2 + exit 1 +fi + +build_targets="//phaser/runtime:phaser_runtime" +test_targets=( + "//phaser:arm32_platform_test" + "//phaser/runtime:payload_buffer_test" + "//phaser/runtime:md5_test" +) + +bazel build --config=linux_arm32 ${build_targets} +readelf -h bazel-bin/phaser/runtime/libphaser_runtime.so | grep -E 'Class:|Machine:' + +if [[ ${run_tests} -eq 1 ]]; then + if ! command -v qemu-arm-static >/dev/null 2>&1 && ! command -v qemu-arm >/dev/null 2>&1; then + echo "qemu-arm-static or qemu-arm required to run armhf tests" >&2 + exit 1 + fi + bazel test --config=linux_arm32 "${test_targets[@]}" +fi From 0ce12b41dbf7cb35d1a57980b7a01671f494fcc7 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Wed, 11 Nov 2026 12:28:32 -0800 Subject: [PATCH 2/4] Bump module version to 3.1.2 for armhf support release. --- MODULE.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MODULE.bazel b/MODULE.bazel index 42b7316..c44233a 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -1,6 +1,6 @@ module( name = "phaser", - version = "3.1.1" + version = "3.1.2" ) bazel_dep(name = "bazel_skylib", version = "1.9.0") From 3bdece360efdcff7f62bee4d291105e412a38fd6 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Wed, 11 Nov 2026 13:41:23 -0800 Subject: [PATCH 3/4] Fix armhf testing, stable PayloadBuffer header, and small-block naming. Run the full cc_test suite under QEMU in CI scripts; fix 32-bit movable-buffer header alignment and static bank/plugin registration; pad PayloadBuffer to 48 bytes on all hosts; rename bitmap allocator terminology to small-block size-class free lists. --- .bazelrc | 2 + README.md | 8 +- phaser/docs/phaser_user_guide.md | 45 +++++------ phaser/phaser_library.bzl | 7 ++ phaser/plugins/arrow/BUILD.bazel | 2 + phaser/plugins/avro/BUILD.bazel | 3 + phaser/plugins/parquet/BUILD.bazel | 3 + phaser/plugins/protobuf/BUILD.bazel | 3 + phaser/plugins/ros/BUILD.bazel | 3 + phaser/receive_allocation_test.cc | 8 +- phaser/runtime/BUILD.bazel | 5 +- phaser/runtime/message.h | 32 ++++---- phaser/runtime/message_test.cc | 6 +- phaser/runtime/payload_buffer.cc | 61 ++++++++------- phaser/runtime/payload_buffer.h | 103 ++++++++++++++++---------- phaser/runtime/payload_buffer_test.cc | 29 ++++---- phaser/runtime/wireformat.h | 18 ++--- phaser/runtime/wireformat_test.cc | 6 +- phaser/testdata/BUILD | 13 +++- platform/BUILD.bazel | 5 ++ scripts/build-armhf-colima.sh | 12 ++- scripts/build-armhf-linux.sh | 33 ++++++--- 22 files changed, 239 insertions(+), 168 deletions(-) diff --git a/.bazelrc b/.bazelrc index d759ea7..d117913 100644 --- a/.bazelrc +++ b/.bazelrc @@ -113,6 +113,8 @@ build:linux_arm32 --platforms=//platform:linux_arm32 build:linux_arm32 --extra_toolchains=@linux_arm32_toolchain//:cc_toolchain,@linux_arm32_toolchain//:cc_toolchain_aarch64 build:linux_arm32 --cpu=armv7 build:linux_arm32 --features=-external_include_paths +# Keep static bank registrars when the linker would gc unreferenced sections. +build:linux_arm32 --linkopt=-Wl,--no-gc-sections test:linux_arm32 --run_under=//bazel/toolchains/linux_arm32:qemu test:linux_arm32 --test_env=QEMU_LD_PREFIX=/usr/arm-linux-gnueabihf run:linux_arm32 --run_under=//bazel/toolchains/linux_arm32:qemu diff --git a/README.md b/README.md index 5cbc855..2ee7483 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,8 @@ payloads. Protobuf and ROS wire formats are unchanged. The `PayloadBuffer` (from the [cpp_toolbelt](https://github.com/dallison/cpp_toolbelt) library) is a relocatable heap — a malloc/free/realloc allocator that uses only offsets (never raw pointers), so the whole buffer can be copied or moved anywhere. It offers a fast -**bitmap allocator** for small blocks (performance mode, the default) and a **free-list +**small-block size-class allocator** for blocks up to 128 bytes (performance mode, +the default) and a **free-list allocator** that trades speed for compactness (size mode), selectable via `::phaser::Tuning`. @@ -586,6 +587,11 @@ scripts/build-armhf-linux.sh --test scripts/build-armhf-colima.sh --test ``` +Arm32 CI runs the same automated `cc_test` targets as the main Linux job under +QEMU (`bazel query 'tests(//...)'` minus `perf_test`, `receive_fuzz_test`, and +host-only Python/Rust/shell tests). LibFuzzer and host `protoc-gen-phaser` tests +are excluded from the armhf job. + ### Using Phaser without Bazel Phaser is a `protoc` plugin, so any build system can drive it as long as the plugin binary diff --git a/phaser/docs/phaser_user_guide.md b/phaser/docs/phaser_user_guide.md index 45fd089..de5a419 100644 --- a/phaser/docs/phaser_user_guide.md +++ b/phaser/docs/phaser_user_guide.md @@ -958,14 +958,14 @@ The memory for the actual message contents is allocated inside the `PayloadBuffe In performance mode (the default), two types of allocators are used depending on the size of the block being allocated: -1. A bitmap allocator for blocks up to 16, 32, 64 and 128 bytes. +1. A small-block size-class allocator for requests up to 16, 32, 64 and 128 bytes. 2. A free-list allocator for all other block sizes -The bitmap allocator is about twice as fast when allocating memory but does use more memory +The small-block allocator is about twice as fast when allocating memory but does use more memory in the buffer. This is most appropriate when you want the maximum performance out of the allocator but are not concerned about the size of the message. If you are putting your messages in shared memory or somewhere where the message size isn't a concern, you can gain -performance by using the bitmap allocator. +performance by using the small-block allocator. However, if you are sending your messages over a network and want to keep them small, the size mode might be more appropiate. It should be noted, though, that if you are concerned @@ -1995,21 +1995,19 @@ of the requirement that it can't use any virtual addresses (pointers). There are two types of allocators in the `PayloadBuffer`, the choice of which to use being based on the block being allocated. If the block is small -a `bitmap allocator` is used to speed up the allocation. The definition of -a small block is one whose size is less than 16, 32, 64 or 128 bytes. There -are 4 bitmap allocators, one for each of those block sizes. Bitmap -allocators are fast but use more memory because they allocate a set of -fixed size blocks up front and keep track of them using a bit mask. This uses -more memory than a simple free-list allocator. +the small-block size-class allocator is used to speed up the allocation. There +are four size classes (16, 32, 64 and 128 bytes). Each class keeps a LIFO free +list of returned blocks in the buffer header; when a list is empty, a block is +carved from the main free list. The second type of allocator is used for all other block sizes above -128 bytes and is a simple free-list based allocator. The bitmap allocator -prevents heap fragmentation by using fixed size blocks, but with the free-list -allocator, fragmentation is always possible. +128 bytes and is a simple free-list based allocator. The size-class lists +reduce fragmentation for tiny allocations; the main free-list allocator may +still fragment for larger blocks. -You can switch the bitmap allocator off when creating the `PayloadBuffer` using -its constructor. This parameter is controlled by Phaser's `Tuning` message -construction argument. +You can switch the small-block allocator off when creating the `PayloadBuffer` +using its constructor. This parameter is controlled by Phaser's `Tuning` +message construction argument. ### PayloadBuffer header @@ -2029,7 +2027,7 @@ bytes `00 'P' 'H'` followed by a flags byte: | 6 | Allocation failed (`::phaser::kAllocationFailedFlag`). A receiver rejects the buffer; the process that filled it can still read what was stored | | 2-5 | Format version (`::phaser::kBufferFormatVersion`, currently 1) | | 1 | Movable buffer (`::phaser::kMovableBufferMagic`) rather than fixed (`::phaser::kFixedBufferMagic`) | -| 0 | Bitmap allocator on (`::phaser::kBitMapFlag`) | +| 0 | Small-block allocator on (`::phaser::kSmallBlockAllocatorFlag`) | The magic identifies the buffer as a PayloadBuffer of this format version. Because a non-empty protobuf message cannot start with a zero byte, the first @@ -2071,18 +2069,9 @@ that can be used by a receiver. There are functions available in the `::phaser::Message` class to allocate, free and set the metadata field as needed. -Finally we have 4 offsets for the 4 bitmap run vectors. Each offset corresponds to a bitmap run for a -particular size (16, 32, 64 or 128 bytes). The bitmap runs are held in a vector of offsets to -`BitMapRun` structs that grows as needed. Each `BitMapRun` struct holds a bitmask showing -which blocks are allocated, meta information about the run and the blocks themselves, each -of which is prefixed by a 4 byte header. If a block is allocated in a run, its corresponding bit in the -bitmask is set to 1. - -This is shown in the following diagram, for a 32 byte run. - -
- -
+Finally, `small_block_free_lists[4]` holds the head offset of each size-class +free list (16, 32, 64 and 128 byte classes). A freed small block stores the +next offset in its first four bytes. The binary version of a message can be seen in the following diagram: diff --git a/phaser/phaser_library.bzl b/phaser/phaser_library.bzl index d0360e5..5f8b612 100644 --- a/phaser/phaser_library.bzl +++ b/phaser/phaser_library.bzl @@ -547,6 +547,9 @@ def phaser_library( cc_library( name = name, alwayslink = True, + # Static archives keep bank static initializers linked on armhf (QEMU + # would not run registrars in un-loaded shared objects). + linkstatic = True, copts = copts, srcs = [srcs], hdrs = [hdrs], @@ -564,6 +567,10 @@ def phaser_library( srcs = [":" + crate], crate_name = _rust_crate_name(name), edition = "2021", + target_compatible_with = select({ + "//platform:linux_arm32_setting": ["@platforms//:incompatible"], + "//conditions:default": [], + }), deps = [":" + name], ) diff --git a/phaser/plugins/arrow/BUILD.bazel b/phaser/plugins/arrow/BUILD.bazel index 17bf707..55864bb 100644 --- a/phaser/plugins/arrow/BUILD.bazel +++ b/phaser/plugins/arrow/BUILD.bazel @@ -13,6 +13,7 @@ cc_library( ], hdrs = ["gen/arrow_message_codegen.h"], alwayslink = True, + linkstatic = True, copts = PHASER_PROTOC_COPTS, deps = ["//phaser/compiler:message_generator"], ) @@ -21,6 +22,7 @@ pybind_library( name = "pybind", srcs = ["runtime/pybind.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = [ ":runtime", diff --git a/phaser/plugins/avro/BUILD.bazel b/phaser/plugins/avro/BUILD.bazel index 522defd..ae24059 100644 --- a/phaser/plugins/avro/BUILD.bazel +++ b/phaser/plugins/avro/BUILD.bazel @@ -9,6 +9,7 @@ cc_library( name = "codegen", srcs = ["gen/codegen.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_PROTOC_COPTS, deps = ["//phaser/compiler:message_generator"], ) @@ -17,6 +18,7 @@ pybind_library( name = "pybind", srcs = ["runtime/pybind.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = [ ":runtime", @@ -41,6 +43,7 @@ cc_library( name = "conversion", srcs = ["runtime/avro_conversion.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = [ ":runtime", diff --git a/phaser/plugins/parquet/BUILD.bazel b/phaser/plugins/parquet/BUILD.bazel index cd750dd..1587390 100644 --- a/phaser/plugins/parquet/BUILD.bazel +++ b/phaser/plugins/parquet/BUILD.bazel @@ -9,6 +9,7 @@ cc_library( name = "codegen", srcs = ["gen/codegen.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_PROTOC_COPTS, deps = ["//phaser/compiler:message_generator"], ) @@ -17,6 +18,7 @@ pybind_library( name = "pybind", srcs = ["runtime/pybind.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = [ ":runtime", @@ -41,6 +43,7 @@ cc_library( name = "conversion", srcs = ["runtime/parquet_conversion.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = [ ":runtime", diff --git a/phaser/plugins/protobuf/BUILD.bazel b/phaser/plugins/protobuf/BUILD.bazel index ad373c2..9cda112 100644 --- a/phaser/plugins/protobuf/BUILD.bazel +++ b/phaser/plugins/protobuf/BUILD.bazel @@ -12,6 +12,7 @@ cc_library( ], hdrs = ["gen/protobuf_wire_codegen.h"], alwayslink = True, + linkstatic = True, copts = PHASER_PROTOC_COPTS, deps = ["//phaser/compiler:message_generator"], ) @@ -20,6 +21,7 @@ pybind_library( name = "pybind", srcs = ["runtime/pybind.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = [ "//phaser/runtime:phaser_runtime", @@ -31,6 +33,7 @@ cc_library( name = "conversion", srcs = ["runtime/conversion.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = ["//phaser/plugins/common:conversion_plugin"], ) diff --git a/phaser/plugins/ros/BUILD.bazel b/phaser/plugins/ros/BUILD.bazel index 55a7004..adb579e 100644 --- a/phaser/plugins/ros/BUILD.bazel +++ b/phaser/plugins/ros/BUILD.bazel @@ -29,6 +29,7 @@ cc_library( ], hdrs = ["gen/ros_wire_codegen.h"], alwayslink = True, + linkstatic = True, copts = PHASER_PROTOC_COPTS, deps = [ ":ros_codegen_helpers", @@ -41,6 +42,7 @@ pybind_library( name = "pybind", srcs = ["runtime/pybind.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = [ "//phaser/runtime:phaser_runtime", @@ -52,6 +54,7 @@ cc_library( name = "conversion", srcs = ["runtime/conversion.cc"], alwayslink = True, + linkstatic = True, copts = PHASER_COPTS, deps = ["//phaser/plugins/common:conversion_plugin"], ) diff --git a/phaser/receive_allocation_test.cc b/phaser/receive_allocation_test.cc index b9bfee0..297095d 100644 --- a/phaser/receive_allocation_test.cc +++ b/phaser/receive_allocation_test.cc @@ -248,11 +248,11 @@ ExerciseResult ExerciseWireDeserialization(std::string_view any_wire, // A new TestMessage buffer made in place, as CreateMutable makes one when it // has no image of one to copy. ::phaser::PayloadBuffer* MakeTestMessageBuffer(void* addr, size_t size, - bool bitmaps) { + bool small_block_allocator) { return ::phaser::MakeFixedBuffer< foo::bar::phaser::TestMessage, foo::bar::phaser::InnerMessage, ::phaser::AnyMessage, foo::bar::phaser::TestMessage_ValuesEntry>( - addr, size, bitmaps); + addr, size, small_block_allocator); } // The bytes a new TestMessage buffer uses. @@ -544,7 +544,7 @@ TEST(OutputAllocationTest, CreateMutableInABufferTooSmallFails) { << message.status(); } -TEST(OutputAllocationTest, CreateMutableTunedForSizeHasNoBitmaps) { +TEST(OutputAllocationTest, CreateMutableTunedForSizeHasNoSmallBlockAllocator) { constexpr size_t kSize = 32768; std::vector created(kSize); std::vector made(kSize); @@ -552,7 +552,7 @@ TEST(OutputAllocationTest, CreateMutableTunedForSizeHasNoBitmaps) { created.data(), kSize, ::phaser::Tuning::kSize); const ::phaser::PayloadBuffer* pb = MakeTestMessageBuffer(made.data(), kSize, false); - EXPECT_FALSE(message.runtime->pb->BitmapsEnabled()); + EXPECT_FALSE(message.runtime->pb->SmallBlockAllocatorEnabled()); ASSERT_EQ(message.runtime->pb->hwm, pb->hwm); EXPECT_EQ(std::memcmp(created.data(), made.data(), pb->hwm), 0); } diff --git a/phaser/runtime/BUILD.bazel b/phaser/runtime/BUILD.bazel index 3e4cec0..3cf5f0e 100644 --- a/phaser/runtime/BUILD.bazel +++ b/phaser/runtime/BUILD.bazel @@ -149,7 +149,10 @@ py_test( name = "phaser_bank_py_test", srcs = ["phaser_bank_py_test.py"], main = "phaser_bank_py_test.py", - tags = ["no-asan"], + tags = [ + "manual", + "no-asan", + ], data = [ ":phaser_bank_py_testlib", "//phaser:valgrind.supp", diff --git a/phaser/runtime/message.h b/phaser/runtime/message.h index 5de406c..0b11fcc 100644 --- a/phaser/runtime/message.h +++ b/phaser/runtime/message.h @@ -604,7 +604,7 @@ struct MessageRuntime { if (pb == nullptr) { return; } - for (const ::phaser::BufferOffset head : pb->bitmaps) { + for (const ::phaser::BufferOffset head : pb->small_block_free_lists) { if (head != 0) { return; } @@ -682,7 +682,7 @@ struct MessageRuntime { block->next = 0; pb->free_list = mark; pb->hwm = mark + sizeof(::phaser::FreeBlockHeader); - for (::phaser::BufferOffset& head : pb->bitmaps) { + for (::phaser::BufferOffset& head : pb->small_block_free_lists) { head = 0; } pb->ClearAllocationFailed(); @@ -1249,15 +1249,15 @@ struct InternalDefault {}; // handle it was made from, so it is valid only while that handle exists. struct MutablePart {}; -// Tuning parameters for messages. The kPerformance tuning uses a bitmap -// allocator for block sizes up to 128 bytes. This is about twice as fast -// for small blocks but uses more memory. If you are sending messages -// using shared memory where size isn't important, you can use kPerformance. -// If you are sending messages over a network, then you can sacrifice -// allocation peformance for size and use kSize. +// Tuning parameters for messages. The kPerformance tuning uses the +// small-block size-class allocator for requests up to 128 bytes. This is +// about twice as fast for small blocks but uses more memory. If you are +// sending messages using shared memory where size isn't important, you can +// use kPerformance. If you are sending messages over a network, then you +// can sacrifice allocation peformance for size and use kSize. enum class Tuning { - kPerformance, // Use a bitmap allocator for small blocks - kSize, // Use a simple allocator for small blocks + kPerformance, // Use the small-block size-class allocator + kSize, // Use only the main free-list allocator for small blocks }; // Payload buffers can move. All messages in a message tree must all use the @@ -1818,10 +1818,10 @@ struct Message { // be copied from it. class NewBufferImage { public: - // 'make' makes a new buffer, with the small block allocator if 'bitmaps', - // in the 'size' bytes at 'addr', or returns null if it does not fit. + // 'make' makes a new buffer, with the small-block allocator if enabled, in + // the 'size' bytes at 'addr', or returns null if it does not fit. using Maker = ::phaser::PayloadBuffer* (*)(void* addr, size_t size, - bool bitmaps); + bool small_block_allocator); explicit NewBufferImage(Maker make); // The new buffer in the 'size' bytes at 'addr', or null if the image does @@ -1843,12 +1843,12 @@ inline bool CanHoldFixedBuffer(const void* addr, size_t size) { template ::phaser::PayloadBuffer* MakeFixedBuffer(void* addr, size_t size, - bool bitmaps) { + bool small_block_allocator) { if (!CanHoldFixedBuffer(addr, size)) { return nullptr; } - auto* pb = new (addr) - ::phaser::PayloadBuffer(static_cast(size), bitmaps); + auto* pb = new (addr)::phaser::PayloadBuffer(static_cast(size), + small_block_allocator); if (::phaser::PayloadBuffer::AllocateMainMessage(&pb, Root::BinarySize()) == nullptr || !InitializeMetadata(&pb)) { diff --git a/phaser/runtime/message_test.cc b/phaser/runtime/message_test.cc index 04fb6ad..781c94a 100644 --- a/phaser/runtime/message_test.cc +++ b/phaser/runtime/message_test.cc @@ -1312,8 +1312,10 @@ TEST(MessageTest, ReadonlyRuntimeSizeIsNotAResetMark) { EXPECT_FALSE( readonly.ResetFor(msg.absolute_binary_offset, TestMessage::BinarySize())); - phaser::MessageRuntime huge(msg.runtime->pb, size_t{1} << 33); - EXPECT_EQ(UINT32_MAX, huge.BufferSize()); + if constexpr (sizeof(size_t) > sizeof(uint32_t)) { + phaser::MessageRuntime huge(msg.runtime->pb, size_t{1} << 33); + EXPECT_EQ(UINT32_MAX, huge.BufferSize()); + } // Without a size the buffer's own is trusted; a size of 0 trusts nothing. phaser::MessageRuntime unsized(msg.runtime->pb); diff --git a/phaser/runtime/payload_buffer.cc b/phaser/runtime/payload_buffer.cc index bedb83a..e2513c4 100644 --- a/phaser/runtime/payload_buffer.cc +++ b/phaser/runtime/payload_buffer.cc @@ -4,11 +4,12 @@ #include namespace phaser { -static constexpr uint32_t small_block_sizes[kNumBitmapRuns] = { - kBitmapRunSize1, kBitmapRunSize2, kBitmapRunSize3, kBitmapRunSize4}; +static constexpr uint32_t small_block_sizes[kNumSmallBlockClasses] = { + kSmallBlockClassMaxBytes1, kSmallBlockClassMaxBytes2, + kSmallBlockClassMaxBytes3, kSmallBlockClassMaxBytes4}; -inline int BitmapRunIndex(uint32_t n) { - for (size_t i = 0; i < kNumBitmapRuns; i++) { +inline int SmallBlockClassIndex(uint32_t n) { + for (size_t i = 0; i < kNumSmallBlockClasses; i++) { if (n <= small_block_sizes[i]) { return static_cast(i); } @@ -16,12 +17,13 @@ inline int BitmapRunIndex(uint32_t n) { return -1; } -inline int BitmapRunIndexFromEncodedSize(uint64_t n) { +inline int SmallBlockClassIndexFromEncodedSize(uint64_t n) { if ((n & kSmallBlockFlag) == 0) { // Not a small block since the high bit is not set. return -1; } - return BitmapRunIndex(static_cast(n & kBitmapRunSizeMask)); + return SmallBlockClassIndex( + static_cast(n & kSmallBlockEncodedSizeMask)); } void *PayloadBuffer::AllocateMainMessage(PayloadBuffer **self, size_t size) { @@ -282,17 +284,18 @@ void PayloadBuffer::Dump(std::ostream &os) { os << " magic: " << (!IsValidMagic() ? "invalid" : (IsMoveable() ? "moveable" : "fixed")) << std::endl; - os << " bitmaps: " << ((magic & kBitMapFlag) ? "enabled" : "disabled") - << std::endl; + os << " small_block_allocator: " + << (SmallBlockAllocatorEnabled() ? "enabled" : "disabled") << std::endl; os << " hwm: " << hwm << " " << ToAddress(hwm) << std::endl; os << " full_size: " << full_size << std::endl; os << " metadata: " << metadata << " " << ToAddress(metadata) << std::endl; os << " free_list: " << free_list << " " << ToAddress(free_list) << std::endl; os << " message: " << message << " " << ToAddress(message) << std::endl; - for (size_t i = 0; i < kNumBitmapRuns; i++) { - os << " bitmaps[" << i << "]: " << bitmaps[i] << " " - << ToAddress(bitmaps[i]) << std::endl; + for (size_t i = 0; i < kNumSmallBlockClasses; i++) { + os << " small_block_free_lists[" << i << "]: " + << small_block_free_lists[i] << " " + << ToAddress(small_block_free_lists[i]) << std::endl; } DumpFreeList(os); } @@ -320,14 +323,9 @@ void PayloadBuffer::CheckFreeList() { } void PayloadBuffer::InitFreeList() { - char *end_of_header = reinterpret_cast(this + 1); - size_t header_size = sizeof(PayloadBuffer); - if (IsMoveable()) { - end_of_header += - sizeof(Resizer *); // Room for resizer function for movable buffers. - header_size += sizeof(Resizer *); - } - FreeBlockHeader *f = reinterpret_cast(end_of_header); + const uint32_t header_size = AlignedPayloadHeaderSize(IsMoveable()); + char *start_of_free = reinterpret_cast(this) + header_size; + FreeBlockHeader *f = reinterpret_cast(start_of_free); f->length = full_size - header_size; f->next = 0; free_list = ToOffset(f); @@ -379,8 +377,8 @@ void *PayloadBuffer::AllocateSlow(PayloadBuffer **buffer, uint32_t n, if (n == 0 || (*buffer)->AllocationFailed()) { return nullptr; } - if (enable_small_block && (*buffer)->BitmapsEnabled()) { - int small_block_index = BitmapRunIndex(n); + if (enable_small_block && (*buffer)->SmallBlockAllocatorEnabled()) { + int small_block_index = SmallBlockClassIndex(n); if (small_block_index >= 0) { return AllocateSmallBlock(buffer, n, small_block_index, clear); } @@ -549,7 +547,7 @@ void PayloadBuffer::FreeSlow(void *p) { // An allocated block has its length immediately before its address. uint64_t alloc_length = *(reinterpret_cast(p) - 1); // Length of allocated block. - int small_block_index = BitmapRunIndexFromEncodedSize(alloc_length); + int small_block_index = SmallBlockClassIndexFromEncodedSize(alloc_length); if (small_block_index >= 0) { FreeSmallBlock(this, p, small_block_index); return; @@ -692,14 +690,14 @@ void *PayloadBuffer::Realloc(PayloadBuffer **buffer, void *p, uint32_t n, uint64_t orig_length = *len_ptr; // A small block is recognized from its encoded size word even when small // blocks are disabled for this call. - int small_block_index = BitmapRunIndexFromEncodedSize(orig_length); + int small_block_index = SmallBlockClassIndexFromEncodedSize(orig_length); if (small_block_index >= 0) { uint32_t decoded_length = - static_cast(orig_length & kBitmapRunSizeMask); + static_cast(orig_length & kSmallBlockEncodedSizeMask); // If the new size is in the same size class we can just return the // original block. - if (enable_small_block && (*buffer)->BitmapsEnabled() && - BitmapRunIndex(n) == small_block_index) { + if (enable_small_block && (*buffer)->SmallBlockAllocatorEnabled() && + SmallBlockClassIndex(n) == small_block_index) { *len_ptr = kSmallBlockFlag | n; if (clear && n > decoded_length) { memset(reinterpret_cast(p) + decoded_length, 0, @@ -803,7 +801,7 @@ void *PayloadBuffer::Realloc(PayloadBuffer **buffer, void *p, uint32_t n, (*buffer)->Free(p); return newp; } -bool PayloadBuffer::PrimeBitmapAllocator(PayloadBuffer **, size_t) { +bool PayloadBuffer::PrimeSmallBlockAllocator(PayloadBuffer **, size_t) { return true; } @@ -811,14 +809,15 @@ void *PayloadBuffer::AllocateSmallBlock(PayloadBuffer **pb, uint32_t size, int index, bool clear) { const uint32_t block_size = small_block_sizes[index]; char *addr = nullptr; - BufferOffset head = (*pb)->bitmaps[index]; + BufferOffset head = (*pb)->small_block_free_lists[index]; if (head != 0) { // Pop the head of the class's free list. addr = (*pb)->ToAddress(head); if (addr == nullptr) { return nullptr; } - (*pb)->bitmaps[index] = *reinterpret_cast(addr); + (*pb)->small_block_free_lists[index] = + *reinterpret_cast(addr); } else { // Carve a single block from the main free list. addr = static_cast(Allocate(pb, block_size, false, false)); @@ -834,7 +833,7 @@ void *PayloadBuffer::AllocateSmallBlock(PayloadBuffer **pb, uint32_t size, } void PayloadBuffer::FreeSmallBlock(PayloadBuffer *pb, void *p, int index) { - *reinterpret_cast(p) = pb->bitmaps[index]; - pb->bitmaps[index] = pb->ToOffset(p); + *reinterpret_cast(p) = pb->small_block_free_lists[index]; + pb->small_block_free_lists[index] = pb->ToOffset(p); } } // namespace phaser diff --git a/phaser/runtime/payload_buffer.h b/phaser/runtime/payload_buffer.h index 8042312..d50470a 100644 --- a/phaser/runtime/payload_buffer.h +++ b/phaser/runtime/payload_buffer.h @@ -24,7 +24,7 @@ namespace phaser { // message cannot start with a zero byte, so the first byte tells a payload // buffer from protobuf. The flags byte holds a set top bit, the format version // in bits 2-5, the allocation-failed flag in bit 6, the movable flag in bit 1 -// and the bitmap allocator flag in bit 0 (bits 25 and 24 of the magic). +// and the small-block allocator flag in bit 0 (bits 25 and 24 of the magic). constexpr uint32_t kBufferFormatVersion = 1; constexpr uint32_t kFixedBufferMagic = ((0x80 | (kBufferFormatVersion << 2)) << 24) | (uint32_t{'H'} << 16) | @@ -32,16 +32,17 @@ constexpr uint32_t kFixedBufferMagic = constexpr uint32_t kMovableBufferMagic = kFixedBufferMagic | (1u << 25); static_assert((kFixedBufferMagic & 0xff) == 0 && kBufferFormatVersion < 16); -// Set for enabling bitmap allocator. -constexpr uint32_t kBitMapFlag = 1u << 24; -constexpr uint32_t kBitMapMask = ~kBitMapFlag; +// Set when the small-block (size-class) allocator is enabled. +constexpr uint32_t kSmallBlockAllocatorFlag = 1u << 24; +constexpr uint32_t kSmallBlockAllocatorMagicMask = ~kSmallBlockAllocatorFlag; // Set when an allocation failed because a fixed size buffer was full. The // buffer's contents up to that point are unchanged. In-process reads ignore // this bit. A receiver rejects the buffer, because the bit is not part of a // valid magic. constexpr uint32_t kAllocationFailedFlag = 1u << 30; -constexpr uint32_t kMagicFlagsMask = kBitMapFlag | kAllocationFailedFlag; +constexpr uint32_t kMagicFlagsMask = + kSmallBlockAllocatorFlag | kAllocationFailedFlag; using BufferOffset = uint32_t; @@ -103,8 +104,8 @@ using Resizer = // allocation of small blocks, blocks of up to 128 bytes are rounded up to one // of a fixed number of size classes. Each size class has a LIFO free list // (like the fastbins in common malloc implementations) whose head offset is -// held in the PayloadBuffer header ('bitmaps', a name kept for layout -// compatibility). A free small block holds the offset of the next free block +// held in the PayloadBuffer header ('small_block_free_lists'). A free small +// block holds the offset of the next free block // of its class in its first 4 bytes. When a class's free list is empty a // single block is carved from the main free list, so a freshly created buffer // is filled by what is effectively bump allocation and no space is reserved @@ -112,13 +113,13 @@ using Resizer = // are not coalesced back into the main free list. // Number of small block size classes. -inline constexpr size_t kNumBitmapRuns = 4; +inline constexpr size_t kNumSmallBlockClasses = 4; -// Block size for each small block class. -inline constexpr int kBitmapRunSize1 = 16; -inline constexpr int kBitmapRunSize2 = 32; -inline constexpr int kBitmapRunSize3 = 64; -inline constexpr int kBitmapRunSize4 = 128; +// Maximum request size for each small-block size class. +inline constexpr int kSmallBlockClassMaxBytes1 = 16; +inline constexpr int kSmallBlockClassMaxBytes2 = 32; +inline constexpr int kSmallBlockClassMaxBytes3 = 64; +inline constexpr int kSmallBlockClassMaxBytes4 = 128; // The 8 bytes preceding an allocated block hold its size. To distinguish a // small block from a regular block allocated from the free list, a small @@ -126,7 +127,7 @@ inline constexpr int kBitmapRunSize4 = 128; // in bits 7-0. The requested size always maps back to the block's size class // because a block is always taken from the smallest class that fits. inline constexpr uint32_t kSmallBlockFlag = 1U << 31; -inline constexpr uint32_t kBitmapRunSizeMask = 0xff; +inline constexpr uint32_t kSmallBlockEncodedSizeMask = 0xff; // This is a buffer that holds the contents of a message. // It is located at the first address of the actual buffer with the @@ -139,16 +140,19 @@ struct PayloadBuffer { uint32_t full_size; // Full size of buffer. BufferOffset free_list; // Heap free list. BufferOffset metadata; // Offset to message metadata. - BufferOffset - bitmaps[kNumBitmapRuns]; // Free list head for each small block class. + BufferOffset small_block_free_lists[kNumSmallBlockClasses]; + // Explicit tail padding so the header is 48 bytes on 32- and 64-bit hosts + // (matches 64-bit ABI tail padding) without changing field offsets. + uint32_t header_padding[2] = {0, 0}; // Initialize a new PayloadBuffer at this with a message of the // given size. This is a fixed size buffer. - PayloadBuffer(uint32_t size, bool bitmap_allocator = true) - : magic(kFixedBufferMagic | (bitmap_allocator ? kBitMapFlag : 0)), + PayloadBuffer(uint32_t size, bool small_block_allocator = true) + : magic(kFixedBufferMagic | + (small_block_allocator ? kSmallBlockAllocatorFlag : 0)), message(0), hwm(0), full_size(size), metadata(0) { - for (size_t i = 0; i < kNumBitmapRuns; i++) { - bitmaps[i] = 0; + for (size_t i = 0; i < kNumSmallBlockClasses; i++) { + small_block_free_lists[i] = 0; } InitFreeList(); } @@ -163,11 +167,13 @@ struct PayloadBuffer { // This implies that you need to destruct the payload buffer to avoid // a memory leak. This is only necessary for resizable buffers. Fixed // size buffers don't need to be destructed. - PayloadBuffer(uint32_t initial_size, Resizer r, bool bitmap_allocator = true) - : magic(kMovableBufferMagic | (bitmap_allocator ? kBitMapFlag : 0)), + PayloadBuffer(uint32_t initial_size, Resizer r, + bool small_block_allocator = true) + : magic(kMovableBufferMagic | + (small_block_allocator ? kSmallBlockAllocatorFlag : 0)), message(0), hwm(0), full_size(initial_size), metadata(0) { - for (size_t i = 0; i < kNumBitmapRuns; i++) { - bitmaps[i] = 0; + for (size_t i = 0; i < kNumSmallBlockClasses; i++) { + small_block_free_lists[i] = 0; } InitFreeList(); SetResizer(std::move(r)); @@ -181,7 +187,9 @@ struct PayloadBuffer { } } - bool BitmapsEnabled() const { return (magic & kBitMapFlag) != 0; } + bool SmallBlockAllocatorEnabled() const { + return (magic & kSmallBlockAllocatorFlag) != 0; + } void SetResizer(Resizer r) { // Place a pointer to the resizer function in the buffer just after the @@ -208,7 +216,7 @@ struct PayloadBuffer { static void AllocateMetadata(PayloadBuffer **self, void *md, size_t size); // The small block allocator has no per-class setup cost so there is nothing // to prime. Always returns true. - static bool PrimeBitmapAllocator(PayloadBuffer **self, size_t size); + static bool PrimeSmallBlockAllocator(PayloadBuffer **self, size_t size); // Address and offset conversions without validation, for a buffer this // process built and is mutating, whose offsets all came from the buffer. @@ -268,7 +276,7 @@ struct PayloadBuffer { if ((*p & kSmallBlockFlag) == 0) { return *p; } - return *p & kBitmapRunSizeMask; + return *p & kSmallBlockEncodedSizeMask; } template @@ -423,10 +431,10 @@ struct PayloadBuffer { // Index of the small block class for an allocation of 'n' bytes, or -1 if // it is too big for a small block. static int SmallBlockIndex(uint32_t n) { - return n <= uint32_t(kBitmapRunSize1) ? 0 - : n <= uint32_t(kBitmapRunSize2) ? 1 - : n <= uint32_t(kBitmapRunSize3) ? 2 - : n <= uint32_t(kBitmapRunSize4) ? 3 + return n <= uint32_t(kSmallBlockClassMaxBytes1) ? 0 + : n <= uint32_t(kSmallBlockClassMaxBytes2) ? 1 + : n <= uint32_t(kSmallBlockClassMaxBytes3) ? 2 + : n <= uint32_t(kSmallBlockClassMaxBytes4) ? 3 : -1; } static uint32_t SmallBlockSize(int index) { return 16U << index; } @@ -460,7 +468,7 @@ struct PayloadBuffer { void MarkAllocationFailed() { magic |= kAllocationFailedFlag; free_list = 0; - for (BufferOffset &head : bitmaps) { + for (BufferOffset &head : small_block_free_lists) { head = 0; } } @@ -499,7 +507,7 @@ struct PayloadBuffer { static uint32_t DecodedSize(BufferOffset *addr) { BufferOffset *p = addr - 2; if (*p & kSmallBlockFlag) { - return *p & kBitmapRunSizeMask; + return *p & kSmallBlockEncodedSizeMask; } return *p; } @@ -607,6 +615,19 @@ struct PayloadBuffer { } }; +static_assert(sizeof(PayloadBuffer) == 48, + "PayloadBuffer wire layout must match on all platforms"); + +// Bytes reserved before the heap/free list: fixed 48-byte header plus an +// optional movable resizer pointer, rounded up to 8-byte alignment. +inline uint32_t AlignedPayloadHeaderSize(bool movable) { + uint32_t n = static_cast(sizeof(PayloadBuffer)); + if (movable) { + n += static_cast(sizeof(Resizer *)); + } + return (n + 7u) & ~7u; +} + // A string to be copied into a buffer. It can be in that buffer, which // allocating can move, so it is found again there by its offset. class StringSource { @@ -725,17 +746,17 @@ inline void *PayloadBuffer::TryAllocateInPlace(uint32_t n, bool clear, uint64_t size_word; uint32_t block_size; int index = -1; - if (enable_small_block && pb->BitmapsEnabled() && + if (enable_small_block && pb->SmallBlockAllocatorEnabled() && (index = SmallBlockIndex(n)) >= 0) { block_size = SmallBlockSize(index); size_word = kSmallBlockFlag | n; - const BufferOffset head = pb->bitmaps[index]; + const BufferOffset head = pb->small_block_free_lists[index]; if (head != 0) { if (head > pb->full_size - block_size) { return nullptr; } char *addr = base + head; - pb->bitmaps[index] = *reinterpret_cast(addr); + pb->small_block_free_lists[index] = *reinterpret_cast(addr); *(reinterpret_cast(addr) - 1) = size_word; if (clear) { memset(addr, 0, block_size); @@ -782,10 +803,10 @@ inline void PayloadBuffer::Free(void *p) { const uint64_t size_word = *(reinterpret_cast(p) - 1); if ((size_word & kSmallBlockFlag) != 0) { const int index = - SmallBlockIndex(static_cast(size_word & kBitmapRunSizeMask)); + SmallBlockIndex(static_cast(size_word & kSmallBlockEncodedSizeMask)); if (index >= 0) { - *reinterpret_cast(p) = bitmaps[index]; - bitmaps[index] = BufferOffset(reinterpret_cast(p) - + *reinterpret_cast(p) = small_block_free_lists[index]; + small_block_free_lists[index] = BufferOffset(reinterpret_cast(p) - reinterpret_cast(this)); return; } @@ -820,9 +841,9 @@ inline bool PayloadBuffer::VectorPush(PayloadBuffer **self, VectorHeader *hdr, // A small block can use the rest of its size class. Its size word must // still cover the elements, and stays in the same class because the // block came from the smallest class that fit. - const int index = SmallBlockIndex(size_word & kBitmapRunSizeMask); + const int index = SmallBlockIndex(size_word & kSmallBlockEncodedSizeMask); capacity = index >= 0 ? SmallBlockSize(index) : 0; - if (needed <= capacity && needed > (size_word & kBitmapRunSizeMask)) { + if (needed <= capacity && needed > (size_word & kSmallBlockEncodedSizeMask)) { *size_ptr = kSmallBlockFlag | needed; } } diff --git a/phaser/runtime/payload_buffer_test.cc b/phaser/runtime/payload_buffer_test.cc index c2ccec7..378b725 100644 --- a/phaser/runtime/payload_buffer_test.cc +++ b/phaser/runtime/payload_buffer_test.cc @@ -238,10 +238,10 @@ TEST(BufferTest, BestCasePerformance) { char *buffer = (char *)calloc(1, kSize); PayloadBuffer *pb = new (buffer) PayloadBuffer(kSize); - ASSERT_TRUE(PayloadBuffer::PrimeBitmapAllocator(&pb, 16)); - ASSERT_TRUE(PayloadBuffer::PrimeBitmapAllocator(&pb, 32)); - ASSERT_TRUE(PayloadBuffer::PrimeBitmapAllocator(&pb, 64)); - ASSERT_TRUE(PayloadBuffer::PrimeBitmapAllocator(&pb, 128)); + ASSERT_TRUE(PayloadBuffer::PrimeSmallBlockAllocator(&pb, 16)); + ASSERT_TRUE(PayloadBuffer::PrimeSmallBlockAllocator(&pb, 32)); + ASSERT_TRUE(PayloadBuffer::PrimeSmallBlockAllocator(&pb, 64)); + ASSERT_TRUE(PayloadBuffer::PrimeSmallBlockAllocator(&pb, 128)); uint64_t small_start = toolbelt::Now(); @@ -480,9 +480,10 @@ TEST(BufferTest, CopyStringCopiesExactlyTheBytes) { TEST(BufferTest, NewStringsOfEveryShortLength) { constexpr size_t kMaxLength = 70; - for (bool bitmaps : {true, false}) { + for (bool small_block_allocator : {true, false}) { char *buffer = (char *)calloc(1, 8192); - PayloadBuffer *pb = new (buffer) PayloadBuffer(8192, bitmaps); + PayloadBuffer *pb = + new (buffer) PayloadBuffer(8192, small_block_allocator); PayloadBuffer::AllocateMainMessage(&pb, (kMaxLength + 1) * sizeof(BufferOffset)); std::string all; @@ -496,7 +497,7 @@ TEST(BufferTest, NewStringsOfEveryShortLength) { for (size_t n = 0; n <= kMaxLength; ++n) { EXPECT_EQ(pb->GetString(pb->message + n * sizeof(BufferOffset)), all.substr(0, n)) - << n << " " << bitmaps; + << n << " " << small_block_allocator; } free(buffer); } @@ -533,9 +534,10 @@ TEST(BufferTest, StringThatDoesNotFitLeavesTheOldValue) { } TEST(BufferTest, NothingIsStoredAfterAFailureEvenWhenSpaceIsFreed) { - for (bool bitmaps : {false, true}) { + for (bool small_block_allocator : {false, true}) { char *buffer = (char *)calloc(1, 4096); - PayloadBuffer *pb = new (buffer) PayloadBuffer(4096, bitmaps); + PayloadBuffer *pb = + new (buffer) PayloadBuffer(4096, small_block_allocator); PayloadBuffer::AllocateMainMessage(&pb, 32); const BufferOffset offset = pb->message; void *block = PayloadBuffer::Allocate(&pb, 64); @@ -546,13 +548,14 @@ TEST(BufferTest, NothingIsStoredAfterAFailureEvenWhenSpaceIsFreed) { EXPECT_TRUE(pb->AllocationFailed()); pb->Free(block); - EXPECT_EQ(PayloadBuffer::Allocate(&pb, 16), nullptr) << bitmaps; + EXPECT_EQ(PayloadBuffer::Allocate(&pb, 16), nullptr) + << small_block_allocator; // The string is just below the free space, where it could grow in place. EXPECT_EQ( PayloadBuffer::SetString(&pb, std::string("a longer string"), offset), nullptr) - << bitmaps; - EXPECT_EQ(pb->GetString(offset), "small") << bitmaps; + << small_block_allocator; + EXPECT_EQ(pb->GetString(offset), "small") << small_block_allocator; EXPECT_TRUE(pb->AllocationFailed()); free(buffer); } @@ -707,7 +710,7 @@ TEST(BufferTest, VectorPushFillsSmallBlockInPlace) { const uint64_t size_word = *(pb->ToAddress(hdr->data) - 1) & 0xffffffff; ASSERT_NE(0u, size_word & ::phaser::kSmallBlockFlag); - ASSERT_GE(size_word & ::phaser::kBitmapRunSizeMask, i * sizeof(uint32_t)); + ASSERT_GE(size_word & ::phaser::kSmallBlockEncodedSizeMask, i * sizeof(uint32_t)); } PayloadBuffer::VectorPush(&pb, hdr, 5); diff --git a/phaser/runtime/wireformat.h b/phaser/runtime/wireformat.h index f937071..4d19c48 100644 --- a/phaser/runtime/wireformat.h +++ b/phaser/runtime/wireformat.h @@ -65,22 +65,21 @@ inline bool IsStructurallyValidPhaser(absl::Span data) { offsetof(::phaser::PayloadBuffer, free_list); constexpr size_t kMetadataOffset = offsetof(::phaser::PayloadBuffer, metadata); - constexpr size_t kBitmapsOffset = - offsetof(::phaser::PayloadBuffer, bitmaps); + constexpr size_t kSmallBlockFreeListsOffset = + offsetof(::phaser::PayloadBuffer, small_block_free_lists); if (data.size() < sizeof(::phaser::PayloadBuffer)) { return false; } const uint32_t magic = LoadWireUint32(data, kMagicOffset); - const uint32_t base_magic = magic & ::phaser::kBitMapMask; + const uint32_t base_magic = magic & ::phaser::kSmallBlockAllocatorMagicMask; const bool movable = base_magic == ::phaser::kMovableBufferMagic; if (!movable && base_magic != ::phaser::kFixedBufferMagic) { return false; } const size_t minimum_header = - sizeof(::phaser::PayloadBuffer) + - (movable ? sizeof(::phaser::Resizer*) : 0); + ::phaser::AlignedPayloadHeaderSize(movable); const uint32_t message = LoadWireUint32(data, kMessageOffset); const uint32_t hwm = LoadWireUint32(data, kHwmOffset); const uint32_t full_size = LoadWireUint32(data, kFullSizeOffset); @@ -102,10 +101,11 @@ inline bool IsStructurallyValidPhaser(absl::Span data) { (metadata < minimum_header || metadata >= hwm)) { return false; } - for (size_t i = 0; i < ::phaser::kNumBitmapRuns; ++i) { - const uint32_t bitmap = - LoadWireUint32(data, kBitmapsOffset + i * sizeof(uint32_t)); - if (bitmap != 0 && (bitmap < minimum_header || bitmap >= hwm)) { + for (size_t i = 0; i < ::phaser::kNumSmallBlockClasses; ++i) { + const uint32_t free_list_head = LoadWireUint32( + data, kSmallBlockFreeListsOffset + i * sizeof(uint32_t)); + if (free_list_head != 0 && + (free_list_head < minimum_header || free_list_head >= hwm)) { return false; } } diff --git a/phaser/runtime/wireformat_test.cc b/phaser/runtime/wireformat_test.cc index 4c85cac..048ba0b 100644 --- a/phaser/runtime/wireformat_test.cc +++ b/phaser/runtime/wireformat_test.cc @@ -44,7 +44,7 @@ TEST(Wireformat, MagicBytes) { EXPECT_EQ(std::string("\x00PH\x84", 4), bytes(phaser::kFixedBufferMagic)); EXPECT_EQ(std::string("\x00PH\x86", 4), bytes(phaser::kMovableBufferMagic)); EXPECT_EQ(std::string("\x00PH\x85", 4), - bytes(phaser::kFixedBufferMagic | phaser::kBitMapFlag)); + bytes(phaser::kFixedBufferMagic | phaser::kSmallBlockAllocatorFlag)); } TEST(Wireformat, InfersProtobufFromFirstByte) { @@ -62,10 +62,10 @@ TEST(Wireformat, InfersProtobufFromFirstByte) { } TEST(Wireformat, InfersPhaserFromHeader) { - for (bool bitmaps : {false, true}) { + for (bool small_block_allocator : {false, true}) { alignas(8) char buffer[4096] = {}; phaser::PayloadBuffer* pb = - new (buffer) phaser::PayloadBuffer(sizeof(buffer), bitmaps); + new (buffer) phaser::PayloadBuffer(sizeof(buffer), small_block_allocator); phaser::PayloadBuffer::AllocateMainMessage(&pb, 32); const std::string_view payload(buffer, pb->hwm); EXPECT_EQ(MessageWireFormat::kPhaser, diff --git a/phaser/testdata/BUILD b/phaser/testdata/BUILD index e1dc9d1..3dcf605 100644 --- a/phaser/testdata/BUILD +++ b/phaser/testdata/BUILD @@ -83,7 +83,10 @@ py_test( main = "python_test.py", # See test:asan in .bazelrc. Valgrind's --suppressions path is relative to # the test runfiles directory, so the file has to be a data dependency. - tags = ["no-asan"], + tags = [ + "manual", + "no-asan", + ], data = [ ":test_message_phaser_py", "//phaser:valgrind.supp", @@ -124,7 +127,10 @@ rust_test( "@platforms//os:linux": ["-Clink-arg=-lc"], "//conditions:default": [], }), - tags = ["no-asan"], + tags = [ + "manual", + "no-asan", + ], target_compatible_with = select({ ":asan": ["@platforms//:incompatible"], "//conditions:default": [], @@ -329,6 +335,7 @@ cc_binary( sh_test( name = "ros_intrinsics_wire_compatibility_test", + tags = ["manual"], srcs = ["ros_intrinsics_wire_compatibility_test.sh"], args = [ "$(rootpath :ros_intrinsics_phaser_wire_tool)", @@ -343,6 +350,7 @@ sh_test( sh_test( name = "invalid_array_size_test", + tags = ["manual"], srcs = ["invalid_array_size_test.sh"], args = [ "$(rootpath @com_google_protobuf//:protoc)", @@ -362,6 +370,7 @@ sh_test( sh_test( name = "invalid_ros_intrinsic_test", + tags = ["manual"], srcs = ["invalid_ros_intrinsic_test.sh"], args = [ "$(rootpath @com_google_protobuf//:protoc)", diff --git a/platform/BUILD.bazel b/platform/BUILD.bazel index 03077f2..b893345 100644 --- a/platform/BUILD.bazel +++ b/platform/BUILD.bazel @@ -26,3 +26,8 @@ platform( "@platforms//os:linux", ], ) + +config_setting( + name = "linux_arm32_setting", + values = {"platforms": "//platform:linux_arm32"}, +) diff --git a/scripts/build-armhf-colima.sh b/scripts/build-armhf-colima.sh index dba5300..d59d073 100755 --- a/scripts/build-armhf-colima.sh +++ b/scripts/build-armhf-colima.sh @@ -31,9 +31,6 @@ docker build -t phaser-arm32-builder -f docker/arm32/Dockerfile docker/arm32 # Cross-compile the runtime for the device. The phaser protoc plugin stays on the # host (build without --config=linux_arm32). -build_targets="//phaser/runtime:phaser_runtime" -test_targets="//phaser:arm32_platform_test //phaser/runtime:payload_buffer_test //phaser/runtime:md5_test" - docker run --rm \ --user "$(id -u):$(id -g)" \ -e HOME=/tmp \ @@ -44,9 +41,10 @@ docker run --rm \ bash -eo pipefail -c " set -euo pipefail export PATH=/usr/local/bin:\$PATH - bazel build --config=linux_arm32 ${build_targets} - readelf -h bazel-bin/phaser/runtime/libphaser_runtime.so | grep -E 'Class:|Machine:' - if [[ ${run_tests} -eq 1 ]]; then - bazel test --config=linux_arm32 ${test_targets} + if [[ ${run_tests} -eq 0 ]]; then + bazel build --config=linux_arm32 //phaser/runtime:phaser_runtime + readelf -h bazel-bin/phaser/runtime/libphaser_runtime.so | grep -E 'Class:|Machine:' + else + bash scripts/build-armhf-linux.sh --test fi " diff --git a/scripts/build-armhf-linux.sh b/scripts/build-armhf-linux.sh index 8f537ef..66a71ea 100755 --- a/scripts/build-armhf-linux.sh +++ b/scripts/build-armhf-linux.sh @@ -25,20 +25,33 @@ if ! command -v arm-linux-gnueabihf-g++ >/dev/null 2>&1; then exit 1 fi -build_targets="//phaser/runtime:phaser_runtime" -test_targets=( - "//phaser:arm32_platform_test" - "//phaser/runtime:payload_buffer_test" - "//phaser/runtime:md5_test" -) - -bazel build --config=linux_arm32 ${build_targets} -readelf -h bazel-bin/phaser/runtime/libphaser_runtime.so | grep -E 'Class:|Machine:' +if [[ ${run_tests} -eq 0 ]]; then + build_targets="//phaser/runtime:phaser_runtime" + bazel build --config=linux_arm32 ${build_targets} + readelf -h bazel-bin/phaser/runtime/libphaser_runtime.so | grep -E 'Class:|Machine:' +fi if [[ ${run_tests} -eq 1 ]]; then if ! command -v qemu-arm-static >/dev/null 2>&1 && ! command -v qemu-arm >/dev/null 2>&1; then echo "qemu-arm-static or qemu-arm required to run armhf tests" >&2 exit 1 fi - bazel test --config=linux_arm32 "${test_targets[@]}" + # Same cc_test scope as main CI, minus perf_test and host-only tests. + # receive_fuzz_test: libFuzzer is unreliable under qemu-user (bus error). + exclude=( + //phaser:perf_test + //phaser:receive_fuzz_test + //phaser/runtime:phaser_bank_py_test + //phaser/testdata:phaser_python_test + //phaser/testdata:phaser_rust_test + //phaser/testdata:ros_intrinsics_wire_compatibility_test + //phaser/testdata:invalid_array_size_test + //phaser/testdata:invalid_ros_intrinsic_test + ) + query='tests(//...)' + for label in "${exclude[@]}"; do + query+=" except ${label}" + done + mapfile -t test_labels < <(bazel query --output=label "${query}") + bazel test --config=linux_arm32 -- "${test_labels[@]}" fi From a646c54550880ca35919531e012cb4f547fc0ad0 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Wed, 11 Nov 2026 13:43:17 -0800 Subject: [PATCH 4/4] Fix arm32 CI QEMU package install on Ubuntu 26.04. Fall back to qemu-user-binfmt when qemu-user-static is unavailable on newer GitHub ubuntu-latest images. --- .github/workflows/ci.yml | 7 ++++++- README.md | 2 +- scripts/build-armhf-linux.sh | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c74c6d9..4919ed0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -125,7 +125,12 @@ jobs: - name: Install cross toolchain and QEMU run: | sudo apt-get update - sudo apt-get install -y g++-arm-linux-gnueabihf qemu-user-static binutils-arm-linux-gnueabihf + sudo apt-get install -y \ + g++-arm-linux-gnueabihf \ + binutils-arm-linux-gnueabihf + # ubuntu-24.04: qemu-user-static; ubuntu-latest (26.04): qemu-user-binfmt. + sudo apt-get install -y qemu-user-static \ + || sudo apt-get install -y qemu-user-binfmt - name: Cache Bazel uses: actions/cache@v4 diff --git a/README.md b/README.md index 2ee7483..6acc82b 100644 --- a/README.md +++ b/README.md @@ -574,7 +574,7 @@ see [`.bazelrc`](.bazelrc) for the available configurations. Cross-compile `phaser_runtime` for 32-bit ARM Linux with `--config=linux_arm32`. CI and native Ubuntu use [`scripts/build-armhf-linux.sh`](scripts/build-armhf-linux.sh) (requires -`g++-arm-linux-gnueabihf` and `qemu-user-static`). On macOS, [`scripts/build-armhf-colima.sh`](scripts/build-armhf-colima.sh) +`g++-arm-linux-gnueabihf` and `qemu-user-static` or `qemu-user-binfmt`). On macOS, [`scripts/build-armhf-colima.sh`](scripts/build-armhf-colima.sh) builds the same target inside a Colima Docker image. The `protoc-gen-phaser` plugin is built for the host only (not armhf). diff --git a/scripts/build-armhf-linux.sh b/scripts/build-armhf-linux.sh index 66a71ea..99dd351 100755 --- a/scripts/build-armhf-linux.sh +++ b/scripts/build-armhf-linux.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Cross-build Phaser for 32-bit ARM Linux (armhf) on Linux (CI or native Ubuntu). # -# Requires: g++-arm-linux-gnueabihf, qemu-user-static (Debian/Ubuntu). +# Requires: g++-arm-linux-gnueabihf, qemu-user-static or qemu-user-binfmt. # # Usage: # scripts/build-armhf-linux.sh