jni 0.22.4

Rust bindings to the JNI
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
use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::Env;

#[cfg(doc)]
use crate::{EnvOutcome, Outcome, errors::Error};

/// A policy for handling [`EnvOutcome`] errors and panics that may occur within a native method.
///
/// This trait allows customization of error handling strategies, such as throwing Java exceptions,
/// logging errors, or returning error codes. Implementors can define how to respond to errors and
/// panics, providing flexibility in managing native method outcomes.
///
/// Specify a policy by using the `resolve` or `resolve_with` methods on [`EnvOutcome`].
///
/// Some standard policies are provided in this crate, such as [`ThrowRuntimeExAndDefault`] which throws
/// a Java exception for any Rust error or panic, returning `null` or `0` as a default value.
///
/// For example use like:
/// ```rust,no_run
/// # use jni::{Env, EnvUnowned, EnvOutcome};
/// # use jni::objects::JObject;
/// #[unsafe(no_mangle)]
/// pub extern "system" fn Java_HelloWorld_hello<'local>(mut unowned_env: EnvUnowned<'local>) -> JObject<'local> {
///     unowned_env.with_env(|env| -> jni::errors::Result<JObject> {
///         // do stuff that might fail or panic
///         Ok(JObject::null()) // placeholder
///     }).resolve::<jni::errors::ThrowRuntimeExAndDefault>()
/// }
/// ```
///
/// In some situations your error or panic handling may need to capture some state from the native
/// method, including references associated with the local reference frame.
///
/// To capture state your policy can define the associated type `Captures` to be some type
/// that can borrow from the JNI local reference frame and from the native method scope itself.
///
/// If your policy needs to capture state then you would use `resolve_with` to provide a closure
/// that builds the captures.
///
/// For example, implement a policy that captures state like:
/// ```rust,no_run
/// # use jni::{Env, EnvUnowned, EnvOutcome};
/// # use jni::objects::JObject;
/// # use jni::errors::{Error, ErrorPolicy};
/// struct CustomPolicyCaptures<'local, 'native_method>
/// where
///     'local: 'native_method,
/// {
///     context: &'native_method JObject<'local>, // capture a local reference
/// }
///
/// struct CustomPolicy;
///
/// impl<T: Default, E: std::error::Error> jni::errors::ErrorPolicy<T, E> for CustomPolicy {
///     type Captures<'unowned_env_local: 'native_method, 'native_method> = CustomPolicyCaptures<'unowned_env_local, 'native_method>;
///     fn on_error<'unowned_env_local: 'native_method, 'native_method>(
///         env: &mut Env<'unowned_env_local>,
///         cap: &mut CustomPolicyCaptures<'unowned_env_local, 'native_method>,
///         err: E,
///     ) -> jni::errors::Result<T> {
///         // Handle the error, possibly throwing a Java exception
///         eprintln!("Error: {:?}", err);
///         // Return a default value or take other appropriate action
///         Ok(T::default())
///     }
///     fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
///         env: &mut Env<'unowned_env_local>,
///         cap: &mut CustomPolicyCaptures<'unowned_env_local, 'native_method>,
///         payload: Box<dyn std::any::Any + Send + 'static>,
///     ) -> jni::errors::Result<T> {
///         // Handle the panic, possibly throwing a Java exception
///         eprintln!("Panic: {:?}", payload);
///         // Return a default value or take other appropriate action
///         Ok(T::default())
///     }
/// }
///
/// // Then use the policy in a native method, capturing state like:
/// #[unsafe(no_mangle)]
/// pub extern "system" fn Java_HelloWorld_hello<'local>(
///     mut unowned_env: EnvUnowned<'local>,
///     _this: JObject<'local>,
///     context: JObject<'local>,
/// ) -> JObject<'local> {
///    unowned_env.with_env(|env| -> jni::errors::Result<JObject> {
///       // do stuff that might fail or panic
///       Ok(JObject::null()) // placeholder
///    }).resolve_with::<CustomPolicy, _>(|| {
///       // capture state from the native method scope or from the JNI local reference frame
///       CustomPolicyCaptures::<'local, '_> {
///           context: &context, // capture a local reference
///       }
///   })
/// }
/// ```
pub trait ErrorPolicy<T, E> {
    /// Per-call captures; may borrow from the JNI local reference frame
    /// associated with the native method and from the native method scope
    /// itself.
    type Captures<'unowned_env_local: 'native_method, 'native_method>;

