Skip to content

Keel

EnglishEestiEspañolไทย

Tekstide kirjutamisel ja parandamisel kasutasin tehisaru abi, seega võib esineda kirja- ja muid vigu. Kui leiate mõne, andke palun teada: [email protected]

Binary Size and the 16KB Page Requirement: Optimizing Rust .so Files for Release

Binary Size and the 16KB Page Requirement: Optimizing Rust .so Files for Release

Rust ja natiivarendus

Autor: David Cruz Anaya, mobiili ja rakendusliku tehisaru insener

Uuendatud 16. oktoober 202612 min lugemist

Android · Rust · NDK · Binary Size · 16KB Page Size · Release Builds

Rust + NDK on Android, Part 13 of 15. This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own. Next: CI/CD for Rust + Android: GitHub Actions, Cross-Compilation Caching, Reproducible Builds.

Your Rust .so has two release problems, and both are solved in build configuration. The first is compliance: since November 1, 2025, Google Play requires 16KB page size support from every new app and every update that targets Android 15 (API level 35) or higher on 64-bit devices (Android Developers, 2025). The second is waste: a default release build of even a small Rust crate carries formatting machinery, unwinding tables and monomorphized generics that nobody asked for. Not one line of crate source changes in this entire post.

The alignment half is quick, because the series already did most of the work: Part 1 pinned NDK r28, which links 16KB-aligned by default, and made llvm-readelf part of the build routine. The size half takes longer. Four Cargo profile levers do most of the work, cargo-bloat names the dependency eating your megabytes when the levers are not enough, and a measurement script keeps the whole exercise honest. The only prerequisite is the toolchain from Part 1, which is also why this part can be read out of order if the Play deadline is what brought you here.

Key Takeaways

  • Since November 1, 2025, Google Play requires 16KB page size support for new apps and updates targeting Android 15 or higher. The requirement covers the arm64-v8a and x86_64 .so files in your app, including ones you did not build (Android Developers).
  • NDK r28 links 16KB-aligned by default. On r27 or older, Rust needs -Wl,-z,max-page-size=16384 passed through rustflags, and llvm-readelf -lW proves the result either way.
  • Four profile levers do almost all the size work: lto = "fat", codegen-units = 1, opt-level = "z" and panic = "abort". The last one kills the catch_unwind firewall from Part 8, That is the trade.
  • The Android Gradle Plugin strips the native libraries it packages. Keep symbols in the cargo output for ndk-stack, and measure the stripped copy, because that is what users download.

What Android’s 16KB page size requirement demands from a Rust library

A page is the unit the kernel manages memory in, and every Android device you have ever shipped to used 4KB pages. Android 15 added OS support for 16KB pages because larger pages mean fewer page faults and less kernel bookkeeping. Google measured the payoff on 16KB devices: app launch times improved 3.16 percent on average under memory pressure, some apps gained up to 30 percent, and system boot improved by roughly 8 percent, about 950 milliseconds (Android Developers, 2025).

A shared library records, in its program headers, the alignment its LOAD segments were linked for. A library linked for 4KB pages cannot be mapped by a 16KB kernel. System.loadLibrary throws on a 16KB device and the app is dead on first launch. That is why Play enforces the requirement at submission time instead of letting users find out.

The requirement applies to 64-bit ABIs, arm64-v8a and x86_64, and it applies to every .so in the bundle, including the ones you did not compile. A Kotlin-only app that pulls in an SDK with native code is on the hook exactly as much as this series is. For your Rust crates, the toolchain decides compliance. The right NDK gives it to you for free, and an old NDK can be fixed with one linker flag.

Verify the alignment before Play does

Part 1 made this check part of the routine, and it does not change now. Point llvm-readelf at each library that ships, here the parser crate from Part 11:

llvm-readelf -lW app/src/main/jniLibs/arm64-v8a/libparser.so | grep LOAD

The final column of each LOAD row is the segment alignment. 0x4000 is 16384 bytes, which passes. 0x1000 is 4096 bytes, which fails on a 16KB device. Part 1 shows the full captured output for a healthy library; the shape is identical for every crate in this series.

The per-file check is necessary but not sufficient, because your APK contains libraries you did not build. Three whole-app checks close the gap. Android Studio’s APK Analyzer flags misaligned .so files in the lib folder. Google publishes a check_elf_alignment.sh script that sweeps an entire APK (Android Developers). And zipalign verifies the packaging side, which matters because uncompressed native libraries must also sit at 16KB offsets inside the zip:

zipalign -v -c -P 16 4 app-release.apk

If a third-party SDK fails these checks, your only fix is a vendor update. File the ticket early; you cannot relink someone else’s binary.

Fixing alignment from the Rust build

