rust-jni 0.1.0

A package for easy Java interop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use java_string::*;
use jni::*;
use jni_sys;
use std::cell::RefCell;
use std::panic;
use std::ptr;
use std::string;
use version;

/// Unsafe because an incorrect pointer can be passed as an argument.
unsafe fn throw_new_runtime_exception(raw_env: *mut jni_sys::JNIEnv, message: impl AsRef<str>) {
    let message = to_java_string(message.as_ref());
    let class_name = to_java_string("java/lang/RuntimeException");
    let find_class = (**raw_env).FindClass.unwrap();
    let class = find_class(raw_env, class_name.as_ptr() as *const i8);
    if class == ptr::null_mut() {
        panic!(
            "Could not find the java.lang.RuntimeException class on panic, aborting the program."
        );
    } else {
        let throw_new_fn = (**raw_env).ThrowNew.unwrap();
        let status = throw_new_fn(raw_env, class, message.as_ptr() as *const i8);
        if status != jni_sys::JNI_OK {
            panic!("Could not throw a new runtime exception on panic, aborting the program.");
        }
    }
}

/// A function to wrap calls to [`rust-jni`](index.html) API from generated native Java methods.
///
/// THIS FUNCTION SHOULD NOT BE CALLED MANUALLY.
///
/// This method should only be used by generated code for native methods and is unsafe
/// because an incorrect pointer can be passed to it as an argument.
#[doc(hidden)]
pub unsafe fn native_method_wrapper<T, R: JniType>(raw_env: *mut jni_sys::JNIEnv, callback: T) -> R
where
    T: for<'a> FnOnce(&'a JniEnv<'a>, NoException<'a>) -> JavaResult<'a, R> + panic::UnwindSafe,
{
    let result = panic::catch_unwind(|| {
        let exception_check = ((**raw_env).ExceptionCheck).unwrap();
        if exception_check(raw_env) != jni_sys::JNI_FALSE {
            panic!("Native method called from a thread with a pending exception.");
        }

        let mut java_vm: *mut jni_sys::JavaVM = ptr::null_mut();
        let get_java_vm_fn = ((**raw_env).GetJavaVM).unwrap();
        let status = get_java_vm_fn(raw_env, (&mut java_vm) as *mut *mut jni_sys::JavaVM);
        if status != jni_sys::JNI_OK {
            panic!(format!("Could not get Java VM. Status: {:?}", status));
        }

        // Safe because we pass a correct `java_vm` pointer.
        let vm = JavaVM::from_ptr(java_vm);
        let get_version_fn = ((**raw_env).GetVersion).unwrap();
        let env = JniEnv {
            version: version::from_raw(get_version_fn(raw_env)),
            vm: &vm,
            jni_env: raw_env,
            has_token: RefCell::new(true),
            native_method_call: true,
        };

        // Safe because we checked for a pending exception.
        let token = NoException::new_raw();
        let result = callback(&env, token);
        match result {
            Ok(result) => result,
            Err(exception) => {
                // Safe because we already cleared the pending exception at this point.
                let token = NoException::new_raw();
                exception.throw(token);
                R::default()
            }
        }
    });
    match result {
        Ok(result) => result,
        Err(error) => {
            if let Some(string) = error.downcast_ref::<string::String>() {
                throw_new_runtime_exception(raw_env, format!("Rust panic: {}", string));
            } else if let Some(string) = error.downcast_ref::<&str>() {
                throw_new_runtime_exception(raw_env, format!("Rust panic: {}", string));
            } else {
                throw_new_runtime_exception(raw_env, "Rust panic: generic panic.");
            }
            R::default()
        }
    }
}

#[cfg(test)]
mod native_method_wrapper_tests {
    use super::*;
    use jni::testing::*;
    use jni::throwable::test_throwable;

