Skip to content

Apache Lucene open-source search software

Remove all security manager and java security references (#14801)

Dawid Weissa6c60e5fae4b
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.ecj-lint.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.ecj-lint.gradle
index 5d10e9e0f76..204cc5d9fa2 100644
--- a/build-tools/build-infra/src/main/groovy/lucene.validation.ecj-lint.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.ecj-lint.gradle
@@ -1,3 +1,5 @@
+import com.diffplug.gradle.spotless.SpotlessApply
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -74,6 +76,8 @@ def lintTasks = sourceSets.collect { SourceSet sourceSet ->
dependsOn sourceSet.compileClasspath
dependsOn ecjConfiguration
+ mustRunAfter tasks.withType(SpotlessApply)
+
// The inputs are all source files from the sourceSet.
inputs.files sourceSet.allSource.asFileTree
diff --git a/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-java.gradle b/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-java.gradle
index c69474d4616..22b21e0d720 100644
--- a/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-java.gradle
+++ b/build-tools/build-infra/src/main/groovy/lucene.validation.spotless-java.gradle
@@ -32,6 +32,7 @@ configure(allprojects) { prj ->
lineEndings = LineEnding.UNIX
endWithNewline()
googleJavaFormat(deps.versions.googleJavaFormat.get())
+ removeUnusedImports()
// Apply to all Java sources
target("src/**/*.java")
diff --git a/dev-tools/scripts/addBackcompatIndexes.py b/dev-tools/scripts/addBackcompatIndexes.py
index a9378c76381..fe40ed5ebeb 100755
--- a/dev-tools/scripts/addBackcompatIndexes.py
+++ b/dev-tools/scripts/addBackcompatIndexes.py
@@ -60,7 +60,7 @@ def create_and_add_index(source: str, indextype: str, index_version: scriptutil.
"dvupdates": "testCreateIndexWithDocValuesUpdates",
"emptyIndex": "testCreateEmptyIndex",
}[indextype]
- gradle_args = " ".join(["-Ptests.useSecurityManager=false", "-p lucene/%s" % module, "test", "--tests TestGenerateBwcIndices.%s" % test, "-Dtests.bwcdir=%s" % temp_dir, "-Dtests.codec=default"])
+ gradle_args = " ".join(["-p lucene/%s" % module, "test", "--tests TestGenerateBwcIndices.%s" % test, "-Dtests.bwcdir=%s" % temp_dir, "-Dtests.codec=default"])
base_dir = os.getcwd()
bc_index_file = os.path.join(temp_dir, filename)
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 81c913d3caa..310771fa488 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -64,6 +64,9 @@ Changes in Runtime Behavior
Other
---------------------
+* GITHUB#14801: Removed all security manager and java.security-related code, which is effectively dead
+ in Java 24+. (Dawid Weiss)
+
* GITHUB#14229: Bump minimum required Java version to 25
* GITHUB#14564: Remove abstractions from MMapDirectory as we need no MR-JAR anymore. (Uwe Schindler)
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestGenerateBwcIndices.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestGenerateBwcIndices.java
index 6989731ae14..f41209e23f2 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestGenerateBwcIndices.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestGenerateBwcIndices.java
@@ -39,7 +39,7 @@ public class TestGenerateBwcIndices extends LuceneTestCase {
// To generate backcompat indexes with the current default codec, run the following gradle
// command:
// gradlew test -Ptests.bwcdir=/path/to/store/indexes -Ptests.codec=default
- // -Ptests.useSecurityManager=false --tests TestGenerateBwcIndices --max-workers=1
+ // --tests TestGenerateBwcIndices --max-workers=1
//
// Also add testmethod with one of the index creation methods below, for example:
// -Ptestmethod=testCreateCFS
diff --git a/lucene/core/src/java/org/apache/lucene/util/Constants.java b/lucene/core/src/java/org/apache/lucene/util/Constants.java
index ac6604e8ea3..7ebb82edc0e 100644
--- a/lucene/core/src/java/org/apache/lucene/util/Constants.java
+++ b/lucene/core/src/java/org/apache/lucene/util/Constants.java
@@ -16,11 +16,8 @@
*/
package org.apache.lucene.util;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Locale;
import java.util.Optional;
-import java.util.logging.Logger;
import org.apache.lucene.store.ReadAdvice;
/** Some useful constants. */
@@ -166,36 +163,10 @@ public final class Constants {
.orElse(ReadAdvice.RANDOM);
private static String getSysProp(String property) {
- try {
- return doPrivileged(() -> System.getProperty(property));
- } catch (
- @SuppressWarnings("unused")
- SecurityException se) {
- logSecurityWarning(property);
- return null;
- }
+ return System.getProperty(property);
}
private static String getSysProp(String property, String def) {
- try {
- return doPrivileged(() -> System.getProperty(property, def));
- } catch (
- @SuppressWarnings("unused")
- SecurityException se) {
- logSecurityWarning(property);
- return def;
- }
- }
-
- private static void logSecurityWarning(String property) {
- var log = Logger.getLogger(Constants.class.getName());
- log.warning("SecurityManager prevented access to system property: " + property);
- }
-
- // Extracted to a method to be able to apply the SuppressForbidden annotation
- @SuppressWarnings("removal")
- @SuppressForbidden(reason = "security manager")
- private static <T> T doPrivileged(PrivilegedAction<T> action) {
- return AccessController.doPrivileged(action);
+ return System.getProperty(property, def);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/NamedThreadFactory.java b/lucene/core/src/java/org/apache/lucene/util/NamedThreadFactory.java
index 99d2c254aca..b2df74eb815 100644
--- a/lucene/core/src/java/org/apache/lucene/util/NamedThreadFactory.java
+++ b/lucene/core/src/java/org/apache/lucene/util/NamedThreadFactory.java
@@ -48,15 +48,8 @@ public class NamedThreadFactory implements ThreadFactory {
threadPoolNumber.getAndIncrement());
}
- @SuppressWarnings("removal")
- @SuppressForbidden(reason = "security manager")
private static ThreadGroup getThreadGroup() {
- final SecurityManager s = System.getSecurityManager();
- if (s != null) {
- return s.getThreadGroup();
- } else {
- return Thread.currentThread().getThreadGroup();
- }
+ return Thread.currentThread().getThreadGroup();
}
private static String checkPrefix(String prefix) {
diff --git a/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java b/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java
index e922c00064f..7f661585571 100644
--- a/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java
+++ b/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java
@@ -19,9 +19,6 @@ package org.apache.lucene.util;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
-import java.security.AccessControlException;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Collection;
@@ -541,15 +538,7 @@ public final class RamUsageEstimator {
// Walk type hierarchy
for (; clazz != null; clazz = clazz.getSuperclass()) {
- final Class<?> target = clazz;
- final Field[] fields;
- try {
- fields = doPrivileged((PrivilegedAction<Field[]>) target::getDeclaredFields);
- } catch (
- @SuppressWarnings("removal")
- AccessControlException e) {
- throw new RuntimeException("Can't access fields of class: " + target, e);
- }
+ final Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
if (!Modifier.isStatic(f.getModifiers())) {
@@ -560,13 +549,6 @@ public final class RamUsageEstimator {
return alignObjectSize(size);
}
- // Extracted to a method to give the SuppressForbidden annotation the smallest possible scope
- @SuppressWarnings("removal")
- @SuppressForbidden(reason = "security manager")
- private static <T> T doPrivileged(PrivilegedAction<T> action) {
- return AccessController.doPrivileged(action);
- }
-
/** Return shallow size of any <code>array</code>. */
private static long shallowSizeOfArray(Object array) {
long size = NUM_BYTES_ARRAY_HEADER;
diff --git a/lucene/core/src/java/org/apache/lucene/util/VirtualMethod.java b/lucene/core/src/java/org/apache/lucene/util/VirtualMethod.java
index a7c2a71cc1c..862c0d7c780 100644
--- a/lucene/core/src/java/org/apache/lucene/util/VirtualMethod.java
+++ b/lucene/core/src/java/org/apache/lucene/util/VirtualMethod.java
@@ -17,8 +17,6 @@
package org.apache.lucene.util;
import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -60,11 +58,6 @@ import java.util.Set;
* VirtualMethod.compareImplementationDistance(this.getClass(), oldMethod, newMethod) &gt; 0);
* </pre>
*
- * <p>It is important to use {@link AccessController#doPrivileged(PrivilegedAction)} for the actual
- * call to get the implementation distance because the subclass may be in a different package. The
- * static constructors do not need to use {@code AccessController} because it just initializes our
- * own method reference. The caller should have access to all declared members in its own class.
- *
* <p>{@link #getImplementationDistance} returns the distance of the subclass that overrides this
* method. The one with the larger distance should be used preferable. This way also more
* complicated method rename scenarios can be handled (think of 2.9 {@code TokenStream}
diff --git a/lucene/core/src/java24/org/apache/lucene/internal/vectorization/PanamaVectorizationProvider.java b/lucene/core/src/java24/org/apache/lucene/internal/vectorization/PanamaVectorizationProvider.java
index df9d35bc439..2e061ee6f5f 100644
--- a/lucene/core/src/java24/org/apache/lucene/internal/vectorization/PanamaVectorizationProvider.java
+++ b/lucene/core/src/java24/org/apache/lucene/internal/vectorization/PanamaVectorizationProvider.java
@@ -18,8 +18,6 @@ package org.apache.lucene.internal.vectorization;
import java.io.IOException;
import java.lang.foreign.MemorySegment;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Locale;
import java.util.logging.Logger;
import jdk.incubator.vector.FloatVector;
@@ -27,7 +25,6 @@ import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.MemorySegmentAccessInput;
import org.apache.lucene.util.Constants;
-import org.apache.lucene.util.SuppressForbidden;
/** A vectorization provider that leverages the Panama Vector API. */
final class PanamaVectorizationProvider extends VectorizationProvider {
@@ -36,28 +33,12 @@ final class PanamaVectorizationProvider extends VectorizationProvider {
// would get called before we have a chance to perform sanity checks around the vector API in the
// constructor of this class. Put them in PanamaVectorConstants instead.
- // Extracted to a method to be able to apply the SuppressForbidden annotation
- @SuppressWarnings("removal")
- @SuppressForbidden(reason = "security manager")
- private static <T> T doPrivileged(PrivilegedAction<T> action) {
- return AccessController.doPrivileged(action);
- }
-
private final VectorUtilSupport vectorUtilSupport;
PanamaVectorizationProvider() {
// hack to work around for JDK-8309727:
- try {
- doPrivileged(
- () ->
- FloatVector.fromArray(
- FloatVector.SPECIES_PREFERRED,
- new float[FloatVector.SPECIES_PREFERRED.length()],
- 0));
- } catch (SecurityException se) {
- throw new UnsupportedOperationException(
- "We hit initialization failure described in JDK-8309727: " + se);
- }
+ FloatVector.fromArray(
+ FloatVector.SPECIES_PREFERRED, new float[FloatVector.SPECIES_PREFERRED.length()], 0);
if (PanamaVectorConstants.PREFERRED_VECTOR_BITSIZE < 128) {
throw new UnsupportedOperationException(
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestReadOnlyIndex.java b/lucene/core/src/test/org/apache/lucene/index/TestReadOnlyIndex.java
index e6246a1de2c..ca07f50a3b0 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestReadOnlyIndex.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestReadOnlyIndex.java
@@ -16,10 +16,8 @@
*/
package org.apache.lucene.index;
-import java.io.FilePermission;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.PropertyPermission;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
@@ -66,18 +64,6 @@ public class TestReadOnlyIndex extends LuceneTestCase {
}
public void testReadOnlyIndex() throws Exception {
- runWithRestrictedPermissions(
- this::doTestReadOnlyIndex,
- // add some basic permissions (because we are limited already - so we grant all important
- // ones):
- new RuntimePermission("*"),
- new PropertyPermission("*", "read"),
- // only allow read to the given index dir, nothing else:
- new FilePermission(indexPath.toString(), "read"),
- new FilePermission(indexPath.resolve("-").toString(), "read"));
- }
-
- private Void doTestReadOnlyIndex() throws Exception {
Directory dir = FSDirectory.open(indexPath);
IndexReader ireader = DirectoryReader.open(dir);
IndexSearcher isearcher = newSearcher(ireader);
@@ -100,6 +86,5 @@ public class TestReadOnlyIndex extends LuceneTestCase {
assertEquals(1, isearcher.count(phraseQuery));
ireader.close();
- return null; // void
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestClassLoaderUtils.java b/lucene/core/src/test/org/apache/lucene/util/TestClassLoaderUtils.java
index 5c699794708..4f25103603c 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestClassLoaderUtils.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestClassLoaderUtils.java
@@ -22,7 +22,7 @@ import org.apache.lucene.tests.util.LuceneTestCase;
public class TestClassLoaderUtils extends LuceneTestCase {
- public void testParentChild() throws Exception {
+ public void testParentChild() {
final ClassLoader parent = getClass().getClassLoader();
final ClassLoader child = URLClassLoader.newInstance(new URL[0], parent);
assertTrue(checkNoPerms(parent, parent));
@@ -31,7 +31,7 @@ public class TestClassLoaderUtils extends LuceneTestCase {
assertFalse(checkNoPerms(child, parent));
}
- private boolean checkNoPerms(ClassLoader parent, ClassLoader child) throws Exception {
- return runWithRestrictedPermissions(() -> ClassLoaderUtils.isParentClassLoader(parent, child));
+ private boolean checkNoPerms(ClassLoader parent, ClassLoader child) {
+ return ClassLoaderUtils.isParentClassLoader(parent, child);
}
}
diff --git a/lucene/misc/src/java/org/apache/lucene/misc/store/HardlinkCopyDirectoryWrapper.java b/lucene/misc/src/java/org/apache/lucene/misc/store/HardlinkCopyDirectoryWrapper.java
index 4ead4a3c9c9..1add5c0da79 100644
--- a/lucene/misc/src/java/org/apache/lucene/misc/store/HardlinkCopyDirectoryWrapper.java
+++ b/lucene/misc/src/java/org/apache/lucene/misc/store/HardlinkCopyDirectoryWrapper.java
@@ -23,13 +23,10 @@ import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.FilterDirectory;
import org.apache.lucene.store.IOContext;
-import org.apache.lucene.util.SuppressForbidden;
/**
* This directory wrapper overrides {@link Directory#copyFrom(Directory, String, String, IOContext)}
@@ -66,27 +63,22 @@ public final class HardlinkCopyDirectoryWrapper extends FilterDirectory {
if (Files.isReadable(fromPath.resolve(srcFile)) && Files.isWritable(toPath)) {
// only try hardlinks if we have permission to access the files
// if not super.copyFrom() will give us the right exceptions
- suppressedException =
- doPrivileged(
- () -> {
- try {
- Files.createLink(toPath.resolve(destFile), fromPath.resolve(srcFile));
- } catch (FileNotFoundException
- | NoSuchFileException
- | FileAlreadyExistsException ex) {
- return ex; // in these cases we bubble up since it's a true error condition.
- } catch (IOException
- // if the FS doesn't support hard-links
- | UnsupportedOperationException
- // we don't have permission to use hard-links just fall back to byte copy
- | SecurityException ex) {
- // hard-links are not supported or the files are on different filesystems
- // we could go deeper and check if their filesstores are the same and opt
- // out earlier but for now we just fall back to normal file-copy
- return ex;
- }
- return null;
- });
+ try {
+ Files.createLink(toPath.resolve(destFile), fromPath.resolve(srcFile));
+ } catch (FileNotFoundException | NoSuchFileException | FileAlreadyExistsException ex) {
+ suppressedException =
+ ex; // in these cases we bubble up since it's a true error condition.
+ } catch (IOException
+ // if the FS doesn't support hard-links
+ | UnsupportedOperationException
+ // we don't have permission to use hard-links just fall back to byte copy
+ | SecurityException ex) {
+ // hard-links are not supported or the files are on different filesystems
+ // we could go deeper and check if their filesstores are the same and opt
+ // out earlier but for now we just fall back to normal file-copy
+ suppressedException = ex;
+ }
+
tryCopy = suppressedException != null;
}
}
@@ -101,11 +93,4 @@ public final class HardlinkCopyDirectoryWrapper extends FilterDirectory {
}
}
}
-
- // Extracted to a method to give the SuppressForbidden annotation the smallest possible scope
- @SuppressWarnings("removal")
- @SuppressForbidden(reason = "security manager")
- private static <T> T doPrivileged(PrivilegedAction<T> action) {
- return AccessController.doPrivileged(action);
- }
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
index 161b6dcdfa1..a019d5e9325 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
@@ -69,15 +69,6 @@ import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.Permissions;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.security.ProtectionDomain;
-import java.security.SecurityPermission;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
@@ -3137,35 +3128,6 @@ public abstract class LuceneTestCase extends Assert {
return Files.readAllLines(forkArgsPath, StandardCharsets.UTF_8);
}
- /**
- * Runs a code part with restricted permissions (be sure to add all required permissions, because
- * it would start with empty permissions). You cannot grant more permissions than our policy file
- * allows, but you may restrict writing to several dirs...
- *
- * <p><em>Note:</em> This assumes a {@link SecurityManager} enabled, otherwise it stops test
- * execution. If enabled, it needs the following {@link SecurityPermission}: {@code
- * "createAccessControlContext"}
- */
- @SuppressForbidden(reason = "security manager")
- @SuppressWarnings("removal")
- public static <T> T runWithRestrictedPermissions(
- PrivilegedExceptionAction<T> action, Permission... permissions) throws Exception {
- assumeTrue(
- "runWithRestrictedPermissions requires a SecurityManager enabled",
- System.getSecurityManager() != null);
- // be sure to have required permission, otherwise doPrivileged runs with *no* permissions:
- AccessController.checkPermission(new SecurityPermission("createAccessControlContext"));
- final PermissionCollection perms = new Permissions();
- Arrays.stream(permissions).forEach(perms::add);
- final AccessControlContext ctx =
- new AccessControlContext(new ProtectionDomain[] {new ProtectionDomain(null, perms)});
- try {
- return AccessController.doPrivileged(action, ctx);
- } catch (PrivilegedActionException e) {
- throw e.getException();
- }
- }
-
/** True if assertions (-ea) are enabled (at least for this class). */
public static final boolean assertsAreEnabled;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/RamUsageTester.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/RamUsageTester.java
index 60c3fbbc2b8..f3f6a515e20 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/RamUsageTester.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/RamUsageTester.java
@@ -26,8 +26,6 @@ import java.nio.ByteOrder;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Path;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.BitSet;
@@ -312,50 +310,42 @@ public final class RamUsageTester {
/** Create a cached information about shallow size and reference fields for a given class. */
@SuppressForbidden(reason = "We need to access private fields of measured objects.")
private static ClassCache createCacheEntry(final Class<?> clazz) {
- @SuppressWarnings("removal")
- ClassCache classCache =
- AccessController.doPrivileged(
- (PrivilegedAction<ClassCache>)
- () -> {
- ClassCache cachedInfo;
- long shallowInstanceSize = RamUsageEstimator.NUM_BYTES_OBJECT_HEADER;
- final ArrayList<Field> referenceFields = new ArrayList<>(32);
- for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
- if (c == Class.class) {
- // prevent inspection of Class' fields, throws SecurityException in Java 9!
- continue;
- }
- final Field[] fields = c.getDeclaredFields();
- for (final Field f : fields) {
- if (!Modifier.isStatic(f.getModifiers())) {
- shallowInstanceSize =
- RamUsageEstimator.adjustForField(shallowInstanceSize, f);
-
- if (!f.getType().isPrimitive()) {
- try {
- f.setAccessible(true);
- referenceFields.add(f);
- } catch (RuntimeException re) {
- throw new RuntimeException(
- String.format(
- Locale.ROOT,
- "Can't access field '%s' of class '%s' for RAM estimation.",
- f.getName(),
- clazz.getName()),
- re);
- }
- }
- }
- }
- }
-
- cachedInfo =
- new ClassCache(
- RamUsageEstimator.alignObjectSize(shallowInstanceSize),
- referenceFields.toArray(new Field[0]));
- return cachedInfo;
- });
- return classCache;
+ ClassCache cachedInfo;
+ long shallowInstanceSize = RamUsageEstimator.NUM_BYTES_OBJECT_HEADER;
+ final ArrayList<Field> referenceFields = new ArrayList<>(32);
+ for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
+ if (c == Class.class) {
+ // prevent inspection of Class' fields, throws SecurityException in Java 9+
+ continue;
+ }
+ final Field[] fields = c.getDeclaredFields();
+ for (final Field f : fields) {
+ if (!Modifier.isStatic(f.getModifiers())) {
+ shallowInstanceSize = RamUsageEstimator.adjustForField(shallowInstanceSize, f);
+
+ if (!f.getType().isPrimitive()) {
+ try {
+ f.setAccessible(true);
+ referenceFields.add(f);
+ } catch (RuntimeException re) {
+ throw new RuntimeException(
+ String.format(
+ Locale.ROOT,
+ "Can't access field '%s' of class '%s' for RAM estimation.",
+ f.getName(),
+ clazz.getName()),
+ re);
+ }
+ }
+ }
+ }
+ }
+
+ cachedInfo =
+ new ClassCache(
+ RamUsageEstimator.alignObjectSize(shallowInstanceSize),
+ referenceFields.toArray(new Field[0]));
+ return cachedInfo;
}
private static long byteArraySize(int len) {
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestSecurityManager.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestSecurityManager.java
deleted file mode 100644
index 6cef472447b..00000000000
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestSecurityManager.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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
- *
- * http://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.
- */
-package org.apache.lucene.tests.util;
-
-import java.lang.StackWalker.StackFrame;
-import java.util.Locale;
-import java.util.function.Predicate;
-import org.apache.lucene.util.SuppressForbidden;
-
-/**
- * A {@link SecurityManager} that prevents tests calling {@link System#exit(int)}. Only the test
- * runner itself is allowed to exit the JVM. All other security checks are handled by the default
- * security policy.
- *
- * <p>Use this with {@code
- * -Djava.security.manager=org.apache.lucene.tests.util.TestSecurityManager}.
- */
-@SuppressForbidden(reason = "security manager")
-@SuppressWarnings("removal")
-public final class TestSecurityManager extends SecurityManager {
-
- private static final String JUNIT4_TEST_RUNNER_PACKAGE = "com.carrotsearch.ant.tasks.junit4.";
- private static final String ECLIPSE_TEST_RUNNER_PACKAGE =
- "org.eclipse.jdt.internal.junit.runner.";
- private static final String IDEA_TEST_RUNNER_PACKAGE = "com.intellij.rt.execution.junit.";
- private static final String GRADLE_TEST_RUNNER_PACKAGE =
- "worker.org.gradle.process.internal.worker.";
-
- private static final String SYSTEM_CLASS_NAME = System.class.getName();
- private static final String RUNTIME_CLASS_NAME = Runtime.class.getName();
-
- /**
- * Creates a new TestSecurityManager. This ctor is called on JVM startup, when {@code
- * -Djava.security.manager=org.apache.lucene.tests.util.TestSecurityManager} is passed to JVM.
- */
- public TestSecurityManager() {
- super();
- }
-
- /**
- * {@inheritDoc}
- *
- * <p>This method inspects the stack trace and checks who is calling {@link System#exit(int)} and
- * similar methods
- *
- * @throws SecurityException if the caller of this method is not the test runner itself.
- */
- @Override
- public void checkExit(final int status) {
- if (StackWalker.getInstance()
- .walk(
- s ->
- // skip all internal stack frames
- s.dropWhile(Predicate.not(TestSecurityManager::isExitStackFrame))
- // skip all exit()/halt() stack frames
- .dropWhile(TestSecurityManager::isExitStackFrame)
- .limit(1) // only look at one more frame (caller of exit)
- .map(StackFrame::getClassName)
- .noneMatch(
- c ->
- c.startsWith(JUNIT4_TEST_RUNNER_PACKAGE)
- || c.startsWith(ECLIPSE_TEST_RUNNER_PACKAGE)
- || c.startsWith(IDEA_TEST_RUNNER_PACKAGE)
- || c.startsWith(GRADLE_TEST_RUNNER_PACKAGE)))) {
- throw new SecurityException(
- String.format(
- Locale.ENGLISH,
- "System/Runtime.exit(%1$d) or halt(%1$d) calls are not allowed because they terminate the test runner's JVM.",
- status));
- }
- // we passed the stack check, delegate to super, so default policy can still deny permission:
- super.checkExit(status);
- }
-
- private static boolean isExitStackFrame(StackFrame f) {
- final String methodName = f.getMethodName(), className = f.getClassName();
- return ("exit".equals(methodName) || "halt".equals(methodName))
- && (SYSTEM_CLASS_NAME.equals(className) || RUNTIME_CLASS_NAME.equals(className));
- }
-}
diff --git a/lucene/test-framework/src/test/org/apache/lucene/tests/util/TestRunWithRestrictedPermissions.java b/lucene/test-framework/src/test/org/apache/lucene/tests/util/TestRunWithRestrictedPermissions.java
deleted file mode 100644
index 33e1fae621f..00000000000
--- a/lucene/test-framework/src/test/org/apache/lucene/tests/util/TestRunWithRestrictedPermissions.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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
- *
- * http://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.
- */
-package org.apache.lucene.tests.util;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.security.AllPermission;
-
-public class TestRunWithRestrictedPermissions extends LuceneTestCase {
-
- public void testDefaultsPass() throws Exception {
- runWithRestrictedPermissions(this::doSomeForbiddenStuff, new AllPermission());
- }
-
- public void testNormallyAllowedStuff() throws Exception {
- expectThrows(
- SecurityException.class, () -> runWithRestrictedPermissions(this::doSomeForbiddenStuff));
- }
-
- public void testCompletelyForbidden1() throws Exception {
- expectThrows(
- SecurityException.class,
- () -> runWithRestrictedPermissions(this::doSomeCompletelyForbiddenStuff));
- }
-
- public void testCompletelyForbidden2() throws Exception {
- expectThrows(
- SecurityException.class,
- () ->
- runWithRestrictedPermissions(
- this::doSomeCompletelyForbiddenStuff, new AllPermission()));
- }
-
- private Void doSomeForbiddenStuff() throws IOException {
- createTempDir("cannot_create_temp_folder");
- return null; // Void
- }
-
- // something like this should not never pass!!
- private Void doSomeCompletelyForbiddenStuff() throws IOException {
- Files.createFile(Paths.get("denied"));
- return null; // Void
- }
-}