On NDK r28 or newer there is nothing to do. The linker emits 16KB-aligned segments by default, which is the reason Part 1 pinned 28.2.13676358 for the whole series. If a company toolchain pins you to r27 or older, pass the alignment flags to the linker yourself. For Rust the clean place is a cargo config file at rust/.cargo/config.toml, which applies to every crate in the workspace:

[target.aarch64-linux-android]
rustflags = [
  "-C", "link-arg=-Wl,-z,max-page-size=16384",
  "-C", "link-arg=-Wl,-z,common-page-size=16384",
]

[target.x86_64-linux-android]
rustflags = [
  "-C", "link-arg=-Wl,-z,max-page-size=16384",
  "-C", "link-arg=-Wl,-z,common-page-size=16384",
]

max-page-size is the correctness flag: it sets the LOAD alignment the kernel checks. common-page-size is a layout optimization the Android docs recommend alongside it (Android Developers). Only the two 64-bit targets need entries, because the Play requirement covers 64-bit devices.

The Gradle side has its own version floor. The Android Gradle Plugin zipaligns uncompressed native libraries to 16KB boundaries from AGP 8.5.1 onward, and versions between 8.3 and 8.5 align the libraries but leave a bundletool gap that can still trip Play (Android Developers). The build wiring from Part 4 already sits above that floor. Whatever you change, re-run the readelf check afterwards; trust the ELF header, not the changelog.

Cutting the binary size: the release profile

Now the second problem. Rust links its standard library statically into every cdylib, keeps panic and formatting machinery around by default, and stamps out a fresh copy of each generic function per concrete type. There is no R8 for native code: LLVM and the linker are your shrinker, and they only remove what the profile allows. The levers live in the workspace rust/Cargo.toml, and this is the block the series ships:

[profile.release]
opt-level = "z"
lto = "fat"
codegen-units = 1
panic = "unwind"
debug = true
strip = "none"

# audiofx stays speed-first: size wins must never cost audio deadlines.
[profile.release.package.audiofx]
opt-level = 3

Each line is a decision, so here is each decision (The Cargo Book, Profiles):

lto = "fat" runs link-time optimization across the whole program, inlining and discarding dead code across crate boundaries. It is the closest native analogue to R8’s whole-program shrinking, and it usually moves the number more than any other single line. The price is link time, which is why it belongs in release only.

codegen-units = 1 compiles the crate as one LLVM module instead of up to sixteen parallel ones. Optimization sees everything at once, output shrinks, and the build gets slower. Release builds can spend that time.

opt-level = "z" optimizes for size instead of speed. For boundary glue and parsers the speed cost is irrelevant. For the DSP core from Part 10 it is not, which is what the per-package override is for: audiofx keeps opt-level = 3 while everything else shrinks. Package overrides handle exactly this split so you never trade audio deadlines for kilobytes.

panic = "unwind" is the default, spelled out because it is a real choice. Switching to panic = "abort" deletes unwinding tables and landing pads, and in my builds it is often the largest single lever after LTO. It also breaks things this series built on purpose: the catch_unwind firewall from Part 8 stops working, and UniFFI’s panic-to-exception mapping needs unwinding too. My position is unchanged from Part 8: for code living inside an app process I keep unwinding and spend the size. If every boundary in your app maps errors through Result and you accept that any surviving bug becomes a native crash, abort is yours to take.

debug = true with strip = "none" costs your users nothing. The Android Gradle Plugin strips the native libraries it packages, so the fat symbols never reach the APK unless you opt out with keepDebugSymbols. Cargo itself has stripped debuginfo from release builds by default since Rust 1.77, so being explicit here keeps the unstripped copy that ndk-stack needs for symbolication, exactly as the hub’s debugging section sets up. The stripped copy goes to users; the fat one stays with you for the day a crash report needs it.

Finding the offenders with cargo-bloat

The profile shrinks what the compiler generates. It cannot fix a dependency tree that generates too much, and guessing at the culprit wastes afternoons. cargo-bloat reads the compiled artifact and attributes size to functions and crates. It analyzes cdylib targets directly, which is exactly what we build:

cargo install cargo-bloat
cargo ndk -t arm64-v8a bloat --release --lib --crates -n 12

Running it through cargo ndk keeps the analysis on the artifact you actually ship. If your cargo-ndk version refuses a non-build subcommand, run cargo bloat --release --lib --crates against the host build instead; the absolute numbers differ, the ranking rarely does. Drop --crates to see individual functions, which is where monomorphization shows up as the same generic repeated for every concrete type it was called with. The tool’s own documentation calls the attribution guesswork, so treat it as a ranking, not a ledger.

What you do with the ranking is ordinary dependency hygiene. Most oversized Rust libraries are fat because of default features nobody turned off. default-features = false on a heavy dependency, followed by adding back only the features you use, is the edit that removes the most on many real crates. The serde and tokio setups from Part 11 and Part 9 already follow this rule. Past that, the recurring offenders are a regex engine pulled in for one literal match, and derive macros generating serialization for types that never cross the boundary. Nightly’s -Z build-std can rebuild the standard library with your size flags; for an app library the maintenance cost outweighs the savings.