    /// Runs for any [`Outcome::Err`].
    ///
    /// This must map the error to some value that can be returned by the native
    /// method and may be used to throw a Java exception or log the error.
    ///
    /// If this returns an `Err` then `on_internal_jni_error` will be called.
    ///
    /// If this panics then `on_internal_panic` will be called.
    fn on_error<'unowned_env_local: 'native_method, 'native_method>(
        env: &mut Env<'unowned_env_local>,
        cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
        err: E,
    ) -> crate::errors::Result<T>;

    /// Runs for any [`Outcome::Panic`].
    ///
    /// This must return some value that can be returned by the native
    /// method and can be used to throw a Java exception or log the panic
    ///
    /// If this returns an `Err` then `on_internal_jni_error` will be called.
    ///
    /// If this panics then `on_internal_panic` will be called.
    fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
        env: &mut Env<'unowned_env_local>,
        captures: &mut Self::Captures<'unowned_env_local, 'native_method>,
        payload: Box<dyn std::any::Any + Send + 'static>,
    ) -> crate::errors::Result<T>;

    /// Runs if a JNI error occurs within `on_error` or `on_panic`.
    fn on_internal_jni_error<'unowned_env_local: 'native_method, 'native_method>(
        _captures: &mut Self::Captures<'unowned_env_local, 'native_method>,
        err: crate::errors::Error,
    ) -> T
    where
        T: Default,
    {
        log::error!(
            "Secondary failure while handling error or panic in native method: {:?}",
            err
        );
        T::default()
    }

    /// Runs if we panic within `on_error`, `on_panic` or `on_internal_jni_error`
    fn on_internal_panic<'unowned_env_local: 'native_method, 'native_method>(
        _captures: &mut Self::Captures<'unowned_env_local, 'native_method>,
        _payload: Box<dyn std::any::Any + Send + 'static>,
    ) -> T
    where
        T: Default,
    {
        log::error!("Last resort: panic while handling error or panic in native method");
        T::default()
    }
}

/// An error policy that throws `java.lang.RuntimeException` for any Rust error
/// or panic, returning `null` or `0` as a default value.
///
/// If an exception is already pending when an error or panic occurs then that
/// takes precedence and no new exception will be thrown and a default value
/// will be returned.
///
/// Note: pending exceptions are determined by calling [`Env::exception_check`],
/// and not by checking the error type since this is generic over all error
/// types and has no way to downcast to check for [`Error::JavaException`].
///
/// For example use like:
/// ```rust,no_run
/// # use jni::{Env, EnvUnowned, EnvOutcome};
/// # use jni::objects::JObject;
/// #[unsafe(no_mangle)]
/// pub extern "system" fn Java_HelloWorld_hello<'local>(
///     mut unowned_env: EnvUnowned<'local>,
///     _this: JObject<'local>,
/// ) -> JObject<'local> {
///     unowned_env.with_env(|env| -> jni::errors::Result<JObject> {
///         // do stuff that might fail or panic
///         Ok(JObject::null()) // placeholder
///     }).resolve::<jni::errors::ThrowRuntimeExAndDefault>()
/// }
/// ```
#[derive(Debug, Default)]
pub struct ThrowRuntimeExAndDefault;

impl<T: Default, E: std::error::Error> ErrorPolicy<T, E> for ThrowRuntimeExAndDefault {
    type Captures<'unowned_env_local: 'native_method, 'native_method> = (); // no captures

