Skip to content

About

Building Android 17 natively on Apple silicon (arm64 Linux, no x86 emulation): walls, patches, timings, byte-identical clang

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

Building Android 17 natively on Apple silicon (arm64 Linux, no x86 emulation)

This repository documents an experiment: building a GrapheneOS-based Android 17 tree natively on an Apple M4 Max machine running arm64 Linux, with no x86 emulation anywhere in the build, and booting the result on a real phone (Pixel 10 Pro Fold).

AOSP's build only supports x86-64 Linux hosts. Most of the build system is portable, but a number of prebuilt host tools (the compiler, the JDK, Go, Rust, a few build tools) exist only as x86-64 binaries, and a handful of places in the build hard-code an x86 host. This writeup lists each wall we hit, how it was cleared, real timings from the logs, and what is still not done.

It was written by an AI agent from build logs and notes. Numbers below are copied from /usr/bin/time -v output and build summaries, not estimated.

Contents

  • README.md: this file
  • PATCHES.md: every source change, one line each
  • ARTIFACTS.md: native arm64 host toolchains that were built, with sizes and hashes

Hardware and OS

  • Machine: M4 Max MacBook Pro / Mac Studio class machine: 16 CPU cores (12 performance + 4 efficiency), 128 GB unified memory, internal SSD.
  • OS: Arch Linux ARM userspace on an Asahi-derived kernel (the Aurora fork, kernel 7.3), root filesystem btrfs on LUKS. The kernel uses 16 KiB pages (getconf PAGESIZE = 16384). This matters later.
  • Build tree: a GrapheneOS Android 17 tree (about 196 GB checked out) plus a downstream fork of it. The tree was copied from an x86 machine where it was already synced; a fresh repo sync on the arm64 host was not tested.
  • Comparison machine: an x86-64 desktop (Intel Core i7-14700K, 20 cores / 28 threads) building the same sources with Google's stock x86 prebuilts.
  • Phone: Pixel 10 Pro Fold, bootloader unlocked.

The rule: no emulation, and proving it

The host had qemu-user-static x86 binfmt handlers installed. With those active, any x86 prebuilt the build executes would run silently under qemu and the build would "work" without being native. So:

  1. The x86 binfmt entries were masked on the host.
  2. Every build ran inside a user namespace with a fresh, empty binfmt_misc mount, so an attempt to execute an x86-64 binary fails with ENOEXEC instead of being emulated. The wrapper refuses to start if any qemu entry is visible:
unshare -U --map-current-user -m --keep-caps bash -c '
  mount -t binfmt_misc none /proc/sys/fs/binfmt_misc || { echo "binfmt guard FAILED"; exit 99; }
  ls /proc/sys/fs/binfmt_misc | grep -q qemu && { echo "qemu entries visible"; exit 98; }
  # ... build command here ...
'

This relies on the kernel supporting a per-user-namespace binfmt_misc instance (it does on the kernel used here). Every timing in this document comes from a build run inside this guard.

The walls, in the order they were hit

1. Go: no linux-arm64 prebuilt

prebuilts/go ships only linux-x86 (Go 1.25.4 in this tree). Soong's bootstrap needs a Go toolchain under prebuilts/go/<host>.

Fix: a private copy of the distribution's native Go (1.27.4 here) as its own GOROOT, with the standard library installed into it (GODEBUG=installgoroot=all go install std; recent Go versions no longer ship precompiled std packages), symlinked as prebuilts/go/linux-arm64. A newer Go than the pinned one worked without changes for Soong.

2. HOST_ARCH only knows x86_64

build/make/core/envsetup.mk detects the host by uname -m and only accepts x86_64. Soong, on the other hand, already lists LinuxMusl + Arm64 as a host target in android/arch.go, and on an arm64 host it forces musl.

