8331671: Implement JEP 472: Prepare to Restrict the Use of JNI

Reviewed-by: jpai, prr, ihse, kcr, alanb
This commit is contained in:
Maurizio Cimadamore 2024-08-26 09:17:45 +00:00
parent ce83f6af64
commit 20d8f58c92
107 changed files with 551 additions and 182 deletions

View File

@ -94,48 +94,26 @@ PLATFORM_MODULES_windows= \
NATIVE_ACCESS_MODULES= \
java.base \
java.datatransfer \
java.desktop \
java.instrument \
java.logging \
java.management \
java.management.rmi \
java.naming \
java.net.http \
java.prefs \
java.rmi \
java.scripting \
java.se \
java.security.jgss \
java.security.sasl \
java.smartcardio \
java.sql \
java.sql.rowset \
java.transaction.xa \
java.xml \
java.xml.crypto \
jdk.accessibility \
jdk.charsets \
jdk.attach \
jdk.crypto.cryptoki \
jdk.dynalink \
jdk.httpserver \
jdk.incubator.vector \
jdk.crypto.mscapi \
jdk.hotspot.agent \
jdk.internal.le \
jdk.internal.vm.ci \
jdk.jdi \
jdk.jfr \
jdk.jsobject \
jdk.localedata \
jdk.jpackage \
jdk.management \
jdk.management.agent \
jdk.management.jfr \
jdk.naming.dns \
jdk.naming.rmi \
jdk.net \
jdk.nio.mapmode \
jdk.sctp \
jdk.security.auth \
jdk.security.jgss \
jdk.unsupported \
jdk.xml.dom \
jdk.zipfs \
#

View File

