Permission Embedding with Bazel
Embed the .snap.permissions section into SPECS NDK shared libraries in a Bazel build, matching what the CMake toolchain does.
This guide shows you how to reproduce the SPECS NDK's automatic permission
embedding in a Bazel build, so every shared library you build carries the
.snap.permissions section that SPECS checks at import time.
What permission embedding is
Every SPECS NDK shared library (.so) must carry a .snap.permissions ELF
section declaring the permissions it needs: those required by the SPECS APIs it
calls, plus INTERNET if it calls network functions in libcurl, OpenSSL, or
libc. The section is written by a tool shipped with
the NDK, specs-perm-embed, which runs after the library is linked.
In the CMake path this is fully automatic: the SPECS NDK toolchain wires a
post-link hook so the tool runs after every shared/module library links, with no
changes to the consumer's CMakeLists.txt. This guide describes how to
reproduce the same result in a Bazel build.
The specs-perm-embed tool
specs-perm-embed is a prebuilt host binary shipped inside the NDK, one per host
platform:
| Host | Path (relative to the extracted SPECS NDK) |
|---|---|
| macOS | sysroots/x86_64-specsndk-darwin21/usr/bin/specs-perm-embed |
| Windows | sysroots/x86_64-w64-mingw32/usr/bin/specs-perm-embed.exe |
Invocation:
specs-perm-embed <path-to-library.so>
The command line takes only the library path, and the tool modifies the file
in place. But it is not a self-contained .so → .so transform: it has
three runtime dependencies it discovers on its own (see
Key design considerations for Bazel):
specs-permissions.json: the symbol → permission mapping (the "brains").llvm-nm: used to read the library's undefined dynamic symbols.llvm-objcopy: used to write the.snap.permissionssection.
What it does: runs llvm-nm -uD to list the symbols the .so imports
(SPECS APIs, plus the network functions of libcurl, OpenSSL, and libc listed in
the map's external_libraries), intersects them with the symbols map in specs-permissions.json,
unions the permission tokens, and writes them (behind the SNAP_PERMS_V1
marker) into .snap.permissions via llvm-objcopy.
This matches how CMake invokes it, specs-perm-embed "$<TARGET_FILE:target>",
with one argument, because in the CMake path the JSON and llvm tools are found by
self-relative discovery inside the SDK tree. In a Bazel sandbox that discovery
is unreliable, so you pass them explicitly (see
Runtime dependencies
and The embed rule).
Key design considerations for Bazel
In-place mutation becomes a declared output
The tool mutates the .so in place, but Bazel actions must produce
declared outputs and cannot mutate an existing artifact. The embed step therefore
must be modeled as:
input: libfoo.so (produced by the linker)
action: copy input -> output, then run specs-perm-embed on the output copy
output: libfoo.so (a new, declared artifact with the section)
This preserves Bazel's caching and remote-execution correctness.
Runtime dependencies must be declared inputs and pinned via environment
specs-perm-embed locates its inputs in this priority order:
- Environment override:
SPECS_PERM_MANIFEST,SPECS_PERM_LLVM_NM,SPECS_PERM_LLVM_OBJCOPY. SPECSNDK_SYSROOTenvironment →<sysroot>/usr/share/specsndk/specs-permissions.json.- Self-relative walk: up to 8 parent directories of the binary's own location,
probing
usr/share/specsndk/...andsysroots/<target>/usr/share/....
Tier 3 is fragile in this SDK layout: the binary ships in the host sysroot
(sysroots/x86_64-specsndk-darwin21/usr/bin/) while the JSON ships in the
target sysroot (sysroots/armv8a-snap-linux/usr/share/...), bridged only by a
sysroots/%SPECSNDK_SYSROOT%/... path that contains an unresolved template
placeholder. Under a Bazel sandbox or remote executor, the surrounding SDK tree
may not even be present. Therefore: declare the JSON and both llvm tools as
action inputs, and point the tool at them with the tier-1 environment variables. Do not rely
on self-relative discovery.
The tool is fail-soft, so verification is mandatory
Critically, on any internal error (missing manifest, missing llvm-nm,
unreadable JSON, …) specs-perm-embed prints a warning and exits 0. It never
fails the build. If its inputs aren't wired correctly, the action succeeds but
the .so ends up with no section (or a marker with zero tokens), which is
then rejected fail-closed at import time, far from the build.
Consequence: the Bazel action cannot rely on the tool's exit code to know it worked. The post-build section check (see Verification) is not optional: it is the only thing that turns a silent embed failure into a red build.
Policy rules carried over from CMake
- Shared/module libraries only. Never embed into
cc_binaryexecutables. Apps are.so-only by design; executables cannot reach SPECS APIs. - Idempotent. The tool does remove-section-then-add-section, so re-running across relinks is safe.
SPECS_SKIP_PERMISSION_SCAN=1short-circuits the tool (for development only; leaves the section absent). Never set it in CI.
Expose the tool and its dependencies to Bazel
Add a BUILD file over the NDK (or generate it from a repository rule) that
exposes five things per host: the embedder, the permission manifest, and the
three llvm tools the rule uses (llvm-nm, llvm-objcopy, llvm-readelf). All five must be visible so the rule can put
them in the action sandbox.
# ndk/BUILD.bazel
package(default_visibility = ["//visibility:public"])
# One select per tool, keyed on the exec platform. The tools are files in this
# package (paths relative to the extracted NDK), so labels use '/', not ':'.
# On Windows the binaries carry .exe, and the llvm tools live under
# usr/lib/llvm-mingw/bin, not usr/bin.
_MAC = "sysroots/x86_64-specsndk-darwin21/usr/bin"
_WIN = "sysroots/x86_64-w64-mingw32/usr/bin"
_WIN_LLVM = "sysroots/x86_64-w64-mingw32/usr/lib/llvm-mingw/bin"
alias(
name = "specs_perm_embed",
actual = select({
"@platforms//os:macos": _MAC + "/specs-perm-embed",
"@platforms//os:windows": _WIN + "/specs-perm-embed.exe",
}),
)
alias(
name = "llvm_nm",
actual = select({
"@platforms//os:macos": _MAC + "/llvm-nm",
"@platforms//os:windows": _WIN_LLVM + "/llvm-nm.exe",
}),
)
alias(
name = "llvm_objcopy",
actual = select({
"@platforms//os:macos": _MAC + "/llvm-objcopy",
"@platforms//os:windows": _WIN_LLVM + "/llvm-objcopy.exe",
}),
)
alias(
name = "llvm_readelf",
actual = select({
"@platforms//os:macos": _MAC + "/llvm-readelf",
"@platforms//os:windows": _WIN_LLVM + "/llvm-readelf.exe",
}),
)
# The manifest is a data file in the TARGET sysroot (identical in both host bundles).
alias(
name = "specs_permissions_json",
actual = "sysroots/armv8a-snap-linux/usr/share/specsndk/specs-permissions.json",
)
The selects key on the exec platform (the machine running the build), which is correct for build-time host tools.
The embed rule
The rule copies the linked .so to a declared output, then runs
specs-perm-embed on the copy, with the manifest and llvm tools declared as
inputs and pinned via the tier-1 environment variables (see
Runtime dependencies),
and a post-run assertion that the section actually landed, because the tool
is fail-soft (see The tool is fail-soft).
# specs/perm_embed.bzl
"""Embed the .snap.permissions section into a SpecsNDK shared library."""
def _specs_perm_embed_impl(ctx):
src = ctx.file.lib
name = ctx.label.name
out = ctx.actions.declare_file(name if name.endswith(".so") else name + ".so")
embed = ctx.executable._embed
nm = ctx.executable._llvm_nm
objcopy = ctx.executable._llvm_objcopy
readelf = ctx.executable._llvm_readelf
manifest = ctx.file._manifest
# copy -> embed (env-pinned) -> ASSERT the section is present.
# specs-perm-embed is fail-soft (exits 0 on any error), so we must verify
# the section ourselves or a misconfigured embed would pass silently.
ctx.actions.run_shell(
inputs = [src, manifest],
outputs = [out],
tools = [embed, nm, objcopy, readelf],
command = """
set -euo pipefail
cp "$1" "$2"
SPECS_PERM_MANIFEST="$3" \
SPECS_PERM_LLVM_NM="$4" \
SPECS_PERM_LLVM_OBJCOPY="$5" \
"$6" "$2"
# Fail-soft tool: prove the section exists, else fail the build.
"$7" --sections "$2" | grep -q '\\.snap\\.permissions' \
|| { echo "specs-perm-embed produced no .snap.permissions section" >&2; exit 1; }
""",
arguments = [
src.path, out.path,
manifest.path, nm.path, objcopy.path,
embed.path, readelf.path,
],
mnemonic = "SpecsPermEmbed",
progress_message = "Embedding .snap.permissions into %s" % ctx.label.name,
)
return [DefaultInfo(files = depset([out]))]
_tool = lambda default: attr.label(
default = default, executable = True, cfg = "exec", allow_single_file = True,
)
specs_perm_embed = rule(
implementation = _specs_perm_embed_impl,
attrs = {
"lib": attr.label(allow_single_file = [".so"], mandatory = True),
"_embed": _tool("//ndk:specs_perm_embed"),
"_llvm_nm": _tool("//ndk:llvm_nm"),
"_llvm_objcopy": _tool("//ndk:llvm_objcopy"),
"_llvm_readelf": _tool("//ndk:llvm_readelf"),
"_manifest": attr.label(
default = "//ndk:specs_permissions_json",
allow_single_file = True,
),
},
)
About the embed rule:
- Environment-pinned discovery. Setting
SPECS_PERM_MANIFEST/SPECS_PERM_LLVM_NM/SPECS_PERM_LLVM_OBJCOPYmakes the tool use exactly the sandboxed inputs and never fall back to the fragile self-relative walk (see Runtime dependencies). - The assertion is load-bearing.
set -ecatches thecp/embed, but the embed itself exits 0 even on failure. Thereadelf | grepis what actually gates correctness (see The tool is fail-soft). It uses the//ndk:llvm_readelfalias from Expose the tool and its dependencies to Bazel. run_shellkeeps it readable. On Windows, port the shell body to a.bat/ PowerShell wrapper or usectx.actions.runwith a launcher; the inputs, environment vars, and the mandatory post-check stay the same.
Make embedding automatic (recommended)
To match CMake's "runs on every shared library with no per-target work," wrap the shared-library rule in a macro so the embed step is always applied:
# specs/cc.bzl
load("@rules_cc//cc:defs.bzl", "cc_shared_library")
load("//specs:perm_embed.bzl", "specs_perm_embed")
def specs_cc_shared_library(name, **kwargs):
# Build the raw shared library under an internal name...
raw = name + "_raw"
cc_shared_library(name = raw, **kwargs)
# ...then embed permissions to produce the final artifact `name`.
specs_perm_embed(
name = name,
lib = ":" + raw,
)
Consumer usage:
# myproject/BUILD.bazel
load("//specs:cc.bzl", "specs_cc_shared_library")
specs_cc_shared_library(
name = "libfoo.so",
deps = [":foo_impl"],
# ...normal cc_shared_library attrs...
)
Building //myproject:libfoo.so now links the library and runs
specs-perm-embed on it. Because the macro only wraps the shared-library rule,
the "shared libraries only" scoping is enforced automatically.
Keep the Bazel rule in step with the NDK
The mapping in specs-permissions.json is regenerated each NDK release (the SPECS
entries are harvested from SPECS_REQUIRES_PERMISSION(...) annotations on the
SPECS API headers; the external_libraries entries list the network functions
of libcurl, OpenSSL, and libc that require INTERNET). Because the BUILD file in
Expose the tool and its dependencies to Bazel
aliases the manifest straight out of the NDK tree, a Bazel build always uses the
manifest that shipped with the NDK it points at: no vendoring, no drift. Make
sure the //ndk:... aliases track the NDK you actually build against.
If a future specs-perm-embed grows new flags or inputs, extend the rule the
same way The embed rule already does for the manifest: add an
attribute, declare it in inputs, and thread it into the command. Keep the
copy → embed → assert shape and the environment-pinning intact.
Verification (mandatory, because the tool is fail-soft)
specs-perm-embed exits 0 even when it embeds nothing (see
The tool is fail-soft),
so a green action does not prove the section exists. The rule in
The embed rule already asserts this inline with
llvm-readelf --sections | grep .snap.permissions; do not remove that check.
To spot-check a built artifact by hand, or to inspect which permissions were embedded, use the reference reader shipped in the NDK:
# what permissions ended up in the .so:
python3 sysroots/<host>/usr/share/specsndk/specs-perm-read.py libfoo.so
# or with stock ELF tooling:
llvm-readelf --sections libfoo.so | grep .snap.permissions # present?
specs-perm-read.py exits 0 (section present + valid), 3 (absent → never
processed → would be rejected at import), or 4 (present but malformed). A library
that reads clean here is accepted at import; one missing the section is rejected
fail-closed on the device.
How CMake embeds permissions (for parity)
The CMake integration lives in SpecsPostLink.cmake (shipped at
sysroots/<host>/usr/share/specsndk/SpecsPostLink.cmake) and is wired in by the
toolchain via CMAKE_PROJECT_TOP_LEVEL_INCLUDES. It:
- Overrides
add_libraryso every target is hooked at creation, tree-wide. - For
SHARED_LIBRARY/MODULE_LIBRARYtargets only (skippingALIAS/IMPORTED/ executables), attaches aPOST_BUILDcustom command:specs-perm-embed "$<TARGET_FILE:target>".
The CMake path passes only the .so on the command line and lets the tool
self-discover the manifest and llvm tools from its location inside the SDK
tree, which works because everything sits in one relocatable install. The Bazel
design reproduces the same automatic (via the macro) and shared-libraries-only
(via wrapping only the shared-lib rule) behavior, but deliberately replaces
self-discovery with explicit inputs + environment pinning (see
Runtime dependencies)
and adds a post-embed assertion (see
The tool is fail-soft),
both because a sandboxed/remote Bazel action can't assume the surrounding SDK
tree is present and can't trust the tool's exit code.
For the full permission pipeline, see Permission Annotations and Manifest Embedding.