    #[test]
    fn success() {
        const JAVA_VM: *mut jni_sys::JavaVM = 0x1234 as *mut jni_sys::JavaVM;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_FALSE,
            }),
            JniCall::GetJavaVM(GetJavaVM {
                vm: JAVA_VM,
                result: jni_sys::JNI_OK,
            }),
            JniCall::GetVersion(GetVersion {
                result: jni_sys::JNI_VERSION_1_4,
            }),
        ]);
        let result = 10;
        unsafe {
            let actual_result = native_method_wrapper(calls.env, |env, _| {
                assert_eq!(env.raw_env(), calls.env);
                assert_eq!(env.raw_jvm(), JAVA_VM);
                assert_eq!(env.version(), JniVersion::V4);
                Ok(result)
            });
            assert_eq!(actual_result, result);
        }
    }

    #[test]
    fn exception() {
        const EXCEPTION: jni_sys::jobject = 0x2835 as jni_sys::jobject;
        const JAVA_VM: *mut jni_sys::JavaVM = 0x1234 as *mut jni_sys::JavaVM;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_FALSE,
            }),
            JniCall::GetJavaVM(GetJavaVM {
                vm: JAVA_VM,
                result: jni_sys::JNI_OK,
            }),
            JniCall::GetVersion(GetVersion {
                result: jni_sys::JNI_VERSION_1_4,
            }),
            JniCall::Throw(Throw {
                object: EXCEPTION,
                result: jni_sys::JNI_OK,
            }),
            JniCall::DeleteLocalRef(DeleteLocalRef { object: EXCEPTION }),
        ]);
        unsafe {
            let result: i32 = native_method_wrapper(calls.env, |env, _| {
                assert_eq!(env.raw_env(), calls.env);
                assert_eq!(env.raw_jvm(), JAVA_VM);
                assert_eq!(env.version(), JniVersion::V4);
                Err(test_throwable(env, EXCEPTION))
            });
            assert_eq!(result, <i32 as JniType>::default());
        }
    }

    #[test]
    fn panic() {
        const RAW_CLASS: jni_sys::jobject = 0x209375 as jni_sys::jobject;
        const JAVA_VM: *mut jni_sys::JavaVM = 0x1234 as *mut jni_sys::JavaVM;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_FALSE,
            }),
            JniCall::GetJavaVM(GetJavaVM {
                vm: JAVA_VM,
                result: jni_sys::JNI_OK,
            }),
            JniCall::GetVersion(GetVersion {
                result: jni_sys::JNI_VERSION_1_4,
            }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: RAW_CLASS,
            }),
            JniCall::ThrowNew(ThrowNew {
                class: RAW_CLASS,
                message: "Rust panic: ERROR".to_owned(),
                result: jni_sys::JNI_OK,
            }),
        ]);
        unsafe {
            let actual_result: i32 = native_method_wrapper(calls.env, |env, _| {
                assert_eq!(env.raw_env(), calls.env);
                assert_eq!(env.raw_jvm(), JAVA_VM);
                assert_eq!(env.version(), JniVersion::V4);
                panic!("ERROR");
            });
            assert_eq!(actual_result, <i32 as JniType>::default());
        }
    }

    #[test]
    fn panic_owned() {
        const RAW_CLASS: jni_sys::jobject = 0x209375 as jni_sys::jobject;
        const JAVA_VM: *mut jni_sys::JavaVM = 0x1234 as *mut jni_sys::JavaVM;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_FALSE,
            }),
            JniCall::GetJavaVM(GetJavaVM {
                vm: JAVA_VM,
                result: jni_sys::JNI_OK,
            }),
            JniCall::GetVersion(GetVersion {
                result: jni_sys::JNI_VERSION_1_4,
            }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: RAW_CLASS,
            }),
            JniCall::ThrowNew(ThrowNew {
                class: RAW_CLASS,
                message: "Rust panic: ERROR".to_owned(),
                result: jni_sys::JNI_OK,
            }),
        ]);
        unsafe {
            let actual_result: i32 = native_method_wrapper(calls.env, |env, _| {
                assert_eq!(env.raw_env(), calls.env);
                assert_eq!(env.raw_jvm(), JAVA_VM);
                assert_eq!(env.version(), JniVersion::V4);
                panic!("ERROR".to_owned());
            });
            assert_eq!(actual_result, <i32 as JniType>::default());
        }
    }

    #[test]
    fn non_string_panic() {
        const RAW_CLASS: jni_sys::jobject = 0x209375 as jni_sys::jobject;
        const JAVA_VM: *mut jni_sys::JavaVM = 0x1234 as *mut jni_sys::JavaVM;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_FALSE,
            }),
            JniCall::GetJavaVM(GetJavaVM {
                vm: JAVA_VM,
                result: jni_sys::JNI_OK,
            }),
            JniCall::GetVersion(GetVersion {
                result: jni_sys::JNI_VERSION_1_4,
            }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: RAW_CLASS,
            }),
            JniCall::ThrowNew(ThrowNew {
                class: RAW_CLASS,
                message: "Rust panic: generic panic.".to_owned(),
                result: jni_sys::JNI_OK,
            }),
        ]);
        unsafe {
            let actual_result: i32 = native_method_wrapper(calls.env, |_, _| {
                panic!(123);
            });
            assert_eq!(actual_result, <i32 as JniType>::default());
        }
    }

    #[test]
    fn has_exception() {
        const RAW_CLASS: jni_sys::jobject = 0x209375 as jni_sys::jobject;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_TRUE,
            }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: RAW_CLASS,
            }),
            JniCall::ThrowNew(ThrowNew {
                class: RAW_CLASS,
                message: "Rust panic: Native method called from a thread with a pending exception."
                    .to_owned(),
                result: jni_sys::JNI_OK,
            }),
        ]);
        unsafe {
            let result = native_method_wrapper(calls.env, |_, _| Ok(10));
            assert_eq!(result, <i32 as JniType>::default());
        }
    }

    #[test]
    fn get_java_vm_error() {
        const RAW_CLASS: jni_sys::jobject = 0x209375 as jni_sys::jobject;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_FALSE,
            }),
            JniCall::GetJavaVM(GetJavaVM {
                vm: ptr::null_mut(),
                result: jni_sys::JNI_ERR,
            }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: RAW_CLASS,
            }),
            JniCall::ThrowNew(ThrowNew {
                class: RAW_CLASS,
                message: "Rust panic: Could not get Java VM. Status: -1".to_owned(),
                result: jni_sys::JNI_OK,
            }),
        ]);
        unsafe {
            let result = native_method_wrapper(calls.env, |_, _| Ok(10));
            assert_eq!(result, <i32 as JniType>::default());
        }
    }

    #[test]
    fn throw_failed() {
        const RAW_CLASS: jni_sys::jobject = 0x209375 as jni_sys::jobject;
        const EXCEPTION: jni_sys::jobject = 0x2835 as jni_sys::jobject;
        const JAVA_VM: *mut jni_sys::JavaVM = 0x1234 as *mut jni_sys::JavaVM;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_FALSE,
            }),
            JniCall::GetJavaVM(GetJavaVM {
                vm: JAVA_VM,
                result: jni_sys::JNI_OK,
            }),
            JniCall::GetVersion(GetVersion {
                result: jni_sys::JNI_VERSION_1_4,
            }),
            JniCall::Throw(Throw {
                object: EXCEPTION,
                result: jni_sys::JNI_ERR,
            }),
            JniCall::DeleteLocalRef(DeleteLocalRef { object: EXCEPTION }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: RAW_CLASS,
            }),
            JniCall::ThrowNew(ThrowNew {
                class: RAW_CLASS,
                message: "Rust panic: Throwing an exception has failed with status -1.".to_owned(),
                result: jni_sys::JNI_OK,
            }),
        ]);
        unsafe {
            let result: i32 =
                native_method_wrapper(calls.env, |env, _| Err(test_throwable(env, EXCEPTION)));
            assert_eq!(result, <i32 as JniType>::default());
        }
    }

    #[test]
    #[should_panic(
        expected = "Could not find the java.lang.RuntimeException class on panic, aborting the program"
    )]
    fn find_class_error() {
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_TRUE,
            }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: ptr::null_mut(),
            }),
        ]);
        unsafe {
            native_method_wrapper(calls.env, |_, _| Ok(10));
        }
    }

    #[test]
    #[should_panic(
        expected = "Could not throw a new runtime exception on panic, aborting the program"
    )]
    fn throw_new_error() {
        const RAW_CLASS: jni_sys::jobject = 0x209375 as jni_sys::jobject;
        let calls = test_raw_jni_env!(vec![
            JniCall::ExceptionCheck(ExceptionCheck {
                result: jni_sys::JNI_TRUE,
            }),
            JniCall::FindClass(FindClass {
                name: "java/lang/RuntimeException".to_owned(),
                result: RAW_CLASS,
            }),
            JniCall::ThrowNew(ThrowNew {
                class: RAW_CLASS,
                message: "Rust panic: Native method called from a thread with a pending exception."
                    .to_owned(),
                result: jni_sys::JNI_ERR,
            }),
        ]);
        unsafe {
            native_method_wrapper(calls.env, |_, _| Ok(10));
        }
    }
}

