From be40bf84743e8410066f31810d505e23a203ae8e Mon Sep 17 00:00:00 2001 From: TimeToBuildBob Date: Wed, 18 Nov 2026 07:46:00 +0000 Subject: [PATCH] fix(android): synchronize JNI logger initialization and declare greeting safety Git-Session-Id: c3c8da94-dbad-484a-96d4-d196650f3287 --- .github/workflows/build.yml | 2 + aw-server/src/android/mod.rs | 31 ++++--- scripts/test-android-init.py | 162 +++++++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 11 deletions(-) create mode 100644 scripts/test-android-init.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b2a9850c5..4d70ca390 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -124,6 +124,8 @@ jobs: run: bash ./scripts/test-compile-android-cwd.sh - name: Set up Rust uses: dtolnay/rust-toolchain@stable + - name: Test concurrent JNI initialization + run: python3 ./scripts/test-android-init.py - name: Cache cargo build uses: actions/cache@v6 env: diff --git a/aw-server/src/android/mod.rs b/aw-server/src/android/mod.rs index 856ef9c0e..0da61111b 100644 --- a/aw-server/src/android/mod.rs +++ b/aw-server/src/android/mod.rs @@ -12,8 +12,13 @@ use crate::dirs; use android_logger::Config; use rocket::serde::json::json; +/// Return a greeting allocated by Rust. Reclaim it with `CString::from_raw`. +/// +/// # Safety +/// `to` must point to a valid, NUL-terminated C string that remains readable +/// for the duration of this call. #[no_mangle] -pub extern "C" fn rust_greeting(to: *const c_char) -> *mut c_char { +pub unsafe extern "C" fn rust_greeting(to: *const c_char) -> *mut c_char { let c_str = unsafe { CStr::from_ptr(to) }; let recipient = match c_str.to_str() { Err(_) => "there", @@ -46,7 +51,7 @@ pub mod android { }; use aw_datastore::Datastore; use aw_models::{Bucket, Event, TimeInterval}; - use std::sync::{Arc, OnceLock}; + use std::sync::{Arc, Once, OnceLock}; // Several app threads make their first JNI call at about the same time (the // watchers' init threads, the server thread, migrations). With a plain @@ -85,11 +90,11 @@ pub mod android { ) -> jstring { jni_guard(env, "greeting", || { // Our Java companion code might pass-in "world" as a string, hence the name. - let world = rust_greeting( - env.get_string(java_pattern) - .expect("invalid pattern string") - .as_ptr(), - ); + let pattern = env + .get_string(java_pattern) + .expect("invalid pattern string"); + // Keep the JNI string guard alive while rust_greeting reads its C string. + let world = unsafe { rust_greeting(pattern.as_ptr()) }; // Retake pointer so that we can use it below and allow memory to be freed when it goes out of scope. let world_ptr = CString::from_raw(world); let output = env @@ -219,7 +224,7 @@ pub mod android { .await; } - static mut INITIALIZED: bool = false; + static INIT: Once = Once::new(); #[no_mangle] pub unsafe extern "C" fn Java_net_activitywatch_android_RustInterface_initialize( @@ -227,7 +232,10 @@ pub mod android { _: JClass, ) { jni_guard_void("initialize", || { - if !INITIALIZED { + let mut initialized_here = false; + // JNI guards catch setup panics; allow a later caller to retry rather + // than permanently poisoning initialization after a caught failure. + INIT.call_once_force(|_| { android_logger::init_once( Config::default() .with_max_level(log::LevelFilter::Info) // limit log level @@ -243,10 +251,11 @@ pub mod android { log_panics::init(); info!("Initializing aw-server-rust..."); debug!("Redirected aw-server-rust stdout/stderr to logcat"); - } else { + initialized_here = true; + }); + if !initialized_here { info!("Already initialized"); } - INITIALIZED = true; // Without this it might not work due to weird error probably arising from Rust optimizing away the JNIEnv: // JNI DETECTED ERROR IN APPLICATION: use of deleted weak global reference diff --git a/scripts/test-android-init.py b/scripts/test-android-init.py new file mode 100644 index 000000000..29f49a3c8 --- /dev/null +++ b/scripts/test-android-init.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Exercise the production JNI initialization body on a host without Android/JVM. + +Only the JNI/logging dependencies are stubbed. Extract the real entry point so a +regression to an unsynchronized flag fails even though host cargo tests exclude +this module. The Android build separately type-checks the real dependencies. +""" + +from pathlib import Path +import subprocess +import tempfile + + +SOURCE = Path(__file__).resolve().parents[1] / "aw-server/src/android/mod.rs" + +# Match the dependencies of the initialization entry point, not its synchronization. +STUBS = r""" +use std::sync::{Arc, Barrier, Once}; +use std::sync::atomic::{AtomicUsize, Ordering}; +static LOGGER_CALLS: AtomicUsize = AtomicUsize::new(0); +static HOOK_CALLS: AtomicUsize = AtomicUsize::new(0); +static JNI_CALLS: AtomicUsize = AtomicUsize::new(0); +static ALREADY_INITIALIZED: AtomicUsize = AtomicUsize::new(0); +static FAIL_ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +macro_rules! info { + ("Already initialized") => { ALREADY_INITIALIZED.fetch_add(1, Ordering::SeqCst); }; + ($($args:tt)*) => {}; +} +macro_rules! debug { ($($args:tt)*) => {}; } +struct JNIEnv; +struct JClass; +struct Config; +impl Config { + fn default() -> Self { Self } + fn with_max_level(self, _: log::LevelFilter) -> Self { self } + fn with_tag(self, _: &str) -> Self { self } +} +mod log { pub enum LevelFilter { Info } } +mod android_logger { + pub fn init_once(_: super::Config) { + super::LOGGER_CALLS.fetch_add(1, super::Ordering::SeqCst); + // Widen the old check-then-set window. Every other caller must wait + // for the panic hook installation rather than return during this delay. + std::thread::sleep(std::time::Duration::from_millis(100)); + } +} +mod log_panics { + pub fn init() { + if super::FAIL_ONCE.swap(false, super::Ordering::SeqCst) { + panic!("injected initialization failure"); + } + super::HOOK_CALLS.fetch_add(1, super::Ordering::SeqCst); + } +} +fn jni_guard_void(_: &str, f: impl FnOnce()) { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); +} +fn string_to_jstring(_: &JNIEnv, _: String) { + assert_eq!(HOOK_CALLS.load(Ordering::SeqCst), 1); + JNI_CALLS.fetch_add(1, Ordering::SeqCst); +} +""" + +TEST = r""" +fn main() { + if std::env::args().any(|arg| arg == "retry") { + FAIL_ONCE.store(true, Ordering::SeqCst); + unsafe { Java_net_activitywatch_android_RustInterface_initialize(JNIEnv, JClass); } + assert_eq!(JNI_CALLS.load(Ordering::SeqCst), 0); + unsafe { Java_net_activitywatch_android_RustInterface_initialize(JNIEnv, JClass); } + assert_eq!(LOGGER_CALLS.load(Ordering::SeqCst), 2); + assert_eq!(HOOK_CALLS.load(Ordering::SeqCst), 1); + assert_eq!(JNI_CALLS.load(Ordering::SeqCst), 1); + unsafe { Java_net_activitywatch_android_RustInterface_initialize(JNIEnv, JClass); } + assert_eq!(LOGGER_CALLS.load(Ordering::SeqCst), 2); + assert_eq!(JNI_CALLS.load(Ordering::SeqCst), 2); + assert_eq!(ALREADY_INITIALIZED.load(Ordering::SeqCst), 1); + println!("JNI initialization: retry after caught panic passed"); + return; + } + let start = Arc::new(Barrier::new(16)); + let threads: Vec<_> = (0..16).map(|_| { + let start = start.clone(); + std::thread::spawn(move || { + start.wait(); + unsafe { Java_net_activitywatch_android_RustInterface_initialize(JNIEnv, JClass); } + }) + }).collect(); + for t in threads { t.join().unwrap(); } + assert_eq!(LOGGER_CALLS.load(Ordering::SeqCst), 1); + assert_eq!(HOOK_CALLS.load(Ordering::SeqCst), 1); + assert_eq!(JNI_CALLS.load(Ordering::SeqCst), 16); + assert_eq!(ALREADY_INITIALIZED.load(Ordering::SeqCst), 15); + // Repeated initialization still runs the JNI workaround, not the setup. + unsafe { Java_net_activitywatch_android_RustInterface_initialize(JNIEnv, JClass); } + assert_eq!(LOGGER_CALLS.load(Ordering::SeqCst), 1); + assert_eq!(HOOK_CALLS.load(Ordering::SeqCst), 1); + assert_eq!(JNI_CALLS.load(Ordering::SeqCst), 17); + assert_eq!(ALREADY_INITIALIZED.load(Ordering::SeqCst), 16); + println!("JNI initialization: concurrent and repeated callers passed"); +} +""" + + +def main(): + source = SOURCE.read_text() + # Include the state declaration as well as the entry point, so the test + # exercises its actual lifetime (one static for the process). + before, after = source.split( + ' pub unsafe extern "C" fn Java_net_activitywatch_android_RustInterface_initialize(', + 1, + ) + declaration = before.rsplit("\n\n", 2)[-2] + body = after.split("\n #[no_mangle]", 1)[0] + entry = ( + " unsafe fn Java_net_activitywatch_android_RustInterface_initialize(" + body + ) + with tempfile.TemporaryDirectory(prefix="aw-android-init-") as tmp: + harness = Path(tmp) / "init.rs" + binary = Path(tmp) / "init" + harness.write_text(STUBS + declaration + "\n" + entry + TEST) + subprocess.run( + ["rustc", "--edition=2021", "-Awarnings", str(harness), "-o", str(binary)], + check=True, + ) + subprocess.run([str(binary)], check=True, timeout=30) + subprocess.run([str(binary), "retry"], check=True, timeout=30) + + # The C ABI remains callable with a live C string, including non-UTF-8 + # input. Exercise allocation ownership without needing a Java VM. + greeting = source.split("#[no_mangle]", 1)[1].split( + '#[cfg(target_os = "android")]', 1 + )[0] + with tempfile.TemporaryDirectory(prefix="aw-android-greeting-") as tmp: + harness = Path(tmp) / "greeting.rs" + binary = Path(tmp) / "greeting" + harness.write_text( + "use std::ffi::{CStr, CString};\nuse std::os::raw::c_char;\n" + + greeting + + r""" +fn main() { + for (input, expected) in [ + (b"world".as_slice(), "Hello world (from Rust!)"), + (b"".as_slice(), "Hello (from Rust!)"), + (b"\xff".as_slice(), "Hello there (from Rust!)"), + ] { + let input = CString::new(input).unwrap(); + let result = unsafe { CString::from_raw(rust_greeting(input.as_ptr())) }; + assert_eq!(result.to_str().unwrap(), expected); + } + println!("JNI greeting: valid, empty and non-UTF-8 inputs passed"); +} +""" + ) + subprocess.run( + ["rustc", "--edition=2021", str(harness), "-o", str(binary)], check=True + ) + subprocess.run([str(binary)], check=True, timeout=30) + + +if __name__ == "__main__": + main()