Skip to main content

day_platform_android/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Shared Android JVM attachment, class loading, and checked Java bindings.
5//! Hosts initialize this runtime before calling services. Widget rendering belongs to day-toolkit-material.
6
7extern crate self as day_platform_android;
8
9#[cfg(target_os = "android")]
10pub use day_macros::java_class;
11#[cfg(target_os = "android")]
12pub use imp::*;
13
14/// `DayRuntime.initializeServices()`: Android's headless host (a worker, a messaging service) has
15/// a JVM and an application `Context` but no Activity and no widget tree. It attaches the JVM
16/// here and starts the linked process services, exactly as the Activity's launch path does first.
17#[cfg(target_os = "android")]
18#[unsafe(no_mangle)]
19pub extern "system" fn Java_dev_daybrite_day_bridge_DayRuntime_initializeServices(
20    mut env: jni::EnvUnowned,
21    class: jni::objects::JClass,
22) {
23    env.with_env(|env| -> jni::errors::Result<()> {
24        init(env, &class)?;
25        day_process::services::initialize();
26        Ok(())
27    })
28    .resolve::<jni::errors::ThrowRuntimeExAndDefault>();
29}
30
31/// The part↔Java payload convention (docs/extending.md, "The Android bridging contract"):
32/// One `byte[]` crosses JNI per call, laid out as
33/// `[0..4)` status `i32` BE · `[4..8)` meta-block length `i32` BE · meta `"k\nv\n…"` UTF-8 ·
34/// payload bytes. A negative status is a transport-error sentinel and the meta block carries
35/// the error message instead of pairs (each part defines its own sentinel values; day-part-http
36/// uses −1 timeout … −6 bad-url). Pure bytes, no JNI, so this compiles and tests on every
37/// host; `DayEnvelope.java` is the Java twin and the two encode identically.
38pub mod envelope {
39    /// A decoded (or to-be-encoded) bridge envelope.
40    #[derive(Clone, Debug, PartialEq)]
41    pub struct Envelope {
42        /// Non-negative: the call's status (HTTP status, a handle, …). Negative: an error
43        /// sentinel; `meta` is empty and [`Envelope::error_message`] holds the text.
44        pub status: i32,
45        /// Key/value pairs (response headers, attributes); empty for error envelopes.
46        pub meta: Vec<(String, String)>,
47        /// The body / result bytes (for errors, the raw message bytes).
48        pub payload: Vec<u8>,
49    }
50
51    impl Envelope {
52        /// Serialize to the wire layout `DayEnvelope.java` produces.
53        #[must_use]
54        pub fn encode(&self) -> Vec<u8> {
55            let mut meta = String::new();
56            for (k, v) in &self.meta {
57                meta.push_str(k);
58                meta.push('\n');
59                meta.push_str(v);
60                meta.push('\n');
61            }
62            let meta = meta.into_bytes();
63            let mut out = Vec::with_capacity(8 + meta.len() + self.payload.len());
64            out.extend_from_slice(&self.status.to_be_bytes());
65            out.extend_from_slice(&(meta.len() as i32).to_be_bytes());
66            out.extend_from_slice(&meta);
67            out.extend_from_slice(&self.payload);
68            out
69        }
70
71        /// Parse the wire layout. `Err` is a malformed envelope (truncated), not a sentinel:
72        /// sentinel statuses parse fine and are the caller's to interpret.
73        ///
74        /// # Errors
75        ///
76        /// Returns an error when `bytes` is shorter than the 8-byte header or than the
77        /// meta length the header declares.
78        pub fn decode(bytes: &[u8]) -> Result<Envelope, &'static str> {
79            if bytes.len() < 8 {
80                return Err("short envelope");
81            }
82            let status = i32::from_be_bytes(bytes[0..4].try_into().map_err(|_| "short")?);
83            let meta_len =
84                i32::from_be_bytes(bytes[4..8].try_into().map_err(|_| "short")?).max(0) as usize;
85            let rest = &bytes[8..];
86            if rest.len() < meta_len {
87                return Err("truncated envelope");
88            }
89            let (meta_bytes, payload) = rest.split_at(meta_len);
90            let mut meta = Vec::new();
91            if status >= 0 {
92                let mut lines = std::str::from_utf8(meta_bytes).unwrap_or("").split('\n');
93                while let (Some(k), Some(v)) = (lines.next(), lines.next()) {
94                    if !k.is_empty() {
95                        meta.push((k.to_string(), v.to_string()));
96                    }
97                }
98            }
99            Ok(Envelope {
100                status,
101                meta,
102                payload: if status < 0 {
103                    meta_bytes.to_vec() // the error message rides the meta block
104                } else {
105                    payload.to_vec()
106                },
107            })
108        }
109
110        /// For a sentinel (negative-status) envelope: the error message text.
111        #[must_use]
112        pub fn error_message(&self) -> String {
113            String::from_utf8_lossy(&self.payload).into_owned()
114        }
115    }
116
117    #[cfg(test)]
118    mod tests {
119        use super::Envelope;
120
121        #[test]
122        fn round_trip_with_meta_and_payload() {
123            let e = Envelope {
124                status: 200,
125                meta: vec![
126                    ("Content-Type".into(), "text/plain".into()),
127                    ("X-Two".into(), "b".into()),
128                ],
129                payload: b"hello".to_vec(),
130            };
131            assert_eq!(Envelope::decode(&e.encode()).unwrap(), e);
132        }
133
134        #[test]
135        fn sentinel_carries_the_message() {
136            let raw = Envelope {
137                status: -3,
138                meta: vec![("boom: handshake".into(), String::new())],
139                payload: Vec::new(),
140            };
141            // Encode as Java's error() does: message in the meta block, no payload.
142            let mut bytes = (-3i32).to_be_bytes().to_vec();
143            let msg = b"boom: handshake";
144            bytes.extend_from_slice(&(msg.len() as i32).to_be_bytes());
145            bytes.extend_from_slice(msg);
146            let d = Envelope::decode(&bytes).unwrap();
147            assert_eq!(d.status, -3);
148            assert_eq!(d.error_message(), "boom: handshake");
149            let _ = raw;
150        }
151
152        #[test]
153        fn truncation_is_malformed_not_sentinel() {
154            assert!(Envelope::decode(&[0, 0]).is_err());
155            let mut bytes = 200i32.to_be_bytes().to_vec();
156            bytes.extend_from_slice(&99i32.to_be_bytes()); // claims 99 meta bytes, has none
157            assert!(Envelope::decode(&bytes).is_err());
158        }
159    }
160}
161
162#[cfg(target_os = "android")]
163mod imp {
164    pub use jni;
165
166    crate::java_class! {
167        pub DayRuntime => dev.daybrite.day.bridge.DayRuntime,
168        methods {
169            static fn filesDirPath() -> JString,
170            static fn cacheDirPath() -> JString,
171        },
172        fields {
173            static ctx: android.content.Context,
174        },
175    }
176
177    use jni::objects::{Global, JClass, JObject, JString};
178    use jni::{Env, JavaVM};
179    use linkme::distributed_slice;
180    use std::os::raw::{c_char, c_int, c_void};
181    use std::sync::OnceLock;
182
183    /// Cache the JVM and the host's class loader, then validate linked Java bindings.
184    /// Call on a Java-owned thread before using services, after setting `DayRuntime.ctx`.
185    /// Repeated calls retain the process-wide JVM and class loader.
186    ///
187    /// # Errors
188    ///
189    /// Returns the JNI error when the JVM or `host_class`'s class loader cannot be obtained.
190    pub fn init(env: &mut Env, host_class: &JClass) -> jni::errors::Result<()> {
191        let vm = env.get_java_vm()?;
192        let loader = host_class.get_class_loader(env)?;
193        let loader = env.new_global_ref(loader)?;
194        let _ = JAVA_VM.set(vm);
195        let _ = APP_CLASS_LOADER.set(loader);
196        check_java_classes(env);
197        Ok(())
198    }
199
200    // liblog is always present in the Android NDK sysroot.
201    #[link(name = "log")]
202    unsafe extern "C" {
203        fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int;
204    }
205    unsafe extern "C" {
206        fn pipe(fds: *mut c_int) -> c_int;
207        fn dup2(oldfd: c_int, newfd: c_int) -> c_int;
208        fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
209    }
210
211    const ANDROID_LOG_INFO: c_int = 4;
212    const ANDROID_LOG_ERROR: c_int = 6;
213
214    /// Route the process's stdout (fd 1) and stderr (fd 2) into logcat under the tag
215    /// `Day`; Android sends both to /dev/null otherwise, so `println!`/`eprintln!`
216    /// (and Rust panics) would be invisible. stdout logs at `INFO`, stderr at `ERROR`, so
217    /// the `Day` CLI can color them apart. Idempotent; safe to call once at startup.
218    pub fn redirect_stdio_to_logcat() {
219        static DONE: OnceLock<()> = OnceLock::new();
220        if DONE.set(()).is_err() {
221            return;
222        }
223        for (target_fd, prio) in [(1, ANDROID_LOG_INFO), (2, ANDROID_LOG_ERROR)] {
224            let mut fds = [0 as c_int; 2];
225            // SAFETY: standard self-pipe + dup2 redirect; fds live for the process.
226            unsafe {
227                if pipe(fds.as_mut_ptr()) != 0 || dup2(fds[1], target_fd) < 0 {
228                    continue;
229                }
230            }
231            let read_fd = fds[0];
232            std::thread::spawn(move || {
233                let tag = c"Day";
234                let mut buf = [0u8; 2048];
235                let mut line: Vec<u8> = Vec::new();
236                loop {
237                    let n = unsafe { read(read_fd, buf.as_mut_ptr().cast::<c_void>(), buf.len()) };
238                    if n <= 0 {
239                        break;
240                    }
241                    for &b in &buf[..n as usize] {
242                        if b == b'\n' {
243                            line.push(0);
244                            unsafe {
245                                __android_log_write(
246                                    prio,
247                                    tag.as_ptr(),
248                                    line.as_ptr().cast::<c_char>(),
249                                );
250                            }
251                            line.clear();
252                        } else {
253                            line.push(b);
254                        }
255                    }
256                }
257            });
258        }
259    }
260
261    static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
262    /// `GlobalRef` to the app's `ClassLoader` (supplied by the host at init), so a
263    /// `java_class!` binding resolves app classes from Rust-spawned threads too: their
264    /// `FindClass` sees only the system loader, and parts like day-part-http call Java from the
265    /// caller's worker thread.
266    static APP_CLASS_LOADER: OnceLock<Global<jni::objects::JClassLoader<'static>>> =
267        OnceLock::new();
268
269    /// Run `f` with this thread attached to the JVM.
270    ///
271    /// A Java exception still pending when `f` returns is described to logcat and cleared: a
272    /// binding call whose error was dropped must not leave one behind, where it would fail every
273    /// JNI call after it and, back in Java, be thrown from whatever called into Rust. Calls that
274    /// care about the failure go through [`java`], which clears at the call.
275    ///
276    /// # Panics
277    ///
278    /// Panics when [`init`] has not run, or when the thread cannot be attached to the JVM.
279    pub fn with_env<R>(f: impl FnOnce(&mut Env) -> R) -> R {
280        let vm = JAVA_VM
281            .get()
282            .expect("day-platform-android: init() not called");
283        vm.attach_current_thread(|env| {
284            let out = f(env);
285            if env.exception_check() {
286                env.exception_describe();
287                env.exception_clear();
288            }
289            Ok::<R, jni::errors::Error>(out)
290        })
291        .expect("attach_current_thread")
292    }
293
294    /// Run `f` with an attached `Env`, where `?` works on every JNI call inside.
295    ///
296    /// The scope for calls through a [`java_class!`](crate::java_class) binding. Those return
297    /// `jni::errors::Result` and leave a thrown Java exception pending, and almost any JNI call
298    /// made with one pending is undefined behavior. An `Err` here is logged, the exception is
299    /// described to logcat and cleared, and the caller gets `None`, so a failed call can be
300    /// ignored or substituted without the call site remembering the clear.
301    pub fn java<R>(f: impl FnOnce(&mut Env) -> jni::errors::Result<R>) -> Option<R> {
302        with_env(|env| java_in(env, f))
303    }
304
305    /// [`java`] for code that already holds an `Env`: a `with_native` tweak, a native method's
306    /// body, a binding's `realize`.
307    pub fn java_in<R>(
308        env: &mut Env,
309        f: impl FnOnce(&mut Env) -> jni::errors::Result<R>,
310    ) -> Option<R> {
311        match f(env) {
312            Ok(v) => Some(v),
313            Err(e) => {
314                log::warn!("day-platform-android: Java call failed: {e}");
315                if env.exception_check() {
316                    env.exception_describe();
317                    env.exception_clear();
318                }
319                None
320            }
321        }
322    }
323
324    /// `obj` as the bound class `T`, for calling `T`'s instance methods on a View Day holds (a
325    /// tweak's `with_native` handle, say). The cast is checked (`IsInstanceOf`), and the result
326    /// is a local reference of this call's frame, so it never outlives `env`.
327    ///
328    /// # Errors
329    ///
330    /// Returns the JNI error when `obj` is not an instance of `T`, or when the local
331    /// reference cannot be made.
332    pub fn downcast<'l, T: jni::refs::Reference>(
333        env: &mut Env<'l>,
334        obj: &JObject,
335    ) -> jni::errors::Result<T::Kind<'l>> {
336        let local = env.new_local_ref(obj)?;
337        env.cast_local::<T>(local)
338    }
339
340    pub use linkme;
341
342    /// One Java class bound by [`java_class!`](crate::java_class): its name, and the lookup that
343    /// resolves the class, every bound method and field, and registers its native methods.
344    pub struct JavaClassCheck {
345        pub name: &'static str,
346        /// The API level the binding needs (`since = 26`); 0 for every level. Below it the check
347        /// skips the binding, and its callers ask [`sdk_int`] before calling.
348        pub since: i32,
349        pub resolve: fn(&mut Env) -> jni::errors::Result<()>,
350    }
351
352    /// The device's API level (`Build.VERSION.SDK_INT`), read once from the system property
353    /// behind it, so it needs no JNI and works before `init`. 0 if the property cannot be read.
354    pub fn sdk_int() -> i32 {
355        static SDK: OnceLock<i32> = OnceLock::new();
356        *SDK.get_or_init(|| {
357            unsafe extern "C" {
358                fn __system_property_get(name: *const c_char, value: *mut c_char) -> c_int;
359            }
360            // PROP_VALUE_MAX, from <sys/system_properties.h>.
361            let mut value = [0u8; 92];
362            // SAFETY: the name is a NUL-terminated literal and `value` is PROP_VALUE_MAX bytes,
363            // the most the call writes, terminator included.
364            let len = unsafe {
365                __system_property_get(
366                    c"ro.build.version.sdk".as_ptr(),
367                    value.as_mut_ptr().cast::<c_char>(),
368                )
369            };
370            let len = usize::try_from(len).unwrap_or(0).min(value.len());
371            std::str::from_utf8(&value[..len])
372                .ok()
373                .and_then(|s| s.trim().parse().ok())
374                .unwrap_or(0)
375        })
376    }
377
378    /// Every [`java_class!`](crate::java_class) binding linked into the app.
379    #[distributed_slice]
380    pub static JAVA_CLASSES: [JavaClassCheck];
381
382    /// Resolve every binding once, at start, so a Java class that is missing from the build or a
383    /// method whose signature no longer matches is reported by name when the app launches, rather
384    /// than on the page that first calls it.
385    ///
386    /// In a debug build, and in any scripted run (`DAYSCRIPT_PORT` set), a failure ends the
387    /// process after naming every mismatch: a binding that fails takes its whole class with it,
388    /// and a walkthrough drives pieces through Day rather than the native widget, so a piece
389    /// rendering as a placeholder would otherwise pass. A release build outside a script carries
390    /// on, and the calls through that binding fail softly through [`java`].
391    fn check_java_classes(env: &mut Env) {
392        let started = std::time::Instant::now();
393        let mut failed = 0;
394        let sdk = sdk_int();
395        for class in JAVA_CLASSES {
396            if sdk < class.since {
397                continue;
398            }
399            if let Err(e) = (class.resolve)(env) {
400                failed += 1;
401                if env.exception_check() {
402                    env.exception_describe();
403                    env.exception_clear();
404                }
405                // stderr, not `log::`: this runs from `init`, before `crate::start` installs the
406                // logger, and stdio already reaches logcat.
407                eprintln!(
408                    "day-platform-android: Java binding {} does not match the app's classes: {e}",
409                    class.name.replace(' ', "")
410                );
411            }
412        }
413        eprintln!(
414            "day-platform-android: resolved {} Java binding(s) in {:.2} ms ({failed} failed)",
415            JAVA_CLASSES.len(),
416            started.elapsed().as_secs_f64() * 1000.0
417        );
418        let strict = cfg!(debug_assertions) || std::env::var_os("DAYSCRIPT_PORT").is_some();
419        if failed > 0 && strict {
420            eprintln!(
421                "day-platform-android: stopping: {failed} Java binding(s) do not match the classes in this \
422                 build (above). Rebuild after changing Java, or fix the binding's signature."
423            );
424            std::process::abort();
425        }
426    }
427
428    /// The `load_class` hook every [`java_class!`](crate::java_class) binding uses: the app's
429    /// class loader, cached at `init`, so a binding first used on a thread Rust started still
430    /// finds app classes. That thread's own loader is the system one, which cannot (see `dfind`).
431    ///
432    /// # Errors
433    ///
434    /// Returns the JNI error when the class cannot be found or loaded.
435    pub fn load_app_class<'l, T: jni::refs::Reference>(
436        env: &mut Env<'l>,
437        context: &jni::refs::LoaderContext,
438        initialize: bool,
439    ) -> jni::errors::Result<JClass<'l>> {
440        let Some(loader) = APP_CLASS_LOADER.get() else {
441            return context.load_class_for_type::<T>(env, initialize);
442        };
443        jni::refs::LoaderContext::Loader(loader).load_class_for_type::<T>(env, initialize)
444    }
445
446    /// Whether the JVM has been cached, i.e. whether [`with_env`] can run at all.
447    ///
448    /// Public because a bridged part (docs/bridge.md) may be called before, or entirely outside, a
449    /// Day app's `init`: a headless `day-part-*` crate is ordinary Rust that anyone can depend on.
450    /// Asking first turns "no runtime" from a panic into `day_bridge::Error::Runtime`.
451    pub fn vm_ready() -> bool {
452        JAVA_VM.get().is_some()
453    }
454
455    /// Read a Java `String` local ref into a Rust `String` (`None` when the ref is null). Public:
456    /// the `day` crate's JNI native methods use it to decode incoming string args.
457    #[must_use]
458    pub fn read_jstring(env: &Env, s: &JString) -> Option<String> {
459        if s.is_null() {
460            None
461        } else {
462            s.mutf8_chars(env).ok().map(|c| c.to_string())
463        }
464    }
465
466    /// The Java `String` a call returns, read into Rust inside [`java_in`]: `None` when the call
467    /// throws or returns null.
468    pub fn java_string<F>(env: &mut Env, call: F) -> Option<String>
469    where
470        F: for<'a, 'l> FnOnce(&'a mut Env<'l>) -> jni::errors::Result<JString<'l>>,
471    {
472        java_in(env, |env| {
473            let s = call(env)?;
474            if s.is_null() {
475                return Ok(None);
476            }
477            string_of(env, &s).map(Some)
478        })
479        .flatten()
480    }
481
482    /// A Java `String` as a Rust `String` (MUTF-8 decoded).
483    ///
484    /// # Errors
485    ///
486    /// Returns the JNI error when the string's characters cannot be read.
487    pub fn string_of(env: &Env, s: &JString) -> jni::errors::Result<String> {
488        Ok(s.mutf8_chars(env)?.to_string())
489    }
490}