java-native-access / java-native-access/jna

JNI global references leak when native method registration fails

Open
#1,738 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Java
Stars
8.9k
Forks
1.7k
PR merge metrics
No merged PRs in 30d

Description

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_method with DeleteGlobalRef.
  • Delete any from_native and to_native weak global references.
  • Free all allocated arrays, encoding data, and FFI closure memory.

Successful registrations should continue to transfer ownership to Native_unregister.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in native/dispatch.c at Java_com_sun_jna_Native_registerMethod, especially the cleanup path reached after ffi_prep_cif, ffi_closure_alloc, or ffi_prep_closure_loc fails. Trace ownership of closure_method, from_native, to_native, closure_arg_types, encoding, and the FFI closure, then verify failed registrations release them while successful registrations still transfer cleanup to Native_unregister.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, java
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
66/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.