Skip to main content

rust_anything/
android_device.rs

1//! On-device recording and diffing over adb.
2//!
3//! The cases are generated on the host (same generator as `record`), but the original Kotlin
4//! runs under ART and the result comes back as the same `cases.jsonl`. Both sides use the
5//! generated `RustAnythingDriver`: it is compiled to Java classes, dexed with d8 together with
6//! the original Kotlin jar (record) or the generated JNI wrappers (diff), and started with
7//! `app_process`. This covers logic units; Android UI, lifecycle and SDK-only classes stay
8//! outside the profile.
9
10use std::path::{Path, PathBuf};
11use std::process::Command;
12use std::time::Duration;
13
14use anyhow::{Context, Result, bail};
15use serde_json::Value;
16
17use crate::bridge::Manifest;
18use crate::harness::DiffOutcome;
19use crate::lang::Lang;
20
21/// A connected device and its scratch directory. The directory is removed on drop, including
22/// when a step fails, so a recording does not leave jars and libraries behind on the device.
23struct Device {
24    serial: String,
25    dir: String,
26}
27
28impl Drop for Device {
29    fn drop(&mut self) {
30        let _ = adb(
31            Some(&self.serial),
32            &["shell", "rm", "-rf", &self.dir],
33            "device cleanup",
34            Duration::from_secs(10),
35        );
36    }
37}
38
39impl Device {
40    fn connect(explicit: Option<&str>) -> Result<Self> {
41        let serial = select(explicit)?;
42        let dir = format!("/data/local/tmp/rust-anything-{}", std::process::id());
43        adb(
44            Some(&serial),
45            &["shell", "mkdir", "-p", &dir],
46            "device scratch directory",
47            Duration::from_secs(10),
48        )?;
49        Ok(Self { serial, dir })
50    }
51
52    fn push(&self, local: &Path, name: &str) -> Result<String> {
53        let remote = format!("{}/{}", self.dir, name);
54        adb(
55            Some(&self.serial),
56            &["push", &local.to_string_lossy(), &remote],
57            &format!("push {name}"),
58            Duration::from_secs(60),
59        )?;
60        Ok(remote)
61    }
62
63    fn pull(&self, remote: &str, local: &Path) -> Result<()> {
64        adb(
65            Some(&self.serial),
66            &["pull", remote, &local.to_string_lossy()],
67            &format!("pull {remote}"),
68            Duration::from_secs(60),
69        )?;
70        Ok(())
71    }
72
73    fn abi(&self) -> Result<String> {
74        let out = adb(
75            Some(&self.serial),
76            &["shell", "getprop", "ro.product.cpu.abi"],
77            "device ABI",
78            Duration::from_secs(10),
79        )?;
80        let abi = out.trim();
81        if abi.is_empty() {
82            bail!("the device did not report ro.product.cpu.abi");
83        }
84        Ok(abi.to_string())
85    }
86
87    /// Runs the dexed driver under ART. `RA_EXIT` lets us tell a driver failure (stack trace on
88    /// the device) apart from an adb transport failure.
89    fn driver(
90        &self,
91        jar: &str,
92        properties: &[(&str, &str)],
93        mode: &str,
94        args: &[&str],
95    ) -> Result<()> {
96        // The env assignment must come first: `CLASSPATH=x app_process -D... /system/bin ...`.
97        let mut parts = vec![format!("CLASSPATH={jar}"), "app_process".to_string()];
98        parts.push("-Dfile.encoding=UTF-8".to_string());
99        parts.extend(
100            properties
101                .iter()
102                .map(|(key, value)| format!("-D{key}={value}")),
103        );
104        parts.extend(
105            ["/system/bin", "rustanything.RustAnythingDriver", mode]
106                .iter()
107                .map(|s| s.to_string()),
108        );
109        parts.extend(args.iter().map(|s| s.to_string()));
110        let script = format!("{} 2>&1; echo RA_EXIT=$?", parts.join(" "));
111        let out = adb(
112            Some(&self.serial),
113            &["shell", &script],
114            &format!("driver ({mode})"),
115            crate::process::BUILD,
116        )?;
117        let code = out
118            .lines()
119            .rev()
120            .find_map(|l| l.trim().strip_prefix("RA_EXIT="))
121            .unwrap_or("missing");
122        if code != "0" {
123            bail!("the Android driver failed (exit {code}):\n{}", out.trim());
124        }
125        Ok(())
126    }
127}
128
129fn adb(serial: Option<&str>, args: &[&str], what: &str, timeout: Duration) -> Result<String> {
130    let mut cmd = Command::new("adb");
131    if let Some(serial) = serial {
132        cmd.args(["-s", serial]);
133    }
134    cmd.args(args);
135    let out = crate::process::output(&mut cmd, timeout)
136        .with_context(|| format!("running adb ({what}); is adb on PATH?"))?;
137    if !out.success() {
138        let text = if out.stderr_text().trim().is_empty() {
139            out.stdout_text()
140        } else {
141            out.stderr_text()
142        };
143        bail!("adb {what} failed: {}", text.trim());
144    }
145    Ok(out.stdout_text())
146}
147
148fn select(explicit: Option<&str>) -> Result<String> {
149    if let Some(serial) = explicit {
150        return Ok(serial.to_string());
151    }
152    if let Ok(serial) = std::env::var("ANDROID_SERIAL")
153        && !serial.trim().is_empty()
154    {
155        return Ok(serial);
156    }
157    let list = adb(None, &["devices"], "device list", Duration::from_secs(10))?;
158    let devices: Vec<&str> = list
159        .lines()
160        .filter_map(|l| l.strip_suffix("\tdevice"))
161        .map(str::trim)
162        .filter(|s| !s.is_empty())
163        .collect();
164    match devices.as_slice() {
165        [one] => Ok((*one).to_string()),
166        [] => bail!("no connected Android device; connect one or pass --device <serial>"),
167        many => bail!(
168            "{} Android devices connected ({}); pass --device <serial>",
169            many.len(),
170            many.join(", ")
171        ),
172    }
173}
174
175/// d8 from the newest installed build-tools and the newest platform's `android.jar`.
176fn sdk_tools() -> Result<(PathBuf, PathBuf)> {
177    let mut candidates: Vec<PathBuf> = ["ANDROID_HOME", "ANDROID_SDK_ROOT"]
178        .iter()
179        .filter_map(std::env::var_os)
180        .map(PathBuf::from)
181        .collect();
182    candidates.extend(crate::android::sdk_folders());
183    // ANDROID_HOME often points at an old or deleted SDK: pick the first real one.
184    let sdk = candidates
185        .into_iter()
186        .find(|p| p.join("build-tools").is_dir() && p.join("platforms").is_dir())
187        .context("Android SDK not found; set ANDROID_HOME")?;
188    let newest = |dir: PathBuf, file: &str| -> Option<PathBuf> {
189        let mut versions: Vec<(Vec<u32>, PathBuf)> = std::fs::read_dir(dir)
190            .ok()?
191            .flatten()
192            .map(|e| e.path())
193            .filter(|p| p.join(file).is_file())
194            .map(|p| {
195                let key = p
196                    .file_name()
197                    .map(|n| n.to_string_lossy().into_owned())
198                    .unwrap_or_default()
199                    .split(|c: char| !c.is_ascii_digit())
200                    .filter_map(|part| part.parse().ok())
201                    .collect();
202                (key, p)
203            })
204            .collect();
205        versions.sort_by(|a, b| a.0.cmp(&b.0));
206        versions.pop().map(|(_, p)| p)
207    };
208    let d8 = newest(sdk.join("build-tools"), "d8")
209        .context("no d8 in the SDK's build-tools; install build-tools with sdkmanager")?
210        .join("d8");
211    let jar = newest(sdk.join("platforms"), "android.jar")
212        .context("no android.jar in the SDK's platforms; install a platform with sdkmanager")?
213        .join("android.jar");
214    Ok((d8, jar))
215}
216
217/// Compiles Java classes (and optionally the original Kotlin fat jar) into one dexed jar ART can
218/// put on its classpath.
219fn package(classes: &[PathBuf], work: &Path) -> Result<PathBuf> {
220    let (d8, android_jar) = sdk_tools()?;
221    let dex = work.join("dex");
222    if dex.exists() {
223        std::fs::remove_dir_all(&dex)?;
224    }
225    std::fs::create_dir_all(&dex)?;
226    let mut cmd = Command::new(&d8);
227    cmd.arg("--min-api")
228        .arg(crate::android::DEFAULT_API.to_string())
229        .arg("--lib")
230        .arg(&android_jar)
231        .arg("--output")
232        .arg(&dex)
233        .args(classes);
234    tool(&mut cmd, "d8 (dex driver)")?;
235    let jar = work.join("driver.jar");
236    let mut cmd = Command::new("jar");
237    cmd.arg("cf")
238        .arg(&jar)
239        .arg("-C")
240        .arg(&dex)
241        .arg("classes.dex");
242    tool(&mut cmd, "jar (package driver)")?;
243    Ok(jar)
244}
245
246fn tool(cmd: &mut Command, what: &str) -> Result<()> {
247    let out = crate::process::output(cmd, crate::process::BUILD)
248        .with_context(|| format!("running {what}"))?;
249    if !out.success() {
250        bail!(
251            "{what} failed: {}",
252            if out.stderr_text().trim().is_empty() {
253                out.stdout_text()
254            } else {
255                out.stderr_text()
256            }
257            .trim()
258        );
259    }
260    Ok(())
261}
262
263fn work_dir(crate_dir: &Path, mode: &str) -> Result<PathBuf> {
264    let dir = crate_dir
265        .join(crate::harness::WORK_DIR)
266        .join("android-device")
267        .join(mode);
268    if dir.exists() {
269        std::fs::remove_dir_all(&dir)?;
270    }
271    std::fs::create_dir_all(&dir)?;
272    Ok(dir)
273}
274
275fn check_language(m: &Manifest) -> Result<()> {
276    if !matches!(m.language, Lang::Java | Lang::Kotlin) {
277        bail!(
278            "on-device recording needs a JVM crate (Java or Kotlin), not {}",
279            m.language.name()
280        );
281    }
282    Ok(())
283}
284
285fn targets(m: &Manifest, work: &Path) -> Result<PathBuf> {
286    let path = work.join("targets.json");
287    std::fs::write(&path, crate::codegen_kotlin::targets(m).to_string())?;
288    Ok(path)
289}
290
291/// Records the original JVM unit on the device; returns the host's `cases.jsonl`.
292pub fn record(
293    crate_dir: &Path,
294    m: &Manifest,
295    cases: &[Value],
296    device: Option<&str>,
297) -> Result<PathBuf> {
298    check_language(m)?;
299    let device = Device::connect(device)?;
300    let work = work_dir(crate_dir, "record")?;
301    let classes = if m.language == Lang::Java {
302        crate::harness_java::android_classes(crate_dir, m, false)?
303    } else {
304        crate::harness_kotlin::android_classes(crate_dir, m, false)?
305    };
306    let jar = package(&classes, &work)?;
307    let targets = targets(m, &work)?;
308    let inputs = work.join("cases.json");
309    // The driver's record mode takes one JSON array, as it does on the host.
310    std::fs::write(&inputs, serde_json::to_string(cases)?)?;
311    let remote_jar = device.push(&jar, "driver.jar")?;
312    let remote_targets = device.push(&targets, "targets.json")?;
313    let remote_inputs = device.push(&inputs, "cases.json")?;
314    let remote_out = format!("{}/out.jsonl", device.dir);
315    device.driver(
316        &remote_jar,
317        &[],
318        "record",
319        &[&remote_targets, &remote_inputs, &remote_out, "0"],
320    )?;
321    let local = work.join("out.jsonl");
322    device.pull(&remote_out, &local)?;
323    let out = crate_dir.join(crate::harness::CASES);
324    crate::harness::install(&local, &out)?;
325    Ok(out)
326}
327
328/// Diffs the Android `.so` built for the connected device's ABI against the recording.
329pub fn diff(
330    crate_dir: &Path,
331    m: &Manifest,
332    device: Option<&str>,
333    jni_libs: Option<&Path>,
334) -> Result<DiffOutcome> {
335    check_language(m)?;
336    let cases = crate_dir.join(crate::harness::CASES);
337    if !cases.is_file() {
338        bail!(
339            "no {} in {} (run `rust-anything record --profile android` first)",
340            crate::harness::CASES,
341            crate_dir.display()
342        );
343    }
344    let device = Device::connect(device)?;
345    let abi = device.abi()?;
346    let base = jni_libs
347        .map(Path::to_path_buf)
348        .unwrap_or_else(|| crate_dir.join("jniLibs"));
349    let lib = base.join(&abi).join(format!("lib{}.so", m.lib_name()));
350    if !lib.is_file() {
351        bail!(
352            "no {} for the device ABI {abi}; run `rust-anything build {crate} --profile android --abi {abi}` first",
353            lib.display(),
354            crate = crate_dir.display()
355        );
356    }
357    if crate::harness::sources_newer_than(crate_dir, &lib) {
358        bail!(
359            "{} is older than the crate's sources, so diff would test the previous port; run \
360             `rust-anything build {crate} --profile android --abi {abi}` first",
361            lib.display(),
362            crate = crate_dir.display()
363        );
364    }
365    let work = work_dir(crate_dir, "diff")?;
366    let classes = if m.language == Lang::Java {
367        crate::harness_java::android_classes(crate_dir, m, true)?
368    } else {
369        crate::harness_kotlin::android_classes(crate_dir, m, true)?
370    };
371    let jar = package(&classes, &work)?;
372    let targets = targets(m, &work)?;
373    let remote_jar = device.push(&jar, "driver.jar")?;
374    let remote_targets = device.push(&targets, "targets.json")?;
375    let remote_cases = device.push(&cases, "cases.jsonl")?;
376    let remote_lib = device.push(&lib, "port.so")?;
377    let remote_out = format!("{}/diff.json", device.dir);
378    device.driver(
379        &remote_jar,
380        &[(
381            &format!("rust-anything.lib.{}", m.lib_name()),
382            remote_lib.as_str(),
383        )],
384        "diff",
385        &[&remote_targets, &remote_cases, &remote_out, "0"],
386    )?;
387    let local = work.join("diff.json");
388    device.pull(&remote_out, &local)?;
389    Ok(serde_json::from_str(&std::fs::read_to_string(&local)?)?)
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    #[test]
397    fn chooses_an_explicit_serial_without_adb() {
398        assert_eq!(select(Some("emulator-5554")).unwrap(), "emulator-5554");
399    }
400}