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