    fn on_error<'unowned_env_local: 'native_method, 'native_method>(
        env: &mut Env<'unowned_env_local>,
        _cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
        err: E,
    ) -> crate::errors::Result<T> {
        if env.exception_check() {
            return Ok(T::default()); // already thrown
        }
        let err_string = format!("Rust error: {}", err);
        // Note: `env.throw()` will return `Err(Error::JavaException)` after throwing but in this case
        // (where we are going to be letting the exception propagate to Java), we want to ensure we
        // don't return that as an error
        let _ = env.throw(err_string);
        Ok(T::default())
    }

    fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
        env: &mut Env<'unowned_env_local>,
        _cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
        payload: Box<dyn std::any::Any + Send + 'static>,
    ) -> crate::errors::Result<T> {
        let panic_string = match payload.downcast::<&'static str>() {
            Ok(s) => (*s).to_string(),
            Err(payload) => {
                // Since it's possible that dropping a panic payload may itself panic,
                // we catch any panic and fallback to forgetting/leaking the payload.
                if let Err(drop_panic) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
                    log::error!("Panic while dropping panic payload: {:?}", drop_panic);
                    std::mem::forget(drop_panic);
                }
                "non-string panic payload".to_string()
            }
        };

        // Note: `env.throw()` will return `Err(Error::JavaException)` after throwing but in this case
        // (where we are going to be letting the exception propagate to Java), we want to ensure we
        // don't return that as an error
        let _ = env.throw(format!("Rust panic: {}", panic_string));
        Ok(T::default())
    }
}

/// An error policy that logs errors and panics before returning a default value.
///
/// Error logs and panic messages are formatted like: "Rust error: {message}" or
/// "Rust panic: {message}" before returning a default value.
#[derive(Debug, Default)]
pub struct LogErrorAndDefault;

impl<T: Default, E: std::error::Error> ErrorPolicy<T, E> for LogErrorAndDefault {
    type Captures<'unowned_env_local: 'native_method, 'native_method> = (); // no captures

    fn on_error<'unowned_env_local: 'native_method, 'native_method>(
        _env: &mut Env<'unowned_env_local>,
        _cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
        err: E,
    ) -> crate::errors::Result<T> {
        log::error!("Rust error: {}", err);
        Ok(T::default())
    }

    fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
        _env: &mut Env<'unowned_env_local>,
        _cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
        payload: Box<dyn std::any::Any + Send + 'static>,
    ) -> crate::errors::Result<T> {
        let panic_string = match payload.downcast::<&'static str>() {
            Ok(s) => (*s).to_string(),
            Err(payload) => {
                // Since it's possible that dropping a panic payload may itself panic,
                // we catch any panic and fallback to forgetting/leaking the payload.
                if let Err(drop_panic) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
                    log::error!("Panic while dropping panic payload: {:?}", drop_panic);
                    std::mem::forget(drop_panic);
                }
                "non-string panic payload".to_string()
            }
        };
        log::error!("Rust panic: {}", panic_string);
        Ok(T::default())
    }
}

/// An error policy that logs errors and panics along with a context string
/// before returning a default value.
///
/// For example it can be used like:
/// ```rust,no_run
/// # use jni::{Env, EnvUnowned, EnvOutcome};
/// # use jni::objects::{JClass, JObject, JString};
/// # use jni::errors::{Error, ErrorPolicy};
/// #[unsafe(no_mangle)]
/// pub extern "system" fn Java_HelloWorld_logErrorWithContextString<'local>(
///     mut unowned_env: EnvUnowned<'local>,
///     _this: JObject<'local>,
///     context: JObject<'local>,
///     arg: JString<'local>,
/// ) -> JClass<'local> {
///    unowned_env.with_env(|env| -> jni::errors::Result<JClass> {
///       // do stuff that might fail or panic
///       let class = env.get_object_class(&context)?;
///       Ok(class) // placeholder
///    }).resolve_with::<jni::errors::LogContextErrorAndDefault, _>(|| {
///       format!("In 'logErrorWithContextString' with arg: {arg}")
///   })
/// }
/// ```
///
/// Error logs and panic messages are formatted like: "{context}: {message}"
/// before returning a default value.
#[derive(Debug, Default)]
pub struct LogContextErrorAndDefault;

impl<T: Default, E: std::error::Error> ErrorPolicy<T, E> for LogContextErrorAndDefault {
    type Captures<'unowned_env_local: 'native_method, 'native_method> = String;

