JNI global references leak when native method registration fails
Summary
Java_com_sun_jna_Native_registerMethod creates persistent JNI references before several fallible FFI initialization steps.
Affected code: https://github.com/java-native-access/jna/blob/d036ad9781adad4b66693e8fa7098e4ac665e0a3/native/dispatch.c#L3553-L3587
If ffi_prep_cif, ffi_closure_alloc, or ffi_prep_closure_loc fails, execution jumps to cleanup. That path frees data without calling DeleteGlobalRef for data->closure_method.
Because registration did not complete, Native_unregister cannot release this reference later.
Impact
Each failed registration permanently retains the reflected Java Method and potentially its class-loader object graph until JVM shutdown. Repeated failures may cause persistent memory growth.
The same cleanup path also omits some related resources, including weak global references, closure_arg_types, encoding, and an allocated FFI closure.
Suggested fix
Before freeing data on failure:
- Delete
closure_methodwithDeleteGlobalRef. - Delete any
from_nativeandto_nativeweak global references. - Free all allocated arrays, encoding data, and FFI closure memory.
Successful registrations should continue to transfer ownership to Native_unregister.
Source: java-native-access/jna