diff --git a/.github/workflows/graalvm.yaml b/.github/workflows/graalvm.yaml new file mode 100644 index 000000000..98bcf3d3a --- /dev/null +++ b/.github/workflows/graalvm.yaml @@ -0,0 +1,34 @@ +# 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: Native Image" + run: ant dist && ant install && ant nativeImage && ant nativeRun diff --git a/build.xml b/build.xml index 5ba1b0e14..d46cb5712 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,23 @@ uri="antlib:org.codehaus.mojo.animal_sniffer" classpathref="maven-ant-tasks.classpath" /> + + + + + + + + + + + + + + + + + @@ -131,6 +156,7 @@ + + + + + + @@ -192,6 +229,7 @@ + @@ -237,6 +275,9 @@ + + + @@ -246,12 +287,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -569,6 +660,9 @@ osname=macosx;processor=aarch64 + + + @@ -649,7 +743,7 @@ osname=macosx;processor=aarch64 - + @@ -1014,21 +1108,37 @@ cd .. + + includes="jnidispatch.dll,libjnidispatch.*" + excludes="*.lib,*.a"/> + + + + + - + + + + + + + + @@ -1036,6 +1146,7 @@ cd .. + @@ -1292,6 +1403,54 @@ cd .. Reports generated in ${reports.clover} + + + + + + + + + + + + + + + + + + + JNA GraalVM Integration +
${header}
+ ${footer} + + + + + + + + + + + +
+ + + +
+ @@ -1351,7 +1510,7 @@ cd .. - + @@ -1366,6 +1525,9 @@ cd .. + + + @@ -1431,6 +1593,12 @@ cd .. + + + + + + @@ -1483,6 +1651,17 @@ cd .. + + + + + + + + + + + @@ -1538,6 +1717,19 @@ cd .. + + + + + + + + + + + + + @@ -1553,6 +1745,7 @@ cd .. + @@ -1581,4 +1774,20 @@ cd .. + + + + + + + + + + + + + + + + diff --git a/common.xml b/common.xml index cb09efa3b..7e26ebcc0 100644 --- a/common.xml +++ b/common.xml @@ -19,6 +19,7 @@ + diff --git a/lib/gvm/AbstractJNAFeature.java b/lib/gvm/AbstractJNAFeature.java new file mode 100644 index 000000000..4bcc71344 --- /dev/null +++ b/lib/gvm/AbstractJNAFeature.java @@ -0,0 +1,202 @@ +/* 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. +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..f11ecbf2f --- /dev/null +++ b/lib/gvm/JavaNativeAccess.java @@ -0,0 +1,163 @@ +/* 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. + */ +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(JNIEnv.class); + + 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")); + // @TODO: how do we register constructors? + // registerJniMethods(method(Pointer.class, "", long.class)); + + 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, + Native.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/SubstrateStaticJNA.java b/lib/gvm/SubstrateStaticJNA.java new file mode 100644 index 000000000..fa4e974aa --- /dev/null +++ b/lib/gvm/SubstrateStaticJNA.java @@ -0,0 +1,55 @@ +/* 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; + +/** + * 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. + */ +public final class SubstrateStaticJNA extends AbstractJNAFeature { + @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 void beforeAnalysis(BeforeAnalysisAccess access) { + // + } +} diff --git a/lib/gvm/native-image.properties b/lib/gvm/native-image.properties new file mode 100644 index 000000000..27763ef53 --- /dev/null +++ b/lib/gvm/native-image.properties @@ -0,0 +1,24 @@ +# 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 diff --git a/native/Makefile b/native/Makefile index 70078089f..c8de3a759 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,16 @@ $(LIBRARY): $(JNIDISPATCH_OBJS) $(FFI_LIB) $(LD) $(LDFLAGS) $(JNIDISPATCH_OBJS) $(FFI_LIB) $(LIBS) $(STRIP) $@ +$(LIBRARY_STATIC): $(JNIDISPATCH_OBJS) $(FFI_LIB) + @# the inert mkdir has to be here for spacing + @mkdir -p $(BUILD) +ifeq ($(OS),linux) + $(AR) rcs $@ $(JNIDISPATCH_OBJS) $(FFI_LIB) $(LIBS) +else + $(LD) $(subst -shared,-static,$(LDFLAGS)) $(JNIDISPATCH_OBJS) $(FFI_LIB) $(LIBS) +endif + $(STRIP) $@ + $(TESTLIB): $(BUILD)/testlib.o $(LD) $(LDFLAGS) $< $(LIBS) 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..07512e3c1 --- /dev/null +++ b/samples/README.md @@ -0,0 +1,5 @@ +# JNA Samples + +This directory contains sample projects that use JNA in different ways. See below for a list of available samples: + +- **GraalVM Native JNA:** Builds a GraalVM native image using JNA features with Gradle. 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..e90bb56e7 --- /dev/null +++ b/samples/graalvm-native-jna/build.gradle.kts @@ -0,0 +1,80 @@ +/* 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) +} + +graalvmNative { + testSupport = true + toolchainDetection = false + + binaries { + named("main") { + buildArgs.addAll(listOf( + "-H:+UnlockExperimentalVMOptions", + "-H:+ReportExceptionStackTraces", + "-H:+JNIEnhancedErrorCodes", + )) + } + } +} + +// 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..23d84f347 --- /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= + 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]); + } + } +}