diff --git a/.github/workflows/graalvm.yaml b/.github/workflows/graalvm.yaml index 98bcf3d3a..66ab1b56e 100644 --- a/.github/workflows/graalvm.yaml +++ b/.github/workflows/graalvm.yaml @@ -30,5 +30,9 @@ jobs: - 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 + - 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 a8f295d18..430542648 100644 --- a/build.xml +++ b/build.xml @@ -292,9 +292,9 @@ + - @@ -656,9 +656,6 @@ osname=macosx;processor=aarch64 - - - @@ -1123,6 +1120,8 @@ cd .. + @@ -1135,6 +1134,7 @@ cd .. + @@ -1781,9 +1781,36 @@ cd .. + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/gvm/SubstrateStaticJNA.java b/lib/gvm/SubstrateStaticJNA.java index fa4e974aa..35828e4c0 100644 --- a/lib/gvm/SubstrateStaticJNA.java +++ b/lib/gvm/SubstrateStaticJNA.java @@ -23,8 +23,18 @@ */ 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. * @@ -36,8 +46,125 @@ * *

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"; @@ -48,8 +175,34 @@ 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 index 27763ef53..95904edb4 100644 --- a/lib/gvm/native-image.properties +++ b/lib/gvm/native-image.properties @@ -21,4 +21,9 @@ # A copy is also included in the downloadable source code package # containing JNA, in file "AL2.0". -Args = --features=com.sun.jna.JavaNativeAccess +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/samples/README.md b/samples/README.md index 07512e3c1..80326eb8d 100644 --- a/samples/README.md +++ b/samples/README.md @@ -2,4 +2,10 @@ 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. +- **[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-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 c98dc6a22..2d1ea03d2 100644 --- a/src/com/sun/jna/Native.java +++ b/src/com/sun/jna/Native.java @@ -106,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