Sub topic 10
Restricted methods and --enable-native-access
This chapter assumes you can already create a downcall handle with Linker, SymbolLookup and FunctionDescriptor. It covers why the JDK treats some of those calls as dangerous, what happens when you call them, and how to grant or withhold permission.
Why some methods are restricted
Java normally guarantees memory safety. A bug in Java code throws an exception. It does not corrupt the heap or crash the process. Native code gives up that guarantee, for two reasons:
- A C function can read or write any address it is given, or any address it computes itself.
- The JVM cannot check a
FunctionDescriptoragainst the real C signature. If you declare(int) -> intfor a function that takes along, the call can crash the VM or return garbage.
The FFM API therefore splits its methods in two groups. Safe methods, such as allocating a segment from an arena and reading within its bounds, are always available. A small set of restricted methods can break memory safety if used incorrectly. The JDK expects the application owner to grant permission explicitly before such methods are used.
The permission is called native access. It is granted per module, and the launcher decides which modules get it.
Which methods are restricted
In Java 22, the restricted methods in java.lang.foreign are:
| Method | What can go wrong |
|---|---|
| `Linker.downcallHandle(...)` | The descriptor may not match the real C signature. |
| `Linker.upcallStub(...)` | Native code gets a function pointer into the JVM, and a mismatch there is equally unchecked. |
| `MemorySegment.reinterpret(...)` | You assert a size or lifetime for memory the JVM knows nothing about. |
| `AddressLayout.withTargetLayout(...)` | Pointers read with this layout become segments of a size you claimed. |
| `SymbolLookup.libraryLookup(...)` | Loading a library runs its initialization code. |
System.load, System.loadLibrary, Runtime.load and Runtime.loadLibrary are restricted for the same reason: they let a library run native code in the process.
Looking up a symbol with defaultLookup() or find(...) is not restricted, because it only produces an address. The danger starts when you try to call it.
The reinterpret case deserves attention. A pointer returned from C, such as the result of getenv, arrives as a zero-length segment. Any access fails the bounds check. reinterpret(long) returns a new view with the size you assert, so the JDK cannot verify the size and treats the call as restricted:
MemorySegment zeroLength = (MemorySegment) getenv.invokeExact(name);
MemorySegment usable = zeroLength.reinterpret(64); // restricted: you promise 64 readable bytesIf the memory is really 10 bytes long, reading byte 40 is no longer caught by Java. This is the clearest example of why the check exists.
What happens when you call a restricted method
The outcome depends on how the JVM was launched.
- No
--enable-native-accessoption at all. The call succeeds, but the JVM prints a warning once per module, the first time that module uses a restricted method. The warning names the method and suggests the option. --enable-native-accessgiven, and the caller's module is listed. The call succeeds silently.--enable-native-accessgiven, and the caller's module is not listed. The call throwsIllegalCallerException.
Case 1 is a transition aid. Warnings are easy to ignore, so do not rely on them as your configuration. Case 3 is the strict behavior: once you list modules, everything else is blocked. A later JDK release may change the default so that case 1 also fails. If you enable native access explicitly now, your application will not break when that happens.
Enabling native access
The option takes a comma-separated list of module names:
--enable-native-access=com.example.app,com.example.utilCode on the class path does not belong to a named module. All class-path code is in the unnamed module, which you enable with the special value ALL-UNNAMED:
--enable-native-access=ALL-UNNAMEDALL-UNNAMED is coarse. It grants access to every class-path library, including transitive dependencies you did not write. Where you can, run the application as a named module and list only that module. That limits native access to the code you reviewed.
The rules for choosing the value:
- Application on the module path: list your module names.
- Application on the class path: use
ALL-UNNAMED. - A mix: list the named modules and add
ALL-UNNAMEDas one more entry.
Other ways to set it
For an executable JAR started with java -jar, you can put a manifest attribute in the JAR instead of passing a command-line flag:
Enable-Native-Access: ALL-UNNAMEDIn Java 22 the attribute accepts only ALL-UNNAMED. It applies only to the main JAR of a java -jar launch. It has no effect on other JARs on the class path.
You can also put the flag in the JAVA_TOOL_OPTIONS environment variable, or in a launcher script. Build tools need the flag in the place that starts the JVM. For tests that is the test runner's JVM arguments, not the build tool's own JVM.
A module can query its own state with Module.isNativeAccessEnabled().
Seeing all three outcomes
This program calls the C function abs through a downcall handle. It catches IllegalCallerException so you can see the strict case.
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class RestrictedDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
try {
MethodHandle abs = linker.downcallHandle(
linker.defaultLookup().find("abs").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
int result = (int) abs.invokeExact(-5);
System.out.println("abs(-5) = " + result);
} catch (IllegalCallerException e) {
System.out.println("Native access is not enabled for this module");
}
}
}Run it three ways with Java 22 or later:
# 1. No option: prints a warning on stderr, then abs(-5) = 5
java RestrictedDemo.java
# 2. Option lists the unnamed module: prints abs(-5) = 5 with no warning
java --enable-native-access=ALL-UNNAMED RestrictedDemo.java
# 3. Option lists some other module: the unnamed module is blocked
java --enable-native-access=java.base RestrictedDemo.javaThe third run prints "Native access is not enabled for this module". The JVM only blocks a module that is missing from a list that exists.
What the permission does not do
Enabling native access removes the gate, not the hazards. It does not check that:
- your
FunctionDescriptormatches the C signature, including types such assize_tandlong, whose size differs between platforms; - sizes you pass to
reinterpretare accurate; - the native function behaves well with the pointers you hand it.
A wrong descriptor is a bug that may show up as a crash far from its cause. Treat every downcallHandle call as a place that needs review, because it is the one place the compiler and the JVM cannot help you.
Practical guidance
- Isolate restricted calls. Keep
downcallHandle,upcallStubandreinterpretin one small class. Everything else in the codebase then uses a safe Java interface. - Create handles once. Store them in
static finalfields. This is also faster, because the JIT can inline a constantMethodHandle. - Prefer layouts over
reinterpret. Where a pointer points to a known structure,withTargetLayoutgives you a bounded segment automatically. Usereinterpretonly when no better information exists, and keep the claimed size as small as you can justify. - Test with the strict setting. Run your test suite with an explicit list of modules. Otherwise a missing grant may only show up in production, when a later JDK changes the default.
Exercises
Exercise
A class-path application calls Linker.downcallHandle and prints a warning on stderr but works. You then add --enable-native-access=com.example.lib to the launch command, where com.example.lib is a module that is not on the module path. What happens to the class-path code, and why?
Show answer
The call throws IllegalCallerException. Once the option is present, only the listed modules are allowed to call restricted methods. Class-path code is in the unnamed module, which is not listed. To fix it, add ALL-UNNAMED to the list: --enable-native-access=com.example.lib,ALL-UNNAMED.
Exercise
Why is MemorySegment.reinterpret(long) restricted while MemorySegment.get(ValueLayout.JAVA_INT, 0) is not?
Show answer
get is checked against the segment's size and lifetime, so a mistake throws an exception. reinterpret creates a new segment with a size or lifetime that you assert, and the JVM cannot verify it. If the claim is wrong, later reads and writes can touch memory outside the real block.
Exercise
Your executable JAR is started with java -jar app.jar and uses FFM from class-path code. Name one way to enable native access without changing the command line.
Show answer
Add the manifest attribute Enable-Native-Access: ALL-UNNAMED to the main JAR. In Java 22 it accepts only ALL-UNNAMED, and it works only for the main JAR of a java -jar launch.