Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
31 changes: 20 additions & 11 deletions aw-server/src/android/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -219,15 +224,18 @@ 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(
env: JNIEnv,
_: 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
Expand All @@ -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
Expand Down
162 changes: 162 additions & 0 deletions scripts/test-android-init.py
Original file line number Diff line number Diff line change
@@ -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()
Loading