Fix: an aarch64 branch in envsetup.mk setting HOST_ARCH := arm64, no second arch, USE_HOST_MUSL := true (so Make agrees with Soong), and HOST_PREBUILT_ARCH := arm64 so Make's HOST_OUT is out/host/linux-arm64, the same directory Soong uses. Without that last part Kati stops with SOONG_ZIP does not match between Make and Soong. Kati then wants build/make/core/clang/HOST_arm64.mk, which does not exist; a small new file fixes it. In build/envsetup.sh, get_host_prebuilt_prefix also needs to return linux-arm64 on aarch64, or lunch fails (it looks for an awk under prebuilts/build-tools/linux-x86).

3. JDK

prebuilts/jdk/jdk21 ships linux-x86 and darwin-arm64 but no linux-arm64.

Fix: a native OpenJDK 21 (21.0.13, from the distribution) copied into the tree at prebuilts/jdk/jdk21/linux-arm64, selected with OVERRIDE_ANDROID_JAVA_HOME=prebuilts/jdk/jdk21/linux-arm64. It has to be a relative, in-tree path, because sandboxed build actions only see the source tree. The javap prebuilt tool module also needed an arm64 branch in prebuilts/jdk/jdk21/Android.bp. For JDK 8, only the pure-bytecode jars are needed (jre/lib/*.jar and lib/tools.jar, used on javac's classpath by dokka and annotation processors), so prebuilts/jdk/jdk8/linux-arm64 is a set of symlinks to the linux-x86 jars.

4. Clang: rebuilt natively, with byte-identical output

prebuilts/clang/host (about 19 GB) is linux-x86 only. This was the largest piece of work.

First version (works, output not identical): build the host half of Android's clang from the exact pinned sources:

  • toolchain/llvm-project at the revision named in the prebuilt's clang_source_info.md
  • the patch list from toolchain/llvm_android PATCHES.json, filtered to the version range that includes this clang revision: 55 patches, all applied cleanly, which is exactly the set the x86 prebuilt's clang_source_info.md lists
  • configured to mirror llvm_android's builders: projects clang;lld;clang-tools-extra, targets AArch64;ARM;BPF;RISCV;WebAssembly;X86, assertions off, LLVM_VERSION_PATCH=1 (so it reports 22.0.1, matching AndroidVersion.txt), lld as default linker, statically linked C++ runtime, tools linked statically (no LLVM dylib)

The prebuilt directory is then assembled: a reflink copy of the linux-x86 prebuilt, with every x86 host binary and host library replaced by the native build. Target runtimes (compiler-rt, libc++ for Android and for the musl host, sanitizer runtimes, headers) are target artifacts, not host code, so they are kept verbatim. The final tree has no x86-64 ELF files except the runtimes for x86 targets. lldb, BOLT and Polly were not built; nothing in the platform build needed them.

The native build of llvm/clang/lld took 557 s (9 min 17 s) at -j16.

MLGO. Soong passes -enable-ml-inliner=release and -regalloc-enable-advisor=release to ThinLTO links. Google's clang has the release ML models compiled in; a plain build does not, and the LTO link fails (Requested regalloc eviction advisor analysis could not be created). Soong has a switch, THINLTO_USE_MLGO=false, which drops those flags. That gets a working build but different codegen.

Second version (output byte-identical to Google's x86 clang): rebuild with the MLGO models compiled in, using TensorFlow 2.18 AOT (in a Python 3.10 venv) and the arm64 models already shipped in the tree (prebuilts/clang/host/linux-x86/mlgo-models/arm64: inlining-Oz-chromium and regalloc-evict-aosp). That build took 570 s at -j16.

To compare outputs, the compiler's identity strings also have to match, because clang writes its version string into every object (.comment) and into __VERSION__. So CLANG_VENDOR, LLVM_FORCE_VC_REVISION and LLVM_FORCE_VC_REPOSITORY were set to the exact values Google's prebuilt reports. The vendor string therefore says +pgo, +bolt, +lto, but this compiler binary is not PGO, BOLT or LTO optimized. Those are optimizations of the compiler itself and affect only how fast it runs, not what it emits. Rename the vendor string for any redistributed copy (see ARTIFACTS.md).

Byte-identity proof. The same sources were compiled with Google's x86 prebuilt on the x86 machine and with the native clang on the M4, using the same command lines, and outputs were hashed:

Module Objects Linked output
external/zlib (libz.so) 19 / 19 identical identical
system/dmesgd 2 / 2 identical identical
system/libbase 17 / 17 identical identical
statsd 83 / 83 identical identical

Negative controls, to show the comparison can fail: linking libz.so without the regalloc advisor flag, and dmesgd without the ML inliner flags, both produced different hashes. Invoking the same compiler from a differently named directory (linux-arm64/... instead of linux-x86/...) also changed the output (5 of 19 libz objects identical, 0 of 2 dmesgd), because the compiler path ends up in the output. The fix is one -ffile-prefix-map entry in Soong's global cflags that rewrites the arm64 prebuilt path to the x86 one. That entry is only needed for the identity comparison.

Bindgen loads libclang.so at runtime from a musl-hosted process, so a separate musl-linked aarch64 libclang.so was built (with static zstd), and build/soong/rust/bindgen.go points at the linux-arm64 clang prebuilt on an arm64 musl host. LLVM_BINDGEN_PREBUILTS_VERSION selects it.

5. Rust: rebuilt as an aarch64 musl-hosted toolchain

prebuilts/rust-toolchain has linux-x86 and linux-musl-x86 host toolchains. Since Soong forces musl on arm64 hosts, the needed host is aarch64-unknown-linux-musl.

Fix: build Rust 1.93.1 from the upstream source tarball (sha256 checked), bootstrapped from the upstream native aarch64-unknown-linux-gnu 1.92.0 stage0 (sha256 checked):

  • Android's library changes: taken by diffing the x86 prebuilt's shipped lib/rustlib/src against upstream 1.93.1. Four files differ (panic_abort Android abort message, no backtrace on Android, CLOCK_BOOTTIME in time.rs, compiler-builtins/build.rs); all four applied. From toolchain/android_rust, the "do not LTO libunwind" patch applies and was applied. Most others no longer apply to 1.93.1.
  • musl host sysroot: built from the tree's own external/musl with the native clang, with LIBC_SONAME=libc_musl.so, because Android's musl loader identifies itself by that soname.
  • bootstrap.toml: build aarch64-unknown-linux-gnu, host/target aarch64-unknown-linux-musl, channel = "dev" (Soong passes -Z flags; Android's rustc is also a -dev build), in-tree libunwind, LLVM targets matching clang's, LLVM zlib/zstd/libxml2 off (otherwise glibc headers leak into the musl LLVM build).
  • The last wall: Soong links host proc-macros with -Z link-native-libraries=no -nostdlib, so they leave _Unwind_* undefined and expect the rustc process to provide them. Android's rustc gets them from a dynamically linked musl libc++.so that carries and exports the LLVM unwinder. A statically linked rustc failed at runtime with libserde_derive.so: Error relocating ...: _Unwind_GetTextRelBase: symbol not found. Linking libc++ dynamically fixed it.

Soong wiring: rust/config/global.go returns linux-musl-arm64 as the host prebuilt tag, rust/toolchain_library.go gets a linux_musl_arm64 branch (and skips the linux-musl-x86 one, or there are two prebuilt_libstd modules), and prebuilts/rust-toolchain/linux-musl-arm64/Android.bp is a copy of the x86 one. One more Soong fix was needed in cc/builder.go: on the arm64 musl host, the generated Rust staticlib could get the source-built sysroot std passed via --extern in addition to the toolchain's own, which gives two incompatible std crates.

Each rebuild of the Rust toolchain after a config change took 3.5 to 4.5 minutes (LLVM cached). From starting the Rust work to a natively built toybox took about 1 h 40 min, including failed attempts.

6. Prebuilt build tools and small host assumptions

prebuilts/build-tools/linux-arm64 already exists upstream and has native ninja, ckati, make, aconfig, aidl, m4, flex, bison, nsjail and more. Most of the remaining walls were places that never expect to use it:

  • m4 / flex / bison are enabled only for x86_64 in prebuilts/build-tools/Android.bp. Added linux_arm64 sources. The arm64 bison's data directory is resolved relative to linux-x86/bin, so a small wrapper sets BISON_PKGDATADIR.
  • The linux-arm64 build tools are musl binaries that load ../lib64/libc_musl.so relative to themselves. Inside a sandboxed rule, only declared inputs exist, so android/rule_builder.go (for prebuilt tools) and cc/gen.go (for m4) add libc_musl.so as an implicit input on arm64 hosts.
  • genrule host_second_srcs: resolved unconditionally, but no dependency is added when there is no 32-bit host target (there is none on arm64). Only resolve when a 32-bit host target exists.
  • Install directory for arch-common host modules (Java etc.): android/paths.go puts them in linux-x86; on an arm64 host they belong next to the arm64 ones.
  • llvm_prebuilt_build_tool (prebuilts/clang/host/linux-x86/soong/clangprebuilts.go) hard-codes the linux-x86 clang, so a cronet rule ran an x86 llvm-objdump. On arm64 it now uses the linux-arm64 prebuilt.
  • cronet passes -msse3 to host builds in about 600 places outside x86-specific sections. A script drops "-msse3" only when it is not inside an x86 arch block (1,904 occurrences: 1,292 kept, 612 dropped, 93 files changed).
  • berberis (the binary-translation project) has host-arch-independent text generators that are only enabled on x86 hosts; enabled them on arm64 hosts.
  • sepolicy tools (checkfc, sepolicy-check, sepolicy-analyze) store getopt()'s return in a char. char is unsigned on arm64 Linux, so -1 never matches, the loop never ends, and checkfc printed its usage and failed. Changing the variable to int fixes all four.

7. Sandboxing

build/soong/ui/build/sandbox_linux.go hard-codes prebuilts/build-tools/linux-x86/bin/nsjail. On arm64 that exec fails, and the build prints "Build sandboxing disabled due to nsjail error" and continues unsandboxed. That is easy to miss, and it makes a native build less strict than an x86 one.

Fix: use prebuilts/build-tools/linux-arm64/bin/nsjail when runtime.GOARCH == "arm64". After the fix, soong.log shows Kati and siso running under the arm64 nsjail, and the "sandboxing disabled" message count is 0.

8. The boot crash: EROFS block size follows the host page size

With all of the above, the first image for the Pixel 10 Pro Fold built fine and failed at boot: zygote crash-looped.

Cause: mkfs.erofs picks its default block size from the host's page size (blkszbits = ilog2(min(getpagesize(), EROFS_MAX_BLOCK_SIZE))), and the AOSP build compiles it with EROFS_MAX_BLOCK_SIZE=16384. On a 16 KiB-page host, every EROFS image built without an explicit -b gets 16 KiB blocks. The phone's kernel uses 4 KiB pages and cannot mount them. Two images in the system partition are affected: the payload of one APEX (com.android.virt) and /system/etc/apexd/empty_erofs.img. The other 43 APEXes in the image use ext4 payloads, and ext4 already gets an explicit 4096 block size from apexer. On an x86 host the page size is 4 KiB, so this never shows up there.

Measured from the two target_files.zip outputs (blkszbits is the byte at offset 1024 + 12 of an EROFS image):

Build empty_erofs.img com.android.virt payload Result on device
before fix blkszbits=14 (16 KiB) blkszbits=14 zygote crash loop
after fix blkszbits=12 (4 KiB) blkszbits=12 boots to setup, stable

Fix: pin the block size to 4096 in three places:

  • external/erofs-utils/mkfs/main.c: for host builds (!__ANDROID__), default blkszbits to ilog2(4096) instead of the host page size. On-device behavior is unchanged.
  • system/apex/apexer/apexer.py: mkfs.erofs -b 4096
  • system/apex/apexd/Android.bp: -b 4096 in the empty_erofs.img genrule

Both images are made by the tree's own host mkfs.erofs, so the first change should cover both; the other two make the block size explicit at the call sites and do not depend on the default. After rebuilding, the phone booted to the setup wizard and ran stable.

Anyone building Android on a 16 KiB-page host (Apple silicon Linux, or some arm64 servers) should check any image tool that defaults to getpagesize().

Timings

All wall-clock and memory numbers are from /usr/bin/time -v. "Peak RSS" is the largest single process (normally soong_build during analysis), not total system memory. All M4 builds used -j16.

Stock GrapheneOS, full clean device build (Pixel 9 Pro Fold target; goals systemimage vbmetaimage vendorbootimage vendorkernelbootimage target-files-package; test keys; no ccache):

Host Jobs Toolchain Wall clock Peak RSS
x86-64 desktop (i7-14700K) 28 Google x86 prebuilts 1:22:58 about 45 GB (as recorded)
M4 Max, arm64 Linux 16 native clang (no MLGO) 1:42:00 42.1 GiB
M4 Max, arm64 Linux 16 native clang (MLGO, identical output) 1:45:15 40.7 GiB

The M4 ran at about 113 to 117 °C die temperature for most of the build, with P-cores around 3.3 GHz. Forcing the fans to maximum raised P-core clocks from about 3.47 to 3.62 GHz under all-core load. On a laptop this is a thermally limited workload.

Downstream tree (GSI-style system image plus device overlays):

Build Wall clock CPU time (user + sys) CPU use Peak RSS
Clean, no ccache, Pixel 9 Pro Fold product 2:02:03 106,271 s + 4,475 s 1512% 55.7 GiB
Pixel 10 Pro Fold product, ccache on but mostly cold (18% hits) 2:05:28 107,244 s + 6,131 s 1505% 52.9 GiB
Incremental rebuild of the same product (reused out/, no ccache) 0:12:45 54.1 GiB

Toolchain builds (-j16): native clang (no MLGO) 557 s; clang with MLGO 570 s; Rust toolchain rebuild after a config change 3.5 to 4.5 min; first Soong analysis of the product on the arm64 host about 22 s (88 s including bootstrap).

How close is the output to an x86 build?

The devices do not require identical output, but it is a good check that nothing host-specific leaks into the images.

  • Compiler level: identical (see the table in wall 4).
  • Whole build, stock tree: with the first native clang, 8,278 of 10,278 files in target_files were byte-identical to the x86 build. Differences were in .so files, binaries, dexpreopt outputs (odex/vdex/art/oat) and fs-verity metadata. With the identical-output clang, 8,072 of 9,566 were identical (the two counts come from slightly different comparison runs). vendor_kernel_boot.img was identical.
  • Whole build, downstream tree (same build number and timestamp as the x86 build): 5,784 entries on both sides, same file set, 4,872 identical (84%). Differences: 223 in lib64, 210 framework oat files, 104 framework jars, 49 in bin, 43 APEXes.

The remaining differences are not root-caused. The likely contributor is THINLTO_USE_MLGO=false, which was still set in these comparison builds even after the MLGO clang existed. dexpreopt running on an arm64 host is another candidate.

Recipe

This is the order that worked. $TREE is the root of an already-synced Android 17 (GrapheneOS) tree on the arm64 Linux host. Paths inside $TREE are the real ones.

  1. Host packages: native Go, OpenJDK 21, clang + lld, cmake, ninja, python, git, zstd, libxml2, GNU time. Mask any qemu-* x86 binfmt handlers, and run everything below inside the binfmt guard shown above.

  2. Go: copy the distribution GOROOT to a private directory, install std into it, and symlink it as $TREE/prebuilts/go/linux-arm64.

  3. JDK: copy the native JDK 21 into $TREE/prebuilts/jdk/jdk21/linux-arm64. Create $TREE/prebuilts/jdk/jdk8/linux-arm64/{jre/lib,lib} with symlinks to the linux-x86 jars and tools.jar.

  4. Clang: fetch toolchain/llvm-project at the revision in prebuilts/clang/host/linux-x86/clang-<rev>/clang_source_info.md and toolchain/llvm_android at the revision it references. Apply the PATCHES.json entries whose version range includes the revision. Configure as described in wall 4 (add the TensorFlow AOT path and the two MLGO model paths if you want identical output). Build and install. Assemble $TREE/prebuilts/clang/host/linux-arm64/clang-<rev> from a reflink copy of the x86 one with the host binaries and libraries replaced. Build a musl-linked aarch64 libclang.so for bindgen.

  5. Rust: build aarch64-unknown-linux-musl-hosted Rust (same version as prebuilts/rust-toolchain/linux-x86) against a musl sysroot built from external/musl, with the Android library diffs and dynamic libc++. Install to $TREE/prebuilts/rust-toolchain/linux-musl-arm64/<version>.

  6. Apply the source changes in PATCHES.md.

  7. Environment:

    export OVERRIDE_ANDROID_JAVA_HOME=prebuilts/jdk/jdk21/linux-arm64   # relative, in-tree
    export LLVM_BINDGEN_PREBUILTS_VERSION=clang-<rev>
    export THINLTO_USE_MLGO=false     # only if your clang has no MLGO models compiled in
  8. Build: source build/envsetup.sh && lunch <target>-<release>-<variant>, then m systemimage vbmetaimage target-files-package (plus the vendor/boot goals for a full device build). Use test keys; this experiment never put release signing keys on the arm64 host for the stock-tree builds.

  9. Check EROFS block sizes before flashing:

    # prints 12 for 4 KiB blocks; 14 means 16 KiB and the image will not mount on a 4 KiB-page kernel
    python3 -c 'import sys; b=open(sys.argv[1],"rb").read(1040); print(b[1036])' empty_erofs.img

    For APEXes, check apex_payload.img inside each .apex zip the same way (only EROFS payloads have magic 0xE0F5E1E2 at offset 1024).

  10. Flash: the phone was first flashed with its stock factory image for the matching Android 17 release, then the natively built system image and vbmeta images were written (system from fastbootd), with a userdata wipe.

Limitations and what is not done

  • Not bit-identical as a whole. The compiler is, on the modules tested. Full builds are 80 to 84% identical, and the remaining differences are not explained yet.
  • The flashable images were assembled on x86. The target_files.zip for the phone was built natively, but merging it with the device's vendor/boot partitions and producing the flashable images (otatools steps) ran on the x86 machine in this attempt. Doing that step on arm64 has not been tested.
  • The Rust toolchain is not relocatable. rustc, rustdoc, clippy-driver and rustfmt have an absolute PT_INTERP pointing at libc_musl.so inside the build tree, and librustc_driver has an absolute RUNPATH. Move the tree and rustc stops starting. Android's own musl host binaries avoid this with a relative-interpreter trampoline (external/musl/android/relinterp.c). The clean way is a second pass: build libc_musl_sysroot with Soong on the arm64 host, then rebuild Rust against it.
  • One Android Rust compiler patch was not applied: android_rust's "Revert Set branch protection function attributes" does not apply to 1.93.1 and was not ported. aarch64 branch-protection function attributes in Rust code may differ from Google's rustc.
  • The native clang has no lldb, BOLT or Polly, and the compiler itself is not PGO/LTO/BOLT optimized, so it is somewhat slower than Google's.
  • Sources were copied, not synced on the arm64 host. Several fixes are content edits (the cronet script, berberis, sepolicy) that may need rework on a different tree revision.
  • One flaky Soong failure was seen once (generic_system.mk produces files outside its artifact path requirement: data/nativetest/jemalloc5_integrationtests). It passed on rerun with no change.
  • Validation on device is limited to one phone booting to setup and running stable. No CTS or other test suites were run.
  • Other 16 KiB-page hazards may exist in tools not used by these targets. The EROFS one was found only by booting.
  • Thermals: the laptop runs at its thermal ceiling for the whole build. A desktop-class Apple silicon machine with more cooling would likely do better; not measured.

About

Building Android 17 natively on Apple silicon (arm64 Linux, no x86 emulation): walls, patches, timings, byte-identical clang

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors