Skip to main content

webbluetooth_android/
runtime.rs

1//! Turning a generated DEX into a live class.
2//!
3//! The Apple backend synthesises a delegate with `objc_allocateClassPair` and
4//! installs Rust functions with `class_addMethod`. Android's equivalent is
5//! three steps rather than two, because the class arrives as a *file*:
6//!
7//! 1. [`crate::dex`] emits a DEX defining the subclass, its overrides `native`.
8//! 2. `InMemoryDexClassLoader` loads it — from a `ByteBuffer` over memory we
9//!    own, so nothing is ever written to disk.
10//! 3. `RegisterNatives` binds each `native` method to a Rust function.
11//!
12//! The result is a class Android cannot distinguish from a compiled one. It has
13//! a real superclass, a real constructor, and real methods; they simply happen
14//! to be implemented in Rust.
15//!
16//! # Two things that will bite
17//!
18//! * **`InMemoryDexClassLoader` is API 26+.** Below that the DEX has to reach a
19//!   file, and `DexClassLoader` needs a writable optimised-output directory.
20//!   There is no fallback here; the crate targets 26 and up.
21//! * **The DEX bytes must outlive the loader.** `NewDirectByteBuffer` does not
22//!   copy, so the buffer is leaked deliberately — one allocation per class, for
23//!   the life of the process.
24
25#![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
32/// The pieces of the Android runtime this crate needs, resolved once.
33pub struct Runtime {
34    vm: Vm,
35    /// The application `Context`, as a global reference.
36    context: JObject,
37    /// `dev/webbluetooth/…` → the loaded class, as a global reference.
38    classes: Mutex<HashMap<String, JClass>>,
39}
40
41// Every field is a global reference or the VM itself, both valid on any thread.
42unsafe impl Send for Runtime {}
43unsafe impl Sync for Runtime {}
44
45static RUNTIME: OnceLock<Runtime> = OnceLock::new();
46
47/// Why the runtime could not start.
48#[derive(Debug, Clone)]
49pub enum Error {
50    /// No thread could be attached to the VM.
51    NoEnv,
52    /// A framework class was missing — almost always an API level below 26.
53    MissingClass(String),
54    /// A method or constructor was missing.
55    MissingMethod(String),
56    /// The generated class did not load.
57    ClassLoad(String),
58    /// `RegisterNatives` refused the table, meaning a signature disagrees with
59    /// the DEX.
60    RegisterNatives(String),
61    /// No Android `Context` was supplied and none could be found.
62    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    /// Start the runtime with a VM and an Android `Context`.
92    ///
93    /// `context` may be null, in which case the application context is looked
94    /// up through `ActivityThread.currentApplication()` — which works inside a
95    /// normal app process and nowhere else.
96    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    /// The runtime, if [`Runtime::init`] has run.
118    pub fn get() -> Option<&'static Runtime> {
119        RUNTIME.get()
120    }
121
122    pub fn vm(&self) -> Vm {
123        self.vm
124    }
125
126    /// The application `Context`, a global reference.
127    pub fn context(&self) -> JObject {
128        self.context
129    }
130
131    /// An environment for the calling thread, attaching it if necessary.
132    pub fn env(&self) -> Result<Env> {
133        self.vm.attach().ok_or(Error::NoEnv)
134    }
135
136    /// Define a class from a DEX and bind its native methods.
137    ///
138    /// Returns a global reference, cached — asking twice is free and yields the
139    /// same class, which matters because two `Class` objects from two loaders
140    /// are not interchangeable.
141    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        // The buffer is not copied, so it must live as long as the loader. One
153        // deliberate leak per class, for the life of the process.
154        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        // new InMemoryDexClassLoader(ByteBuffer, ClassLoader)
163        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        // Parent the loader on the app's, so framework classes resolve.
175        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        // loader.loadClass("dev.webbluetooth.GattCallback")
186        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        // Bind the native methods. The strings must outlive the call, which is
201        // why they are collected before the table is built.
202        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    /// Instantiate one of the generated classes.
232    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    /// `context.getClassLoader()`.
247    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
258/// `ActivityThread.currentApplication()`, the standard way to reach a Context
259/// with nothing but a VM.
260///
261/// Works in an ordinary app process. It is hidden API in the sense that no
262/// public entry point returns it, but the method itself is public and stable,
263/// and it is what every native library that needs a Context uses.
264fn 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        // A missing class on Android almost always means the API level, and a
279        // missing Context almost always means init was never called.
280        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        // Every entry point checks this rather than assuming.
294        assert!(Runtime::get().is_none());
295    }
296}