extern crate self as day_platform_android;
#[cfg(target_os = "android")]
pub use day_macros::java_class;
#[cfg(target_os = "android")]
pub use imp::*;
#[cfg(target_os = "android")]
#[unsafe(no_mangle)]
pub extern "system" fn Java_dev_daybrite_day_bridge_DayRuntime_initializeServices(
mut env: jni::EnvUnowned,
class: jni::objects::JClass,
) {
env.with_env(|env| -> jni::errors::Result<()> {
init(env, &class)?;
day_process::services::initialize();
Ok(())
})
.resolve::<jni::errors::ThrowRuntimeExAndDefault>();
}
pub mod envelope {
#[derive(Clone, Debug, PartialEq)]
pub struct Envelope {
pub status: i32,
pub meta: Vec<(String, String)>,
pub payload: Vec<u8>,
}
impl Envelope {
#[must_use]
pub fn encode(&self) -> Vec<u8> {
let mut meta = String::new();
for (k, v) in &self.meta {
meta.push_str(k);
meta.push('\n');
meta.push_str(v);
meta.push('\n');
}
let meta = meta.into_bytes();
let mut out = Vec::with_capacity(8 + meta.len() + self.payload.len());
out.extend_from_slice(&self.status.to_be_bytes());
out.extend_from_slice(&(meta.len() as i32).to_be_bytes());
out.extend_from_slice(&meta);
out.extend_from_slice(&self.payload);
out
}
pub fn decode(bytes: &[u8]) -> Result<Envelope, &'static str> {
if bytes.len() < 8 {
return Err("short envelope");
}
let status = i32::from_be_bytes(bytes[0..4].try_into().map_err(|_| "short")?);
let meta_len =
i32::from_be_bytes(bytes[4..8].try_into().map_err(|_| "short")?).max(0) as usize;
let rest = &bytes[8..];
if rest.len() < meta_len {
return Err("truncated envelope");
}
let (meta_bytes, payload) = rest.split_at(meta_len);
let mut meta = Vec::new();
if status >= 0 {
let mut lines = std::str::from_utf8(meta_bytes).unwrap_or("").split('\n');
while let (Some(k), Some(v)) = (lines.next(), lines.next()) {
if !k.is_empty() {
meta.push((k.to_string(), v.to_string()));
}
}
}
Ok(Envelope {
status,
meta,
payload: if status < 0 {
meta_bytes.to_vec() } else {
payload.to_vec()
},
})
}
#[must_use]
pub fn error_message(&self) -> String {
String::from_utf8_lossy(&self.payload).into_owned()
}
}
#[cfg(test)]
mod tests {
use super::Envelope;
#[test]
fn round_trip_with_meta_and_payload() {
let e = Envelope {
status: 200,
meta: vec![
("Content-Type".into(), "text/plain".into()),
("X-Two".into(), "b".into()),
],
payload: b"hello".to_vec(),
};
assert_eq!(Envelope::decode(&e.encode()).unwrap(), e);
}
#[test]
fn sentinel_carries_the_message() {
let raw = Envelope {
status: -3,
meta: vec![("boom: handshake".into(), String::new())],
payload: Vec::new(),
};
let mut bytes = (-3i32).to_be_bytes().to_vec();
let msg = b"boom: handshake";
bytes.extend_from_slice(&(msg.len() as i32).to_be_bytes());
bytes.extend_from_slice(msg);
let d = Envelope::decode(&bytes).unwrap();
assert_eq!(d.status, -3);
assert_eq!(d.error_message(), "boom: handshake");
let _ = raw;
}
#[test]
fn truncation_is_malformed_not_sentinel() {
assert!(Envelope::decode(&[0, 0]).is_err());
let mut bytes = 200i32.to_be_bytes().to_vec();
bytes.extend_from_slice(&99i32.to_be_bytes()); assert!(Envelope::decode(&bytes).is_err());
}
}
}
#[cfg(target_os = "android")]
mod imp {
pub use jni;
crate::java_class! {
pub DayRuntime => dev.daybrite.day.bridge.DayRuntime,
methods {
static fn filesDirPath() -> JString,
static fn cacheDirPath() -> JString,
},
fields {
static ctx: android.content.Context,
},
}
use jni::objects::{Global, JClass, JObject, JString};
use jni::{Env, JavaVM};
use linkme::distributed_slice;
use std::os::raw::{c_char, c_int, c_void};
use std::sync::OnceLock;
pub fn init(env: &mut Env, host_class: &JClass) -> jni::errors::Result<()> {
let vm = env.get_java_vm()?;
let loader = host_class.get_class_loader(env)?;
let loader = env.new_global_ref(loader)?;
let _ = JAVA_VM.set(vm);
let _ = APP_CLASS_LOADER.set(loader);
check_java_classes(env);
Ok(())
}
#[link(name = "log")]
unsafe extern "C" {
fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int;
}
unsafe extern "C" {
fn pipe(fds: *mut c_int) -> c_int;
fn dup2(oldfd: c_int, newfd: c_int) -> c_int;
fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
}
const ANDROID_LOG_INFO: c_int = 4;
const ANDROID_LOG_ERROR: c_int = 6;
pub fn redirect_stdio_to_logcat() {
static DONE: OnceLock<()> = OnceLock::new();
if DONE.set(()).is_err() {
return;
}
for (target_fd, prio) in [(1, ANDROID_LOG_INFO), (2, ANDROID_LOG_ERROR)] {
let mut fds = [0 as c_int; 2];
unsafe {
if pipe(fds.as_mut_ptr()) != 0 || dup2(fds[1], target_fd) < 0 {
continue;
}
}
let read_fd = fds[0];
std::thread::spawn(move || {
let tag = c"Day";
let mut buf = [0u8; 2048];
let mut line: Vec<u8> = Vec::new();
loop {
let n = unsafe { read(read_fd, buf.as_mut_ptr().cast::<c_void>(), buf.len()) };
if n <= 0 {
break;
}
for &b in &buf[..n as usize] {
if b == b'\n' {
line.push(0);
unsafe {
__android_log_write(
prio,
tag.as_ptr(),
line.as_ptr().cast::<c_char>(),
);
}
line.clear();
} else {
line.push(b);
}
}
}
});
}
}
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
static APP_CLASS_LOADER: OnceLock<Global<jni::objects::JClassLoader<'static>>> =
OnceLock::new();
pub fn with_env<R>(f: impl FnOnce(&mut Env) -> R) -> R {
let vm = JAVA_VM
.get()
.expect("day-platform-android: init() not called");
vm.attach_current_thread(|env| {
let out = f(env);
if env.exception_check() {
env.exception_describe();
env.exception_clear();
}
Ok::<R, jni::errors::Error>(out)
})
.expect("attach_current_thread")
}
pub fn java<R>(f: impl FnOnce(&mut Env) -> jni::errors::Result<R>) -> Option<R> {
with_env(|env| java_in(env, f))
}
pub fn java_in<R>(
env: &mut Env,
f: impl FnOnce(&mut Env) -> jni::errors::Result<R>,
) -> Option<R> {
match f(env) {
Ok(v) => Some(v),
Err(e) => {
log::warn!("day-platform-android: Java call failed: {e}");
if env.exception_check() {
env.exception_describe();
env.exception_clear();
}
None
}
}
}
pub fn downcast<'l, T: jni::refs::Reference>(
env: &mut Env<'l>,
obj: &JObject,
) -> jni::errors::Result<T::Kind<'l>> {
let local = env.new_local_ref(obj)?;
env.cast_local::<T>(local)
}
pub use linkme;
pub struct JavaClassCheck {
pub name: &'static str,
pub since: i32,
pub resolve: fn(&mut Env) -> jni::errors::Result<()>,
}
pub fn sdk_int() -> i32 {
static SDK: OnceLock<i32> = OnceLock::new();
*SDK.get_or_init(|| {
unsafe extern "C" {
fn __system_property_get(name: *const c_char, value: *mut c_char) -> c_int;
}
let mut value = [0u8; 92];
let len = unsafe {
__system_property_get(
c"ro.build.version.sdk".as_ptr(),
value.as_mut_ptr().cast::<c_char>(),
)
};
let len = usize::try_from(len).unwrap_or(0).min(value.len());
std::str::from_utf8(&value[..len])
.ok()
.and_then(|s| s.trim().parse().ok())
.unwrap_or(0)
})
}
#[distributed_slice]
pub static JAVA_CLASSES: [JavaClassCheck];
fn check_java_classes(env: &mut Env) {
let started = std::time::Instant::now();
let mut failed = 0;
let sdk = sdk_int();
for class in JAVA_CLASSES {
if sdk < class.since {
continue;
}
if let Err(e) = (class.resolve)(env) {
failed += 1;
if env.exception_check() {
env.exception_describe();
env.exception_clear();
}
eprintln!(
"day-platform-android: Java binding {} does not match the app's classes: {e}",
class.name.replace(' ', "")
);
}
}
eprintln!(
"day-platform-android: resolved {} Java binding(s) in {:.2} ms ({failed} failed)",
JAVA_CLASSES.len(),
started.elapsed().as_secs_f64() * 1000.0
);
let strict = cfg!(debug_assertions) || std::env::var_os("DAYSCRIPT_PORT").is_some();
if failed > 0 && strict {
eprintln!(
"day-platform-android: stopping: {failed} Java binding(s) do not match the classes in this \
build (above). Rebuild after changing Java, or fix the binding's signature."
);
std::process::abort();
}
}
pub fn load_app_class<'l, T: jni::refs::Reference>(
env: &mut Env<'l>,
context: &jni::refs::LoaderContext,
initialize: bool,
) -> jni::errors::Result<JClass<'l>> {
let Some(loader) = APP_CLASS_LOADER.get() else {
return context.load_class_for_type::<T>(env, initialize);
};
jni::refs::LoaderContext::Loader(loader).load_class_for_type::<T>(env, initialize)
}
pub fn vm_ready() -> bool {
JAVA_VM.get().is_some()
}
#[must_use]
pub fn read_jstring(env: &Env, s: &JString) -> Option<String> {
if s.is_null() {
None
} else {
s.mutf8_chars(env).ok().map(|c| c.to_string())
}
}
pub fn java_string<F>(env: &mut Env, call: F) -> Option<String>
where
F: for<'a, 'l> FnOnce(&'a mut Env<'l>) -> jni::errors::Result<JString<'l>>,
{
java_in(env, |env| {
let s = call(env)?;
if s.is_null() {
return Ok(None);
}
string_of(env, &s).map(Some)
})
.flatten()
}
pub fn string_of(env: &Env, s: &JString) -> jni::errors::Result<String> {
Ok(s.mutf8_chars(env)?.to_string())
}
}