< prev index next >

src/java.base/share/classes/java/lang/foreign/package-info.java

Print this page

 76  * <h2 id="ffa">Foreign function access</h2>
 77  * The key abstractions introduced to support foreign function access are {@link java.lang.foreign.SymbolLookup},
 78  * {@link java.lang.foreign.FunctionDescriptor} and {@link java.lang.foreign.Linker}. The first is used to look up symbols
 79  * inside libraries; the second is used to model the signature of foreign functions, while the third is used
 80  * to link foreign functions as {@link java.lang.invoke.MethodHandle} instances,
 81  * so that clients can perform foreign function calls directly in Java, without the need for intermediate layers of C/C++
 82  * code (as is the case with the <a href="{@docRoot}/../specs/jni/index.html">Java Native Interface (JNI)</a>).
 83  * <p>
 84  * For example, to compute the length of a string using the C standard library function {@code strlen} on a Linux/x64 platform,
 85  * we can use the following code:
 86  *
 87  * {@snippet lang = java:
 88  * Linker linker = Linker.nativeLinker();
 89  * SymbolLookup stdlib = linker.defaultLookup();
 90  * MethodHandle strlen = linker.downcallHandle(
 91  *     stdlib.find("strlen").orElseThrow(),
 92  *     FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)
 93  * );
 94  *
 95  * try (Arena arena = Arena.ofConfined()) {
 96  *     MemorySegment cString = arena.allocateUtf8String("Hello");
 97  *     long len = (long)strlen.invokeExact(cString); // 5
 98  * }
 99  *}
