Skip to main content

rust_anything/
android.rs

1//! Android NDK builds: the JNI `cdylib` for each ABI, installed into `jniLibs/`.
2//!
3//! The JVM records and diffs on the host; an Android app needs the same library built for
4//! its ABIs instead. This links with the NDK's clang directly, so `cargo-ndk` is not needed:
5//! the only moving parts are the linker path and the Rust target.
6//!
7//! The recording step still runs on a desktop JVM (phase 3, on-device recording, is not
8//! implemented). What this adds is a library Gradle can package: `<crate>/jniLibs/<abi>/lib*.so`.
9
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13use anyhow::{Context, Result, bail};
14use serde::Serialize;
15
16use crate::bridge::{Kind, Manifest};
17use crate::lang::Lang;
18
19/// The ABIs built when `--abi` is not given: phones (64 and 32 bit) and emulators.
20pub const DEFAULT_ABIS: &[Abi] = &[Abi::Arm64, Abi::Armv7, Abi::X86_64];
21
22/// The generated Java runtime uses `java.util.Optional` and `java.util.function` (API 24) and
23/// `ThreadLocal.withInitial` (API 26), so libraries built for a lower API would load but fail in
24/// the wrapper before the first call reaches Rust. API 26 is the honest floor.
25pub const MIN_API: u32 = 26;
26
27/// The API level the libraries target when `--api` is not given.
28pub const DEFAULT_API: u32 = MIN_API;
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum Abi {
32    Arm64,
33    Armv7,
34    X86_64,
35    X86,
36}
37
38impl Abi {
39    pub fn parse(name: &str) -> Result<Self> {
40        match name {
41            "arm64-v8a" => Ok(Self::Arm64),
42            "armeabi-v7a" => Ok(Self::Armv7),
43            "x86_64" => Ok(Self::X86_64),
44            "x86" => Ok(Self::X86),
45            other => bail!(
46                "unknown Android ABI `{other}`; use one of arm64-v8a, armeabi-v7a, x86_64, x86"
47            ),
48        }
49    }
50
51    /// The name Gradle uses for the ABI directory.
52    pub fn name(self) -> &'static str {
53        match self {
54            Self::Arm64 => "arm64-v8a",
55            Self::Armv7 => "armeabi-v7a",
56            Self::X86_64 => "x86_64",
57            Self::X86 => "x86",
58        }
59    }
60
61    /// The Rust target triple.
62    pub fn triple(self) -> &'static str {
63        match self {
64            Self::Arm64 => "aarch64-linux-android",
65            Self::Armv7 => "armv7-linux-androideabi",
66            Self::X86_64 => "x86_64-linux-android",
67            Self::X86 => "i686-linux-android",
68        }
69    }
70
71    /// Android's 16 KB page-size requirement applies to 64-bit libraries.
72    fn is_64_bit(self) -> bool {
73        matches!(self, Self::Arm64 | Self::X86_64)
74    }
75
76    /// The NDK clang driver's prefix; the API level is appended (`aarch64-linux-android26-clang`).
77    fn clang_prefix(self) -> &'static str {
78        match self {
79            Self::Arm64 => "aarch64-linux-android",
80            Self::Armv7 => "armv7a-linux-androideabi",
81            Self::X86_64 => "x86_64-linux-android",
82            Self::X86 => "i686-linux-android",
83        }
84    }
85}
86
87#[derive(Debug, Serialize)]
88pub struct Library {
89    pub abi: &'static str,
90    pub path: PathBuf,
91    /// JNI entry points checked against the library's dynamic symbols.
92    pub entry_points: usize,
93}
94
95#[derive(Debug, Serialize)]
96pub struct Report {
97    pub ndk: PathBuf,
98    pub api: u32,
99    pub libraries: Vec<Library>,
100}
101
102pub struct Options {
103    /// ABIs to build; `DEFAULT_ABIS` when empty.
104    pub abis: Vec<String>,
105    pub api: u32,
106    /// NDK root; found from the environment and the SDK when `None`.
107    pub ndk: Option<PathBuf>,
108    /// Where to install the libraries; `<crate>/jniLibs` when `None`.
109    pub out: Option<PathBuf>,
110}
111
112impl Default for Options {
113    fn default() -> Self {
114        Self {
115            abis: Vec::new(),
116            api: DEFAULT_API,
117            ndk: None,
118            out: None,
119        }
120    }
121}
122
123/// Builds the JNI library for each ABI and installs it under `<out>/<abi>/`.
124pub fn build(crate_dir: &Path, manifest: &Manifest, opts: &Options) -> Result<Report> {
125    if !matches!(manifest.language, Lang::Java | Lang::Kotlin) {
126        bail!(
127            "an Android build needs a JNI crate (Java or Kotlin), not {}",
128            manifest.language.name()
129        );
130    }
131    if manifest.kind != Kind::Ffi {
132        bail!(
133            "an Android build needs an `ffi` crate, not {:?}",
134            manifest.kind
135        );
136    }
137    check_api(opts.api)?;
138    let ndk = ndk_root(opts.ndk.as_deref())?;
139    let bin = ndk
140        .join("toolchains/llvm/prebuilt")
141        .join(host_tag())
142        .join("bin");
143    if !bin.is_dir() {
144        bail!("no NDK toolchain in {}", bin.display());
145    }
146    let mut abis = Vec::new();
147    if opts.abis.is_empty() {
148        abis.extend_from_slice(DEFAULT_ABIS);
149    } else {
150        for name in &opts.abis {
151            let abi = Abi::parse(name)?;
152            if !abis.contains(&abi) {
153                abis.push(abi);
154            }
155        }
156    }
157    check_targets(crate_dir, &abis)?;
158    let out = opts
159        .out
160        .clone()
161        .unwrap_or_else(|| crate_dir.join("jniLibs"));
162    let lib = manifest.lib_name();
163    let target_dir = crate_dir.join("target");
164    let mut libraries = Vec::new();
165    for abi in abis {
166        let linker = bin.join(format!("{}{}-clang", abi.clang_prefix(), opts.api));
167        if !linker.is_file() {
168            bail!(
169                "no NDK linker for API {} at {}; this NDK does not ship that API level, lower `--api` (minimum {})",
170                opts.api,
171                linker.display(),
172                MIN_API
173            );
174        }
175        let mut cmd = Command::new("cargo");
176        cmd.args([
177            "build",
178            "--release",
179            "--target",
180            abi.triple(),
181            "--manifest-path",
182        ])
183        .arg(crate_dir.join("Cargo.toml"))
184        // Cargo config and rust-toolchain.toml belong to the crate, not to whoever called us.
185        .current_dir(crate_dir)
186        .env("CARGO_TARGET_DIR", &target_dir)
187        .env(linker_var(abi.triple()), &linker)
188        // `cc`-based build scripts (none today, but crates bring them) read these.
189        .env(format!("CC_{}", abi.triple().replace('-', "_")), &linker)
190        .env(
191            format!("AR_{}", abi.triple().replace('-', "_")),
192            bin.join("llvm-ar"),
193        )
194        // Android requires 16 KB ELF alignment on 64-bit devices (Play enforces it for new
195        // apps since 2025). NDK r28+ does this by default; the flags are harmless on newer NDKs.
196        .env(
197            rustflags_var(abi.triple()),
198            "-C link-arg=-Wl,-z,max-page-size=16384 -C link-arg=-Wl,-z,common-page-size=16384",
199        );
200        run(&mut cmd, &format!("cargo build --target {}", abi.triple()))?;
201        let built = target_dir
202            .join(abi.triple())
203            .join("release")
204            .join(format!("lib{lib}.so"));
205        if !built.is_file() {
206            bail!("no library at {}", built.display());
207        }
208        let entry_points = check_symbols(crate_dir, abi, &bin.join("llvm-nm"), &built)?;
209        check_page_size(abi, &bin.join("llvm-readelf"), &built)?;
210        let dest = out.join(abi.name()).join(format!("lib{lib}.so"));
211        if let Some(dir) = dest.parent() {
212            std::fs::create_dir_all(dir)?;
213        }
214        crate::harness::install(&built, &dest)?;
215        libraries.push(Library {
216            abi: abi.name(),
217            path: dest,
218            entry_points,
219        });
220    }
221    Ok(Report {
222        ndk,
223        api: opts.api,
224        libraries,
225    })
226}
227
228/// The generated Java runtime needs API 26+ even though the NDK itself can link for API 21.
229pub fn check_api(api: u32) -> Result<()> {
230    if api < MIN_API {
231        bail!(
232            "--api {api} is too low: the generated Java runtime needs API {MIN_API}+ \
233             (java.util.Optional, java.util.function, ThreadLocal.withInitial)"
234        );
235    }
236    Ok(())
237}
238
239/// The NDK root: `--ndk`, then `ANDROID_NDK_HOME`/`ANDROID_NDK_ROOT`, then the newest complete
240/// NDK under `ANDROID_HOME`/`ANDROID_SDK_ROOT`, then the usual SDK folders.
241pub fn ndk_root(explicit: Option<&Path>) -> Result<PathBuf> {
242    if let Some(path) = explicit {
243        return valid_ndk(path);
244    }
245    for var in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT"] {
246        if let Some(path) = std::env::var_os(var) {
247            return valid_ndk(Path::new(&path));
248        }
249    }
250    for var in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {
251        if let Some(sdk) = std::env::var_os(var)
252            && let Some(ndk) = newest_ndk(Path::new(&sdk).join("ndk"))
253        {
254            return Ok(ndk);
255        }
256    }
257    for sdk in sdk_folders() {
258        if let Some(ndk) = newest_ndk(sdk.join("ndk")) {
259            return Ok(ndk);
260        }
261    }
262    bail!(
263        "Android NDK not found: set ANDROID_NDK_HOME, pass `--ndk <path>`, or install one with \
264         `sdkmanager \"ndk;28.0.13004108\"`"
265    )
266}
267
268/// A usable NDK needs its clang toolchain for this host, not just a `source.properties` file:
269/// an interrupted `sdkmanager` download often leaves an empty newer directory behind.
270fn valid_ndk(path: &Path) -> Result<PathBuf> {
271    if path
272        .join("toolchains/llvm/prebuilt")
273        .join(host_tag())
274        .join("bin")
275        .is_dir()
276    {
277        Ok(path.to_path_buf())
278    } else {
279        bail!(
280            "{} is not a usable Android NDK (no toolchains/llvm/prebuilt/{}/bin)",
281            path.display(),
282            host_tag()
283        )
284    }
285}
286
287fn newest_ndk(dir: PathBuf) -> Option<PathBuf> {
288    let mut found: Vec<(Vec<u32>, PathBuf)> = std::fs::read_dir(dir)
289        .ok()?
290        .flatten()
291        .map(|e| e.path())
292        .filter(|p| p.join("source.properties").is_file() && valid_ndk(p).is_ok())
293        .map(|p| {
294            let key = p
295                .file_name()
296                .map(|n| n.to_string_lossy().into_owned())
297                .unwrap_or_default()
298                .split(|c: char| !c.is_ascii_digit())
299                .filter_map(|part| part.parse().ok())
300                .collect();
301            (key, p)
302        })
303        .collect();
304    found.sort_by(|a, b| a.0.cmp(&b.0));
305    found.pop().map(|(_, p)| p)
306}
307
308pub fn sdk_folders() -> Vec<PathBuf> {
309    let mut out = Vec::new();
310    if let Some(home) = std::env::var_os("HOME") {
311        let home = PathBuf::from(home);
312        out.push(home.join("Android/Sdk"));
313        out.push(home.join("Library/Android/sdk"));
314        out.push(home.join("Documents/Android/Sdk"));
315    }
316    if cfg!(windows)
317        && let Some(local) = std::env::var_os("LOCALAPPDATA")
318    {
319        out.push(PathBuf::from(local).join("Android/Sdk"));
320    }
321    out.push(PathBuf::from("/usr/lib/android-sdk"));
322    out.push(PathBuf::from("/opt/android-sdk"));
323    out
324}
325
326/// NDK prebuilts are x86_64 even on Linux machines with an arm64 CPU; say so when they are absent.
327fn host_tag() -> &'static str {
328    if cfg!(target_os = "macos") {
329        "darwin-x86_64"
330    } else if cfg!(windows) {
331        "windows-x86_64"
332    } else {
333        // NDK prebuilts are x86_64 even on Linux hosts with an arm64 CPU.
334        "linux-x86_64"
335    }
336}
337
338fn linker_var(triple: &str) -> String {
339    format!(
340        "CARGO_TARGET_{}_LINKER",
341        triple.replace('-', "_").to_uppercase()
342    )
343}
344
345fn rustflags_var(triple: &str) -> String {
346    format!(
347        "CARGO_TARGET_{}_RUSTFLAGS",
348        triple.replace('-', "_").to_uppercase()
349    )
350}
351
352/// Fails before cargo does, listing every target to install at once.
353fn check_targets(crate_dir: &Path, abis: &[Abi]) -> Result<()> {
354    let Some(installed) = installed_targets(crate_dir) else {
355        return Ok(());
356    };
357    let missing: Vec<&str> = abis
358        .iter()
359        .map(|a| a.triple())
360        .filter(|t| !installed.iter().any(|i| i == t))
361        .collect();
362    if missing.is_empty() {
363        return Ok(());
364    }
365    bail!(
366        "Rust targets for Android are not installed: {}",
367        format_args!("rustup target add {}", missing.join(" "))
368    )
369}
370
371fn installed_targets(crate_dir: &Path) -> Option<Vec<String>> {
372    let out = crate::process::output(
373        Command::new("rustup")
374            .args(["target", "list", "--installed"])
375            .current_dir(crate_dir),
376        crate::process::QUICK,
377    )
378    .ok()?;
379    out.success().then(|| {
380        out.stdout_text()
381            .lines()
382            .map(str::trim)
383            .map(String::from)
384            .collect()
385    })
386}
387
388/// The JNI entry points `src/lib.rs` declares.
389fn expected_symbols(crate_dir: &Path) -> Result<Vec<String>> {
390    let lib = std::fs::read_to_string(crate_dir.join("src/lib.rs"))
391        .with_context(|| format!("reading {}/src/lib.rs", crate_dir.display()))?;
392    let symbols: Vec<String> = lib
393        .lines()
394        .filter_map(|line| {
395            let at = line.find("extern \"system\" fn Java_")?;
396            let name: String = line[at + "extern \"system\" fn ".len()..]
397                .chars()
398                .take_while(|c| c.is_alphanumeric() || *c == '_')
399                .collect();
400            (!name.is_empty()).then_some(name)
401        })
402        .collect();
403    if symbols.is_empty() {
404        bail!(
405            "{} declares no JNI entry points; is this a Java or Kotlin crate?",
406            crate_dir.join("src/lib.rs").display()
407        );
408    }
409    Ok(symbols)
410}
411
412/// Runs a build tool with the same timeout and output cap as the rest of the tool.
413fn run(cmd: &mut Command, what: &str) -> Result<String> {
414    let out = crate::process::output(cmd, crate::process::BUILD)
415        .with_context(|| format!("running {what}"))?;
416    if out.success() {
417        return Ok(out.stdout_text());
418    }
419    let stderr = out.stderr_text();
420    let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
421    bail!(
422        "{what} failed ({}):\n{}",
423        out.status,
424        tail.into_iter().rev().collect::<Vec<_>>().join("\n")
425    )
426}
427
428/// Checks that the built library exports every declared JNI entry point, which catches a library
429/// that links but would fail `System.loadLibrary` with `UnsatisfiedLinkError`.
430fn check_symbols(crate_dir: &Path, abi: Abi, nm: &Path, library: &Path) -> Result<usize> {
431    let expected = expected_symbols(crate_dir)?;
432    let out = crate::process::output(
433        Command::new(nm).args(["-D", "--defined-only"]).arg(library),
434        crate::process::QUICK,
435    )
436    .with_context(|| format!("running {}", nm.display()))?;
437    if !out.success() {
438        bail!("{} failed on {}", nm.display(), library.display());
439    }
440    let have = out.stdout_text();
441    let missing: Vec<&String> = expected
442        .iter()
443        .filter(|s| {
444            !have
445                .lines()
446                .any(|l| l.split_whitespace().any(|w| w == s.as_str()))
447        })
448        .collect();
449    if !missing.is_empty() {
450        bail!(
451            "the {} library {} does not export {}",
452            abi.name(),
453            library.display(),
454            missing
455                .iter()
456                .map(|s| s.as_str())
457                .collect::<Vec<_>>()
458                .join(", ")
459        );
460    }
461    Ok(expected.len())
462}
463
464/// Every `LOAD` segment of a 64-bit Android library must be 16 KB aligned.
465fn check_page_size(abi: Abi, readelf: &Path, library: &Path) -> Result<()> {
466    if !abi.is_64_bit() {
467        return Ok(());
468    }
469    let text = run(
470        Command::new(readelf).arg("-l").arg(library),
471        &format!("llvm-readelf -l (ABI {})", abi.name()),
472    )?;
473    check_alignment(&text).with_context(|| format!("checking {}", library.display()))
474}
475
476fn check_alignment(readelf: &str) -> Result<()> {
477    let segments: Vec<&str> = readelf
478        .lines()
479        .filter(|l| l.split_whitespace().next() == Some("LOAD"))
480        .collect();
481    if segments.is_empty() {
482        bail!("llvm-readelf listed no LOAD segments");
483    }
484    let misaligned: Vec<&str> = segments
485        .iter()
486        .copied()
487        .filter(|line| {
488            line.split_whitespace()
489                .last()
490                .and_then(|a| u64::from_str_radix(a.trim_start_matches("0x"), 16).ok())
491                .is_none_or(|align| align < 0x4000)
492        })
493        .collect();
494    if !misaligned.is_empty() {
495        bail!(
496            "{} LOAD segment(s) are not 16 KB aligned: {}",
497            misaligned.len(),
498            misaligned[0]
499        );
500    }
501    Ok(())
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn parses_gradle_abi_names() {
510        assert_eq!(Abi::parse("arm64-v8a").unwrap(), Abi::Arm64);
511        assert_eq!(Abi::parse("armeabi-v7a").unwrap(), Abi::Armv7);
512        assert_eq!(Abi::parse("x86_64").unwrap(), Abi::X86_64);
513        assert!(Abi::parse("mips").is_err());
514    }
515
516    #[test]
517    fn clang_driver_names_match_the_ndk() {
518        assert_eq!(
519            format!("{}{}-clang", Abi::Arm64.clang_prefix(), 21),
520            "aarch64-linux-android21-clang"
521        );
522        assert_eq!(
523            format!("{}{}-clang", Abi::Armv7.clang_prefix(), 21),
524            "armv7a-linux-androideabi21-clang"
525        );
526    }
527
528    #[test]
529    fn rejects_too_low_an_api() {
530        assert!(check_api(DEFAULT_API).is_ok());
531        assert!(check_api(21).unwrap_err().to_string().contains("API 26"));
532    }
533
534    #[test]
535    fn the_newest_complete_ndk_wins() {
536        let dir = std::env::temp_dir().join(format!("ra-ndk-{}", std::process::id()));
537        let _ = std::fs::remove_dir_all(&dir);
538        for version in ["25.1.8937393", "30.0.16248370", "99.0.0"] {
539            let root = dir.join(version);
540            std::fs::create_dir_all(root.join("source.properties").parent().unwrap()).unwrap();
541            std::fs::write(root.join("source.properties"), "").unwrap();
542            // 99.0.0 is an interrupted download: no clang toolchain.
543            if version != "99.0.0" {
544                std::fs::create_dir_all(
545                    root.join("toolchains/llvm/prebuilt")
546                        .join(host_tag())
547                        .join("bin"),
548                )
549                .unwrap();
550            }
551        }
552        let found = newest_ndk(dir.clone()).unwrap();
553        assert_eq!(found.file_name().unwrap(), "30.0.16248370");
554        std::fs::remove_dir_all(&dir).unwrap();
555    }
556
557    #[test]
558    fn the_16kb_check_reads_elf_load_alignment() {
559        let aligned = "  LOAD 0x000000 0x00000000 0x00000000 0x1000 0x1000 R E 0x4000\n\
560                       LOAD 0x001000 0x00001000 0x00001000 0x0200 0x0200 R W 0x4000\n";
561        assert!(check_alignment(aligned).is_ok());
562        let bad = aligned.replace("0x4000\n", "0x1000\n");
563        assert!(
564            check_alignment(&bad)
565                .unwrap_err()
566                .to_string()
567                .contains("16 KB")
568        );
569        assert!(check_alignment("no segments here").is_err());
570    }
571
572    #[cfg(unix)]
573    #[test]
574    fn the_symbol_check_ignores_comments_and_reports_missing_entries() {
575        use std::os::unix::fs::PermissionsExt as _;
576
577        let dir = std::env::temp_dir().join(format!("ra-symbols-{}", std::process::id()));
578        let _ = std::fs::remove_dir_all(&dir);
579        std::fs::create_dir_all(dir.join("src")).unwrap();
580        std::fs::write(
581            dir.join("src/lib.rs"),
582            "// fn Java_pkg_Fake_not_real()\n\
583             pub extern \"system\" fn Java_pkg_Fake_call() {}\n",
584        )
585        .unwrap();
586        let nm = dir.join("nm");
587        std::fs::write(&nm, "#!/bin/sh\nexit 0\n").unwrap();
588        std::fs::set_permissions(&nm, std::fs::Permissions::from_mode(0o755)).unwrap();
589        let err = check_symbols(&dir, Abi::Arm64, &nm, Path::new("libfake.so"))
590            .unwrap_err()
591            .to_string();
592        assert!(err.contains("Java_pkg_Fake_call"), "{err}");
593        assert!(!err.contains("not_real"), "{err}");
594        assert!(err.contains("arm64-v8a"), "{err}");
595        std::fs::write(&nm, "#!/bin/sh\necho '0000 T Java_pkg_Fake_call'\n").unwrap();
596        assert_eq!(
597            check_symbols(&dir, Abi::Arm64, &nm, Path::new("libfake.so")).unwrap(),
598            1
599        );
600        std::fs::remove_dir_all(&dir).unwrap();
601    }
602}