Skip to main content

webbluetooth_android/
jni.rs

1//! JNI, spoken directly.
2//!
3//! `JNIEnv` is a pointer to a pointer to a table of function pointers, and the
4//! table's layout is fixed by the JNI specification and identical on every VM —
5//! so it needs no binding crate, only the right indices.
6//!
7//! Indices are named as constants below rather than expressed as a `struct`
8//! with two hundred reserved fields. Getting one wrong is silent memory
9//! corruption rather than a compile error, so `tests/jvm.rs` calls a
10//! representative set against a real JVM to check them.
11//!
12//! # Only the `A` call variants
13//!
14//! JNI offers three forms of every `Call*Method`: variadic, `va_list`, and an
15//! array of `jvalue`. Only the last is used here. The variadic form cannot be
16//! called correctly from Rust on AArch64 — arguments would be passed in
17//! registers where the callee looks on the stack — which is the same hazard
18//! `objc_msgSend` poses on Apple, and it gets the same answer.
19
20// Every JNI reference is a raw pointer, and these methods hand them to the VM
21// rather than dereferencing them in Rust — the VM is what validates them, and
22// it does so far better than a null check here could. Marking each one `unsafe`
23// would put an `unsafe` block around every BLE call in the crate without
24// telling the reader anything the type does not already say: a `JObject` must
25// be a live reference, obtained from JNI and not yet deleted.
26#![allow(clippy::not_unsafe_ptr_arg_deref)]
27
28use core::ffi::{c_char, c_void};
29
30/// A JNI local or global reference to a Java object.
31///
32/// Opaque: the pointer is the VM's, and dereferencing it is not a thing this
33/// crate ever does.
34pub type JObject = *mut c_void;
35/// A reference to a `java.lang.Class`.
36pub type JClass = JObject;
37/// A reference to a `java.lang.String`.
38pub type JString = JObject;
39/// A reference to a Java array.
40pub type JArray = JObject;
41/// A resolved method, from `GetMethodID` or `GetStaticMethodID`.
42///
43/// Valid only while the class that produced it is loaded.
44pub type JMethodId = *mut c_void;
45/// A resolved field, from `GetFieldID` or `GetStaticFieldID`.
46pub type JFieldId = *mut c_void;
47
48/// A `jvalue`, the union JNI passes arguments in.
49#[repr(C)]
50#[derive(Clone, Copy)]
51pub union JValue {
52    pub z: u8,
53    pub b: i8,
54    pub c: u16,
55    pub s: i16,
56    pub i: i32,
57    pub j: i64,
58    pub f: f32,
59    pub d: f64,
60    pub l: JObject,
61}
62
63impl JValue {
64    pub fn object(v: JObject) -> Self {
65        Self { l: v }
66    }
67    pub fn int(v: i32) -> Self {
68        Self { i: v }
69    }
70    pub fn long(v: i64) -> Self {
71        Self { j: v }
72    }
73    pub fn bool(v: bool) -> Self {
74        Self { z: u8::from(v) }
75    }
76    pub fn byte(v: i8) -> Self {
77        Self { b: v }
78    }
79}
80
81/// One entry in a `RegisterNatives` table.
82#[repr(C)]
83pub struct NativeMethod {
84    pub name: *const c_char,
85    pub signature: *const c_char,
86    pub function: *const c_void,
87}
88
89// JNI 1.6 has 233 function-pointer slots. Naming the ones used, with the index
90// each occupies in `JNINativeInterface_`.
91mod slot {
92    pub const GET_VERSION: usize = 4;
93    pub const FIND_CLASS: usize = 6;
94    pub const THROW_NEW: usize = 14;
95    pub const EXCEPTION_OCCURRED: usize = 15;
96    pub const EXCEPTION_DESCRIBE: usize = 16;
97    pub const EXCEPTION_CLEAR: usize = 17;
98    pub const PUSH_LOCAL_FRAME: usize = 19;
99    pub const POP_LOCAL_FRAME: usize = 20;
100    pub const NEW_GLOBAL_REF: usize = 21;
101    pub const DELETE_GLOBAL_REF: usize = 22;
102    pub const DELETE_LOCAL_REF: usize = 23;
103    pub const IS_SAME_OBJECT: usize = 24;
104    pub const GET_OBJECT_CLASS: usize = 31;
105    pub const GET_METHOD_ID: usize = 33;
106    pub const CALL_OBJECT_METHOD_A: usize = 36;
107    pub const CALL_BOOLEAN_METHOD_A: usize = 39;
108    pub const CALL_INT_METHOD_A: usize = 51;
109    pub const CALL_LONG_METHOD_A: usize = 54;
110    pub const CALL_VOID_METHOD_A: usize = 63;
111    pub const GET_STATIC_METHOD_ID: usize = 113;
112    pub const CALL_STATIC_OBJECT_METHOD_A: usize = 116;
113    pub const CALL_STATIC_INT_METHOD_A: usize = 131;
114    pub const CALL_STATIC_VOID_METHOD_A: usize = 143;
115    pub const GET_STATIC_FIELD_ID: usize = 144;
116    pub const GET_STATIC_OBJECT_FIELD: usize = 145;
117    pub const GET_STATIC_INT_FIELD: usize = 150;
118    pub const NEW_STRING_UTF: usize = 167;
119    pub const GET_STRING_UTF_CHARS: usize = 169;
120    pub const RELEASE_STRING_UTF_CHARS: usize = 170;
121    pub const GET_ARRAY_LENGTH: usize = 171;
122    pub const NEW_OBJECT_ARRAY: usize = 172;
123    pub const GET_OBJECT_ARRAY_ELEMENT: usize = 173;
124    pub const SET_OBJECT_ARRAY_ELEMENT: usize = 174;
125    pub const NEW_BYTE_ARRAY: usize = 176;
126    pub const GET_BYTE_ARRAY_ELEMENTS: usize = 184;
127    pub const RELEASE_BYTE_ARRAY_ELEMENTS: usize = 192;
128    pub const REGISTER_NATIVES: usize = 215;
129    pub const NEW_DIRECT_BYTE_BUFFER: usize = 229;
130    pub const NEW_OBJECT_A: usize = 30;
131    pub const ALLOC_OBJECT: usize = 27;
132}
133
134/// A JNI environment pointer, valid only on the thread that produced it.
135///
136/// `repr(transparent)` because the VM passes this as a bare `JNIEnv*` to every
137/// native method — it must have exactly a pointer's layout.
138#[repr(transparent)]
139#[derive(Clone, Copy)]
140pub struct Env(pub *mut *const [*const c_void; 234]);
141
142impl Env {
143    #[inline]
144    fn f<T: Copy>(&self, index: usize) -> T {
145        debug_assert!(!self.0.is_null(), "null JNIEnv");
146        // SAFETY: the table is owned by the VM and outlives every use; the
147        // caller has picked an index whose signature matches `T`.
148        unsafe {
149            let table = *self.0;
150            core::mem::transmute_copy(&(*table)[index])
151        }
152    }
153
154    pub fn version(&self) -> i32 {
155        let f: unsafe extern "C" fn(Env) -> i32 = self.f(slot::GET_VERSION);
156        unsafe { f(*self) }
157    }
158
159    /// `FindClass`, with an internal name like `android/bluetooth/BluetoothAdapter`.
160    ///
161    /// Returns a **local** reference; promote it with
162    /// [`Env::new_global_ref`] to keep it past the current frame.
163    pub fn find_class(&self, name: &str) -> Option<JClass> {
164        let name = cstring(name);
165        let f: unsafe extern "C" fn(Env, *const c_char) -> JClass = self.f(slot::FIND_CLASS);
166        let class = unsafe { f(*self, name.as_ptr()) };
167        self.check_exception();
168        (!class.is_null()).then_some(class)
169    }
170
171    pub fn get_object_class(&self, object: JObject) -> JClass {
172        let f: unsafe extern "C" fn(Env, JObject) -> JClass = self.f(slot::GET_OBJECT_CLASS);
173        unsafe { f(*self, object) }
174    }
175
176    pub fn method_id(&self, class: JClass, name: &str, signature: &str) -> Option<JMethodId> {
177        let (name, signature) = (cstring(name), cstring(signature));
178        let f: unsafe extern "C" fn(Env, JClass, *const c_char, *const c_char) -> JMethodId =
179            self.f(slot::GET_METHOD_ID);
180        let id = unsafe { f(*self, class, name.as_ptr(), signature.as_ptr()) };
181        self.check_exception();
182        (!id.is_null()).then_some(id)
183    }
184
185    pub fn static_method_id(
186        &self,
187        class: JClass,
188        name: &str,
189        signature: &str,
190    ) -> Option<JMethodId> {
191        let (name, signature) = (cstring(name), cstring(signature));
192        let f: unsafe extern "C" fn(Env, JClass, *const c_char, *const c_char) -> JMethodId =
193            self.f(slot::GET_STATIC_METHOD_ID);
194        let id = unsafe { f(*self, class, name.as_ptr(), signature.as_ptr()) };
195        self.check_exception();
196        (!id.is_null()).then_some(id)
197    }
198
199    pub fn static_field_id(&self, class: JClass, name: &str, signature: &str) -> Option<JFieldId> {
200        let (name, signature) = (cstring(name), cstring(signature));
201        let f: unsafe extern "C" fn(Env, JClass, *const c_char, *const c_char) -> JFieldId =
202            self.f(slot::GET_STATIC_FIELD_ID);
203        let id = unsafe { f(*self, class, name.as_ptr(), signature.as_ptr()) };
204        self.check_exception();
205        (!id.is_null()).then_some(id)
206    }
207
208    pub fn static_object_field(&self, class: JClass, field: JFieldId) -> JObject {
209        let f: unsafe extern "C" fn(Env, JClass, JFieldId) -> JObject =
210            self.f(slot::GET_STATIC_OBJECT_FIELD);
211        unsafe { f(*self, class, field) }
212    }
213
214    pub fn static_int_field(&self, class: JClass, field: JFieldId) -> i32 {
215        let f: unsafe extern "C" fn(Env, JClass, JFieldId) -> i32 =
216            self.f(slot::GET_STATIC_INT_FIELD);
217        unsafe { f(*self, class, field) }
218    }
219
220    // ── Calls ───────────────────────────────────────────────────────────────
221
222    pub fn call_object(&self, object: JObject, method: JMethodId, args: &[JValue]) -> JObject {
223        let f: unsafe extern "C" fn(Env, JObject, JMethodId, *const JValue) -> JObject =
224            self.f(slot::CALL_OBJECT_METHOD_A);
225        let out = unsafe { f(*self, object, method, args.as_ptr()) };
226        self.check_exception();
227        out
228    }
229
230    pub fn call_bool(&self, object: JObject, method: JMethodId, args: &[JValue]) -> bool {
231        let f: unsafe extern "C" fn(Env, JObject, JMethodId, *const JValue) -> u8 =
232            self.f(slot::CALL_BOOLEAN_METHOD_A);
233        let out = unsafe { f(*self, object, method, args.as_ptr()) } != 0;
234        self.check_exception();
235        out
236    }
237
238    pub fn call_int(&self, object: JObject, method: JMethodId, args: &[JValue]) -> i32 {
239        let f: unsafe extern "C" fn(Env, JObject, JMethodId, *const JValue) -> i32 =
240            self.f(slot::CALL_INT_METHOD_A);
241        let out = unsafe { f(*self, object, method, args.as_ptr()) };
242        self.check_exception();
243        out
244    }
245
246    pub fn call_long(&self, object: JObject, method: JMethodId, args: &[JValue]) -> i64 {
247        let f: unsafe extern "C" fn(Env, JObject, JMethodId, *const JValue) -> i64 =
248            self.f(slot::CALL_LONG_METHOD_A);
249        let out = unsafe { f(*self, object, method, args.as_ptr()) };
250        self.check_exception();
251        out
252    }
253
254    pub fn call_void(&self, object: JObject, method: JMethodId, args: &[JValue]) {
255        let f: unsafe extern "C" fn(Env, JObject, JMethodId, *const JValue) =
256            self.f(slot::CALL_VOID_METHOD_A);
257        unsafe { f(*self, object, method, args.as_ptr()) };
258        self.check_exception();
259    }
260
261    pub fn call_static_object(&self, class: JClass, method: JMethodId, args: &[JValue]) -> JObject {
262        let f: unsafe extern "C" fn(Env, JClass, JMethodId, *const JValue) -> JObject =
263            self.f(slot::CALL_STATIC_OBJECT_METHOD_A);
264        let out = unsafe { f(*self, class, method, args.as_ptr()) };
265        self.check_exception();
266        out
267    }
268
269    pub fn call_static_int(&self, class: JClass, method: JMethodId, args: &[JValue]) -> i32 {
270        let f: unsafe extern "C" fn(Env, JClass, JMethodId, *const JValue) -> i32 =
271            self.f(slot::CALL_STATIC_INT_METHOD_A);
272        let out = unsafe { f(*self, class, method, args.as_ptr()) };
273        self.check_exception();
274        out
275    }
276
277    pub fn call_static_void(&self, class: JClass, method: JMethodId, args: &[JValue]) {
278        let f: unsafe extern "C" fn(Env, JClass, JMethodId, *const JValue) =
279            self.f(slot::CALL_STATIC_VOID_METHOD_A);
280        unsafe { f(*self, class, method, args.as_ptr()) };
281        self.check_exception();
282    }
283
284    pub fn new_object(&self, class: JClass, ctor: JMethodId, args: &[JValue]) -> JObject {
285        let f: unsafe extern "C" fn(Env, JClass, JMethodId, *const JValue) -> JObject =
286            self.f(slot::NEW_OBJECT_A);
287        let out = unsafe { f(*self, class, ctor, args.as_ptr()) };
288        self.check_exception();
289        out
290    }
291
292    /// Allocate without running a constructor.
293    pub fn alloc_object(&self, class: JClass) -> JObject {
294        let f: unsafe extern "C" fn(Env, JClass) -> JObject = self.f(slot::ALLOC_OBJECT);
295        let out = unsafe { f(*self, class) };
296        self.check_exception();
297        out
298    }
299
300    // ── References ──────────────────────────────────────────────────────────
301
302    pub fn new_global_ref(&self, object: JObject) -> JObject {
303        let f: unsafe extern "C" fn(Env, JObject) -> JObject = self.f(slot::NEW_GLOBAL_REF);
304        unsafe { f(*self, object) }
305    }
306
307    pub fn delete_global_ref(&self, object: JObject) {
308        let f: unsafe extern "C" fn(Env, JObject) = self.f(slot::DELETE_GLOBAL_REF);
309        unsafe { f(*self, object) };
310    }
311
312    pub fn delete_local_ref(&self, object: JObject) {
313        let f: unsafe extern "C" fn(Env, JObject) = self.f(slot::DELETE_LOCAL_REF);
314        unsafe { f(*self, object) };
315    }
316
317    pub fn is_same_object(&self, a: JObject, b: JObject) -> bool {
318        let f: unsafe extern "C" fn(Env, JObject, JObject) -> u8 = self.f(slot::IS_SAME_OBJECT);
319        unsafe { f(*self, a, b) != 0 }
320    }
321
322    /// Push a local frame, so a burst of locals is released together.
323    ///
324    /// The default local-reference table is small — 512 entries on Android —
325    /// and a scan callback that leaks a few per advertisement exhausts it.
326    pub fn push_local_frame(&self, capacity: i32) -> bool {
327        let f: unsafe extern "C" fn(Env, i32) -> i32 = self.f(slot::PUSH_LOCAL_FRAME);
328        unsafe { f(*self, capacity) == 0 }
329    }
330
331    pub fn pop_local_frame(&self) {
332        let f: unsafe extern "C" fn(Env, JObject) -> JObject = self.f(slot::POP_LOCAL_FRAME);
333        unsafe { f(*self, core::ptr::null_mut()) };
334    }
335
336    // ── Strings and arrays ──────────────────────────────────────────────────
337
338    pub fn new_string(&self, s: &str) -> JString {
339        let s = cstring(s);
340        let f: unsafe extern "C" fn(Env, *const c_char) -> JString = self.f(slot::NEW_STRING_UTF);
341        unsafe { f(*self, s.as_ptr()) }
342    }
343
344    pub fn get_string(&self, string: JString) -> Option<String> {
345        if string.is_null() {
346            return None;
347        }
348        let get: unsafe extern "C" fn(Env, JString, *mut u8) -> *const c_char =
349            self.f(slot::GET_STRING_UTF_CHARS);
350        let release: unsafe extern "C" fn(Env, JString, *const c_char) =
351            self.f(slot::RELEASE_STRING_UTF_CHARS);
352        unsafe {
353            let chars = get(*self, string, core::ptr::null_mut());
354            if chars.is_null() {
355                return None;
356            }
357            let out = core::ffi::CStr::from_ptr(chars)
358                .to_string_lossy()
359                .into_owned();
360            release(*self, string, chars);
361            Some(out)
362        }
363    }
364
365    pub fn array_length(&self, array: JArray) -> i32 {
366        if array.is_null() {
367            return 0;
368        }
369        let f: unsafe extern "C" fn(Env, JArray) -> i32 = self.f(slot::GET_ARRAY_LENGTH);
370        unsafe { f(*self, array) }
371    }
372
373    pub fn object_array_element(&self, array: JArray, index: i32) -> JObject {
374        let f: unsafe extern "C" fn(Env, JArray, i32) -> JObject =
375            self.f(slot::GET_OBJECT_ARRAY_ELEMENT);
376        unsafe { f(*self, array, index) }
377    }
378
379    pub fn new_object_array(&self, length: i32, class: JClass, initial: JObject) -> JArray {
380        let f: unsafe extern "C" fn(Env, i32, JClass, JObject) -> JArray =
381            self.f(slot::NEW_OBJECT_ARRAY);
382        unsafe { f(*self, length, class, initial) }
383    }
384
385    pub fn set_object_array_element(&self, array: JArray, index: i32, value: JObject) {
386        let f: unsafe extern "C" fn(Env, JArray, i32, JObject) =
387            self.f(slot::SET_OBJECT_ARRAY_ELEMENT);
388        unsafe { f(*self, array, index, value) };
389    }
390
391    /// Copy a `byte[]` out of the VM.
392    pub fn byte_array(&self, array: JArray) -> Option<Vec<u8>> {
393        if array.is_null() {
394            return None;
395        }
396        let length = self.array_length(array) as usize;
397        let get: unsafe extern "C" fn(Env, JArray, *mut u8) -> *mut i8 =
398            self.f(slot::GET_BYTE_ARRAY_ELEMENTS);
399        let release: unsafe extern "C" fn(Env, JArray, *mut i8, i32) =
400            self.f(slot::RELEASE_BYTE_ARRAY_ELEMENTS);
401        unsafe {
402            let elements = get(*self, array, core::ptr::null_mut());
403            if elements.is_null() {
404                return None;
405            }
406            let out = core::slice::from_raw_parts(elements as *const u8, length).to_vec();
407            // Mode 2 = JNI_ABORT: release without copying back, since we only read.
408            release(*self, array, elements, 2);
409            Some(out)
410        }
411    }
412
413    /// Make a `byte[]` the VM owns.
414    pub fn new_byte_array(&self, data: &[u8]) -> JArray {
415        let new: unsafe extern "C" fn(Env, i32) -> JArray = self.f(slot::NEW_BYTE_ARRAY);
416        let array = unsafe { new(*self, data.len() as i32) };
417        if array.is_null() || data.is_empty() {
418            return array;
419        }
420        let get: unsafe extern "C" fn(Env, JArray, *mut u8) -> *mut i8 =
421            self.f(slot::GET_BYTE_ARRAY_ELEMENTS);
422        let release: unsafe extern "C" fn(Env, JArray, *mut i8, i32) =
423            self.f(slot::RELEASE_BYTE_ARRAY_ELEMENTS);
424        unsafe {
425            let elements = get(*self, array, core::ptr::null_mut());
426            if !elements.is_null() {
427                core::ptr::copy_nonoverlapping(data.as_ptr(), elements as *mut u8, data.len());
428                // Mode 0: commit and free.
429                release(*self, array, elements, 0);
430            }
431        }
432        array
433    }
434
435    // ── Natives and exceptions ──────────────────────────────────────────────
436
437    /// Bind Rust functions to a class's `native` methods.
438    pub fn register_natives(&self, class: JClass, methods: &[NativeMethod]) -> bool {
439        let f: unsafe extern "C" fn(Env, JClass, *const NativeMethod, i32) -> i32 =
440            self.f(slot::REGISTER_NATIVES);
441        let rc = unsafe { f(*self, class, methods.as_ptr(), methods.len() as i32) };
442        self.check_exception();
443        rc == 0
444    }
445
446    /// Wrap memory we own as a `java.nio.ByteBuffer` the VM can read.
447    ///
448    /// No copy is made, so the memory must outlive every use of the buffer —
449    /// which for a DEX means the life of the class loader built from it.
450    pub fn new_direct_byte_buffer(&self, data: *mut u8, len: usize) -> JObject {
451        let f: unsafe extern "C" fn(Env, *mut c_void, i64) -> JObject =
452            self.f(slot::NEW_DIRECT_BYTE_BUFFER);
453        unsafe { f(*self, data as *mut c_void, len as i64) }
454    }
455
456    pub fn exception_occurred(&self) -> JObject {
457        let f: unsafe extern "C" fn(Env) -> JObject = self.f(slot::EXCEPTION_OCCURRED);
458        unsafe { f(*self) }
459    }
460
461    pub fn exception_clear(&self) {
462        let f: unsafe extern "C" fn(Env) = self.f(slot::EXCEPTION_CLEAR);
463        unsafe { f(*self) };
464    }
465
466    pub fn exception_describe(&self) {
467        let f: unsafe extern "C" fn(Env) = self.f(slot::EXCEPTION_DESCRIBE);
468        unsafe { f(*self) };
469    }
470
471    pub fn throw_new(&self, class: JClass, message: &str) {
472        let message = cstring(message);
473        let f: unsafe extern "C" fn(Env, JClass, *const c_char) -> i32 = self.f(slot::THROW_NEW);
474        unsafe { f(*self, class, message.as_ptr()) };
475    }
476
477    /// Clear any pending exception.
478    ///
479    /// **A pending exception makes almost every later JNI call undefined**, so
480    /// every wrapper above clears before returning. The alternative — checking
481    /// at each call site — is the same work done less reliably.
482    pub fn check_exception(&self) -> bool {
483        let thrown = self.exception_occurred();
484        if thrown.is_null() {
485            return false;
486        }
487        // Printing the stack trace is invaluable when wiring a new call and
488        // noise everywhere else, so it is opt-in.
489        if std::env::var_os("WEBBLUETOOTH_JNI_TRACE").is_some() {
490            self.exception_describe();
491        }
492        self.exception_clear();
493        self.delete_local_ref(thrown);
494        true
495    }
496}
497
498/// A `JavaVM`, which unlike [`Env`] is valid on every thread.
499#[repr(transparent)]
500#[derive(Clone, Copy)]
501pub struct Vm(pub *mut *const [*const c_void; 8]);
502
503unsafe impl Send for Vm {}
504unsafe impl Sync for Vm {}
505
506mod vm_slot {
507    pub const DESTROY_JAVA_VM: usize = 3;
508    pub const ATTACH_CURRENT_THREAD: usize = 4;
509    pub const DETACH_CURRENT_THREAD: usize = 5;
510    pub const GET_ENV: usize = 6;
511    pub const ATTACH_CURRENT_THREAD_AS_DAEMON: usize = 7;
512}
513
514/// `JNI_VERSION_1_6`.
515pub const JNI_VERSION_1_6: i32 = 0x0001_0006;
516
517impl Vm {
518    #[inline]
519    fn f<T: Copy>(&self, index: usize) -> T {
520        unsafe {
521            let table = *self.0;
522            core::mem::transmute_copy(&(*table)[index])
523        }
524    }
525
526    /// The environment for this thread, if it is already attached.
527    pub fn env(&self) -> Option<Env> {
528        let f: unsafe extern "C" fn(Vm, *mut *mut c_void, i32) -> i32 = self.f(vm_slot::GET_ENV);
529        let mut env: *mut c_void = core::ptr::null_mut();
530        let rc = unsafe { f(*self, &mut env, JNI_VERSION_1_6) };
531        (rc == 0 && !env.is_null()).then_some(Env(env as *mut _))
532    }
533
534    /// Attach this thread, as a daemon so it never blocks VM shutdown.
535    pub fn attach(&self) -> Option<Env> {
536        if let Some(env) = self.env() {
537            return Some(env);
538        }
539        let f: unsafe extern "C" fn(Vm, *mut *mut c_void, *mut c_void) -> i32 =
540            self.f(vm_slot::ATTACH_CURRENT_THREAD_AS_DAEMON);
541        let mut env: *mut c_void = core::ptr::null_mut();
542        let rc = unsafe { f(*self, &mut env, core::ptr::null_mut()) };
543        (rc == 0 && !env.is_null()).then_some(Env(env as *mut _))
544    }
545
546    pub fn detach(&self) {
547        let f: unsafe extern "C" fn(Vm) -> i32 = self.f(vm_slot::DETACH_CURRENT_THREAD);
548        unsafe { f(*self) };
549        let _ = (vm_slot::DESTROY_JAVA_VM, vm_slot::ATTACH_CURRENT_THREAD);
550    }
551}
552
553/// A NUL-terminated copy, since JNI takes C strings throughout.
554fn cstring(s: &str) -> Vec<c_char> {
555    let mut out: Vec<c_char> = s.bytes().map(|b| b as c_char).collect();
556    out.push(0);
557    out
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    #[test]
565    fn jvalue_is_a_machine_word() {
566        // JNI passes arguments as an array of these; a wrong size shifts every
567        // argument after the first.
568        assert_eq!(core::mem::size_of::<JValue>(), 8);
569        assert_eq!(core::mem::align_of::<JValue>(), 8);
570    }
571
572    #[test]
573    fn native_method_struct_is_three_pointers() {
574        // struct JNINativeMethod { char* name; char* signature; void* fnPtr; }
575        assert_eq!(core::mem::size_of::<NativeMethod>(), 24);
576    }
577
578    #[test]
579    fn cstrings_are_nul_terminated() {
580        let s = cstring("abc");
581        assert_eq!(s.len(), 4);
582        assert_eq!(s[3], 0);
583        assert_eq!(cstring("")[0], 0);
584    }
585
586    #[test]
587    fn slot_indices_are_distinct() {
588        // A duplicate index means two names for one function — and one of them
589        // is wrong.
590        let indices = [
591            slot::GET_VERSION,
592            slot::FIND_CLASS,
593            slot::THROW_NEW,
594            slot::EXCEPTION_OCCURRED,
595            slot::EXCEPTION_DESCRIBE,
596            slot::EXCEPTION_CLEAR,
597            slot::PUSH_LOCAL_FRAME,
598            slot::POP_LOCAL_FRAME,
599            slot::NEW_GLOBAL_REF,
600            slot::DELETE_GLOBAL_REF,
601            slot::DELETE_LOCAL_REF,
602            slot::IS_SAME_OBJECT,
603            slot::ALLOC_OBJECT,
604            slot::NEW_OBJECT_A,
605            slot::GET_OBJECT_CLASS,
606            slot::GET_METHOD_ID,
607            slot::CALL_OBJECT_METHOD_A,
608            slot::CALL_BOOLEAN_METHOD_A,
609            slot::CALL_INT_METHOD_A,
610            slot::CALL_LONG_METHOD_A,
611            slot::CALL_VOID_METHOD_A,
612            slot::GET_STATIC_METHOD_ID,
613            slot::CALL_STATIC_OBJECT_METHOD_A,
614            slot::CALL_STATIC_INT_METHOD_A,
615            slot::CALL_STATIC_VOID_METHOD_A,
616            slot::GET_STATIC_FIELD_ID,
617            slot::GET_STATIC_OBJECT_FIELD,
618            slot::GET_STATIC_INT_FIELD,
619            slot::NEW_STRING_UTF,
620            slot::GET_STRING_UTF_CHARS,
621            slot::RELEASE_STRING_UTF_CHARS,
622            slot::GET_ARRAY_LENGTH,
623            slot::NEW_OBJECT_ARRAY,
624            slot::GET_OBJECT_ARRAY_ELEMENT,
625            slot::SET_OBJECT_ARRAY_ELEMENT,
626            slot::NEW_BYTE_ARRAY,
627            slot::GET_BYTE_ARRAY_ELEMENTS,
628            slot::RELEASE_BYTE_ARRAY_ELEMENTS,
629            slot::REGISTER_NATIVES,
630            slot::NEW_DIRECT_BYTE_BUFFER,
631        ];
632        let mut seen = std::collections::HashSet::new();
633        for i in indices {
634            assert!(i < 234, "slot {i} is past the end of JNINativeInterface_");
635            assert!(seen.insert(i), "slot {i} is named twice");
636        }
637    }
638}