/// Test that a value implements the [`JniArgumentType`](trait.JniArgumentType.html)
/// in compile-time.
///
/// THIS FUNCTION SHOULD NOT BE CALLED MANUALLY.
///
/// # Examples
/// ```
/// # extern crate rust_jni;
/// # extern crate jni_sys;
/// ::rust_jni::__generator::test_jni_argument_type(0 as ::jni_sys::jint);
/// ```
/// ```compile_fail
/// # extern crate rust_jni;
/// ::rust_jni::__generator::test_jni_argument_type(0 as u64);
/// ```
#[doc(hidden)]
pub fn test_jni_argument_type<T: JniArgumentType>(_value: T) {}

/// Test that a value implements the [`FromJni`](trait.FromJni.html)
/// in compile-time.
///
/// THIS FUNCTION SHOULD NOT BE CALLED MANUALLY.
///
/// # Examples
/// ```
/// # extern crate rust_jni;
/// # extern crate jni_sys;
/// ::rust_jni::__generator::test_from_jni_type(&(0 as i32));
/// ```
/// ```compile_fail
/// # extern crate rust_jni;
/// ::rust_jni::__generator::test_from_jni_type(&(0 as u64));
/// ```
#[doc(hidden)]
pub fn test_from_jni_type<'env, T: FromJni<'env>>(_value: &T) {}