Measuring the playbook: scripts/size-report.sh

Every size claim in this series has to survive the same rule as every benchmark claim: measured or not stated. The methodology is one lever at a time, applied cumulatively, with all four levers pinned explicitly at every step so each delta is attributable to exactly one change. The measured artifact is the stripped arm64 library, because stripping is what AGP does before packaging, and the stripped copy is what a user downloads. Save the following as scripts/size-report.sh next to your workspace and it walks the whole ladder:

#!/usr/bin/env bash
# Measures the stripped arm64 parser library after each size lever.
# Levers are cumulative; every step pins all four so deltas are attributable.
set -euo pipefail

ABI="arm64-v8a"
CRATE="rust/parser"
SO="libparser.so"
STRIP=("$ANDROID_NDK_HOME"/toolchains/llvm/prebuilt/*/bin/llvm-strip)
OUT="$(mktemp -d)"

measure() {
  local label="$1"
  shift
  env "$@" cargo ndk -t "$ABI" -o "$OUT" build --release \
    --manifest-path "$CRATE/Cargo.toml" >/dev/null 2>&1
  "${STRIP[0]}" "$OUT/$ABI/$SO"
  printf '%-20s %10d bytes\n' "$label" "$(wc -c < "$OUT/$ABI/$SO")"
}

measure "baseline" \
  CARGO_PROFILE_RELEASE_LTO=off \
  CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 \
  CARGO_PROFILE_RELEASE_OPT_LEVEL=3 \
  CARGO_PROFILE_RELEASE_PANIC=unwind
measure "+ lto fat" \
  CARGO_PROFILE_RELEASE_LTO=fat \
  CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 \
  CARGO_PROFILE_RELEASE_OPT_LEVEL=3 \
  CARGO_PROFILE_RELEASE_PANIC=unwind
measure "+ codegen-units 1" \
  CARGO_PROFILE_RELEASE_LTO=fat \
  CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 \
  CARGO_PROFILE_RELEASE_OPT_LEVEL=3 \
  CARGO_PROFILE_RELEASE_PANIC=unwind
measure "+ opt-level z" \
  CARGO_PROFILE_RELEASE_LTO=fat \
  CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 \
  CARGO_PROFILE_RELEASE_OPT_LEVEL=z \
  CARGO_PROFILE_RELEASE_PANIC=unwind
measure "+ panic abort" \
  CARGO_PROFILE_RELEASE_LTO=fat \
  CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 \
  CARGO_PROFILE_RELEASE_OPT_LEVEL=z \
  CARGO_PROFILE_RELEASE_PANIC=abort

The CARGO_PROFILE_RELEASE_* environment variables override the profile in Cargo.toml per invocation, which is what lets one script walk the ladder without editing files between builds (The Cargo Book, Environment Variables). Change ABI and rerun to get the other architectures.

There is no results table under that script, on purpose. The deltas depend on your dependency tree far more than on anything I control, so my numbers would tell you little about your APK. Run the ladder against your own library instead: it takes a few minutes, and the output describes what you actually ship. Two things hold whatever it prints. Each ABI carries its own full copy of everything, which is why the app bundle setup from Part 4 matters, since a device downloads one ABI, not four. And the big steps come early. The last rung, panic = "abort", is there for apps that can afford it; mine keep unwinding.

Frequently Asked Questions

Does the 16KB page size requirement apply to armeabi-v7a?

No. Google Play’s requirement covers 64-bit devices, so it applies to the arm64-v8a and x86_64 libraries in your app (Android Developers). If you still ship armeabi-v7a for old devices, those libraries are out of scope, which is why the cargo config above only touches the two 64-bit targets.

Why is a Rust .so bigger than the equivalent C++ one?

Rust links its standard library statically into each cdylib, while Android C++ builds usually share libc++_shared.so, so the C++ number hides a library the APK still carries. Add panic machinery and monomorphized generics, and an unoptimized comparison flatters C++. Compare stripped, LTO release builds before drawing conclusions.

My app is all Kotlin. Can I ignore the 16KB requirement?

Only if your APK contains no native code at all. Open the lib folder in APK Analyzer: analytics, database, ML and crypto SDKs routinely ship .so files you never compiled. If anything is in there and you target Android 15 or higher, the requirement applies to your next update, and your fix is updating the SDK that shipped the misaligned library.

Where this leaves you

The weak point is that config drifts when only humans watch it. Part 14, CI/CD for Rust + Android: GitHub Actions, Cross-Compilation Caching, Reproducible Builds, runs these checks in a pipeline that fails the build when alignment or size regresses. If you landed here from a Play Console warning rather than from Part 12, the series hub has the map of everything else.

Sources

Jaga: