diff --git a/.github/workflows/graalvm.yaml b/.github/workflows/graalvm.yaml new file mode 100644 index 000000000..66ab1b56e --- /dev/null +++ b/.github/workflows/graalvm.yaml @@ -0,0 +1,38 @@ +# GraalVM build and native test. +name: GraalVM CI + +on: + workflow_dispatch: + workflow_call: + pull_request: + push: + branches: + - master + +permissions: + contents: read + +env: + ANT_OPTS: -Djava.security.manager=allow + +jobs: + build: + runs-on: ubuntu-latest + name: Test GVM 22, ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '22' + distribution: 'graalvm-community' + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Linux requirements + run: sudo apt-get -y install texinfo + - uses: gradle/actions/setup-gradle@v3 + - name: "Build: Compile & Install JNA" + run: ant && ant install + - name: "Build: Native Images (Dynamic JNI)" + run: ant nativeImage && ant nativeRun + - name: "Build: Native Image (Static JNI)" + run: ant nativeImageStatic && ant nativeRunStatic diff --git a/build.xml b/build.xml index 5ba1b0e14..430542648 100644 --- a/build.xml +++ b/build.xml @@ -39,6 +39,7 @@ + @@ -52,6 +53,7 @@ + @@ -60,6 +62,7 @@ + @@ -69,6 +72,9 @@ + + + @@ -88,10 +94,12 @@ + + @@ -112,6 +120,19 @@ uri="antlib:org.codehaus.mojo.animal_sniffer" classpathref="maven-ant-tasks.classpath" /> + + + + + + + + + + + + + @@ -131,6 +152,7 @@ + + + + + + @@ -192,6 +225,7 @@ + @@ -237,6 +271,9 @@ + + + @@ -246,12 +283,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -649,7 +736,7 @@ osname=macosx;processor=aarch64 - + @@ -1014,21 +1101,40 @@ cd .. + + includes="jnidispatch.dll,libjnidispatch.*" + excludes="*.lib,*.a"/> + + + + + + - + + + + + + + + + @@ -1036,6 +1142,7 @@ cd .. + @@ -1292,6 +1399,54 @@ cd .. Reports generated in ${reports.clover} + + + + + + + + + + + + + + + + + + + JNA GraalVM Integration +
${header}
+ ${footer} + + + + + + + + + + + +
+ + + +
+ @@ -1351,7 +1506,7 @@ cd .. - + @@ -1366,6 +1521,9 @@ cd .. + + + @@ -1431,6 +1589,12 @@ cd .. + + + + + + @@ -1483,6 +1647,17 @@ cd .. + + + + + + + + + + + @@ -1538,6 +1713,19 @@ cd .. + + + + + + + + + + + + + @@ -1553,6 +1741,7 @@ cd .. + @@ -1581,4 +1770,47 @@ cd .. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/common.xml b/common.xml index cb09efa3b..eada46b5d 100644 --- a/common.xml +++ b/common.xml @@ -19,6 +19,7 @@ + @@ -26,7 +27,7 @@ - + diff --git a/lib/gvm/AbstractJNAFeature.java b/lib/gvm/AbstractJNAFeature.java new file mode 100644 index 000000000..055b00edc --- /dev/null +++ b/lib/gvm/AbstractJNAFeature.java @@ -0,0 +1,209 @@ +/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +package com.sun.jna; + +import org.graalvm.nativeimage.hosted.Feature; +import org.graalvm.nativeimage.hosted.RuntimeClassInitialization; +import org.graalvm.nativeimage.hosted.RuntimeJNIAccess; +import org.graalvm.nativeimage.hosted.RuntimeProxyCreation; +import org.graalvm.nativeimage.hosted.RuntimeReflection; +import org.graalvm.nativeimage.hosted.RuntimeResourceAccess; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; + +/** + * Provides common logic for JNA-related GraalVM feature classes. + * + *

These classes should only be included at build time for a `native-image` target.

+ * + * @since 5.15.0 + * @author Sam Gammon (sam@elide.dev) + * @author Dario Valdespino (dario@elide.dev) + */ +abstract class AbstractJNAFeature implements Feature { + /** + * Obtain a reference to a method on a class, in order to register it for reflective access + * + * @param clazz Class to obtain method reference from + * @param methodName Name of the method to obtain a reference to + * @param args Method arguments + * @return Method reference + */ + protected static Method method(Class clazz, String methodName, Class... args) { + try { + return clazz.getDeclaredMethod(methodName, args); + } catch (NoSuchMethodException e) { + throw new IllegalStateException(e); + } + } + + /** + * Obtain a reference to one or more fields on a class, in order to register them for reflective access + * + * @param clazz Class to obtain field references from + * @param fieldNames Names of the fields to obtain references to + * @return Field references + */ + protected static Field[] fields(Class clazz, String... fieldNames) { + try { + Field[] fields = new Field[fieldNames.length]; + for (int i = 0; i < fieldNames.length; i++) { + fields[i] = clazz.getDeclaredField(fieldNames[i]); + } + return fields; + } catch (NoSuchFieldException e) { + throw new IllegalStateException(e); + } + } + + /** + * Register a class for reflective access at runtime + * + * @param clazz Class to register + */ + protected static void reflectiveClass(Class... clazz) { + RuntimeReflection.register(clazz); + } + + /** + * Register a resource for use in the final image + * + * @param module Module which owns the resource + * @param resource Path to the resource to register + */ + protected static void registerResource(Module module, String resource) { + RuntimeResourceAccess.addResource(module, resource); + } + + /** + * Register a resource for use in the final image + * + * @param resource Path to the resource to register + */ + protected static void registerResource(String resource) { + registerResource(AbstractJNAFeature.class.getModule(), resource); + } + + /** + * Register a class for JNI access at runtime + * + * @param clazz Class to register + */ + protected static void registerJniClass(Class clazz) { + RuntimeJNIAccess.register(clazz); + Arrays.stream(clazz.getConstructors()).forEach(RuntimeJNIAccess::register); + Arrays.stream(clazz.getMethods()).forEach(RuntimeJNIAccess::register); + } + + /** + * Register a class for JNI access at runtime, potentially with reflective access as well + * + * @param clazz Class to register + * @param reflective Whether to register the class and constructors for reflective access + */ + protected static void registerJniClass(Class clazz, Boolean reflective) { + registerJniClass(clazz); + if (reflective) { + RuntimeReflection.register(clazz); + RuntimeReflection.registerAllConstructors(clazz); + } + } + + /** + * Register a suite of JNA methods for use at runtime + * + * @param reflective Whether to register the methods for reflective access + * @param methods Methods to register + */ + protected static void registerJniMethods(Boolean reflective, Method... methods) { + RuntimeJNIAccess.register(methods); + if (reflective) { + RuntimeReflection.register(methods); + } + } + + /** + * Register a suite of JNA methods for use at runtime + * + * @param methods Methods to register + */ + protected static void registerJniMethods(Method... methods) { + registerJniMethods(false, methods); + } + + /** + * Register a suite of JNA fields for use at runtime + * + * @param reflective Whether to register the fields for reflective access + * @param fields Fields to register + */ + protected static void registerJniFields(Boolean reflective, Field[] fields) { + RuntimeJNIAccess.register(fields); + if (reflective) { + RuntimeReflection.register(fields); + } + } + + /** + * Register a suite of JNA fields for use at runtime + * + * @param fields Fields to register + */ + protected static void registerJniFields(Field[] fields) { + registerJniFields(false, fields); + } + + /** + * Register a combination of interfaces used at runtime as a dynamic proxy object + * + * @param classes Combination of interface classes; order matters + */ + protected static void registerProxyInterfaces(Class... classes) { + RuntimeProxyCreation.register(classes); + } + + /** + * Assign the specified class or classes to initialize at image build time + * + * @param clazz Classes to register for build-time initialization + */ + protected static void initializeAtBuildTime(Class... clazz) { + for (Class c : clazz) { + RuntimeClassInitialization.initializeAtBuildTime(c); + } + } + + /** + * Assign the specified class or classes to initialize at image run-time + * + * @param clazz Classes to register for run-time initialization + */ + protected static void initializeAtRunTime(Class... clazz) { + for (Class c : clazz) { + RuntimeClassInitialization.initializeAtRunTime(c); + } + } +} diff --git a/lib/gvm/JavaNativeAccess.java b/lib/gvm/JavaNativeAccess.java new file mode 100644 index 000000000..8a563d558 --- /dev/null +++ b/lib/gvm/JavaNativeAccess.java @@ -0,0 +1,162 @@ +/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +package com.sun.jna; + +import com.sun.jna.*; +import com.sun.jna.ptr.IntByReference; +import com.sun.jna.ptr.PointerByReference; +import org.graalvm.nativeimage.hosted.*; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Arrays; + +/** + * Feature for use at build time on GraalVM, which enables basic support for JNA. + * + *

This "Feature" implementation is discovered on the class path, via the argument file at native-image.properties. + * At build-time, the feature is registered with the Native Image compiler. + * + *

If JNA is detected on the class path, the feature is enabled, and the JNA library is initialized and configured + * for native access support. + * + *

Certain features like reflection and JNI access are configured by this feature; to enable static optimized + * support for JNA, see the {@link SubstrateStaticJNA} feature. + * + * @since 5.15.0 + * @author Sam Gammon (sam@elide.dev) + * @author Dario Valdespino (dario@elide.dev) + */ +public final class JavaNativeAccess extends AbstractJNAFeature implements Feature { + static final String NATIVE_LAYOUT = "com.sun.jna.Native"; + + @Override + public String getDescription() { + return "Enables access to JNA at runtime on SubstrateVM"; + } + + @Override + public boolean isInConfiguration(IsInConfigurationAccess access) { + return access.findClassByName(NATIVE_LAYOUT) != null; + } + + private void registerCommonTypes() { + registerJniClass(Callback.class); + registerJniClass(CallbackReference.class); + registerJniMethods( + method(CallbackReference.class, "getCallback", Class.class, Pointer.class)); + registerJniMethods( + method(CallbackReference.class, "getCallback", Class.class, Pointer.class, boolean.class)); + registerJniMethods( + method(CallbackReference.class, "getFunctionPointer", Callback.class)); + registerJniMethods( + method(CallbackReference.class, "getFunctionPointer", Callback.class, boolean.class)); + registerJniMethods( + method(CallbackReference.class, "getNativeString", Object.class, boolean.class)); + registerJniMethods( + method(CallbackReference.class, "initializeThread", Callback.class, CallbackReference.AttachOptions.class)); + + registerJniClass(com.sun.jna.CallbackReference.AttachOptions.class); + + registerJniClass(FromNativeConverter.class); + registerJniMethods(method(FromNativeConverter.class, "nativeType")); + + registerJniClass(IntegerType.class); + registerJniFields(fields(IntegerType.class, "value")); + + registerJniClass(Native.class); + registerJniMethods( + method(Native.class, "dispose"), + method(Native.class, "fromNative", FromNativeConverter.class, Object.class, Method.class), + method(Native.class, "fromNative", Class.class, Object.class), + method(Native.class, "nativeType", Class.class), + method(Native.class, "toNative", ToNativeConverter.class, Object.class), + method(Native.class, "open", String.class, int.class), + method(Native.class, "close", long.class), + method(Native.class, "findSymbol", long.class, String.class)); + + registerJniClass(Native.ffi_callback.class); + registerJniMethods(method(Native.ffi_callback.class, "invoke", long.class, long.class, long.class)); + + registerJniClass(NativeLong.class); + + registerJniClass(NativeMapped.class); + registerJniMethods(method(NativeMapped.class, "toNative")); + + registerJniClass(Pointer.class); + registerJniFields(fields(Pointer.class, "peer")); + + registerJniClass(PointerType.class); + registerJniFields(fields(PointerType.class, "pointer")); + + registerJniClass(Structure.class); + registerJniFields(fields(Structure.class, "memory", "typeInfo")); + registerJniMethods( + method(Structure.class, "autoRead"), + method(Structure.class, "autoWrite"), + method(Structure.class, "getTypeInfo"), + method(Structure.class, "getTypeInfo", Object.class), + method(Structure.class, "newInstance", Class.class), + method(Structure.class, "newInstance", Class.class, long.class), + method(Structure.class, "newInstance", Class.class, Pointer.class)); + + registerJniClass(Structure.ByValue.class); + registerJniClass(Structure.FFIType.class); + registerJniClass(WString.class); + registerJniClass(PointerByReference.class); + } + + private void registerCommonProxies() { + registerProxyInterfaces(Callback.class); + registerProxyInterfaces(Library.class); + } + + private void registerReflectiveAccess() { + reflectiveClass( + CallbackProxy.class, + CallbackReference.class, + Klass.class, + NativeLong.class, + Structure.class, + IntByReference.class, + PointerByReference.class); + } + + @Override + public void beforeAnalysis(BeforeAnalysisAccess access) { + registerCommonTypes(); + registerCommonProxies(); + registerReflectiveAccess(); + + // extending `com.sun.jna.Library` should add interfaces as proxies + access.registerSubtypeReachabilityHandler((duringAnalysisAccess, aClass) -> { + // must extend `Library`, be an interface, and not already be a proxy + assert aClass.isInterface(); + if (Library.class.isAssignableFrom(aClass) && !Proxy.isProxyClass(aClass)) { + registerProxyInterfaces(aClass); + } + }, Library.class); + } +} diff --git a/lib/gvm/README.md b/lib/gvm/README.md new file mode 100644 index 000000000..a87f0b781 --- /dev/null +++ b/lib/gvm/README.md @@ -0,0 +1,280 @@ +# JNA for Native Image + +This directory specifies sources for running JNA under [GraalVM Native Image](https://www.graalvm.org/latest/reference-manual/native-image/). + +Native Image targets run under the [Substrate Virtual Machine (SVM)](https://docs.oracle.com/en/graalvm/enterprise/20/docs/reference-manual/native-image/SubstrateVM/), rather than a traditional JVM. + +JNA is usable out of the box on JVM but requires some configuration for SVM: + +- [JNI registration](https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/JNI/): Lookups and calls over JNI must be registered in a configuration file. + +- [Proxy registration](https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/DynamicProxy/): Classes that extend JNA's `Library` interface must also be registered as dynamic proxies. + +**There are several ways to properly configure SVM: manually or via the built-in GraalVM [`Feature`](https://www.graalvm.org/sdk/javadoc/org/graalvm/nativeimage/hosted/Feature.html) support.** + +## Automatic Configuration + +To automatically configure `native-image` for JNA, **add the `jna-graalvm.jar` to your classpath:** + +**Maven (`pom.xml`):** +```xml + + net.java.dev.jna + jna-graalvm + ... (5.15.0 or greater) ... + +``` + +**Gradle Groovy DSL (`build.gradle`):** +```groovy + // check maven central for the latest version + implementation 'net.java.dev.jna:jna-graalvm:5.15.0' +``` + +**Gradle Kotlin DSL (`build.gradle.kts`):** +```kotlin + // check maven central for the latest version + implementation("net.java.dev.jna:jna-graalvm:5.15.0") +``` + +That's it! You should see `com.sun.jna.JavaNativeAccess` show up during your native image build: + +``` + ======================================================================================================================== + GraalVM Native Image: Generating 'graalvm-native-static-jna' (executable)... + ======================================================================================================================== + For detailed information and explanations on the build output, visit: + https://github.com/oracle/graal/blob/master/docs/reference-manual/native-image/BuildOutput.md + ------------------------------------------------------------------------------------------------------------------------ + [1/8] Initializing... (2.7s @ 0.18GB) + Java version: 22.0.1+8, vendor version: Oracle GraalVM 22.0.1+8.1 + Graal compiler: optimization level: 2, target machine: armv8-a, PGO: off + C compiler: cc (apple, arm64, 15.0.0) + Garbage collector: Serial GC (max heap size: 80% of RAM) + 3 user-specific feature(s): + - com.oracle.svm.thirdparty.gson.GsonFeature +→ - com.sun.jna.JavaNativeAccess: Enables access to JNA at runtime on SubstrateVM + ... +``` + +## Manual Configuration + +The configuration produced by the automatic route is generally identical to the configuration needed to run your app, but you can also set it up manually instead. + +**Omit the `jna-graalvm.jar` dependency** + +If you include it on your Native Image classpath at build-time, the `JavaNativeAccess` feature is added automatically. If you want to manually configure JNI for JNA, don't include it on your classpath. + +> [!WARNING] +> These configurations are provided on a best-effort basis and may be different for your app. + +### Specify JNI configurations + +If you don't already have one, create a [`jni-config.json`](https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/JNI/#reflection-metadata) file within your Java app, and configure Native Image to find it. + +Then, add the configurations below to your `jni-config.json`. + +

+Click to show JSON configuration entries +
+[
+  {
+  "name":"com.sun.jna.Callback",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+},
+{
+  "name":"com.sun.jna.CallbackReference",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "methods":[{"name":"getCallback","parameterTypes":["java.lang.Class","com.sun.jna.Pointer","boolean"] }, {"name":"getFunctionPointer","parameterTypes":["com.sun.jna.Callback","boolean"] }, {"name":"getNativeString","parameterTypes":["java.lang.Object","boolean"] }, {"name":"initializeThread","parameterTypes":["com.sun.jna.Callback","com.sun.jna.CallbackReference$AttachOptions"] }]
+},
+{
+  "name":"com.sun.jna.CallbackReference$AttachOptions",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+},
+{
+  "name":"com.sun.jna.FromNativeConverter",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "methods":[{"name":"nativeType","parameterTypes":[] }]
+},
+{
+  "name":"com.sun.jna.IntegerType",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "fields":[{"name":"value", "allowWrite":true}]
+},
+{
+  "name":"com.sun.jna.JNIEnv",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+},
+{
+  "name":"com.sun.jna.Native",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "methods":[
+    {"name":"dispose","parameterTypes":[] },
+    {"name":"fromNative","parameterTypes":["com.sun.jna.FromNativeConverter","java.lang.Object","java.lang.reflect.Method"] },
+    {"name":"fromNative","parameterTypes":["java.lang.Class","java.lang.Object"] },
+    {"name":"fromNative","parameterTypes":["java.lang.reflect.Method","java.lang.Object"] },
+    {"name":"nativeType","parameterTypes":["java.lang.Class"] },
+    {"name":"toNative","parameterTypes":["com.sun.jna.ToNativeConverter","java.lang.Object"]},
+    {"name":"open","parameterTypes":["java.lang.String","java.lang.Integer"]},
+    {"name":"close","parameterTypes":["java.lang.Long"]},
+    {"name":"findSymbol","parameterTypes":["java.lang.Long","java.lang.String"]}
+  ]
+},
+{
+  "name":"com.sun.jna.Native$ffi_callback",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "methods":[{"name":"invoke","parameterTypes":["long","long","long"] }]
+},
+{
+  "name":"com.sun.jna.NativeLong",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+},
+{
+  "name":"com.sun.jna.NativeMapped",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "methods":[{"name":"toNative","parameterTypes":[] }]
+},
+{
+  "name":"com.sun.jna.Pointer",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "fields":[{"name":"peer", "allowWrite":true}],
+  "methods":[{"name":"","parameterTypes":["long"] }]
+},
+{
+  "name":"com.sun.jna.PointerType",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "fields":[{"name":"pointer", "allowWrite":true}]
+},
+{
+  "name":"com.sun.jna.Structure",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "fields":[{"name":"memory", "allowWrite":true}, {"name":"typeInfo", "allowWrite":true}],
+  "methods":[{"name":"autoRead","parameterTypes":[] }, {"name":"autoWrite","parameterTypes":[] }, {"name":"getTypeInfo","parameterTypes":[] }, {"name":"getTypeInfo","parameterTypes":["java.lang.Object"] }, {"name":"newInstance","parameterTypes":["java.lang.Class"] }, {"name":"newInstance","parameterTypes":["java.lang.Class","long"] }, {"name":"newInstance","parameterTypes":["java.lang.Class","com.sun.jna.Pointer"] }]
+},
+{
+  "name":"com.sun.jna.Structure$ByValue",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+},
+{
+  "name":"com.sun.jna.Structure$FFIType",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+},
+{
+  "name":"com.sun.jna.Structure$FFIType$FFITypes",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "fields":[{"name":"ffi_type_double", "allowWrite":true}, {"name":"ffi_type_float", "allowWrite":true}, {"name":"ffi_type_longdouble", "allowWrite":true}, {"name":"ffi_type_pointer", "allowWrite":true}, {"name":"ffi_type_sint16", "allowWrite":true}, {"name":"ffi_type_sint32", "allowWrite":true}, {"name":"ffi_type_sint64", "allowWrite":true}, {"name":"ffi_type_sint8", "allowWrite":true}, {"name":"ffi_type_uint16", "allowWrite":true}, {"name":"ffi_type_uint32", "allowWrite":true}, {"name":"ffi_type_uint64", "allowWrite":true}, {"name":"ffi_type_uint8", "allowWrite":true}, {"name":"ffi_type_void", "allowWrite":true}]
+},
+{
+  "name":"com.sun.jna.WString",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true,
+  "methods":[{"name":"","parameterTypes":["java.lang.String"] }]
+},
+{
+  "name":"com.sun.jna.ptr.PointerByReference",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+},
+{
+  "name":"com.sun.jna.platform.mac.CoreFoundation$CFStringRef",
+  "allDeclaredMethods":true,
+  "allPublicMethods":true,
+  "allDeclaredConstructors":true,
+  "allPublicConstructors":true
+}
+]
+
+
+ +### Specify proxy configurations + +If you don't already have one, create a [`proxy-config.json`](https://www.graalvm.org/latest/reference-manual/native-image/metadata/#dynamic-proxy) file within your Java app, and configure Native Image to find it. + +Then, add the configurations below to your `proxy-config.json`. + +
+Click to show JSON configuration entries +
+[
+  {
+    "interfaces":["com.sun.jna.Callback"]
+  },
+  {
+    "interfaces":["com.sun.jna.Library"]
+  },
+  {
+    "interfaces":["com.sun.jna.platform.unix.LibC"]
+  },
+  {
+    "interfaces":["com.sun.jna.platform.linux.Udev"]
+  },
+  {
+    "interfaces":["com.sun.jna.platform.linux.LibRT"]
+  },
+  {
+    "interfaces":["com.sun.jna.platform.mac.SystemB"]
+  },
+  {
+    "interfaces":["com.sun.jna.platform.mac.IOKit"]
+  },
+  {
+    "interfaces":["com.sun.jna.platform.mac.CoreFoundation"]
+  },
+  {
+    "interfaces":["com.sun.jna.win32.StdCallLibrary"]
+  }
+]
+
+
diff --git a/lib/gvm/SubstrateStaticJNA.java b/lib/gvm/SubstrateStaticJNA.java new file mode 100644 index 000000000..35828e4c0 --- /dev/null +++ b/lib/gvm/SubstrateStaticJNA.java @@ -0,0 +1,208 @@ +/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +package com.sun.jna; + +import com.oracle.svm.core.jdk.NativeLibrarySupport; +import com.oracle.svm.core.jdk.PlatformNativeLibrarySupport; +import com.oracle.svm.hosted.FeatureImpl.BeforeAnalysisAccessImpl; +import org.graalvm.nativeimage.Platform; +import org.graalvm.nativeimage.hosted.Feature; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Collections; +import java.util.List; + +/** + * Feature for use at build time on GraalVM, which enables static JNI support for JNA. + * + *

This "Feature" implementation is discovered on the classpath, via the argument file at native-image.properties. + * At build-time, the feature is registered with the Native Image compiler. + * + *

If JNA is detected on the classpath, and if static JNI is enabled, the feature is enabled, and the JNA library is + * initialized and configured for native access support. + * + *

This class extends the base {@link com.sun.jna.JavaNativeAccess} feature by providing JNA's JNI layer statically, + * so that no library unpacking step needs to take place. + * + * @since 5.15.0 + * @author Sam Gammon (sam@elide.dev) + * @author Dario Valdespino (dario@elide.dev) + */ +public final class SubstrateStaticJNA extends AbstractJNAFeature { + /** + * Name for the FFI native library used during static linking by Native Image. + */ + private static final String FFI_LINK_NAME = "ffi"; + + /** + * Name for the JNI Dispatch native library used during static linking by Native Image. + */ + private static final String JNA_LINK_NAME = "jnidispatch"; + + /** + * Name prefix used by native functions from the JNI Dispatch library. + */ + private static final String JNA_NATIVE_LAYOUT = "com_sun_jna_Native"; + + /** + * Name of the JNI Dispatch static library on UNIX-based platforms. + */ + private static final String JNI_DISPATCH_UNIX_NAME = "libjnidispatch.a"; + + /** + * Name of the JNI Dispatch static library on Windows. + */ + private static final String JNI_DISPATCH_WINDOWS_NAME = "jnidispatch.lib"; + + /** + * Name of the FFI static library on UNIX-based platforms. + */ + private static final String FFI_UNIX_NAME = "libffi.a"; + + /** + * Name of the FFI static library on Windows. + */ + private static final String FFI_WINDOWS_NAME = "ffi.lib"; + + /** + * Returns the name of the static JNI Dispatch library for the current platform. On UNIX-based systems, + * {@link #JNI_DISPATCH_UNIX_NAME} is used; on Windows, {@link #JNI_DISPATCH_WINDOWS_NAME} is returned instead. + * + * @see #getStaticLibraryResource + * @return The JNI Dispatch library name for the current platform. + */ + private static String getStaticLibraryFileName() { + if (Platform.includedIn(Platform.WINDOWS.class)) return JNI_DISPATCH_WINDOWS_NAME; + if (Platform.includedIn(Platform.LINUX.class)) return JNI_DISPATCH_UNIX_NAME; + if (Platform.includedIn(Platform.DARWIN.class)) return JNI_DISPATCH_UNIX_NAME; + + // If the current platform is not in the Platform class, this code would not run at all + throw new UnsupportedOperationException("Current platform does not support static linking"); + } + + /** + * Returns the name of the static FFI library for the current platform. On UNIX-based systems, + * {@link #FFI_UNIX_NAME} is used; on Windows, {@link #FFI_WINDOWS_NAME} is returned instead. + * + * @see #getStaticLibraryResource + * @return The FFI library name for the current platform. + */ + private static String getFFILibraryFileName() { + if (Platform.includedIn(Platform.WINDOWS.class)) return FFI_WINDOWS_NAME; + if (Platform.includedIn(Platform.LINUX.class)) return FFI_UNIX_NAME; + if (Platform.includedIn(Platform.DARWIN.class)) return FFI_UNIX_NAME; + + // If the current platform is not in the Platform class, this code would not run at all + throw new UnsupportedOperationException("Current platform does not support static FFI"); + } + + /** + * Returns the full path to the static JNI Dispatch library embedded in the JAR, accounting for platform-specific + * library names. + * + * @see #getStaticLibraryFileName() + * @return The JNI Dispatch library resource path for the current platform. + */ + private static String getStaticLibraryResource() { + return "/com/sun/jna/" + com.sun.jna.Platform.RESOURCE_PREFIX + "/" + getStaticLibraryFileName(); + } + + /** + * Returns the full path to the static FFI library which JNA depends on, accounting for platform-specific + * library names. + * + * @see #getFFILibraryFileName() + * @return The FFI library resource path for the current platform. + */ + private static String getFFILibraryResource() { + return "/com/sun/jna/" + com.sun.jna.Platform.RESOURCE_PREFIX + "/" + getFFILibraryFileName(); + } + + /** + * Extracts a library resource and returns the file it was extracted to. + * + * @param resource Resource path for the library to extract. + * @param filename Expected filename for the library. + * @return The extracted library file. + */ + private static File unpackLibrary(String resource, String filename) { + // Unpack the static library from resources so Native Image can use it + File extractedLib; + try { + extractedLib = Native.extractFromResourcePath(resource, Native.class.getClassLoader()); + + // The library is extracted into a file with a `.tmp` name, which will not be picked up by the linker + // We need to rename it first using the platform-specific convention or the build will fail + File platformLib = new File(extractedLib.getParentFile(), filename); + if (!extractedLib.renameTo(platformLib)) throw new IllegalStateException("Renaming extract file failed"); + extractedLib = platformLib; + } catch (IOException e) { + throw new RuntimeException("Failed to extract native dispatch library from resources", e); + } + return extractedLib; + } + + @Override + public String getDescription() { + return "Enables optimized static access to JNA at runtime"; + } + + @Override + public boolean isInConfiguration(IsInConfigurationAccess access) { + return access.findClassByName(JavaNativeAccess.NATIVE_LAYOUT) != null; + } + + @Override + public List> getRequiredFeatures() { + return Collections.singletonList(JavaNativeAccess.class); + } + + @Override + public void beforeAnalysis(BeforeAnalysisAccess access) { + var nativeLibraries = NativeLibrarySupport.singleton(); + var platformLibraries = PlatformNativeLibrarySupport.singleton(); + + // Register as a built-in library with Native Image and set the name prefix used by native symbols + nativeLibraries.preregisterUninitializedBuiltinLibrary(JNA_LINK_NAME); + platformLibraries.addBuiltinPkgNativePrefix(JNA_NATIVE_LAYOUT); + + // Extract the main JNA library from the platform-specific resource path; next, extract the FFI + // library it depends on + unpackLibrary(getFFILibraryResource(), getFFILibraryFileName()); + var extractedLib = unpackLibrary(getStaticLibraryResource(), getStaticLibraryFileName()); + + // WARNING: the static JNI linking feature is unstable and may be removed in the future; + // this code uses the access implementation directly in order to register the static library. We + // inform the Native Image compiler that JNA depends on `ffi`, so that it forces it to load first + // when JNA is initialized at image runtime. + var nativeLibsImpl = ((BeforeAnalysisAccessImpl) access).getNativeLibraries(); + nativeLibsImpl.addStaticNonJniLibrary(FFI_LINK_NAME); + nativeLibsImpl.addStaticJniLibrary(JNA_LINK_NAME, FFI_LINK_NAME); + + // Enhance the Native Image lib paths so the injected static libraries are available to the linker + nativeLibsImpl.getLibraryPaths().add(extractedLib.getParentFile().getAbsolutePath()); + } +} diff --git a/lib/gvm/native-image.properties b/lib/gvm/native-image.properties new file mode 100644 index 000000000..95904edb4 --- /dev/null +++ b/lib/gvm/native-image.properties @@ -0,0 +1,29 @@ +# Copyright (c) 2015 Adam Marcionek, All Rights Reserved +# +# The contents of this file is dual-licensed under 2 +# alternative Open Source/Free licenses: LGPL 2.1 or later and +# Apache License 2.0. (starting with JNA version 4.0.0). +# +# You can freely decide which license you want to apply to +# the project. +# +# You may obtain a copy of the LGPL License at: +# +# http://www.gnu.org/licenses/licenses.html +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "LGPL2.1". +# +# You may obtain a copy of the Apache License at: +# +# http://www.apache.org/licenses/ +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "AL2.0". + +Args = --features=com.sun.jna.JavaNativeAccess \ + -J--add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.hosted.jni=ALL-UNNAMED \ + -J--add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.core.jni=ALL-UNNAMED \ + -J--add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.hosted=ALL-UNNAMED \ + -J--add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.hosted.c=ALL-UNNAMED \ + -J--add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.core.jdk=ALL-UNNAMED diff --git a/native/Makefile b/native/Makefile index 70078089f..12f72264e 100644 --- a/native/Makefile +++ b/native/Makefile @@ -73,6 +73,7 @@ FFI_ENV=CC="$(CC)" CFLAGS="$(COPT) $(CDEBUG) -DFFI_STATIC_BUILD" CPPFLAGS="$(CDE FFI_CONFIG=--enable-static --disable-shared --with-pic=yes endif LIBRARY=$(BUILD)/$(LIBPFX)jnidispatch$(JNISFX) +LIBRARY_STATIC=$(BUILD)/$(LIBPFX)jnidispatch$(ARSFX) TESTLIB=$(BUILD)/$(LIBPFX)testlib$(LIBSFX) TESTLIB_JAR=$(BUILD)/$(LIBPFX)testlib-jar$(LIBSFX) TESTLIB_PATH=$(BUILD)/$(LIBPFX)testlib-path$(LIBSFX) @@ -85,6 +86,7 @@ LIBSFX=.so ARSFX=.a JNISFX=$(LIBSFX) CC=gcc +AR=ar LD=$(CC) LIBS= # Default to Sun recommendations for JNI compilation @@ -473,7 +475,7 @@ else $(CC) $(CFLAGS) $(LOC_CC_OPTS) -c $< $(COUT) endif -all: $(LIBRARY) $(TESTLIB) $(TESTLIB2) $(TESTLIB_JAR) $(TESTLIB_PATH) $(TESTLIB_TRUNC) +all: $(LIBRARY) $(LIBRARY_STATIC) $(TESTLIB) $(TESTLIB2) $(TESTLIB_JAR) $(TESTLIB_PATH) $(TESTLIB_TRUNC) install: mkdir $(INSTALLDIR) @@ -495,6 +497,9 @@ $(LIBRARY): $(JNIDISPATCH_OBJS) $(FFI_LIB) $(LD) $(LDFLAGS) $(JNIDISPATCH_OBJS) $(FFI_LIB) $(LIBS) $(STRIP) $@ +$(LIBRARY_STATIC): $(JNIDISPATCH_OBJS) $(FFI_LIB) + $(AR) rcs $@ $(JNIDISPATCH_OBJS) + $(TESTLIB): $(BUILD)/testlib.o $(LD) $(LDFLAGS) $< $(LIBS) diff --git a/native/dispatch.c b/native/dispatch.c index 8a03a643b..98c971352 100644 --- a/native/dispatch.c +++ b/native/dispatch.c @@ -2334,10 +2334,10 @@ Java_com_sun_jna_Native_findSymbol(JNIEnv *env, jclass UNUSED(cls), /* * Class: com_sun_jna_Native - * Method: write + * Method: writeBytes * Signature: (Lcom/sun/jna/Pointer;JJ[BII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3BII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_writeBytes (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jbyteArray arr, jint off, jint n) { PSTART(); @@ -2347,10 +2347,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3 /* * Class: com_sun_jna_Native - * Method: write + * Method: writeChars * Signature: (Lcom/sun/jna/Pointer;JJ[CII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3CII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_writeChars (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jcharArray arr, jint off, jint n) { getChars(env, (wchar_t*)L2A(addr + offset), arr, off, n); @@ -2358,10 +2358,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3 /* * Class: com_sun_jna_Native - * Method: write + * Method: writeDoubles * Signature: (Lcom/sun/jna/Pointer;JJ[DII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3DII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_writeDoubles (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jdoubleArray arr, jint off, jint n) { PSTART(); @@ -2371,10 +2371,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3 /* * Class: com_sun_jna_Native - * Method: write + * Method: writeFloats * Signature: (Lcom/sun/jna/Pointer;JJ[FII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3FII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_writeFloats (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jfloatArray arr, jint off, jint n) { PSTART(); @@ -2384,10 +2384,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3 /* * Class: com_sun_jna_Native - * Method: write + * Method: writeInts * Signature: (Lcom/sun/jna/Pointer;JJ[III)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3III +JNIEXPORT void JNICALL Java_com_sun_jna_Native_writeInts (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jintArray arr, jint off, jint n) { PSTART(); @@ -2397,10 +2397,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3 /* * Class: com_sun_jna_Native - * Method: write + * Method: writeLongs * Signature: (Lcom/sun/jna/Pointer;JJ[JII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3JII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_writeLongs (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlongArray arr, jint off, jint n) { PSTART(); @@ -2410,10 +2410,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3 /* * Class: com_sun_jna_Native - * Method: write + * Method: writeShorts * Signature: (Lcom/sun/jna/Pointer;JJ[SII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_write__Lcom_sun_jna_Pointer_2JJ_3SII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_writeShorts (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jshortArray arr, jint off, jint n) { PSTART(); @@ -2445,10 +2445,10 @@ JNIEXPORT jlong JNICALL Java_com_sun_jna_Native_indexOf /* * Class: com_sun_jna_Native - * Method: read + * Method: readBytes * Signature: (Lcom/sun/jna/Pointer;JJ[BII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3BII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_readBytes (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jbyteArray arr, jint off, jint n) { PSTART(); @@ -2458,10 +2458,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3B /* * Class: com_sun_jna_Native - * Method: read + * Method: readChars * Signature: (Lcom/sun/jna/Pointer;JJ[CII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3CII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_readChars (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jcharArray arr, jint off, jint n) { setChars(env, (wchar_t*)L2A(addr + offset), arr, off, n); @@ -2469,10 +2469,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3C /* * Class: com_sun_jna_Native - * Method: read + * Method: readDoubles * Signature: (Lcom/sun/jna/Pointer;JJ[DII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3DII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_readDoubles (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jdoubleArray arr, jint off, jint n) { PSTART(); @@ -2482,10 +2482,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3D /* * Class: com_sun_jna_Native - * Method: read + * Method: readFloats * Signature: (Lcom/sun/jna/Pointer;JJ[FII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3FII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_readFloats (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jfloatArray arr, jint off, jint n) { PSTART(); @@ -2495,10 +2495,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3F /* * Class: com_sun_jna_Native - * Method: read + * Method: readInts * Signature: (Lcom/sun/jna/Pointer;JJ[III)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3III +JNIEXPORT void JNICALL Java_com_sun_jna_Native_readInts (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jintArray arr, jint off, jint n) { PSTART(); @@ -2508,10 +2508,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3I /* * Class: com_sun_jna_Native - * Method: read + * Method: readLongs * Signature: (Lcom/sun/jna/Pointer;JJ[JII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3JII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_readLongs (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlongArray arr, jint off, jint n) { PSTART(); @@ -2521,10 +2521,10 @@ JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3J /* * Class: com_sun_jna_Native - * Method: read + * Method: readShorts * Signature: (Lcom/sun/jna/Pointer;JJ[SII)V */ -JNIEXPORT void JNICALL Java_com_sun_jna_Native_read__Lcom_sun_jna_Pointer_2JJ_3SII +JNIEXPORT void JNICALL Java_com_sun_jna_Native_readShorts (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jshortArray arr, jint off, jint n) { PSTART(); @@ -2576,7 +2576,7 @@ JNIEXPORT jlong JNICALL Java_com_sun_jna_Native__1getPointer * Method: getDirectByteBuffer * Signature: (Lcom/sun/jna/Pointer;JJJ)Ljava/nio/ByteBuffer; */ -JNIEXPORT jobject JNICALL Java_com_sun_jna_Native_getDirectByteBuffer__Lcom_sun_jna_Pointer_2JJJ +JNIEXPORT jobject JNICALL Java_com_sun_jna_Native_getDirectByteBuffer (JNIEnv *env, jclass UNUSED(cls), jobject UNUSED(pointer), jlong addr, jlong offset, jlong length) { #ifdef NO_NIO_BUFFERS @@ -3314,6 +3314,20 @@ is_protected() { return JNI_FALSE; } +jint initializeJnaStatics(JNIEnv *env) { + int result = JNI_VERSION_1_4; + const char* err; + if ((err = JNA_init(env)) != NULL) { + fprintf(stderr, "JNA: Problems loading core IDs: %s\n", err); + result = 0; + } + else if ((err = JNA_callback_init(env)) != NULL) { + fprintf(stderr, "JNA: Problems loading callback IDs: %s\n", err); + result = 0; + } + return result; +} + JNIEXPORT jboolean JNICALL Java_com_sun_jna_Native_isProtected(JNIEnv *UNUSED(env), jclass UNUSED(classp)) { return is_protected(); @@ -3335,6 +3349,10 @@ Java_com_sun_jna_Native_getNativeVersion(JNIEnv *env, jclass UNUSED(classp)) { #ifndef JNA_JNI_VERSION #define JNA_JNI_VERSION "undefined" #endif + // sanity check initialization + if (classString == NULL) { + initializeJnaStatics(env); + } return newJavaString(env, JNA_JNI_VERSION, CHARSET_UTF8); } @@ -3346,39 +3364,43 @@ Java_com_sun_jna_Native_getAPIChecksum(JNIEnv *env, jclass UNUSED(classp)) { return newJavaString(env, CHECKSUM, CHARSET_UTF8); } -JNIEXPORT jint JNICALL -JNI_OnLoad(JavaVM *jvm, void *UNUSED(reserved)) { +JNIEXPORT jboolean JNICALL Java_com_sun_jna_Native_isStaticEnabled(JNIEnv * UNUSED(env), jclass UNUSED(classp)) { + return JNI_TRUE; +} + +JNIEXPORT jint JNICALL Java_com_sun_jna_Native_initializeStatic(JNIEnv *env, jclass UNUSED(classp)) { + return initializeJnaStatics(env); +} + +jint setupJna(JavaVM *jvm) { JNIEnv* env; - int result = JNI_VERSION_1_4; int attached = (*jvm)->GetEnv(jvm, (void *)&env, JNI_VERSION_1_4) == JNI_OK; - const char* err; - if (!attached) { if ((*jvm)->AttachCurrentThread(jvm, (void *)&env, NULL) != JNI_OK) { fprintf(stderr, "JNA: Can't attach native thread to VM on load\n"); return 0; } } - - if ((err = JNA_init(env)) != NULL) { - fprintf(stderr, "JNA: Problems loading core IDs: %s\n", err); - result = 0; - } - else if ((err = JNA_callback_init(env)) != NULL) { - fprintf(stderr, "JNA: Problems loading callback IDs: %s\n", err); - result = 0; - } + int result = initializeJnaStatics(env); if (!attached) { if ((*jvm)->DetachCurrentThread(jvm) != 0) { fprintf(stderr, "JNA: could not detach thread on initial load\n"); } } - return result; } -JNIEXPORT void JNICALL -JNI_OnUnload(JavaVM *vm, void *UNUSED(reserved)) { +JNIEXPORT jint JNICALL +JNI_OnLoad_jnidispatch(JavaVM *jvm, void *UNUSED(reserved)) { + return setupJna(jvm); +} + +JNIEXPORT jint JNICALL +JNI_OnLoad(JavaVM *jvm, void *UNUSED(reserved)) { + return setupJna(jvm); +} + +void unloadJna(JavaVM *vm) { jobject* refs[] = { &classObject, &classClass, &classMethod, &classString, @@ -3443,6 +3465,17 @@ JNI_OnUnload(JavaVM *vm, void *UNUSED(reserved)) { } } +JNIEXPORT void JNICALL +JNI_OnUnload(JavaVM *jvm, void *UNUSED(reserved)) { + unloadJna(jvm); +} + + +JNIEXPORT void JNICALL +JNI_OnUnload_jnidispatch(JavaVM *jvm, void *UNUSED(reserved)) { + unloadJna(jvm); +} + JNIEXPORT void JNICALL Java_com_sun_jna_Native_unregister(JNIEnv *env, jclass UNUSED(ncls), jclass cls, jlongArray handles) { jlong* data = (*env)->GetLongArrayElements(env, handles, NULL); diff --git a/pom-jna-graalvm.xml b/pom-jna-graalvm.xml new file mode 100644 index 000000000..d1c71c753 --- /dev/null +++ b/pom-jna-graalvm.xml @@ -0,0 +1,87 @@ + + 4.0.0 + + net.java.dev.jna + jna-graalvm + TEMPLATE + jar + + Java Native Access + Java Native Access + https://github.com/java-native-access/jna + + + + LGPL-2.1-or-later + https://www.gnu.org/licenses/old-licenses/lgpl-2.1 + repo + + Java Native Access (JNA) is licensed under the LGPL, version 2.1 or + later, or the Apache License, version 2.0. You can freely decide which + license you want to apply to the project. + + + + Apache-2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + Java Native Access (JNA) is licensed under the LGPL, version 2.1 or + later, or the Apache License, version 2.0. You can freely decide which + license you want to apply to the project. + + + + + + scm:git:https://github.com/java-native-access/jna + scm:git:ssh://git@github.com/java-native-access/jna.git + https://github.com/java-native-access/jna + + + + + twall + Timothy Wall + + Owner + + + + mblaesing@doppel-helix.eu + Matthias Bläsing + https://github.com/matthiasblaesing/ + + Developer + + + + sam@elide.dev + Sam Gammon + https://github.com/sgammon/ + + Developer + + + + dario@elide.dev + Dario Valdespino + https://github.com/darvld/ + + Developer + + + + + + + org.graalvm.sdk + nativeimage + GRAALVM_VERSION + + + + diff --git a/samples/README.md b/samples/README.md new file mode 100644 index 000000000..80326eb8d --- /dev/null +++ b/samples/README.md @@ -0,0 +1,11 @@ +# JNA Samples + +This directory contains sample projects that use JNA in different ways. See below for a list of available samples: + +- **[GraalVM Native JNA][0]:** Builds a GraalVM native image using JNA features with Gradle. + +- **[Graalvm Native JNA (Static)][1]:** Uses the [SubstrateStaticJNA](../lib/gvm/SubstrateStaticJNA.java) feature to build + JNA code statically into the Native Image. + +[0]: ./graalvm-native-jna +[1]: ./graalvm-native-static-jna diff --git a/samples/graalvm-native-jna/.gitignore b/samples/graalvm-native-jna/.gitignore new file mode 100644 index 000000000..12eb6a96f --- /dev/null +++ b/samples/graalvm-native-jna/.gitignore @@ -0,0 +1,2 @@ +/.gradle +/build diff --git a/samples/graalvm-native-jna/README.md b/samples/graalvm-native-jna/README.md new file mode 100644 index 000000000..72dae1231 --- /dev/null +++ b/samples/graalvm-native-jna/README.md @@ -0,0 +1,3 @@ +# JNA Sample: GraalVM Native Image + +This directory contains a sample Gradle project which uses JNA with [GraalVM](https://graalvm.org/). The project builds a [native image](https://www.graalvm.org/latest/reference-manual/native-image/) which uses JNA features, powered by JNA's integration library for Substrate. diff --git a/samples/graalvm-native-jna/build.gradle.kts b/samples/graalvm-native-jna/build.gradle.kts new file mode 100644 index 000000000..c6ed78815 --- /dev/null +++ b/samples/graalvm-native-jna/build.gradle.kts @@ -0,0 +1,88 @@ +/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +plugins { + java + application + alias(libs.plugins.graalvm) +} + +application { + mainClass = "com.example.JnaNative" +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(22) + vendor = JvmVendorSpec.GRAAL_VM + } +} + +dependencies { + implementation(libs.bundles.jna) + implementation(libs.bundles.graalvm.api) + nativeImageClasspath(libs.jna.graalvm) +} + +val nativeImageDebug: String by properties + +graalvmNative { + testSupport = true + toolchainDetection = false + + binaries { + named("main") { + buildArgs.addAll(if (nativeImageDebug != "true") emptyList() else listOf( + "--verbose", + "--debug-attach", + "-H:+UnlockExperimentalVMOptions", + "-H:+JNIEnhancedErrorCodes", + "-H:+SourceLevelDebug", + "-H:-DeleteLocalSymbols", + "-H:-RemoveUnusedSymbols", + "-H:+PreserveFramePointer", + "-H:+ReportExceptionStackTraces", + )) + } + } +} + +// Allow the outer Ant build to override the version of JNA or GraalVM. +// These properties are used in JNA's CI and don't need to be in projects that use JNA. + +val jnaVersion: String by properties +val graalvmVersion: String by properties +val overrides = jnaVersion.isNotBlank() || graalvmVersion.isNotBlank() + +if (overrides) configurations.all { + resolutionStrategy.eachDependency { + if (requested.group == "net.java.dev.jna") { + useVersion(jnaVersion) + because("overridden by ant build") + } + if (requested.group == "org.graalvm") { + useVersion(graalvmVersion) + because("overridden by ant build") + } + } +} diff --git a/samples/graalvm-native-jna/gradle.properties b/samples/graalvm-native-jna/gradle.properties new file mode 100644 index 000000000..d88e8c59d --- /dev/null +++ b/samples/graalvm-native-jna/gradle.properties @@ -0,0 +1,28 @@ +# Copyright (c) 2015 Adam Marcionek, All Rights Reserved +# +# The contents of this file is dual-licensed under 2 +# alternative Open Source/Free licenses: LGPL 2.1 or later and +# Apache License 2.0. (starting with JNA version 4.0.0). +# +# You can freely decide which license you want to apply to +# the project. +# +# You may obtain a copy of the LGPL License at: +# +# http://www.gnu.org/licenses/licenses.html +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "LGPL2.1". +# +# You may obtain a copy of the Apache License at: +# +# http://www.apache.org/licenses/ +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "AL2.0". + +# These properties are left blank, to be filled in by the outer Ant build. +# When given a value, these versions override the values declared in the version catalog. +jnaVersion= +graalvmVersion= +nativeImageDebug= diff --git a/samples/graalvm-native-jna/gradle/libs.versions.toml b/samples/graalvm-native-jna/gradle/libs.versions.toml new file mode 100644 index 000000000..81d0b8e67 --- /dev/null +++ b/samples/graalvm-native-jna/gradle/libs.versions.toml @@ -0,0 +1,57 @@ +# Copyright (c) 2015 Adam Marcionek, All Rights Reserved +# +# The contents of this file is dual-licensed under 2 +# alternative Open Source/Free licenses: LGPL 2.1 or later and +# Apache License 2.0. (starting with JNA version 4.0.0). +# +# You can freely decide which license you want to apply to +# the project. +# +# You may obtain a copy of the LGPL License at: +# +# http://www.gnu.org/licenses/licenses.html +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "LGPL2.1". +# +# You may obtain a copy of the Apache License at: +# +# http://www.apache.org/licenses/ +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "AL2.0". + +[versions] +jna = "5.15.0-SNAPSHOT" +graalvm = "24.0.1" +graalvm-plugin = "0.10.2" + +[plugins] +graalvm = { id = "org.graalvm.buildtools.native", version.ref = "graalvm-plugin" } + +[libraries] +jna = { group = "net.java.dev.jna", name = "jna", version.ref = "jna" } +jna-graalvm = { group = "net.java.dev.jna", name = "jna-graalvm", version.ref = "jna" } +jna-jpms = { group = "net.java.dev.jna", name = "jna-jpms", version.ref = "jna" } +jna-platform = { group = "net.java.dev.jna", name = "jna-platform", version.ref = "jna" } +jna-platform-jpms = { group = "net.java.dev.jna", name = "jna-platform-jpms", version.ref = "jna" } +graalvm-nativeimage-svm = { group = "org.graalvm.nativeimage", name = "svm", version.ref = "graalvm" } +graalvm-sdk-nativeimage = { group = "org.graalvm.sdk", name = "nativeimage", version.ref = "graalvm" } +graalvm-sdk-jniutils = { group = "org.graalvm.sdk", name = "jniutils", version.ref = "graalvm" } + +[bundles] + +jna = [ + "jna", + "jna-platform" +] + +jna-jpms = [ + "jna-jpms", + "jna-platform-jpms" +] + +graalvm-api = [ + "graalvm-sdk-nativeimage", + "graalvm-sdk-jniutils" +] diff --git a/samples/graalvm-native-jna/gradle/wrapper/gradle-wrapper.jar b/samples/graalvm-native-jna/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e6441136f Binary files /dev/null and b/samples/graalvm-native-jna/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/graalvm-native-jna/gradle/wrapper/gradle-wrapper.properties b/samples/graalvm-native-jna/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..a4413138c --- /dev/null +++ b/samples/graalvm-native-jna/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/graalvm-native-jna/gradlew b/samples/graalvm-native-jna/gradlew new file mode 100755 index 000000000..b740cf133 --- /dev/null +++ b/samples/graalvm-native-jna/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/graalvm-native-jna/gradlew.bat b/samples/graalvm-native-jna/gradlew.bat new file mode 100644 index 000000000..25da30dbd --- /dev/null +++ b/samples/graalvm-native-jna/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/graalvm-native-jna/settings.gradle.kts b/samples/graalvm-native-jna/settings.gradle.kts new file mode 100644 index 000000000..27052984f --- /dev/null +++ b/samples/graalvm-native-jna/settings.gradle.kts @@ -0,0 +1,42 @@ +/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version ("0.8.0") +} + +dependencyResolutionManagement { + repositoriesMode = RepositoriesMode.PREFER_PROJECT + + repositories { + mavenLocal() + mavenCentral() + } +} diff --git a/samples/graalvm-native-jna/src/main/java/com/example/JnaNative.java b/samples/graalvm-native-jna/src/main/java/com/example/JnaNative.java new file mode 100644 index 000000000..5265bbaf9 --- /dev/null +++ b/samples/graalvm-native-jna/src/main/java/com/example/JnaNative.java @@ -0,0 +1,45 @@ +/* Copyright (c) 2007-2015 Timothy Wall, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +package com.example; + +import com.sun.jna.Library; +import com.sun.jna.Native; +import com.sun.jna.Platform; + +public final class JnaNative { + public interface CLibrary extends Library { + CLibrary INSTANCE = (CLibrary) + Native.load((Platform.isWindows() ? "msvcrt" : "c"), + CLibrary.class); + + void printf(String format, Object... args); + } + + public static void main(String[] args) { + System.out.println("Hello, JNA!"); + for (int i=0;i < args.length;i++) { + CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]); + } + } +} diff --git a/samples/graalvm-native-static-jna/.gitignore b/samples/graalvm-native-static-jna/.gitignore new file mode 100644 index 000000000..12eb6a96f --- /dev/null +++ b/samples/graalvm-native-static-jna/.gitignore @@ -0,0 +1,2 @@ +/.gradle +/build diff --git a/samples/graalvm-native-static-jna/README.md b/samples/graalvm-native-static-jna/README.md new file mode 100644 index 000000000..f8a969548 --- /dev/null +++ b/samples/graalvm-native-static-jna/README.md @@ -0,0 +1,10 @@ +# JNA Sample: GraalVM Native Image (Static) + +This directory contains a sample Gradle project which uses JNA with [GraalVM](https://graalvm.org/). The project builds a +[native image](https://www.graalvm.org/latest/reference-manual/native-image/) which uses JNA features, powered by JNA's integration library for Substrate. + +This sample leverages [Static JNI](https://www.blog.akhil.cc/static-jni) to build JNA and JNA-related user code +directly into the native image. + +Using this technique can optimize startup time and other performance factors, because no dynamic library unpack-and-load +step is required to use JNA. diff --git a/samples/graalvm-native-static-jna/build.gradle.kts b/samples/graalvm-native-static-jna/build.gradle.kts new file mode 100644 index 000000000..6481a3030 --- /dev/null +++ b/samples/graalvm-native-static-jna/build.gradle.kts @@ -0,0 +1,93 @@ +/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +plugins { + java + application + alias(libs.plugins.graalvm) +} + +application { + mainClass = "com.example.JnaNative" +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(22) + vendor = JvmVendorSpec.GRAAL_VM + } +} + +dependencies { + implementation(libs.bundles.jna) + implementation(libs.bundles.graalvm.api) + nativeImageClasspath(libs.jna.graalvm) +} + +val nativeImageDebug: String by properties + +graalvmNative { + testSupport = true + toolchainDetection = false + + binaries { + named("main") { + buildArgs.addAll(listOf( + "--features=com.sun.jna.SubstrateStaticJNA", + ).plus(if (nativeImageDebug != "true") emptyList() else listOf( + "--verbose", + "--debug-attach", + "-J-Xlog:library=info", + "-H:+UnlockExperimentalVMOptions", + "-H:+JNIEnhancedErrorCodes", + "-H:+SourceLevelDebug", + "-H:-DeleteLocalSymbols", + "-H:-RemoveUnusedSymbols", + "-H:+PreserveFramePointer", + "-H:+ReportExceptionStackTraces", + "-H:CCompilerOption=-v", + "-H:NativeLinkerOption=-v", + ))) + } + } +} + +// Allow the outer Ant build to override the version of JNA or GraalVM. +// These properties are used in JNA's CI and don't need to be in projects that use JNA. + +val jnaVersion: String by properties +val graalvmVersion: String by properties +val overrides = jnaVersion.isNotBlank() || graalvmVersion.isNotBlank() + +if (overrides) configurations.all { + resolutionStrategy.eachDependency { + if (requested.group == "net.java.dev.jna") { + useVersion(jnaVersion) + because("overridden by ant build") + } + if (requested.group == "org.graalvm") { + useVersion(graalvmVersion) + because("overridden by ant build") + } + } +} diff --git a/samples/graalvm-native-static-jna/gradle.properties b/samples/graalvm-native-static-jna/gradle.properties new file mode 100644 index 000000000..d88e8c59d --- /dev/null +++ b/samples/graalvm-native-static-jna/gradle.properties @@ -0,0 +1,28 @@ +# Copyright (c) 2015 Adam Marcionek, All Rights Reserved +# +# The contents of this file is dual-licensed under 2 +# alternative Open Source/Free licenses: LGPL 2.1 or later and +# Apache License 2.0. (starting with JNA version 4.0.0). +# +# You can freely decide which license you want to apply to +# the project. +# +# You may obtain a copy of the LGPL License at: +# +# http://www.gnu.org/licenses/licenses.html +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "LGPL2.1". +# +# You may obtain a copy of the Apache License at: +# +# http://www.apache.org/licenses/ +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "AL2.0". + +# These properties are left blank, to be filled in by the outer Ant build. +# When given a value, these versions override the values declared in the version catalog. +jnaVersion= +graalvmVersion= +nativeImageDebug= diff --git a/samples/graalvm-native-static-jna/gradle/libs.versions.toml b/samples/graalvm-native-static-jna/gradle/libs.versions.toml new file mode 100644 index 000000000..81d0b8e67 --- /dev/null +++ b/samples/graalvm-native-static-jna/gradle/libs.versions.toml @@ -0,0 +1,57 @@ +# Copyright (c) 2015 Adam Marcionek, All Rights Reserved +# +# The contents of this file is dual-licensed under 2 +# alternative Open Source/Free licenses: LGPL 2.1 or later and +# Apache License 2.0. (starting with JNA version 4.0.0). +# +# You can freely decide which license you want to apply to +# the project. +# +# You may obtain a copy of the LGPL License at: +# +# http://www.gnu.org/licenses/licenses.html +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "LGPL2.1". +# +# You may obtain a copy of the Apache License at: +# +# http://www.apache.org/licenses/ +# +# A copy is also included in the downloadable source code package +# containing JNA, in file "AL2.0". + +[versions] +jna = "5.15.0-SNAPSHOT" +graalvm = "24.0.1" +graalvm-plugin = "0.10.2" + +[plugins] +graalvm = { id = "org.graalvm.buildtools.native", version.ref = "graalvm-plugin" } + +[libraries] +jna = { group = "net.java.dev.jna", name = "jna", version.ref = "jna" } +jna-graalvm = { group = "net.java.dev.jna", name = "jna-graalvm", version.ref = "jna" } +jna-jpms = { group = "net.java.dev.jna", name = "jna-jpms", version.ref = "jna" } +jna-platform = { group = "net.java.dev.jna", name = "jna-platform", version.ref = "jna" } +jna-platform-jpms = { group = "net.java.dev.jna", name = "jna-platform-jpms", version.ref = "jna" } +graalvm-nativeimage-svm = { group = "org.graalvm.nativeimage", name = "svm", version.ref = "graalvm" } +graalvm-sdk-nativeimage = { group = "org.graalvm.sdk", name = "nativeimage", version.ref = "graalvm" } +graalvm-sdk-jniutils = { group = "org.graalvm.sdk", name = "jniutils", version.ref = "graalvm" } + +[bundles] + +jna = [ + "jna", + "jna-platform" +] + +jna-jpms = [ + "jna-jpms", + "jna-platform-jpms" +] + +graalvm-api = [ + "graalvm-sdk-nativeimage", + "graalvm-sdk-jniutils" +] diff --git a/samples/graalvm-native-static-jna/gradle/wrapper/gradle-wrapper.jar b/samples/graalvm-native-static-jna/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e6441136f Binary files /dev/null and b/samples/graalvm-native-static-jna/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/graalvm-native-static-jna/gradle/wrapper/gradle-wrapper.properties b/samples/graalvm-native-static-jna/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..a4413138c --- /dev/null +++ b/samples/graalvm-native-static-jna/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/graalvm-native-static-jna/gradlew b/samples/graalvm-native-static-jna/gradlew new file mode 100755 index 000000000..b740cf133 --- /dev/null +++ b/samples/graalvm-native-static-jna/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/graalvm-native-static-jna/gradlew.bat b/samples/graalvm-native-static-jna/gradlew.bat new file mode 100644 index 000000000..25da30dbd --- /dev/null +++ b/samples/graalvm-native-static-jna/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/graalvm-native-static-jna/settings.gradle.kts b/samples/graalvm-native-static-jna/settings.gradle.kts new file mode 100644 index 000000000..27052984f --- /dev/null +++ b/samples/graalvm-native-static-jna/settings.gradle.kts @@ -0,0 +1,42 @@ +/* Copyright (c) 2015 Adam Marcionek, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version ("0.8.0") +} + +dependencyResolutionManagement { + repositoriesMode = RepositoriesMode.PREFER_PROJECT + + repositories { + mavenLocal() + mavenCentral() + } +} diff --git a/samples/graalvm-native-static-jna/src/main/java/com/example/JnaNative.java b/samples/graalvm-native-static-jna/src/main/java/com/example/JnaNative.java new file mode 100644 index 000000000..4a341fa80 --- /dev/null +++ b/samples/graalvm-native-static-jna/src/main/java/com/example/JnaNative.java @@ -0,0 +1,47 @@ +/* Copyright (c) 2007-2015 Timothy Wall, All Rights Reserved + * + * The contents of this file is dual-licensed under 2 + * alternative Open Source/Free licenses: LGPL 2.1 or later and + * Apache License 2.0. (starting with JNA version 4.0.0). + * + * You can freely decide which license you want to apply to + * the project. + * + * You may obtain a copy of the LGPL License at: + * + * http://www.gnu.org/licenses/licenses.html + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "LGPL2.1". + * + * You may obtain a copy of the Apache License at: + * + * http://www.apache.org/licenses/ + * + * A copy is also included in the downloadable source code package + * containing JNA, in file "AL2.0". + */ +package com.example; + +import com.sun.jna.Library; +import com.sun.jna.Native; +import com.sun.jna.Platform; + +public final class JnaNative { + static { + System.loadLibrary("jnidispatch"); + } + + public interface CLibrary extends Library { + CLibrary INSTANCE = (CLibrary) + Native.load((Platform.isWindows() ? "msvcrt" : "c"), + CLibrary.class); + + void puts(String value); + } + + public static void main(String[] args) { + System.out.println("Hello, JNA!"); + CLibrary.INSTANCE.puts("Hello from C!"); + } +} diff --git a/src/com/sun/jna/Native.java b/src/com/sun/jna/Native.java index 7edeb05c5..2d1ea03d2 100644 --- a/src/com/sun/jna/Native.java +++ b/src/com/sun/jna/Native.java @@ -33,6 +33,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; +import java.lang.System; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Array; @@ -105,6 +106,13 @@ *

Native Library Loading

* Native libraries loaded via {@link #load(Class)} may be found in * several locations. + *

Static Linkage under GraalVM Native Image

+ *

When using Static JNI under GraalVM, JNA's native library must be + * loaded statically; this call happens before all others. For platforms + * that want to force this check to be skipped (for instance, if it is known + * that the library will never ship to Substrate), the property + * jna.skipStatic=true can be set; in this case, the static + * load step is skipped.

* @see Library * @author Todd Fast, todd.fast@sun.com * @author twall@users.sf.net @@ -947,6 +955,18 @@ private static void loadNativeDispatchLibrary() { } String libName = System.getProperty("jna.boot.library.name", "jnidispatch"); + + // if in static init mode, load the library by name and force-run the initializer + if (!Boolean.getBoolean("jna.skipStatic")) { + try { + System.loadLibrary(libName); + assert isStaticEnabled(); + assert initializeStatic() == 0x00010004; + return; + } catch (UnsatisfiedLinkError err) { + // continue + } + } String bootPath = System.getProperty("jna.boot.library.path"); if (bootPath != null) { // String.split not available in 1.4 @@ -1198,6 +1218,8 @@ else if (!Boolean.getBoolean("jna.nounpack")) { **/ private static native int sizeof(int type); + private static synchronized native boolean isStaticEnabled(); + private static synchronized native int initializeStatic(); private static native String getNativeVersion(); private static native String getAPIChecksum(); @@ -2020,6 +2042,7 @@ public static void main(String[] args) { ? pkg.getImplementationVersion() : DEFAULT_BUILD; if (version == null) version = DEFAULT_BUILD; System.out.println("Version: " + version); + System.out.println(" Static: " + isStaticEnabled()); System.out.println(" Native: " + getNativeVersion() + " (" + getAPIChecksum() + ")"); System.out.println(" Prefix: " + Platform.RESOURCE_PREFIX); @@ -2213,33 +2236,33 @@ static long open(String name) { */ static native long indexOf(Pointer pointer, long baseaddr, long offset, byte value); - static native void read(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length); + static native void readBytes(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length); - static native void read(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length); + static native void readShorts(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length); - static native void read(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length); + static native void readChars(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length); - static native void read(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length); + static native void readInts(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length); - static native void read(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length); + static native void readLongs(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length); - static native void read(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length); + static native void readFloats(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length); - static native void read(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length); + static native void readDoubles(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length); - static native void write(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length); + static native void writeBytes(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length); - static native void write(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length); + static native void writeShorts(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length); - static native void write(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length); + static native void writeChars(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length); - static native void write(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length); + static native void writeInts(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length); - static native void write(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length); + static native void writeLongs(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length); - static native void write(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length); + static native void writeFloats(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length); - static native void write(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length); + static native void writeDoubles(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length); static native byte getByte(Pointer pointer, long baseaddr, long offset); diff --git a/src/com/sun/jna/Pointer.java b/src/com/sun/jna/Pointer.java index 444035f51..3dad56909 100644 --- a/src/com/sun/jna/Pointer.java +++ b/src/com/sun/jna/Pointer.java @@ -137,7 +137,7 @@ public long indexOf(long offset, byte value) { * @param length number of elements from native pointer that must be copied */ public void read(long offset, byte[] buf, int index, int length) { - Native.read(this, this.peer, offset, buf, index, length); + Native.readBytes(this, this.peer, offset, buf, index, length); } /** @@ -150,7 +150,7 @@ public void read(long offset, byte[] buf, int index, int length) { * @param length number of elements from native pointer that must be copied */ public void read(long offset, short[] buf, int index, int length) { - Native.read(this, this.peer, offset, buf, index, length); + Native.readShorts(this, this.peer, offset, buf, index, length); } /** @@ -163,7 +163,7 @@ public void read(long offset, short[] buf, int index, int length) { * @param length number of elements from native pointer that must be copied */ public void read(long offset, char[] buf, int index, int length) { - Native.read(this, this.peer, offset, buf, index, length); + Native.readChars(this, this.peer, offset, buf, index, length); } /** @@ -176,7 +176,7 @@ public void read(long offset, char[] buf, int index, int length) { * @param length number of elements from native pointer that must be copied */ public void read(long offset, int[] buf, int index, int length) { - Native.read(this, this.peer, offset, buf, index, length); + Native.readInts(this, this.peer, offset, buf, index, length); } /** @@ -189,7 +189,7 @@ public void read(long offset, int[] buf, int index, int length) { * @param length number of elements from native pointer that must be copied */ public void read(long offset, long[] buf, int index, int length) { - Native.read(this, this.peer, offset, buf, index, length); + Native.readLongs(this, this.peer, offset, buf, index, length); } /** @@ -202,7 +202,7 @@ public void read(long offset, long[] buf, int index, int length) { * @param length number of elements from native pointer that must be copied */ public void read(long offset, float[] buf, int index, int length) { - Native.read(this, this.peer, offset, buf, index, length); + Native.readFloats(this, this.peer, offset, buf, index, length); } /** @@ -215,7 +215,7 @@ public void read(long offset, float[] buf, int index, int length) { * @param length number of elements from native pointer that must be copied */ public void read(long offset, double[] buf, int index, int length) { - Native.read(this, this.peer, offset, buf, index, length); + Native.readDoubles(this, this.peer, offset, buf, index, length); } /** @@ -254,7 +254,7 @@ public void read(long offset, Pointer[] buf, int index, int length) { * copied */ public void write(long offset, byte[] buf, int index, int length) { - Native.write(this, this.peer, offset, buf, index, length); + Native.writeBytes(this, this.peer, offset, buf, index, length); } /** @@ -268,7 +268,7 @@ public void write(long offset, byte[] buf, int index, int length) { * copied */ public void write(long offset, short[] buf, int index, int length) { - Native.write(this, this.peer, offset, buf, index, length); + Native.writeShorts(this, this.peer, offset, buf, index, length); } /** @@ -282,7 +282,7 @@ public void write(long offset, short[] buf, int index, int length) { * copied */ public void write(long offset, char[] buf, int index, int length) { - Native.write(this, this.peer, offset, buf, index, length); + Native.writeChars(this, this.peer, offset, buf, index, length); } /** @@ -296,7 +296,7 @@ public void write(long offset, char[] buf, int index, int length) { * copied */ public void write(long offset, int[] buf, int index, int length) { - Native.write(this, this.peer, offset, buf, index, length); + Native.writeInts(this, this.peer, offset, buf, index, length); } /** @@ -310,7 +310,7 @@ public void write(long offset, int[] buf, int index, int length) { * copied */ public void write(long offset, long[] buf, int index, int length) { - Native.write(this, this.peer, offset, buf, index, length); + Native.writeLongs(this, this.peer, offset, buf, index, length); } /** @@ -324,7 +324,7 @@ public void write(long offset, long[] buf, int index, int length) { * copied */ public void write(long offset, float[] buf, int index, int length) { - Native.write(this, this.peer, offset, buf, index, length); + Native.writeFloats(this, this.peer, offset, buf, index, length); } /** @@ -338,7 +338,7 @@ public void write(long offset, float[] buf, int index, int length) { * copied */ public void write(long offset, double[] buf, int index, int length) { - Native.write(this, this.peer, offset, buf, index, length); + Native.writeDoubles(this, this.peer, offset, buf, index, length); } /** Write the given array of Pointer to native memory.