    fn on_error<'unowned_env_local: 'native_method, 'native_method>(
        _env: &mut Env<'unowned_env_local>,
        cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
        err: E,
    ) -> crate::errors::Result<T> {
        log::error!("{cap}: {err}");
        Ok(T::default())
    }

    fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
        _env: &mut Env<'unowned_env_local>,
        cap: &mut Self::Captures<'unowned_env_local, 'native_method>,
        payload: Box<dyn std::any::Any + Send + 'static>,
    ) -> crate::errors::Result<T> {
        let panic_string = match payload.downcast::<&'static str>() {
            Ok(s) => (*s).to_string(),
            Err(payload) => {
                // Since it's possible that dropping a panic payload may itself panic,
                // we catch any panic and fallback to forgetting/leaking the payload.
                if let Err(drop_panic) = catch_unwind(AssertUnwindSafe(|| drop(payload))) {
                    log::error!("Panic while dropping panic payload: {:?}", drop_panic);
                    std::mem::forget(drop_panic);
                }
                "non-string panic payload".to_string()
            }
        };
        log::error!("{cap}: {panic_string}");
        Ok(T::default())
    }
}

// Smoke test implementation for a custom policy that captures a local reference
#[cfg(test)]
mod tests {
    use crate::{
        EnvUnowned,
        objects::{JClass, JObject, JString},
    };

    use super::*;
    struct TestCustomPolicyCaptures<'local, 'native_method>
    where
        'local: 'native_method,
    {
        context: &'native_method JObject<'local>, // capture a local reference
    }

    struct TestCustomPolicy;

    impl<T: Default, E: std::error::Error> ErrorPolicy<T, E> for TestCustomPolicy {
        type Captures<'unowned_env_local: 'native_method, 'native_method> =
            TestCustomPolicyCaptures<'unowned_env_local, 'native_method>;

        fn on_error<'unowned_env_local: 'native_method, 'native_method>(
            _env: &mut Env<'unowned_env_local>,
            cap: &mut TestCustomPolicyCaptures<'unowned_env_local, 'native_method>,
            err: E,
        ) -> crate::errors::Result<T> {
            // Handle the error, possibly throwing a Java exception
            eprintln!("Error: {:?}, context: {:?}", err, cap.context);
            // You can access cap.context here
            Ok(T::default())
        }

        fn on_panic<'unowned_env_local: 'native_method, 'native_method>(
            _env: &mut Env<'unowned_env_local>,
            _cap: &mut TestCustomPolicyCaptures<'unowned_env_local, 'native_method>,
            payload: Box<dyn std::any::Any + Send + 'static>,
        ) -> crate::errors::Result<T> {
            // Handle the panic, possibly throwing a Java exception
            eprintln!("Panic: {:?}", payload);
            // You can access cap.context here
            Ok(T::default())
        }
    }

    #[unsafe(no_mangle)]
    pub extern "system" fn Java_HelloWorld_test<'local>(
        mut unowned_env: EnvUnowned<'local>,
        _this: JObject<'local>,
        context: JObject<'local>,
    ) -> JClass<'local> {
        unowned_env
            .with_env(|env| -> crate::errors::Result<_> {
                // do stuff that might fail or panic
                // for the sake of testing, use the context that will also be captured
                let class = env.get_object_class(&context)?;
                Ok(class)
            })
            .resolve_with::<TestCustomPolicy, _>(|| {
                // capture state from the native method scope or from the JNI local reference frame
                TestCustomPolicyCaptures::<'local, '_> {
                    context: &context, // capture a local reference
                }
            })
    }

    #[unsafe(no_mangle)]
    pub extern "system" fn Java_HelloWorld_logErrorWithContextString<'local>(
        mut unowned_env: EnvUnowned<'local>,
        _this: JObject<'local>,
        context: JObject<'local>,
        arg: JString<'local>,
    ) -> JClass<'local> {
        unowned_env
            .with_env(|env| -> crate::errors::Result<_> {
                // do stuff that might fail or panic
                // for the sake of testing, use the context that will also be captured
                let class = env.get_object_class(&context)?;
                Ok(class)
            })
            .resolve_with::<LogContextErrorAndDefault, _>(|| {
                format!("In 'logErrorWithContextString' with arg: {arg}")
            })
    }
}