webbluetooth_android/
runtime.rs1#![allow(clippy::not_unsafe_ptr_arg_deref)]
26
27use crate::jni::{Env, JClass, JObject, JValue, NativeMethod, Vm};
28use std::collections::HashMap;
29use std::ffi::CString;
30use std::sync::{Mutex, OnceLock};
31
32pub struct Runtime {
34 vm: Vm,
35 context: JObject,
37 classes: Mutex<HashMap<String, JClass>>,
39}
40
41unsafe impl Send for Runtime {}
43unsafe impl Sync for Runtime {}
44
45static RUNTIME: OnceLock<Runtime> = OnceLock::new();
46
47#[derive(Debug, Clone)]
49pub enum Error {
50 NoEnv,
52 MissingClass(String),
54 MissingMethod(String),
56 ClassLoad(String),
58 RegisterNatives(String),
61 NoContext,
63}
64
65impl std::fmt::Display for Error {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 match self {
68 Self::NoEnv => f.write_str("could not attach to the Java VM"),
69 Self::MissingClass(c) => write!(f, "class not found: {c} (is minSdk at least 26?)"),
70 Self::MissingMethod(m) => write!(f, "method not found: {m}"),
71 Self::ClassLoad(c) => write!(f, "the generated class {c} did not load"),
72 Self::RegisterNatives(c) => {
73 write!(
74 f,
75 "RegisterNatives refused {c} — a signature disagrees with the DEX"
76 )
77 }
78 Self::NoContext => f.write_str(
79 "no Android Context: call Runtime::init(vm, context) from JNI_OnLoad or your \
80 Activity, or run inside an app where ActivityThread.currentApplication() works",
81 ),
82 }
83 }
84}
85
86impl std::error::Error for Error {}
87
88type Result<T> = std::result::Result<T, Error>;
89
90impl Runtime {
91 pub fn init(vm: Vm, context: JObject) -> Result<&'static Runtime> {
97 if let Some(existing) = RUNTIME.get() {
98 return Ok(existing);
99 }
100 let env = vm.attach().ok_or(Error::NoEnv)?;
101
102 let context = if context.is_null() {
103 current_application(env).ok_or(Error::NoContext)?
104 } else {
105 context
106 };
107 let context = env.new_global_ref(context);
108
109 let runtime = Runtime {
110 vm,
111 context,
112 classes: Mutex::new(HashMap::new()),
113 };
114 Ok(RUNTIME.get_or_init(|| runtime))
115 }
116
117 pub fn get() -> Option<&'static Runtime> {
119 RUNTIME.get()
120 }
121
122 pub fn vm(&self) -> Vm {
123 self.vm
124 }
125
126 pub fn context(&self) -> JObject {
128 self.context
129 }
130
131 pub fn env(&self) -> Result<Env> {
133 self.vm.attach().ok_or(Error::NoEnv)
134 }
135
136 pub fn define_class(
142 &self,
143 binary_name: &str,
144 dex_bytes: Vec<u8>,
145 natives: &[(&str, &str, *const std::ffi::c_void)],
146 ) -> Result<JClass> {
147 if let Some(existing) = self.classes.lock().unwrap().get(binary_name) {
148 return Ok(*existing);
149 }
150 let env = self.env()?;
151
152 let leaked = Box::leak(dex_bytes.into_boxed_slice());
155 let buffer = env.new_direct_byte_buffer(leaked.as_mut_ptr(), leaked.len());
156 if buffer.is_null() {
157 return Err(Error::ClassLoad(
158 "could not wrap the dex in a ByteBuffer".into(),
159 ));
160 }
161
162 let loader_class = env
164 .find_class("dalvik/system/InMemoryDexClassLoader")
165 .ok_or_else(|| Error::MissingClass("dalvik.system.InMemoryDexClassLoader".into()))?;
166 let ctor = env
167 .method_id(
168 loader_class,
169 "<init>",
170 "(Ljava/nio/ByteBuffer;Ljava/lang/ClassLoader;)V",
171 )
172 .ok_or_else(|| Error::MissingMethod("InMemoryDexClassLoader.<init>".into()))?;
173
174 let parent = self.class_loader(env).unwrap_or(std::ptr::null_mut());
176 let loader = env.new_object(
177 loader_class,
178 ctor,
179 &[JValue::object(buffer), JValue::object(parent)],
180 );
181 if loader.is_null() {
182 return Err(Error::ClassLoad(binary_name.into()));
183 }
184
185 let load_class = env
187 .method_id(
188 env.get_object_class(loader),
189 "loadClass",
190 "(Ljava/lang/String;)Ljava/lang/Class;",
191 )
192 .ok_or_else(|| Error::MissingMethod("ClassLoader.loadClass".into()))?;
193 let name = env.new_string(binary_name);
194 let class = env.call_object(loader, load_class, &[JValue::object(name)]);
195 if class.is_null() {
196 return Err(Error::ClassLoad(binary_name.into()));
197 }
198 let class = env.new_global_ref(class);
199
200 let names: Vec<CString> = natives
203 .iter()
204 .map(|(n, _, _)| CString::new(*n).expect("method name"))
205 .collect();
206 let signatures: Vec<CString> = natives
207 .iter()
208 .map(|(_, s, _)| CString::new(*s).expect("signature"))
209 .collect();
210 let table: Vec<NativeMethod> = natives
211 .iter()
212 .enumerate()
213 .map(|(i, (_, _, f))| NativeMethod {
214 name: names[i].as_ptr(),
215 signature: signatures[i].as_ptr(),
216 function: *f,
217 })
218 .collect();
219
220 if !table.is_empty() && !env.register_natives(class, &table) {
221 return Err(Error::RegisterNatives(binary_name.into()));
222 }
223
224 self.classes
225 .lock()
226 .unwrap()
227 .insert(binary_name.into(), class);
228 Ok(class)
229 }
230
231 pub fn new_instance(&self, class: JClass) -> Result<JObject> {
233 let env = self.env()?;
234 let ctor = env
235 .method_id(class, "<init>", "()V")
236 .ok_or_else(|| Error::MissingMethod("<init>".into()))?;
237 let object = env.new_object(class, ctor, &[]);
238 if object.is_null() {
239 return Err(Error::ClassLoad(
240 "could not instantiate the generated class".into(),
241 ));
242 }
243 Ok(env.new_global_ref(object))
244 }
245
246 fn class_loader(&self, env: Env) -> Option<JObject> {
248 let method = env.method_id(
249 env.get_object_class(self.context),
250 "getClassLoader",
251 "()Ljava/lang/ClassLoader;",
252 )?;
253 let loader = env.call_object(self.context, method, &[]);
254 (!loader.is_null()).then_some(loader)
255 }
256}
257
258fn current_application(env: Env) -> Option<JObject> {
265 let class = env.find_class("android/app/ActivityThread")?;
266 let method =
267 env.static_method_id(class, "currentApplication", "()Landroid/app/Application;")?;
268 let application = env.call_static_object(class, method, &[]);
269 (!application.is_null()).then_some(application)
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 #[test]
277 fn errors_say_what_to_do() {
278 assert!(
281 Error::MissingClass("dalvik.system.InMemoryDexClassLoader".into())
282 .to_string()
283 .contains("minSdk")
284 );
285 assert!(Error::NoContext.to_string().contains("Runtime::init"));
286 assert!(Error::RegisterNatives("X".into())
287 .to_string()
288 .contains("signature"));
289 }
290
291 #[test]
292 fn the_runtime_is_absent_until_initialised() {
293 assert!(Runtime::get().is_none());
295 }
296}