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