100  *
101  * Here, we obtain a {@linkplain java.lang.foreign.Linker#nativeLinker() native linker} and we use it
102  * to {@linkplain java.lang.foreign.SymbolLookup#find(java.lang.String) look up} the {@code strlen} function in the
103  * standard C library; a <em>downcall method handle</em> targeting said function is subsequently
104  * {@linkplain java.lang.foreign.Linker#downcallHandle(FunctionDescriptor, Linker.Option...) obtained}.
105  * To complete the linking successfully, we must provide a {@link java.lang.foreign.FunctionDescriptor} instance,
106  * describing the signature of the {@code strlen} function.
107  * From this information, the linker will uniquely determine the sequence of steps which will turn
108  * the method handle invocation (here performed using {@link java.lang.invoke.MethodHandle#invokeExact(java.lang.Object...)})
109  * into a foreign function call, according to the rules specified by the ABI of the underlying platform.
110  * The {@link java.lang.foreign.Arena} class also provides many useful methods for
111  * interacting with foreign code, such as
112  * {@linkplain java.lang.foreign.SegmentAllocator#allocateUtf8String(java.lang.String) converting} Java strings into
113  * zero-terminated, UTF-8 strings, as demonstrated in the above example.
114  *
115  * <h2 id="restricted">Restricted methods</h2>
116  * Some methods in this package are considered <em>restricted</em>. Restricted methods are typically used to bind native
117  * foreign data and/or functions to first-class Java API elements which can then be used directly by clients. For instance
118  * the restricted method {@link java.lang.foreign.MemorySegment#reinterpret(long)}
119  * can be used to create a fresh segment with the same address and temporal bounds,
120  * but with the provided size. This can be useful to resize memory segments obtained when interacting with native functions.
121  * <p>
122  * Binding foreign data and/or functions is generally unsafe and, if done incorrectly, can result in VM crashes,
123  * or memory corruption when the bound Java API element is accessed. For instance, incorrectly resizing a native
124  * memory sgement using {@link java.lang.foreign.MemorySegment#reinterpret(long)} can lead to a JVM crash, or, worse,
125  * lead to silent memory corruption when attempting to access the resized segment. For these reasons, it is crucial for
126  * code that calls a restricted method to never pass arguments that might cause incorrect binding of foreign data and/or
127  * functions to a Java API.
128  * <p>
129  * Given the potential danger of restricted methods, the Java runtime issues a warning on the standard error stream
130  * every time a restricted method is invoked. Such warnings can be disabled by granting access to restricted methods
131  * to selected modules. This can be done either via implementation-specific command line options, or programmatically, e.g. by calling
132  * {@link java.lang.ModuleLayer.Controller#enableNativeAccess(java.lang.Module)}.
133  * <p>
134  * For every class in this package, unless specified otherwise, any method arguments of reference
135  * type must not be null, and any null argument will elicit a {@code NullPointerException}.  This fact is not individually
136  * documented for methods of this API.
137  *
138  * @apiNote Usual memory model guarantees, for example stated in {@jls 6.6} and {@jls 10.4}, do not apply
139  * when accessing native memory segments as these segments are backed by off-heap regions of memory.
140  *
141  * @implNote
142  * In the reference implementation, access to restricted methods can be granted to specific modules using the command line option
143  * {@code --enable-native-access=M1,M2, ... Mn}, where {@code M1}, {@code M2}, {@code ... Mn} are module names
144  * (for the unnamed module, the special value {@code ALL-UNNAMED} can be used). If this option is specified, access to
145  * restricted methods is only granted to the modules listed by that option. If this option is not specified,
146  * access to restricted methods is enabled for all modules, but access to restricted methods will result in runtime warnings.
147  *
148  * @spec jni/index.html Java Native Interface Specification
149  *
150  * @since 19
151  */
152 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
153 package java.lang.foreign;
154 
155 import jdk.internal.javac.PreviewFeature;

 76  * <h2 id="ffa">Foreign function access</h2>
 77  * The key abstractions introduced to support foreign function access are {@link java.lang.foreign.SymbolLookup},
 78  * {@link java.lang.foreign.FunctionDescriptor} and {@link java.lang.foreign.Linker}. The first is used to look up symbols
 79  * inside libraries; the second is used to model the signature of foreign functions, while the third is used
 80  * to link foreign functions as {@link java.lang.invoke.MethodHandle} instances,
 81  * so that clients can perform foreign function calls directly in Java, without the need for intermediate layers of C/C++
 82  * code (as is the case with the <a href="{@docRoot}/../specs/jni/index.html">Java Native Interface (JNI)</a>).
 83  * <p>
 84  * For example, to compute the length of a string using the C standard library function {@code strlen} on a Linux/x64 platform,
 85  * we can use the following code:
 86  *
 87  * {@snippet lang = java:
 88  * Linker linker = Linker.nativeLinker();
 89  * SymbolLookup stdlib = linker.defaultLookup();
 90  * MethodHandle strlen = linker.downcallHandle(
 91  *     stdlib.find("strlen").orElseThrow(),
 92  *     FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)
 93  * );
 94  *
 95  * try (Arena arena = Arena.ofConfined()) {
 96  *     MemorySegment cString = arena.allocateFrom("Hello");
 97  *     long len = (long)strlen.invokeExact(cString); // 5
 98  * }
 99  *}
100  *
101  * Here, we obtain a {@linkplain java.lang.foreign.Linker#nativeLinker() native linker} and we use it
102  * to {@linkplain java.lang.foreign.SymbolLookup#find(java.lang.String) look up} the {@code strlen} function in the
103  * standard C library; a <em>downcall method handle</em> targeting said function is subsequently
104  * {@linkplain java.lang.foreign.Linker#downcallHandle(FunctionDescriptor, Linker.Option...) obtained}.
105  * To complete the linking successfully, we must provide a {@link java.lang.foreign.FunctionDescriptor} instance,
106  * describing the signature of the {@code strlen} function.
107  * From this information, the linker will uniquely determine the sequence of steps which will turn
108  * the method handle invocation (here performed using {@link java.lang.invoke.MethodHandle#invokeExact(java.lang.Object...)})
109  * into a foreign function call, according to the rules specified by the ABI of the underlying platform.
110  * The {@link java.lang.foreign.Arena} class also provides many useful methods for
111  * interacting with foreign code, such as
112  * {@linkplain java.lang.foreign.SegmentAllocator#allocateFrom(java.lang.String) converting} Java strings into
113  * zero-terminated, UTF-8 strings, as demonstrated in the above example.
114  *
115  * <h2 id="restricted">Restricted methods</h2>
116  * Some methods in this package are considered <em>restricted</em>. Restricted methods are typically used to bind native
117  * foreign data and/or functions to first-class Java API elements which can then be used directly by clients. For instance
118  * the restricted method {@link java.lang.foreign.MemorySegment#reinterpret(long)}
119  * can be used to create a fresh segment with the same address and temporal bounds,
120  * but with the provided size. This can be useful to resize memory segments obtained when interacting with native functions.
121  * <p>
122  * Binding foreign data and/or functions is generally unsafe and, if done incorrectly, can result in VM crashes,
123  * or memory corruption when the bound Java API element is accessed. For instance, incorrectly resizing a native
124  * memory sgement using {@link java.lang.foreign.MemorySegment#reinterpret(long)} can lead to a JVM crash, or, worse,
125  * lead to silent memory corruption when attempting to access the resized segment. For these reasons, it is crucial for
126  * code that calls a restricted method to never pass arguments that might cause incorrect binding of foreign data and/or
127  * functions to a Java API.
128  * <p>
129  * Given the potential danger of restricted methods, the Java runtime issues a warning on the standard error stream
130  * every time a restricted method is invoked. Such warnings can be disabled by granting access to restricted methods
131  * to selected modules. This can be done either via implementation-specific command line options, or programmatically, e.g. by calling
132  * {@link java.lang.ModuleLayer.Controller#enableNativeAccess(java.lang.Module)}.
133  * <p>
134  * For every class in this package, unless specified otherwise, any method arguments of reference
135  * type must not be null, and any null argument will elicit a {@code NullPointerException}.  This fact is not individually
136  * documented for methods of this API.
137  *
138  * @apiNote Usual memory model guarantees, for example stated in {@jls 6.6} and {@jls 10.4}, do not apply
139  * when accessing native memory segments as these segments are backed by off-heap regions of memory.
140  *
141  * @implNote
142  * In the reference implementation, access to restricted methods can be granted to specific modules using the command line option
143  * {@code --enable-native-access=M1,M2, ... Mn}, where {@code M1}, {@code M2}, {@code ... Mn} are module names
144  * (for the unnamed module, the special value {@code ALL-UNNAMED} can be used). If this option is specified, access to
145  * restricted methods is only granted to the modules listed by that option. If this option is not specified,
146  * access to restricted methods is enabled for all modules, but access to restricted methods will result in runtime warnings.
147  *
148  * @spec jni/index.html Java Native Interface Specification
149  *
150  * @since 22
151  */

152 package java.lang.foreign;
153 

< prev index next >