#![allow(clippy::not_unsafe_ptr_arg_deref)]
use crate::jni::{Env, JClass, JObject, JValue, NativeMethod, Vm};
use std::collections::HashMap;
use std::ffi::CString;
use std::sync::{Mutex, OnceLock};
pub struct Runtime {
vm: Vm,
context: JObject,
classes: Mutex<HashMap<String, JClass>>,
}
unsafe impl Send for Runtime {}
unsafe impl Sync for Runtime {}
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
#[derive(Debug, Clone)]
pub enum Error {
NoEnv,
MissingClass(String),
MissingMethod(String),
ClassLoad(String),
RegisterNatives(String),
NoContext,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoEnv => f.write_str("could not attach to the Java VM"),
Self::MissingClass(c) => write!(f, "class not found: {c} (is minSdk at least 26?)"),
Self::MissingMethod(m) => write!(f, "method not found: {m}"),
Self::ClassLoad(c) => write!(f, "the generated class {c} did not load"),
Self::RegisterNatives(c) => {
write!(
f,
"RegisterNatives refused {c} — a signature disagrees with the DEX"
)
}
Self::NoContext => f.write_str(
"no Android Context: call Runtime::init(vm, context) from JNI_OnLoad or your \
Activity, or run inside an app where ActivityThread.currentApplication() works",
),
}
}
}
impl std::error::Error for Error {}
type Result<T> = std::result::Result<T, Error>;
impl Runtime {
pub fn init(vm: Vm, context: JObject) -> Result<&'static Runtime> {
if let Some(existing) = RUNTIME.get() {
return Ok(existing);
}
let env = vm.attach().ok_or(Error::NoEnv)?;
let context = if context.is_null() {
current_application(env).ok_or(Error::NoContext)?
} else {
context
};
let context = env.new_global_ref(context);
let runtime = Runtime {
vm,
context,
classes: Mutex::new(HashMap::new()),
};
Ok(RUNTIME.get_or_init(|| runtime))
}
pub fn get() -> Option<&'static Runtime> {
RUNTIME.get()
}
pub fn vm(&self) -> Vm {
self.vm
}
pub fn context(&self) -> JObject {
self.context
}
pub fn env(&self) -> Result<Env> {
self.vm.attach().ok_or(Error::NoEnv)
}
pub fn define_class(
&self,
binary_name: &str,
dex_bytes: Vec<u8>,
natives: &[(&str, &str, *const std::ffi::c_void)],
) -> Result<JClass> {
if let Some(existing) = self.classes.lock().unwrap().get(binary_name) {
return Ok(*existing);
}
let env = self.env()?;
let leaked = Box::leak(dex_bytes.into_boxed_slice());
let buffer = env.new_direct_byte_buffer(leaked.as_mut_ptr(), leaked.len());
if buffer.is_null() {
return Err(Error::ClassLoad(
"could not wrap the dex in a ByteBuffer".into(),
));
}
let loader_class = env
.find_class("dalvik/system/InMemoryDexClassLoader")
.ok_or_else(|| Error::MissingClass("dalvik.system.InMemoryDexClassLoader".into()))?;
let ctor = env
.method_id(
loader_class,
"<init>",
"(Ljava/nio/ByteBuffer;Ljava/lang/ClassLoader;)V",
)
.ok_or_else(|| Error::MissingMethod("InMemoryDexClassLoader.<init>".into()))?;
let parent = self.class_loader(env).unwrap_or(std::ptr::null_mut());
let loader = env.new_object(
loader_class,
ctor,
&[JValue::object(buffer), JValue::object(parent)],
);
if loader.is_null() {
return Err(Error::ClassLoad(binary_name.into()));
}
let load_class = env
.method_id(
env.get_object_class(loader),
"loadClass",
"(Ljava/lang/String;)Ljava/lang/Class;",
)
.ok_or_else(|| Error::MissingMethod("ClassLoader.loadClass".into()))?;
let name = env.new_string(binary_name);
let class = env.call_object(loader, load_class, &[JValue::object(name)]);
if class.is_null() {
return Err(Error::ClassLoad(binary_name.into()));
}
let class = env.new_global_ref(class);
let names: Vec<CString> = natives
.iter()
.map(|(n, _, _)| CString::new(*n).expect("method name"))
.collect();
let signatures: Vec<CString> = natives
.iter()
.map(|(_, s, _)| CString::new(*s).expect("signature"))
.collect();
let table: Vec<NativeMethod> = natives
.iter()
.enumerate()
.map(|(i, (_, _, f))| NativeMethod {
name: names[i].as_ptr(),
signature: signatures[i].as_ptr(),
function: *f,
})
.collect();
if !table.is_empty() && !env.register_natives(class, &table) {
return Err(Error::RegisterNatives(binary_name.into()));
}
self.classes
.lock()
.unwrap()
.insert(binary_name.into(), class);
Ok(class)
}
pub fn new_instance(&self, class: JClass) -> Result<JObject> {
let env = self.env()?;
let ctor = env
.method_id(class, "<init>", "()V")
.ok_or_else(|| Error::MissingMethod("<init>".into()))?;
let object = env.new_object(class, ctor, &[]);
if object.is_null() {
return Err(Error::ClassLoad(
"could not instantiate the generated class".into(),
));
}
Ok(env.new_global_ref(object))
}
fn class_loader(&self, env: Env) -> Option<JObject> {
let method = env.method_id(
env.get_object_class(self.context),
"getClassLoader",
"()Ljava/lang/ClassLoader;",
)?;
let loader = env.call_object(self.context, method, &[]);
(!loader.is_null()).then_some(loader)
}
}
fn current_application(env: Env) -> Option<JObject> {
let class = env.find_class("android/app/ActivityThread")?;
let method =
env.static_method_id(class, "currentApplication", "()Landroid/app/Application;")?;
let application = env.call_static_object(class, method, &[]);
(!application.is_null()).then_some(application)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn errors_say_what_to_do() {
assert!(
Error::MissingClass("dalvik.system.InMemoryDexClassLoader".into())
.to_string()
.contains("minSdk")
);
assert!(Error::NoContext.to_string().contains("Runtime::init"));
assert!(Error::RegisterNatives("X".into())
.to_string()
.contains("signature"));
}
#[test]
fn the_runtime_is_absent_until_initialised() {
assert!(Runtime::get().is_none());
}
}