@ -64,7 +64,7 @@ $(eval $(call SetupJavaCompilation, BUILD_TEST_LIB_JAR, \
BIN := $(TEST_LIB_SUPPORT)/test-lib_classes, \
HEADERS := $(TEST_LIB_SUPPORT)/test-lib_headers, \
JAR := $(TEST_LIB_SUPPORT)/test-lib.jar, \
DISABLED_WARNINGS := try deprecation rawtypes unchecked serial cast removal preview dangling-doc-comments, \
DISABLED_WARNINGS := try deprecation rawtypes unchecked serial cast removal preview restricted dangling-doc-comments, \
JAVAC_FLAGS := --add-exports java.base/sun.security.util=ALL-UNNAMED \
--add-exports java.base/jdk.internal.classfile=ALL-UNNAMED \
--add-exports java.base/jdk.internal.classfile.attribute=ALL-UNNAMED \

View File

@ -77,6 +77,7 @@
do_klass(StackOverflowError_klass, java_lang_StackOverflowError ) \
do_klass(IllegalMonitorStateException_klass, java_lang_IllegalMonitorStateException ) \
do_klass(Reference_klass, java_lang_ref_Reference ) \
do_klass(IllegalCallerException_klass, java_lang_IllegalCallerException ) \
\
/* ref klasses and set reference types */ \
do_klass(SoftReference_klass, java_lang_ref_SoftReference ) \

View File

@ -203,6 +203,7 @@ class SerializeClosure;
template(java_lang_CloneNotSupportedException, "java/lang/CloneNotSupportedException") \
template(java_lang_IllegalAccessException, "java/lang/IllegalAccessException") \
template(java_lang_IllegalArgumentException, "java/lang/IllegalArgumentException") \
template(java_lang_IllegalCallerException, "java/lang/IllegalCallerException") \
template(java_lang_IllegalStateException, "java/lang/IllegalStateException") \
template(java_lang_IllegalMonitorStateException, "java/lang/IllegalMonitorStateException") \
template(java_lang_IllegalThreadStateException, "java/lang/IllegalThreadStateException") \
@ -588,7 +589,7 @@ class SerializeClosure;
template(string_boolean_class_signature, "(Ljava/lang/String;Z)Ljava/lang/Class;") \
template(object_object_object_signature, "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;") \
template(string_string_signature, "(Ljava/lang/String;)Ljava/lang/String;") \
template(classloader_string_long_signature, "(Ljava/lang/ClassLoader;Ljava/lang/String;)J") \
template(classloader_class_string_string_long_signature, "(Ljava/lang/ClassLoader;Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)J") \
template(byte_array_void_signature, "([B)V") \
template(long_long_void_signature, "(JJ)V") \
template(void_byte_array_signature, "()[B") \

View File

@ -273,16 +273,22 @@ address NativeLookup::lookup_style(const methodHandle& method, char* pure_name,
// Otherwise call static method findNative in ClassLoader
Klass* klass = vmClasses::ClassLoader_klass();
Handle name_arg = java_lang_String::create_from_str(jni_name, CHECK_NULL);
Handle jni_class(THREAD, method->method_holder()->java_mirror());
Handle jni_name_arg = java_lang_String::create_from_str(jni_name, CHECK_NULL);
Handle java_name_arg = java_lang_String::create_from_str(method->name()->as_C_string(), CHECK_NULL);
JavaCallArguments args;
args.push_oop(loader);
args.push_oop(jni_class);
args.push_oop(jni_name_arg);
args.push_oop(java_name_arg);
JavaValue result(T_LONG);
JavaCalls::call_static(&result,
klass,
vmSymbols::findNative_name(),
vmSymbols::classloader_string_long_signature(),
// Arguments
loader,
name_arg,
vmSymbols::classloader_class_string_string_long_signature(),
&args,
CHECK_NULL);
entry = (address) (intptr_t) result.get_jlong();
@ -409,6 +415,14 @@ address NativeLookup::lookup_base(const methodHandle& method, TRAPS) {
entry = lookup_entry_prefixed(method, CHECK_NULL);
if (entry != nullptr) return entry;
if (THREAD->has_pending_exception()) {
oop exception = THREAD->pending_exception();
if (exception->is_a(vmClasses::IllegalCallerException_klass())) {
// we already have a pending exception from the restricted method check, just return
return nullptr;
}
}
// Native function not found, throw UnsatisfiedLinkError
stringStream ss;
ss.print("'");

View File

@ -305,6 +305,8 @@ bool needs_module_property_warning = false;
#define UPGRADE_PATH_LEN 12
#define ENABLE_NATIVE_ACCESS "enable.native.access"
#define ENABLE_NATIVE_ACCESS_LEN 20
#define ILLEGAL_NATIVE_ACCESS "illegal.native.access"
#define ILLEGAL_NATIVE_ACCESS_LEN 21
// Return TRUE if option matches 'property', or 'property=', or 'property.'.
static bool matches_property_suffix(const char* option, const char* property, size_t len) {
@ -326,6 +328,7 @@ bool Arguments::is_internal_module_property(const char* property) {
matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN) ||
matches_property_suffix(property_suffix, ILLEGAL_NATIVE_ACCESS, ILLEGAL_NATIVE_ACCESS_LEN) ||
matches_property_suffix(property_suffix, ENABLE_NATIVE_ACCESS, ENABLE_NATIVE_ACCESS_LEN)) {
return true;
}
@ -2243,6 +2246,10 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_m
if (!create_numbered_module_property("jdk.module.enable.native.access", tail, enable_native_access_count++)) {
return JNI_ENOMEM;
}
} else if (match_option(option, "--illegal-native-access=", &tail)) {
if (!create_module_property("jdk.module.illegal.native.access", tail, InternalProperty)) {
return JNI_ENOMEM;
}
} else if (match_option(option, "--limit-modules=", &tail)) {
if (!create_module_property("jdk.module.limitmods", tail, InternalProperty)) {
return JNI_ENOMEM;

View File

@ -2442,10 +2442,27 @@ public abstract class ClassLoader {
" in java.library.path: " + StaticProperty.javaLibraryPath());
}
/*
/**
* Invoked in the VM class linking code.
* @param loader the class loader used to look up the native library symbol
* @param clazz the class in which the native method is declared
* @param entryName the native method's mangled name (this is the name used for the native lookup)
* @param javaName the native method's declared name
*/
static long findNative(ClassLoader loader, String entryName) {
static long findNative(ClassLoader loader, Class<?> clazz, String entryName, String javaName) {
long addr = findNativeInternal(loader, entryName);
if (addr != 0 && loader != null) {
Reflection.ensureNativeAccess(clazz, clazz, javaName, true);
}
return addr;
}
/*
* This is also called by SymbolLookup::loaderLookup. In that case, we need
* to avoid a restricted check, as that check has already been performed when
* obtaining the lookup.
*/
static long findNativeInternal(ClassLoader loader, String entryName) {
if (loader == null) {
return BootLoader.getNativeLibraries().find(entryName);
} else {

View File

@ -62,7 +62,9 @@ import jdk.internal.loader.BootLoader;
import jdk.internal.loader.ClassLoaders;
import jdk.internal.misc.CDS;
import jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
import jdk.internal.module.ModuleBootstrap;
import jdk.internal.module.ModuleBootstrap.IllegalNativeAccess;
import jdk.internal.module.ModuleLoaderMap;
import jdk.internal.module.ServicesCatalog;
import jdk.internal.module.Resources;
@ -300,26 +302,43 @@ public final class Module implements AnnotatedElement {
}
// This is invoked from Reflection.ensureNativeAccess
void ensureNativeAccess(Class<?> owner, String methodName, Class<?> currentClass) {
void ensureNativeAccess(Class<?> owner, String methodName, Class<?> currentClass, boolean jni) {
// The target module whose enableNativeAccess flag is ensured
Module target = moduleForNativeAccess();
if (!EnableNativeAccess.isNativeAccessEnabled(target)) {
if (ModuleBootstrap.hasEnableNativeAccessFlag()) {
throw new IllegalCallerException("Illegal native access from: " + this);
ModuleBootstrap.IllegalNativeAccess illegalNativeAccess = ModuleBootstrap.illegalNativeAccess();
if (illegalNativeAccess != ModuleBootstrap.IllegalNativeAccess.ALLOW &&
!EnableNativeAccess.isNativeAccessEnabled(target)) {
String mod = isNamed() ? "module " + getName() : "an unnamed module";
if (currentClass != null) {
// try to extract location of the current class (e.g. jar or folder)
URL url = System.codeSource(currentClass);
if (url != null) {
mod += " (" + url + ")";
}
}
if (EnableNativeAccess.trySetEnableNativeAccess(target)) {
if (illegalNativeAccess == ModuleBootstrap.IllegalNativeAccess.DENY) {
throw new IllegalCallerException("Illegal native access from " + mod);
} else if (EnableNativeAccess.trySetEnableNativeAccess(target)) {
// warn and set flag, so that only one warning is reported per module
String cls = owner.getName();
String mtd = cls + "::" + methodName;
String mod = isNamed() ? "module " + getName() : "an unnamed module";
String modflag = isNamed() ? getName() : "ALL-UNNAMED";
String caller = currentClass != null ? currentClass.getName() : "code";
System.err.printf("""
WARNING: A restricted method in %s has been called
WARNING: %s has been called by %s in %s
WARNING: Use --enable-native-access=%s to avoid a warning for callers in this module
WARNING: Restricted methods will be blocked in a future release unless native access is enabled
%n""", cls, mtd, caller, mod, modflag);
if (jni) {
VM.initialErr().printf("""
WARNING: A native method in %s has been bound
WARNING: %s is declared in %s
WARNING: Use --enable-native-access=%s to avoid a warning for native methods declared in this module
WARNING: Restricted methods will be blocked in a future release unless native access is enabled
%n""", cls, mtd, mod, modflag);
} else {
VM.initialErr().printf("""
WARNING: A restricted method in %s has been called
WARNING: %s has been called by %s in %s
WARNING: Use --enable-native-access=%s to avoid a warning for callers in this module
WARNING: Restricted methods will be blocked in a future release unless native access is enabled
%n""", cls, mtd, caller, mod, modflag);
}
}
}
}

View File

@ -323,7 +323,7 @@ public final class ModuleLayer {
public Controller enableNativeAccess(Module target) {
ensureInLayer(target);
Reflection.ensureNativeAccess(Reflection.getCallerClass(), Module.class,
"enableNativeAccess");
"enableNativeAccess", false);
target.implAddEnableNativeAccess();
return this;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1995, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, Azul Systems, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@ -36,6 +36,7 @@ import java.util.Optional;
import java.util.StringTokenizer;
import jdk.internal.access.SharedSecrets;
import jdk.internal.javac.Restricted;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
@ -828,14 +829,19 @@ public class Runtime {
* a native library image by the host system.
* @throws NullPointerException if {@code filename} is
* {@code null}
* @throws IllegalCallerException if the caller is in a module that
* does not have native access enabled.
* @spec jni/index.html Java Native Interface Specification
* @see java.lang.Runtime#getRuntime()
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
@Restricted
public void load(String filename) {
load0(Reflection.getCallerClass(), filename);
Class<?> caller = Reflection.getCallerClass();
Reflection.ensureNativeAccess(caller, Runtime.class, "load", false);
load0(caller, filename);
}
void load0(Class<?> fromClass, String filename) {
@ -894,13 +900,18 @@ public class Runtime {
* native library image by the host system.
* @throws NullPointerException if {@code libname} is
* {@code null}
* @throws IllegalCallerException if the caller is in a module that
* does not have native access enabled.
* @spec jni/index.html Java Native Interface Specification
* @see java.lang.SecurityException
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
@Restricted
public void loadLibrary(String libname) {
loadLibrary0(Reflection.getCallerClass(), libname);
Class<?> caller = Reflection.getCallerClass();
Reflection.ensureNativeAccess(caller, Runtime.class, "loadLibrary", false);
loadLibrary0(caller, libname);
}
void loadLibrary0(Class<?> fromClass, String libname) {

View File

@ -69,6 +69,7 @@ import java.util.function.Supplier;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import jdk.internal.javac.Restricted;
import jdk.internal.logger.LoggerFinderLoader.TemporaryLoggerFinder;
import jdk.internal.misc.Blocker;
import jdk.internal.misc.CarrierThreadLocal;
@ -355,7 +356,7 @@ public final class System {
= Collections.synchronizedMap(new WeakHashMap<>());
}
private static URL codeSource(Class<?> clazz) {
static URL codeSource(Class<?> clazz) {
PrivilegedAction<ProtectionDomain> pa = clazz::getProtectionDomain;
@SuppressWarnings("removal")
CodeSource cs = AccessController.doPrivileged(pa).getCodeSource();
@ -2017,14 +2018,19 @@ public final class System {
* linked with the VM, or the library cannot be mapped to
* a native library image by the host system.
* @throws NullPointerException if {@code filename} is {@code null}
* @throws IllegalCallerException if the caller is in a module that
* does not have native access enabled.
*
* @spec jni/index.html Java Native Interface Specification
* @see java.lang.Runtime#load(java.lang.String)
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
@Restricted
public static void load(String filename) {
Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);
Class<?> caller = Reflection.getCallerClass();
Reflection.ensureNativeAccess(caller, System.class, "load", false);
Runtime.getRuntime().load0(caller, filename);
}
/**
@ -2055,14 +2061,19 @@ public final class System {
* linked with the VM, or the library cannot be mapped to a
* native library image by the host system.
* @throws NullPointerException if {@code libname} is {@code null}
* @throws IllegalCallerException if the caller is in a module that
* does not have native access enabled.
*
* @spec jni/index.html Java Native Interface Specification
* @see java.lang.Runtime#loadLibrary(java.lang.String)
* @see java.lang.SecurityManager#checkLink(java.lang.String)
*/
@CallerSensitive
@Restricted
public static void loadLibrary(String libname) {
Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
Class<?> caller = Reflection.getCallerClass();
Reflection.ensureNativeAccess(caller, System.class, "loadLibrary", false);
Runtime.getRuntime().loadLibrary0(caller, libname);
}
/**
@ -2539,8 +2550,8 @@ public final class System {
public void addEnableNativeAccessToAllUnnamed() {
Module.implAddEnableNativeAccessToAllUnnamed();
}
public void ensureNativeAccess(Module m, Class<?> owner, String methodName, Class<?> currentClass) {
m.ensureNativeAccess(owner, methodName, currentClass);
public void ensureNativeAccess(Module m, Class<?> owner, String methodName, Class<?> currentClass, boolean jni) {
m.ensureNativeAccess(owner, methodName, currentClass, jni);
}
public ServicesCatalog getServicesCatalog(ModuleLayer layer) {
return layer.getServicesCatalog();
@ -2645,7 +2656,7 @@ public final class System {
@Override
public long findNative(ClassLoader loader, String entry) {
return ClassLoader.findNative(loader, entry);
return ClassLoader.findNativeInternal(loader, entry);
}
@Override

View File

@ -108,7 +108,7 @@ public sealed interface AddressLayout extends ValueLayout permits ValueLayouts.O
* @param layout the target layout
* @return an address layout with same characteristics as this layout, but with the
* provided target layout
* @throws IllegalCallerException If the caller is in a module that does not have
* @throws IllegalCallerException if the caller is in a module that does not have
* native access enabled
* @see #targetLayout()
*/

View File

@ -613,7 +613,7 @@ public sealed interface Linker permits AbstractLinker {
* {@code address.equals(MemorySegment.NULL)}
* @throws IllegalArgumentException if an invalid combination of linker options
* is given
* @throws IllegalCallerException If the caller is in a module that does not have
* @throws IllegalCallerException if the caller is in a module that does not have
* native access enabled
*
* @see SymbolLookup
@ -684,7 +684,7 @@ public sealed interface Linker permits AbstractLinker {
* supported by this linker
* @throws IllegalArgumentException if an invalid combination of linker options
* is given
* @throws IllegalCallerException If the caller is in a module that does not have
* @throws IllegalCallerException if the caller is in a module that does not have
* native access enabled
*/
@CallerSensitive
@ -733,7 +733,7 @@ public sealed interface Linker permits AbstractLinker {
* @throws IllegalStateException if {@code arena.scope().isAlive() == false}
* @throws WrongThreadException if {@code arena} is a confined arena, and this method
* is called from a thread {@code T}, other than the arena's owner thread
* @throws IllegalCallerException If the caller is in a module that does not have
* @throws IllegalCallerException if the caller is in a module that does not have
* native access enabled
*/
@CallerSensitive

View File

@ -285,14 +285,14 @@ public interface SymbolLookup {
* @throws WrongThreadException if {@code arena} is a confined arena, and this method
* is called from a thread {@code T}, other than the arena's owner thread
* @throws IllegalArgumentException if {@code name} does not identify a valid library
* @throws IllegalCallerException If the caller is in a module that does not have
* @throws IllegalCallerException if the caller is in a module that does not have
* native access enabled
*/
@CallerSensitive
@Restricted
static SymbolLookup libraryLookup(String name, Arena arena) {
Reflection.ensureNativeAccess(Reflection.getCallerClass(),
SymbolLookup.class, "libraryLookup");
SymbolLookup.class, "libraryLookup", false);
if (Utils.containsNullChars(name)) {
throw new IllegalArgumentException("Cannot open library: " + name);
}
@ -319,14 +319,14 @@ public interface SymbolLookup {
* is called from a thread {@code T}, other than the arena's owner thread
* @throws IllegalArgumentException if {@code path} does not point to a valid library
* in the default file system
* @throws IllegalCallerException If the caller is in a module that does not have
* @throws IllegalCallerException if the caller is in a module that does not have
* native access enabled
*/
@CallerSensitive
@Restricted
static SymbolLookup libraryLookup(Path path, Arena arena) {
Reflection.ensureNativeAccess(Reflection.getCallerClass(),
SymbolLookup.class, "libraryLookup");
SymbolLookup.class, "libraryLookup", false);
if (path.getFileSystem() != FileSystems.getDefault()) {
throw new IllegalArgumentException("Path not in default file system: " + path);
}

View File

@ -165,10 +165,11 @@
* In the reference implementation, access to restricted methods can be granted to
* specific modules using the command line option {@code --enable-native-access=M1,M2, ... Mn},
* where {@code M1}, {@code M2}, {@code ... Mn} are module names (for the unnamed module,
* the special value {@code ALL-UNNAMED} can be used). If this option is specified,
* access to restricted methods are only granted to the modules listed by that option.
* If this option is not specified, access to restricted methods is enabled for all
* modules, but access to restricted methods will result in runtime warnings.
* the special value {@code ALL-UNNAMED} can be used). Access to restricted methods
* from modules not listed by that option is deemed <em>illegal</em>. Clients can
* control how access to restricted methods is handled, using the command line
* option {@code --illegal-native-access}. If this option is not specified,
* illegal access to restricted methods will result in runtime warnings.
*
* @spec jni/index.html Java Native Interface Specification
*

View File

@ -281,10 +281,14 @@ public interface JavaLangAccess {
void addEnableNativeAccessToAllUnnamed();
/**
* Ensure that the given module has native access. If not, warn or
* throw exception depending on the configuration.
* Ensure that the given module has native access. If not, warn or throw exception depending on the configuration.
* @param m the module in which native access occurred
* @param owner the owner of the restricted method being called (or the JNI method being bound)
* @param methodName the name of the restricted method being called (or the JNI method being bound)
* @param currentClass the class calling the restricted method (for JNI, this is the same as {@code owner})
* @param jni {@code true}, if this event is related to a JNI method being bound
*/
void ensureNativeAccess(Module m, Class<?> owner, String methodName, Class<?> currentClass);
void ensureNativeAccess(Module m, Class<?> owner, String methodName, Class<?> currentClass, boolean jni);
/**
* Returns the ServicesCatalog for the given Layer.

View File

@ -152,7 +152,7 @@ public abstract sealed class AbstractMemorySegmentImpl
}
public MemorySegment reinterpretInternal(Class<?> callerClass, long newSize, Scope scope, Consumer<MemorySegment> cleanup) {
Reflection.ensureNativeAccess(callerClass, MemorySegment.class, "reinterpret");
Reflection.ensureNativeAccess(callerClass, MemorySegment.class, "reinterpret", false);
Utils.checkNonNegativeArgument(newSize, "newSize");
if (!isNative()) throw new UnsupportedOperationException("Not a native segment");
Runnable action = cleanup != null ?

View File

@ -80,7 +80,7 @@ public abstract sealed class AbstractLinker implements Linker permits LinuxAArch
@Override
@CallerSensitive
public final MethodHandle downcallHandle(MemorySegment symbol, FunctionDescriptor function, Option... options) {
Reflection.ensureNativeAccess(Reflection.getCallerClass(), Linker.class, "downcallHandle");
Reflection.ensureNativeAccess(Reflection.getCallerClass(), Linker.class, "downcallHandle", false);
SharedUtils.checkSymbol(symbol);
return downcallHandle0(function, options).bindTo(symbol);
}
@ -88,7 +88,7 @@ public abstract sealed class AbstractLinker implements Linker permits LinuxAArch
@Override
@CallerSensitive
public final MethodHandle downcallHandle(FunctionDescriptor function, Option... options) {
Reflection.ensureNativeAccess(Reflection.getCallerClass(), Linker.class, "downcallHandle");
Reflection.ensureNativeAccess(Reflection.getCallerClass(), Linker.class, "downcallHandle", false);
return downcallHandle0(function, options);
}
@ -115,7 +115,7 @@ public abstract sealed class AbstractLinker implements Linker permits LinuxAArch
@Override
@CallerSensitive
public final MemorySegment upcallStub(MethodHandle target, FunctionDescriptor function, Arena arena, Linker.Option... options) {
Reflection.ensureNativeAccess(Reflection.getCallerClass(), Linker.class, "upcallStub");
Reflection.ensureNativeAccess(Reflection.getCallerClass(), Linker.class, "upcallStub", false);
Objects.requireNonNull(arena);
Objects.requireNonNull(target);
Objects.requireNonNull(function);

View File

@ -36,7 +36,7 @@ final class LibFallback {
static final boolean SUPPORTED = tryLoadLibrary();
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static boolean tryLoadLibrary() {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<>() {

View File

@ -332,7 +332,7 @@ public final class ValueLayouts {
@Override
@CallerSensitive
public AddressLayout withTargetLayout(MemoryLayout layout) {
Reflection.ensureNativeAccess(Reflection.getCallerClass(), AddressLayout.class, "withTargetLayout");
Reflection.ensureNativeAccess(Reflection.getCallerClass(), AddressLayout.class, "withTargetLayout", false);
Objects.requireNonNull(layout);
return new OfAddressImpl(order(), byteSize(), byteAlignment(), layout, name());
}

View File

@ -38,6 +38,7 @@ class NativeImageBuffer {
static {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
@SuppressWarnings("restricted")
public Void run() {
System.loadLibrary("jimage");
return null;

View File

@ -787,17 +787,23 @@ public final class ModuleBootstrap {
}
}
private static final boolean HAS_ENABLE_NATIVE_ACCESS_FLAG;
private static final Set<String> USER_NATIVE_ACCESS_MODULES;
private static final Set<String> JDK_NATIVE_ACCESS_MODULES;
private static final IllegalNativeAccess ILLEGAL_NATIVE_ACCESS;
public static boolean hasEnableNativeAccessFlag() {
return HAS_ENABLE_NATIVE_ACCESS_FLAG;
public enum IllegalNativeAccess {
ALLOW,
WARN,
DENY
}
public static IllegalNativeAccess illegalNativeAccess() {
return ILLEGAL_NATIVE_ACCESS;
}
static {
ILLEGAL_NATIVE_ACCESS = addIllegalNativeAccess();
USER_NATIVE_ACCESS_MODULES = decodeEnableNativeAccess();
HAS_ENABLE_NATIVE_ACCESS_FLAG = !USER_NATIVE_ACCESS_MODULES.isEmpty();
JDK_NATIVE_ACCESS_MODULES = ModuleLoaderMap.nativeAccessModules();
}
@ -847,6 +853,27 @@ public final class ModuleBootstrap {
return modules;
}
/**
* Process the --illegal-native-access option (and its default).
*/
private static IllegalNativeAccess addIllegalNativeAccess() {
String value = getAndRemoveProperty("jdk.module.illegal.native.access");
// don't use a switch: bootstrapping issues!
if (value == null) {
return IllegalNativeAccess.WARN; // default
} else if (value.equals("deny")) {
return IllegalNativeAccess.DENY;
} else if (value.equals("allow")) {
return IllegalNativeAccess.ALLOW;
} else if (value.equals("warn")) {
return IllegalNativeAccess.WARN;
} else {
fail("Value specified to --illegal-native-access not recognized:"
+ " '" + value + "'");
return null;
}
}
/**
* Decodes the values of --add-reads, -add-exports, --add-opens or
* --patch-modules options that are encoded in system properties.

View File

@ -111,7 +111,7 @@ public class Reflection {
}
@ForceInline
public static void ensureNativeAccess(Class<?> currentClass, Class<?> owner, String methodName) {
public static void ensureNativeAccess(Class<?> currentClass, Class<?> owner, String methodName, boolean jni) {
// if there is no caller class, act as if the call came from unnamed module of system class loader
Module module = currentClass != null ?
currentClass.getModule() :
@ -119,7 +119,10 @@ public class Reflection {
class Holder {
static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
}
Holder.JLA.ensureNativeAccess(module, owner, methodName, currentClass);
if (module != null) {
// not in init phase
Holder.JLA.ensureNativeAccess(module, owner, methodName, currentClass, jni);
}
}
/**

View File

@ -65,6 +65,11 @@ java.launcher.opt.footer = \
\ --enable-native-access <module name>[,<module name>...]\n\
\ allow code in modules to access code and data outside the Java runtime.\n\
\ <module name> can also be ALL-UNNAMED to indicate code on the class path.\n\
\ --illegal-native-access=<value>\n\
\ allow or deny access to code and data outside the Java runtime\n\
\ by code in modules for which native access is not explicitly enabled.\n\
\ <value> is one of "deny", "warn" or "allow". The default value is "warn".\n\
\ This option will be removed in a future release.\n\
\ --list-modules\n\
\ list observable modules and exit\n\
\ -d <module name>\n\

View File

@ -552,15 +552,45 @@ of the release.
Native access involves access to code or data outside the Java runtime.
This is generally unsafe and, if done incorrectly, might crash the JVM
or result in memory corruption.
Methods that provide native access are restricted, and by default their
use causes warnings.
This option allows code in the specified modules to use restricted
methods without warnings.
\f[I]module\f[R] can be \f[V]ALL-UNNAMED\f[R] to indicate code on the
class path.
When this option is present, any use of restricted methods by code
outside the specified modules causes an
Native access can occur as a result of calling a method that is either
\f[B]restricted\f[R] [https://openjdk.org/jeps/454#Safety], or
\f[V]native\f[R].
This option allows code in the specified modules to perform native
access.
Native access occurring in a module that has not been explicitly enabled
is deemed \f[I]illegal\f[R].
.RS
.PP
\f[I]module\f[R] can be a module name, or \f[V]ALL-UNNAMED\f[R] to
indicate code on the class path.
.RE
.TP
-\f[V]--illegal-native-access=\f[R]\f[I]parameter\f[R]
This option specifies a mode for how illegal native access is handled:
.RS
.RS
.PP
\f[B]Note:\f[R] This option will be removed in a future release.
.RE
.IP \[bu] 2
\f[V]allow\f[R]: This mode allows illegal native access in all modules,
without any warings.
.IP \[bu] 2
\f[V]warn\f[R]: This mode is identical to \f[V]allow\f[R] except that a
warning message is issued for the first illegal native access found in a
module.
This mode is the default for the current JDK but will change in a future
release.
.IP \[bu] 2
\f[V]deny\f[R]: This mode disables illegal native access.
That is, any illegal native access causes an
\f[V]IllegalCallerException\f[R].
This mode will become the default in a future release.
.PP
To verify that your application is ready for a future version of the
JDK, run it with \f[V]--illegal-native-access=deny\f[R] along with any
necessary \f[V]--enable-native-access\f[R] options.
.RE
.TP
\f[V]--finalization=\f[R]\f[I]value\f[R]
Controls whether the JVM performs finalization of objects.

View File

@ -58,7 +58,7 @@ public class FileManager {
loadOSXLibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadOSXLibrary() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -65,7 +65,7 @@ class AquaFileView extends FileView {
loadOSXUILibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadOSXUILibrary() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -154,7 +154,7 @@ public class AquaLookAndFeel extends BasicLookAndFeel {
* @see #uninitialize
* @see UIManager#setLookAndFeel
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public void initialize() {
java.security.AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {

View File

@ -41,7 +41,7 @@ import sun.lwawt.macosx.LWCToolkit;
import sun.security.action.GetBooleanAction;
// MenuBar implementation for Mac L&F
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class AquaMenuBarUI extends BasicMenuBarUI implements ScreenMenuBarProvider {
static {

View File

@ -32,7 +32,7 @@ import javax.swing.plaf.UIResource;
import com.apple.laf.AquaUtils.RecyclableSingleton;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class AquaNativeResources {
static {
java.security.AccessController.doPrivileged(

View File

@ -45,7 +45,7 @@ final class ScreenMenu extends Menu
loadAWTLibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadAWTLibrary() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -30,7 +30,7 @@ import java.awt.Toolkit;
import java.security.AccessController;
import java.security.PrivilegedAction;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class PlatformGraphicsInfo {
static {

View File

@ -77,7 +77,7 @@ class CAccessibility implements PropertyChangeListener {
loadAWTLibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadAWTLibrary() {
// Need to load the native library for this code.
java.security.AccessController.doPrivileged(

View File

@ -146,7 +146,7 @@ public final class LWCToolkit extends LWToolkit {
static {
System.err.flush();
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
ResourceBundle platformResources = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<ResourceBundle>() {
@Override

View File

@ -90,7 +90,7 @@ public class JPEGImageReader extends ImageReader {
initStatic();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void initStatic() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -175,7 +175,7 @@ public class JPEGImageWriter extends ImageWriter {
initStatic();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void initStatic() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -74,7 +74,7 @@ final class Platform {
/**
* Load the native library or libraries.
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadLibraries() {
// load the native library
isNativeLibLoaded = true;

View File

@ -121,7 +121,7 @@ public final class SplashScreen {
* @return the {@link SplashScreen} instance, or {@code null} if there is
* none or it has already been closed
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public static SplashScreen getSplashScreen() {
synchronized (SplashScreen.class) {
if (GraphicsEnvironment.isHeadless()) {

View File

@ -1375,7 +1375,7 @@ public abstract class Toolkit {
* directly. -hung
*/
private static boolean loaded = false;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static void loadLibraries() {
if (!loaded) {
java.security.AccessController.doPrivileged(

View File

@ -52,7 +52,7 @@ class NativeLibLoader {
* For now, we know it's done by the implementation, and we assume
* that the name of the library is "awt". -br.
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static void loadLibraries() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -202,7 +202,7 @@ public abstract class ColorModel implements Transparency{
* that the name of the library is "awt". -br.
*/
private static boolean loaded = false;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static void loadLibraries() {
if (!loaded) {
java.security.AccessController.doPrivileged(

View File

@ -52,7 +52,7 @@ class NativeLibLoader {
* For now, we know it's done by the implementation, and we assume
* that the name of the library is "awt". -br.
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static void loadLibraries() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -51,7 +51,7 @@ import java.security.PrivilegedAction;
* (in which case our java code will be executed) or may throw
* an exception.
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class ImagingLib {
static boolean useLib = true;

View File

@ -42,7 +42,7 @@ import java.awt.image.*;
*
* @author Jim Graham
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class JPEGImageDecoder extends ImageDecoder {
private static ColorModel RGBcolormodel;
private static ColorModel ARGBcolormodel;

View File

@ -52,7 +52,7 @@ class NativeLibLoader {
* For now, we know it's done by the implementation, and we assume
* that the name of the library is "awt". -br.
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static void loadLibraries() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -27,7 +27,7 @@ package sun.font;
import sun.awt.OSInfo;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class FontManagerNativeLibrary {
static {
java.security.AccessController.doPrivileged(

View File

@ -50,7 +50,7 @@ import java.util.concurrent.ConcurrentLinkedDeque;
*
* @see DisposerRecord
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class Disposer implements Runnable {
private static final ReferenceQueue<Object> queue = new ReferenceQueue<>();
private static final Hashtable<java.lang.ref.Reference<Object>, DisposerRecord> records =

View File

@ -143,7 +143,7 @@ final class LCMS implements PCMM {
private static LCMS theLcms = null;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static synchronized PCMM getModule() {
if (theLcms != null) {
return theLcms;

View File

@ -59,7 +59,7 @@ public final class X11GraphicsEnvironment extends SunGraphicsEnvironment {
initStatic();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void initStatic() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Object>() {

View File

@ -90,7 +90,7 @@ public class CUPSPrinter {
initStatic();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void initStatic() {
// load awt library to access native code
java.security.AccessController.doPrivileged(

View File

@ -39,7 +39,7 @@ public class PlatformGraphicsInfo {
hasDisplays = hasDisplays0();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadAWTLibrary() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -168,7 +168,7 @@ public final class WToolkit extends SunToolkit implements Runnable {
*/
private static native void initIDs();
private static boolean loaded = false;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public static void loadLibraries() {
if (!loaded) {
java.security.AccessController.doPrivileged(

View File

@ -54,7 +54,7 @@ public class PrintServiceLookupProvider extends PrintServiceLookup {
loadAWTLibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadAWTLibrary() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -63,6 +63,7 @@ import jdk.internal.vm.annotation.IntrinsicCandidate;
* Keeps a pointer to the native data structure in a scalar field to allow native
* processing behind native methods.
*/
@SuppressWarnings("restricted")
public class InstrumentationImpl implements Instrumentation {
private static final String TRACE_USAGE_PROP_NAME = "jdk.instrument.traceUsage";
private static final boolean TRACE_USAGE;

View File

@ -1020,7 +1020,7 @@ public class ManagementFactory {
loadNativeLib();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadNativeLib() {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
System.loadLibrary("management");

View File

@ -82,7 +82,7 @@ class MacOSXPreferencesFile {
loadPrefsLib();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadPrefsLib() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {

View File

@ -53,7 +53,7 @@ class FileSystemPreferences extends AbstractPreferences {
loadPrefsLib();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadPrefsLib() {
PrivilegedAction<Void> load = () -> {
System.loadLibrary("prefs");

View File

@ -50,7 +50,7 @@ class WindowsPreferences extends AbstractPreferences {
loadPrefsLib();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadPrefsLib() {
PrivilegedAction<Void> load = () -> {
System.loadLibrary("prefs");

View File

@ -39,7 +39,7 @@ import jdk.internal.misc.InnocuousThread;
* @since 1.2
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
class GC {
private GC() { } /* To prevent instantiation */

View File

@ -68,7 +68,7 @@ public final class SunNativeProvider extends Provider {
System.err.println(NAME + ": " + message);
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static final HashMap<String, String> MECH_MAP =
AccessController.doPrivileged(
new PrivilegedAction<>() {

View File

@ -524,7 +524,7 @@ public class Credentials {
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static void ensureLoaded() {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void> () {

View File

@ -45,7 +45,7 @@ public class SCDynamicStoreConfig {
private static native List<String> getKerberosConfig();
static {
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
boolean isMac = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Boolean>() {
public Boolean run() {

View File

@ -61,7 +61,7 @@ class PlatformPCSC {
// empty
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
static final Throwable initException
= AccessController.doPrivileged(new PrivilegedAction<Throwable>() {
public Throwable run() {

View File

@ -41,7 +41,7 @@ class PlatformPCSC {
initException = loadLibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static Throwable loadLibrary() {
try {
AccessController.doPrivileged(new PrivilegedAction<Void>() {

View File

@ -160,7 +160,7 @@ public final class AccessBridge {
initStatic();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void initStatic() {
// Load the appropriate DLLs
boolean is32on64 = false;

View File

@ -38,6 +38,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
/*
* Aix implementation of HotSpotVirtualMachine
*/
@SuppressWarnings("restricted")
public class VirtualMachineImpl extends HotSpotVirtualMachine {
// "/tmp" is used as a global well-known location for the files
// .java_pid<pid>. and .attach_pid<pid>. It is important that this

View File

@ -40,6 +40,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
/*
* Linux implementation of HotSpotVirtualMachine
*/
@SuppressWarnings("restricted")
public class VirtualMachineImpl extends HotSpotVirtualMachine {
// "/tmp" is used as a global well-known location for the files
// .java_pid<pid>. and .attach_pid<pid>. It is important that this

View File

@ -37,6 +37,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
/*
* Bsd implementation of HotSpotVirtualMachine
*/
@SuppressWarnings("restricted")
public class VirtualMachineImpl extends HotSpotVirtualMachine {
// "tmpdir" is used as a global well-known location for the files
// .java_pid<pid>. and .attach_pid<pid>. It is important that this

View File

@ -34,6 +34,7 @@ import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
@SuppressWarnings("restricted")
public class AttachProviderImpl extends HotSpotAttachProvider {
public AttachProviderImpl() {

View File

@ -35,6 +35,7 @@ import java.util.Random;
/*
* Windows implementation of HotSpotVirtualMachine
*/
@SuppressWarnings("restricted")
public class VirtualMachineImpl extends HotSpotVirtualMachine {
// the enqueue code stub (copied into each target VM)

View File

@ -83,7 +83,7 @@ public class PKCS11 {
// cannot use LoadLibraryAction because that would make the native
// library available to the bootclassloader, but we run in the
// extension classloader.
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
var dummy = AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
System.loadLibrary(PKCS11_WRAPPER);

View File

@ -50,7 +50,7 @@ public final class SunMSCAPI extends Provider {
private static final String INFO = "Sun's Microsoft Crypto API provider";
static {
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
var dummy = AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
System.loadLibrary("sunmscapi");

View File

@ -62,6 +62,7 @@ import sun.jvm.hotspot.utilities.PlatformInfo;
RuntimeException if they are called before the debugger is
configured with the Java primitive type sizes. </P> */
@SuppressWarnings("restricted")
public class BsdDebuggerLocal extends DebuggerBase implements BsdDebugger {
private boolean useGCC32ABI;
private boolean attached;

View File

@ -67,6 +67,7 @@ import sun.jvm.hotspot.utilities.PlatformInfo;
RuntimeException if they are called before the debugger is
configured with the Java primitive type sizes. </P> */
@SuppressWarnings("restricted")
public class LinuxDebuggerLocal extends DebuggerBase implements LinuxDebugger {
private boolean useGCC32ABI;
private boolean attached;

View File

@ -54,6 +54,7 @@ import sun.jvm.hotspot.runtime.*;
RuntimeException if they are called before the debugger is
configured with the Java primitive type sizes. </P> */
@SuppressWarnings("restricted")
public class WindbgDebuggerLocal extends DebuggerBase implements WindbgDebugger {
private PageCache cache;
private boolean attached;

View File

@ -65,6 +65,7 @@ class SharedMemoryTransportService extends TransportService {
}
}
@SuppressWarnings("restricted")
SharedMemoryTransportService() {
System.loadLibrary("dt_shmem");
initialize();

View File

@ -48,7 +48,7 @@ import static jdk.jpackage.internal.StandardBundlerParam.VENDOR;
import static jdk.jpackage.internal.StandardBundlerParam.VERSION;
import static jdk.jpackage.internal.WindowsAppImageBuilder.ICON_ICO;
@SuppressWarnings("restricted")
final class ExecutableRebrander {
private static final ResourceBundle I18N = ResourceBundle.getBundle(
"jdk.jpackage.internal.resources.WinResources");

View File

@ -31,6 +31,7 @@ import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Map;
@SuppressWarnings("restricted")
public class WinExeBundler extends AbstractBundler {
static {

View File

@ -28,6 +28,7 @@ package jdk.jpackage.internal;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("restricted")
final class WindowsRegistry {
// Currently we only support HKEY_LOCAL_MACHINE. Native implementation will

View File

@ -31,7 +31,7 @@ import java.io.IOException;
/*
* Linux implementation of jdk.internal.agent.FileSystem
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class FileSystemImpl extends FileSystem {
public boolean supportsFileSecurity(File f) throws IOException {

View File

@ -31,7 +31,7 @@ import java.io.IOException;
/*
* Windows implementation of sun.management.FileSystem
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public class FileSystemImpl extends FileSystem {
public boolean supportsFileSecurity(File f) throws IOException {

View File

@ -36,7 +36,7 @@ import java.security.AccessController;
* corresponds to one VMOption.
*
*/
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
class Flag {
private String name;
private Object value;

View File

@ -44,7 +44,7 @@ import javax.management.DynamicMBean;
import sun.management.ManagementFactoryHelper;
import sun.management.spi.PlatformMBeanProvider;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
public final class PlatformMBeanProviderImpl extends PlatformMBeanProvider {
static final String DIAGNOSTIC_COMMAND_MBEAN_NAME =
"com.sun.management:type=DiagnosticCommand";

View File

@ -32,7 +32,7 @@ import java.security.PrivilegedAction;
import jdk.net.ExtendedSocketOptions.PlatformSocketOptions;
import sun.nio.fs.UnixUserPrincipals;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
class AIXSocketOptions extends PlatformSocketOptions {
public AIXSocketOptions() {

View File

@ -32,7 +32,7 @@ import java.security.PrivilegedAction;
import jdk.net.ExtendedSocketOptions.PlatformSocketOptions;
import sun.nio.fs.UnixUserPrincipals;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
class LinuxSocketOptions extends PlatformSocketOptions {
public LinuxSocketOptions() {

View File

@ -32,7 +32,7 @@ import java.security.PrivilegedAction;
import jdk.net.ExtendedSocketOptions.PlatformSocketOptions;
import sun.nio.fs.UnixUserPrincipals;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
class MacOSXSocketOptions extends PlatformSocketOptions {
public MacOSXSocketOptions() {

View File

@ -30,7 +30,7 @@ import java.security.PrivilegedAction;
import jdk.net.ExtendedSocketOptions.PlatformSocketOptions;
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
class WindowsSocketOptions extends PlatformSocketOptions {
public WindowsSocketOptions() {

View File

@ -1094,7 +1094,7 @@ public class SctpChannelImpl extends SctpChannel
loadSctpLibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadSctpLibrary() {
IOUtil.load(); /* loads nio & net native libraries */
AccessController.doPrivileged(

View File

@ -333,7 +333,7 @@ public class SctpNet {
loadSctpLibrary();
}
@SuppressWarnings("removal")
@SuppressWarnings({"removal", "restricted"})
private static void loadSctpLibrary() {
IOUtil.load(); // loads nio & net native libraries
java.security.AccessController.doPrivileged(

View File

@ -129,7 +129,7 @@ public class NTSystem {
return impersonationToken;
}
@SuppressWarnings("restricted")
private void loadNative() {
System.loadLibrary("jaas");
}

View File

@ -53,6 +53,7 @@ public class UnixSystem {
* Instantiate a {@code UnixSystem} and load
* the native library to access the underlying system information.
*/
@SuppressWarnings("restricted")
public UnixSystem() {
System.loadLibrary("jaas");
getUnixInfo();

View File

@ -49,6 +49,7 @@ public class TestCheckedReleaseArrayElements {
// that might generate output on stderr (which should be empty for this test).
ProcessBuilder pb =
ProcessTools.createLimitedTestJavaProcessBuilder("-Xcheck:jni",
"--enable-native-access=ALL-UNNAMED",
"-Djava.library.path=" + Utils.TEST_NATIVE_PATH,
"TestCheckedReleaseArrayElements");
OutputAnalyzer output = ProcessTools.executeProcess(pb);

View File

@ -88,7 +88,11 @@ public class TestRestricted {
RestrictedMethod.of(MemorySegment.class, "reinterpret", MemorySegment.class, Arena.class, Consumer.class),
RestrictedMethod.of(MemorySegment.class, "reinterpret", MemorySegment.class, long.class, Arena.class, Consumer.class),
RestrictedMethod.of(AddressLayout.class, "withTargetLayout", AddressLayout.class, MemoryLayout.class),
RestrictedMethod.of(ModuleLayer.Controller.class, "enableNativeAccess", ModuleLayer.Controller.class, Module.class)
RestrictedMethod.of(ModuleLayer.Controller.class, "enableNativeAccess", ModuleLayer.Controller.class, Module.class),
RestrictedMethod.of(System.class, "load", void.class, String.class),
RestrictedMethod.of(System.class, "loadLibrary", void.class, String.class),
RestrictedMethod.of(Runtime.class, "load", void.class, String.class),
RestrictedMethod.of(Runtime.class, "loadLibrary", void.class, String.class)
);
@Test

View File

@ -28,6 +28,10 @@
* @library /test/lib
* @build TestEnableNativeAccess
* panama_module/*
* panama_jni_load_module/*
* panama_jni_def_module/*
* panama_jni_use_module/*
*
* org.openjdk.foreigntest.unnamed.PanamaMainUnnamedModule
* @run testng/othervm/timeout=180 TestEnableNativeAccess
* @summary Basic test for java --enable-native-access
@ -62,20 +66,25 @@ public class TestEnableNativeAccess extends TestEnableNativeAccessBase {
{ "panama_enable_native_access", PANAMA_MAIN, successNoWarning(), new String[]{"--enable-native-access=panama_module"} },
{ "panama_enable_native_access_reflection", PANAMA_REFLECTION, successNoWarning(), new String[]{"--enable-native-access=panama_module"} },
{ "panama_enable_native_access_invoke", PANAMA_INVOKE, successNoWarning(), new String[]{"--enable-native-access=panama_module"} },
{ "panama_enable_native_access_jni", PANAMA_JNI, successNoWarning(), new String[]{"--enable-native-access=ALL-UNNAMED"} },
{ "panama_comma_separated_enable", PANAMA_MAIN, successNoWarning(), new String[]{"--enable-native-access=java.base,panama_module"} },
{ "panama_comma_separated_enable_reflection", PANAMA_REFLECTION, successNoWarning(), new String[]{"--enable-native-access=java.base,panama_module"} },
{ "panama_comma_separated_enable_invoke", PANAMA_INVOKE, successNoWarning(), new String[]{"--enable-native-access=java.base,panama_module"} },
{ "panama_comma_separated_enable_jni", PANAMA_JNI, successNoWarning(), new String[]{"--enable-native-access=java.base,ALL-UNNAMED"} },
{ "panama_comma_separated_enable_jni", PANAMA_JNI, successNoWarning(), new String[]{"--enable-native-access=panama_jni_load_module,panama_jni_def_module,ALL-UNNAMED"} },
{ "panama_enable_native_access_warn", PANAMA_MAIN, successWithWarning("panama"), new String[]{} },
{ "panama_enable_native_access_warn_reflection", PANAMA_REFLECTION, successWithWarning("panama"), new String[]{} },
{ "panama_enable_native_access_warn_invoke", PANAMA_INVOKE, successWithWarning("panama"), new String[]{} },
{ "panama_enable_native_access_warn_jni", PANAMA_JNI, successWithWarning("ALL-UNNAMED"), new String[]{} },
{ "panama_enable_native_access_warn_jni", PANAMA_JNI, successWithWarnings("panama_jni_load_module", "panama_jni_def_module", "ALL-UNNAMED"), new String[]{} },
{ "panama_enable_native_access_allow", PANAMA_MAIN, successNoWarning(), new String[]{"--illegal-native-access=allow"} },
{ "panama_enable_native_access_allow_reflection", PANAMA_REFLECTION, successNoWarning(), new String[]{"--illegal-native-access=allow"} },
{ "panama_enable_native_access_allow_invoke", PANAMA_INVOKE, successNoWarning(), new String[]{"--illegal-native-access=allow"} },
{ "panama_enable_native_access_allow_jni", PANAMA_JNI, successNoWarning(), new String[]{"--illegal-native-access=allow"} },
{ "panama_no_unnamed_module_native_access", UNNAMED, successWithWarning("ALL-UNNAMED"), new String[]{} },
{ "panama_all_unnamed_module_native_access", UNNAMED, successNoWarning(), new String[]{"--enable-native-access=ALL-UNNAMED"} },
{ "panama_allow_unnamed_module_native_access", UNNAMED, successNoWarning(), new String[]{"--illegal-native-access=allow"} },
};
}
@ -131,12 +140,38 @@ public class TestEnableNativeAccess extends TestEnableNativeAccessBase {
* Specifies bad value to --enable-native-access.
*/
public void testBadValue() throws Exception {
run("panama_enable_native_access_warn_unknown_module", PANAMA_MAIN,
run("panama_deny_bad_unknown_module", PANAMA_MAIN,
failWithWarning("WARNING: Unknown module: BAD specified to --enable-native-access"),
"--enable-native-access=BAD");
run("panama_no_all_module_path_blanket_native_access", PANAMA_MAIN,
"--illegal-native-access=deny", "--enable-native-access=BAD");
run("panama_deny_bad_all_module_path_module", PANAMA_MAIN,
failWithWarning("WARNING: Unknown module: ALL-MODULE-PATH specified to --enable-native-access"),
"--enable-native-access=ALL-MODULE-PATH" );
"--illegal-native-access=deny", "--enable-native-access=ALL-MODULE-PATH" );
run("panama_deny_no_module_main", PANAMA_MAIN,
failWithError("module panama_module"),
"--illegal-native-access=deny");
run("panama_deny_no_module_invoke", PANAMA_INVOKE,
failWithError("module panama_module"),
"--illegal-native-access=deny");
run("panama_deny_no_module_reflection", PANAMA_REFLECTION,
failWithError("module panama_module"),
"--illegal-native-access=deny");
run("panama_deny_no_module_jni", PANAMA_JNI,
failWithError("module panama_jni_load_module"),
"--illegal-native-access=deny");
}
public void testDetailedWarningMessage() throws Exception {
run("panama_enable_native_access_warn_jni", PANAMA_JNI,
success()
// call to System::loadLibrary from panama_jni_load_module
.expect("WARNING: A restricted method in java.lang.System has been called")
.expect("WARNING: java.lang.System::loadLibrary has been called by org.openjdk.jni.PanamaMainJNI in module panama_jni_load_module")
// JNI native method binding in panama_jni_def_module
.expect("WARNING: A native method in org.openjdk.jni.def.PanamaJNIDef has been bound")
.expect("WARNING: org.openjdk.jni.def.PanamaJNIDef::nativeLinker0 is declared in module panama_jni_def_module")
// upcall to Linker::downcallHandle from JNI code
.expect("WARNING: A restricted method in java.lang.foreign.Linker has been called")
.expect("WARNING: java.lang.foreign.Linker::downcallHandle has been called by code in an unnamed module"));
}
private int count(Iterable<String> lines, CharSequence cs) {

View File

@ -38,8 +38,8 @@ public class TestEnableNativeAccessBase {
static final String PANAMA_REFLECTION = "panama_module/" + PANAMA_REFLECTION_CLS;
static final String PANAMA_INVOKE_CLS = "org.openjdk.foreigntest.PanamaMainInvoke";
static final String PANAMA_INVOKE = "panama_module/" + PANAMA_INVOKE_CLS;
static final String PANAMA_JNI_CLS = "org.openjdk.foreigntest.PanamaMainJNI";
static final String PANAMA_JNI = "panama_module/" + PANAMA_JNI_CLS;
static final String PANAMA_JNI_CLS = "org.openjdk.jni.PanamaMainJNI";
static final String PANAMA_JNI = "panama_jni_load_module/" + PANAMA_JNI_CLS;
static final String UNNAMED = "org.openjdk.foreigntest.unnamed.PanamaMainUnnamedModule";
/**
@ -99,6 +99,14 @@ public class TestEnableNativeAccessBase {
return success().expect("WARNING").expect("--enable-native-access=" + moduleName);
}
static Result successWithWarnings(String... moduleNames) {
Result result = success();
for (String moduleName : moduleNames) {
result = result.expect("WARNING").expect("--enable-native-access=" + moduleName);
}
return result;
}
static Result failWithWarning(String expectedOutput) {
return new Result(false).expect(expectedOutput).expect("WARNING");
}

View File

@ -56,7 +56,7 @@ public class TestEnableNativeAccessDynamic extends TestEnableNativeAccessBase {
@DataProvider(name = "failureCases")
public Object[][] failureCases() {
String errMsg = "Illegal native access from: module panama_module";
String errMsg = "Illegal native access from module panama_module";
return new Object[][] {
{ "panama_enable_native_access_fail", PANAMA_MAIN, failWithError(errMsg) },
{ "panama_enable_native_access_fail_reflection", PANAMA_REFLECTION, failWithError(errMsg) },
@ -73,6 +73,7 @@ public class TestEnableNativeAccessDynamic extends TestEnableNativeAccessBase {
Result expectedResult, boolean panamaModuleInBootLayer) throws Exception
{
List<String> list = new ArrayList<>();
list.add("--illegal-native-access=deny");
if (panamaModuleInBootLayer) {
list.addAll(List.of("-p", MODULE_PATH));
list.add("--add-modules=panama_module");

View File

@ -0,0 +1,26 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
module panama_jni_def_module {
exports org.openjdk.jni.def;
}

View File

@ -0,0 +1,32 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.jni.def;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
public class PanamaJNIDef {
public static native void nativeLinker0(Linker linker, FunctionDescriptor desc, Linker.Option[] options);
}

View File

@ -47,7 +47,7 @@ void call(void* arg) {
extern "C" {
JNIEXPORT void JNICALL
Java_org_openjdk_foreigntest_PanamaMainJNI_nativeLinker0(JNIEnv *env, jclass cls, jobject linker, jobject desc, jobjectArray opts) {
Java_org_openjdk_jni_def_PanamaJNIDef_nativeLinker0(JNIEnv *env, jclass cls, jobject linker, jobject desc, jobjectArray opts) {
Context context;
env->GetJavaVM(&context.jvm);
context.linker = env->NewGlobalRef(linker);

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
module panama_jni_load_module {
exports org.openjdk.jni;
requires panama_jni_use_module;
}

Some files were not shown because too many files have changed in this diff Show More