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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// TODO: https://github.com/jni-rs/jni-rs/issues/348
//! # Safe JNI Bindings in Rust
//!
//! This crate provides a (mostly) safe way to interface with Java and Kotlin
//! using the Java Native Interface (JNI).
//!
//! ## Getting Started by implementing a native method
//!
//! Lets write some Java code that defines a native method and then implement it
//! in Rust.
//!
//! ### The Java side
//!
//! First, you need a Java class definition. `HelloWorld.java`:
//!
//! ```java
//! class HelloWorld {
//! // This declares that the static `hello` method will be provided
//! // by a native library.
//! private static native String hello(String input);
//!
//! static {
//! // This actually loads the shared object that we'll be creating.
//! // The actual location of the .so or .dll may differ based on your
//! // platform.
//! System.loadLibrary("mylib");
//! }
//!
//! // The rest is just regular ol' Java!
//! public static void main(String[] args) {
//! String output = HelloWorld.hello("World");
//! System.out.println(output);
//! }
//! }
//! ```
//!
//! Compile this to a class file with `javac HelloWorld.java`.
//!
//! Trying to run it now will give us the error `Exception in thread "main"
//! java.lang.UnsatisfiedLinkError: no mylib in java.library.path` since we
//! haven't written our native code yet.
//!
//! ### The Rust side
//!
//! There are two approaches to implementing a native method in Rust.
//!
//! In either case you first need to implement an `extern "system"` function
//! that accepts the appropriate arguments and has a matching return type.
//!
//! And then to make the implementation visible to the JVM you can either:
//! 1. Export the function from a shared library with a mangled name that the
//! JVM can look up.
//! 2. You can use the JNI API to explicitly register the implementation with
//! the JVM at runtime using [`Env::register_native_methods`] (in this case
//! the function name doesn't need to be mangled or exported from a shared
//! library)
//!
//! The arguments and return type for a native method implementation are
//! documented in the JNI specification under "Design" -> "Native Method
//! Arguments"
//!
//! <https://docs.oracle.com/en/java/javase/11/docs/specs/jni/design.html#native-method-arguments>
//!
//! which can be summarized as:
//!
//! - The first argument is always an implicit JNI environment pointer that
//! represents the current thread's attachment to the Java VM
//! - Use [`jni::EnvUnowned`] to capture this
//! - Next, if the native method is static, the second argument is a reference
//! to the class that owns the method.
//! - Use [`jni::objects::JClass`] in this case
//! - Alternatively, use [`jni::sys::jclass`] if you want to work with the
//! raw JNI type.
//! - Else, if the native method is non-static, the second argument is a `this`
//! object reference
//! - Use [`jni::objects::JObject`] or a more specific reference type like
//! [`jni::objects::JString`] in this case
//! - Alternatively, use [`jni::sys::jobject`] if you want to work with the
//! raw JNI type.
//! - The rest of the arguments are the Java arguments passed to the method:
//! - Java primitive types are passed as their corresponding JNI types (e.g.
//! [`jni::sys::jint`] for `int`)
//! - Java object types are passed as their corresponding JNI reference
//! types (e.g. `jni::objects::JString` for `java.lang.String`)
//! - Alternatively you can use the raw [`jni::sys::jobject`] type for Java
//! object arguments if you want to work with the raw JNI types.
//! - The return type is the Java return type mapped in the same way as the
//! arguments
//!
//! #### Exporting a native method from a shared library
//!
//! Create your crate with `cargo new mylib`. This will create a directory
//! `mylib` that has everything needed to build a basic crate with `cargo`. We
//! need to make a couple of changes to `Cargo.toml` before we do anything else.
//!
//! * Under `[dependencies]`, add `jni = "0.22"`
//! * Add a new `[lib]` section and under it, `crate-type = ["cdylib"]`.
//!
//! Now, if you run `cargo build` from inside the crate directory, you should
//! see a `libmylib.so` (if you're on Linux) or a `libmylib.dylib` (if you are
//! on macOS) in the `target/debug` directory.
//!
//! The last thing we need to do is implement our native method.
//!
//! As an illustration, we'll avoid using any of the helper macros (like
//! [`jni::jni_mangle`] or [`jni::native_method`]) so it's clear how the
//! underlying API works.
//!
//! Add this to your crate's `src/lib.rs`:
//!
//! ```rust,no_run
//! // As we are going to implement a native method in Rust, the JVM is going
//! // to pass us a `jni_sys::JNIEnv` pointer that implicitly represents
//! // an attachment of the current thread to the Java VM.
//! //
//! // `EnvUnowned` is an FFI-safe type that lets us capture the pointer and also
//! // associate the caller's JNI stack frame with a lifetime.
//! //
//! // IMPORTANT: The first thing a native method must do is to upgrade this into
//! // an `Env`, which has a side effect of ensuring the `jni-rs` crate is initialized
//! // before any other JNI calls are made.
//! use jni::EnvUnowned;
//!
//! // This is the JNI environment interface we'll call the majority of our methods on.
//! use jni::Env;
//!
//! // These objects are what you should use as arguments to your native
//! // function. They carry extra lifetime information to prevent them escaping
//! // this context and getting used after being GC'd.
//! use jni::objects::{JClass, JString};
//!
//! // This type represents an owned, JNI-compatible string.
//! use jni::strings::JNIString;
//!
//! // This keeps Rust from "mangling" the name and making it unique for this crate.
//! #[unsafe(no_mangle)]
//! pub extern "system" fn Java_HelloWorld_hello<'caller>(
//! // This captures the raw `jni_sys::JNIEnv` pointer and associates it with the
//! // caller's JNI stack frame lifetime.
//! mut unowned_env: EnvUnowned<'caller>,
//! // This is the class that owns our static method. It's not going to be used,
//! // but still must be present to match the expected signature of a static
//! // native method.
//! //
//! // If we were implementing a non-static native method then this would be
//! // a `this: JObject<'caller>`, serving as a reference to the instance.
//! class: JClass<'caller>,
//! input: JString<'caller>)
//! -> JString<'caller>
//! {
//! // Before we can access JNI, jni-rs needs to know that the thread is
//! // attached to the Java VM.
//! //
//! // Within a native method we can assume the JVM attaches the thread
//! // before calling our implementation, and this is represented
//! // by the EnvUnowned type.
//! //
//! // We use `with_env` to upgrade the EnvUnowned to a Env, which gives us
//! // access to the full JNI API.
//! //
//! // IMPORTANT: Don't use `jni-rs` in any other way within a native method
//! // until you call `unowned_env.with_env` or `AttachGuard::from_unowned`.
//! //
//! // Internally `with_env()` creates a hidden `AttachGuard`` to track the thread
//! // attachment explicitly and this will also wrap the given closure with
//! // `catch_unwind` to ensure that your code can't panic and unwind across
//! // FFI boundaries.
//! let outcome = unowned_env.with_env(|env| -> Result<_, jni::errors::Error> {
//! // First, we have to get the string out of Java. Check out the `strings`
//! // module for more info on how this works.
//! let input: String = input.to_string();
//! // Then we have to create a new Java string to return. Again, more info
//! // in the `strings` module.
//! JString::from_str(env, format!("Hello, {}!", input))
//! });
//!
//! // Finally, we have to resolve the `EnvOutcome` into a concrete return value.
//! //
//! // Our code above may have failed with a JNI error, or some other
//! // application-specific error, or it may have panicked. None of these things
//! // can pass over the FFI boundary back into the JVM.
//! //
//! // Mapping of errors and panics is done according to the selected
//! // `ErrorPolicy` trait implementation which is able to use JNI for throwing
//! // Java exceptions if necessary.
//! //
//! // This design lets you encapsulate your own approach to forwarding errors
//! // and panics to Java code and then easily reuse it across multiple native
//! // methods.
//! //
//! // In this case we use a built-in policy that throws a Java
//! // `RuntimeException` with a message containing the error/panic details.
//! outcome.resolve::<jni::errors::ThrowRuntimeExAndDefault>()
//! }
//! ```
//!
//! The `Java_HelloWorld_hello` function name was mangled according to the JNI
//! Specification, under "Design" -> "Resolving Native Method Names"
//!
//! <https://docs.oracle.com/en/java/javase/11/docs/specs/jni/design.html#resolving-native-method-names>
//!
//! To avoid having to manually mangle the function name, the
//! [`jni::jni_mangle`], [`jni::native_method`] and [`jni::bind_java_type`]
//! macros can all handle this for you.
//!
//! ### Final steps
//!
//! That's it! Build your crate and try to run your Java class again.
//!
//! ... Same error as before you say? Well that's because JVM is looking for
//! `mylib` in all the wrong places. To tell it where to look you can pass this
//! argument to `java`: `-Djava.library.path=/path/to/mylib/target/debug`. Now,
//! you should get the expected output `Hello, World!` from your Java class.
//!
//! For reference you can find this example in the
//! [`mylib-example`][jni-rs-mylib-example] directory of this repository:
//!
//! ## Launching JVM from Rust
//!
//! It is possible to launch a JVM from a native process using the [Invocation
//! API], provided by [`JavaVM`].
//!
//! ## See Also
//!
//! ### Examples
//! - The [examples directory][jni-rs-examples] in this repository contains a
//! variety of examples that illustrate the utility macros provided by this
//! crate.
//! - [Example mylib project][jni-rs-mylib-example] (as illustrated above)
//! - Our [integration tests][jni-rs-its] and [benchmarks][jni-rs-benches]
//!
//! ### Macros
//! - [`jni_str!`] for compile-time encoding of JNI strings
//! - [`jni_sig!`] for compile-time encoding of JNI type signatures
//! - [`bind_java_type`] for generating full Rust bindings for Java types
//! - [`native_method`] for individual native method bindings
//! - [`jni_mangle`] for mangling native method names
//!
//! ### JNI Documentation
//! - [Java Native Interface Specification][jni-spec]
//! - [JNI tips][jni-tips] — general tips on JNI development and some
//! Android-specific
//!
//! ### Open-Source Users
//! - The Servo browser engine Android [port][users-servo]
//! - The Exonum framework [Java Binding][users-ejb]
//! - MaidSafe [Java Binding][users-maidsafe]
//!
//! ### Other Projects Simplifying Java and Rust Communication
//! - Consider [JNR][projects-jnr] if you just need to use a native library with
//! C interface
//! - Watch OpenJDK [Project Panama][projects-panama] which aims to enable using
//! native libraries with no JNI code
//! - Consider [GraalVM][projects-graalvm] — a recently released VM that gives
//! zero-cost interoperability between various languages (including Java and
//! [Rust][graalvm-rust] compiled into LLVM-bitcode)
//! - See a [plugin](https://github.com/questdb/rust-maven-plugin/) for invoking
//! cargo from Java Maven builds
//!
//! [Invocation API]:
//! https://docs.oracle.com/en/java/javase/21/docs/specs/jni/invocation.html
//! [jni-spec]:
//! https://docs.oracle.com/en/java/javase/21/docs/specs/jni/index.html
//! [jni-tips]: https://developer.android.com/training/articles/perf-jni
//! [jni-rs-examples]:
//! https://github.com/jni-rs/jni-rs/tree/master/examples
//! [jni-rs-mylib-example]:
//! https://github.com/jni-rs/jni-rs/tree/master/mylib-example
//! [jni-rs-its]: https://github.com/jni-rs/jni-rs/tree/master/tests
//! [jni-rs-benches]: https://github.com/jni-rs/jni-rs/tree/master/benches
//! [users-servo]:
//! https://github.com/servo/servo/tree/main/ports/servoshell/egl/android
//! [users-ejb]:
//! https://github.com/exonum/exonum-java-binding/tree/master/exonum-java-binding/core/rust
//! [users-maidsafe]:
//! https://github.com/maidsafe/safe_client_libs/tree/master/safe_app_jni
//! [projects-jnr]: https://github.com/jnr/jnr-ffi/
//! [projects-graalvm]: http://www.graalvm.org/docs/why-graal/#for-java-programs
//! [graalvm-rust]:
//! http://www.graalvm.org/docs/reference-manual/languages/llvm/#running-rust
//! [projects-panama]: https://jdk.java.net/panama/
;
/// `jni-sys` re-exports
pub use jni_sys as sys;
pub use *;
/// Error types and utilities.
/// Parser for java type signatures.
/// Descriptors for classes and method IDs.
// Wrappers around jni value types that add lifetimes and other functionality.
pub use ;
pub use ;
/// JNI identifiers for methods and fields
/// Base support for reference types and auto-release wrappers like [`refs::Auto`] and [`refs::Global`].
/// Reference type implementations and API bindings for various `java.lang` Objects
/// Reference type implementations and API bindings for various `java.lang` Exceptions
/// Helpers for accessing array elements
/// Handling of strings in Java's [modified UTF-8] encoding, including
/// conversion to and from Rust strings (which use standard UTF-8).
///
/// [modified UTF-8]: https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8
pub use *;
/// An FFI safe alias for `EnvUnowned` for (safer) compatibility with
/// existing code.
///
/// Since 0.22 ([#570](https://github.com/jni-rs/jni-rs/pull/570)) the
/// `JNIEnv` type was renamed to [Env], which is no longer an FFI safe
/// pointer wrapper.
///
/// FFI usage of `JNIEnv`, within native method arguments, should be
/// migrated to [EnvUnowned], followed by [`EnvUnowned::with_env`].
///
/// To help make this clear and sign post how to safely migrate to the [Env]
/// and [EnvUnowned] types, we export this deprecated alias with a warning.
pub type JNIEnv<'frame> = ;
/// Java VM interface.
pub use *;
// workaround proc-macro-crate limitations so we can use jni-macros from the jni crate itself
// ref: https://github.com/bkchr/proc-macro-crate/issues/11
extern crate self as jni;
pub use jni_cstr;
pub use jni_str;
pub use jni_mangle;
pub use jni_sig;
pub use jni_sig_cstr;
pub use jni_sig_jstr;
pub use jni_sig_str;
pub use bind_java_type;
pub use native_method;
// For internal jni call macros to ensure their results are checked
// Provides a way to validate all our object bindings in a unit test, considering
// that the `J<Foo>API::get` functions are only exported with `pub(crate)` visibility.
//
// If any typos in method names or incorrect method or field signatures will result
// in a panic here when the binding initialization fails.