Path: blob/master/test/jdk/java/lang/Class/getDeclaredField/FieldSetAccessibleTest.java
41153 views
/*1* Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.FilePermission;24import java.io.IOException;25import java.io.UncheckedIOException;26import java.lang.module.ModuleFinder;27import java.lang.reflect.AccessibleObject;28import java.lang.reflect.Field;29import java.lang.reflect.Modifier;30import java.lang.reflect.InaccessibleObjectException;31import java.lang.reflect.ReflectPermission;32import java.net.URI;33import java.nio.file.FileSystem;34import java.nio.file.FileSystems;35import java.nio.file.Files;36import java.nio.file.Path;37import java.security.CodeSource;38import java.security.Permission;39import java.security.PermissionCollection;40import java.security.Permissions;41import java.security.Policy;42import java.security.ProtectionDomain;43import java.util.ArrayList;44import java.util.Arrays;45import java.util.Collections;46import java.util.Enumeration;47import java.util.Iterator;48import java.util.List;49import java.util.Set;50import java.util.PropertyPermission;51import java.util.concurrent.atomic.AtomicBoolean;52import java.util.concurrent.atomic.AtomicLong;53import java.util.stream.Collectors;54import java.util.stream.Stream;5556import jdk.internal.module.Modules;5758/**59* @test60* @bug 806555261* @summary test that all public fields returned by getDeclaredFields() can62* be set accessible if the right permission is granted; this test63* loads all classes and get their declared fields64* and call setAccessible(false) followed by setAccessible(true);65* @modules java.base/jdk.internal.module66* @run main/othervm --add-modules=ALL-SYSTEM FieldSetAccessibleTest UNSECURE67* @run main/othervm --add-modules=ALL-SYSTEM -Djava.security.manager=allow FieldSetAccessibleTest SECURE68*69* @author danielfuchs70*/71public class FieldSetAccessibleTest {7273static final List<String> cantread = new ArrayList<>();74static final List<String> failed = new ArrayList<>();75static final AtomicLong classCount = new AtomicLong();76static final AtomicLong fieldCount = new AtomicLong();77static long startIndex = 0;78static long maxSize = Long.MAX_VALUE;79static long maxIndex = Long.MAX_VALUE;80static final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();818283// Test that all fields for any given class can be made accessibles84static void testSetFieldsAccessible(Class<?> c) {85Module self = FieldSetAccessibleTest.class.getModule();86Module target = c.getModule();87String pn = c.getPackageName();88boolean exported = self.canRead(target) && target.isExported(pn, self);89for (Field f : c.getDeclaredFields()) {90fieldCount.incrementAndGet();9192// setAccessible succeeds only if it's exported and the member93// is public and of a public class, or it's opened94// otherwise it would fail.95boolean isPublic = Modifier.isPublic(f.getModifiers()) &&96Modifier.isPublic(c.getModifiers());97boolean access = (exported && isPublic) || target.isOpen(pn, self);98try {99f.setAccessible(false);100f.setAccessible(true);101if (!access) {102throw new RuntimeException(103String.format("Expected InaccessibleObjectException is not thrown "104+ "for field %s in class %s%n", f.getName(), c.getName()));105}106} catch (InaccessibleObjectException expected) {107if (access) {108throw new RuntimeException(expected);109}110}111}112}113114// Performs a series of test on the given class.115// At this time, we only call testSetFieldsAccessible(c)116public static boolean test(Class<?> c, boolean addExports) {117Module self = FieldSetAccessibleTest.class.getModule();118Module target = c.getModule();119String pn = c.getPackageName();120boolean exported = self.canRead(target) && target.isExported(pn, self);121if (addExports && !exported) {122Modules.addExports(target, pn, self);123exported = true;124}125126classCount.incrementAndGet();127128// Call getDeclaredFields() and try to set their accessible flag.129testSetFieldsAccessible(c);130131// add more tests here...132133return c == Class.class;134}135136// Prints a summary at the end of the test.137static void printSummary(long secs, long millis, long nanos) {138System.out.println("Tested " + fieldCount.get() + " fields of "139+ classCount.get() + " classes in "140+ secs + "s " + millis + "ms " + nanos + "ns");141}142143144/**145* @param args the command line arguments:146*147* SECURE|UNSECURE [startIndex (default=0)] [maxSize (default=Long.MAX_VALUE)]148*149* @throws java.lang.Exception if the test fails150*/151public static void main(String[] args) throws Exception {152if (args == null || args.length == 0) {153args = new String[] {"SECURE", "0"};154} else if (args.length > 3) {155throw new RuntimeException("Expected at most one argument. Found "156+ Arrays.asList(args));157}158try {159if (args.length > 1) {160startIndex = Long.parseLong(args[1]);161if (startIndex < 0) {162throw new IllegalArgumentException("startIndex args[1]: "163+ startIndex);164}165}166if (args.length > 2) {167maxSize = Long.parseLong(args[2]);168if (maxSize <= 0) {169maxSize = Long.MAX_VALUE;170}171maxIndex = (Long.MAX_VALUE - startIndex) < maxSize172? Long.MAX_VALUE : startIndex + maxSize;173}174TestCase.valueOf(args[0]).run();175} catch (OutOfMemoryError oome) {176System.err.println(classCount.get());177throw oome;178}179}180181public static void run(TestCase test) {182System.out.println("Testing " + test);183test(listAllClassNames());184System.out.println("Passed " + test);185}186187static Iterable<String> listAllClassNames() {188return new ClassNameJrtStreamBuilder();189}190191static void test(Iterable<String> iterable) {192final long start = System.nanoTime();193boolean classFound = false;194int index = 0;195for (String s : iterable) {196if (index == maxIndex) break;197try {198if (index < startIndex) continue;199if (test(s, false)) {200classFound = true;201}202} finally {203index++;204}205}206207// Re-test with all packages exported208for (String s : iterable) {209test(s, true);210}211212classCount.set(classCount.get() / 2);213fieldCount.set(fieldCount.get() / 2);214long elapsed = System.nanoTime() - start;215long secs = elapsed / 1000_000_000;216long millis = (elapsed % 1000_000_000) / 1000_000;217long nanos = elapsed % 1000_000;218System.out.println("Unreadable path elements: " + cantread);219System.out.println("Failed path elements: " + failed);220printSummary(secs, millis, nanos);221222if (!failed.isEmpty()) {223throw new RuntimeException("Test failed for the following classes: " + failed);224}225if (!classFound && startIndex == 0 && index < maxIndex) {226// this is just to verify that we have indeed parsed rt.jar227// (or the java.base module)228throw new RuntimeException("Test failed: Class.class not found...");229}230if (classCount.get() == 0 && startIndex == 0) {231throw new RuntimeException("Test failed: no class found?");232}233}234235static boolean test(String s, boolean addExports) {236String clsName = s.replace('/', '.').substring(0, s.length() - 6);237try {238System.out.println("Loading " + clsName);239final Class<?> c = Class.forName(240clsName,241false,242systemClassLoader);243return test(c, addExports);244} catch (VerifyError ve) {245System.err.println("VerifyError for " + clsName);246ve.printStackTrace(System.err);247failed.add(s);248} catch (Exception t) {249t.printStackTrace(System.err);250failed.add(s);251} catch (NoClassDefFoundError e) {252e.printStackTrace(System.err);253failed.add(s);254}255return false;256}257258static class ClassNameJrtStreamBuilder implements Iterable<String>{259260final FileSystem jrt;261final Path root;262final Set<String> modules;263ClassNameJrtStreamBuilder() {264jrt = FileSystems.getFileSystem(URI.create("jrt:/"));265root = jrt.getPath("/modules");266modules = systemModules();267}268269@Override270public Iterator<String> iterator() {271try {272return Files.walk(root)273.filter(p -> p.getNameCount() > 2)274.filter(p -> modules.contains(p.getName(1).toString()))275.map(p -> p.subpath(2, p.getNameCount()))276.map(p -> p.toString())277.filter(s -> s.endsWith(".class") && !s.endsWith("module-info.class"))278.iterator();279} catch(IOException x) {280throw new UncheckedIOException("Unable to walk \"/modules\"", x);281}282}283284/*285* Filter deployment modules286*/287static Set<String> systemModules() {288Set<String> mods = Set.of("javafx.deploy", "jdk.deploy", "jdk.plugin", "jdk.javaws",289// All JVMCI packages other than jdk.vm.ci.services are dynamically290// exported to jdk.internal.vm.compiler291"jdk.internal.vm.compiler"292);293return ModuleFinder.ofSystem().findAll().stream()294.map(mref -> mref.descriptor().name())295.filter(mn -> !mods.contains(mn))296.collect(Collectors.toSet());297}298}299300// Test with or without a security manager301public static enum TestCase {302UNSECURE, SECURE;303public void run() throws Exception {304System.out.println("Running test case: " + name());305Configure.setUp(this);306FieldSetAccessibleTest.run(this);307}308}309310// A helper class to configure the security manager for the test,311// and bypass it when needed.312static class Configure {313static Policy policy = null;314static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {315@Override316protected AtomicBoolean initialValue() {317return new AtomicBoolean(false);318}319};320static void setUp(TestCase test) {321switch (test) {322case SECURE:323if (policy == null && System.getSecurityManager() != null) {324throw new IllegalStateException("SecurityManager already set");325} else if (policy == null) {326policy = new SimplePolicy(TestCase.SECURE, allowAll);327Policy.setPolicy(policy);328System.setSecurityManager(new SecurityManager());329}330if (System.getSecurityManager() == null) {331throw new IllegalStateException("No SecurityManager.");332}333if (policy == null) {334throw new IllegalStateException("policy not configured");335}336break;337case UNSECURE:338if (System.getSecurityManager() != null) {339throw new IllegalStateException("SecurityManager already set");340}341break;342default:343throw new InternalError("No such testcase: " + test);344}345}346static void doPrivileged(Runnable run) {347allowAll.get().set(true);348try {349run.run();350} finally {351allowAll.get().set(false);352}353}354}355356// A Helper class to build a set of permissions.357static final class PermissionsBuilder {358final Permissions perms;359public PermissionsBuilder() {360this(new Permissions());361}362public PermissionsBuilder(Permissions perms) {363this.perms = perms;364}365public PermissionsBuilder add(Permission p) {366perms.add(p);367return this;368}369public PermissionsBuilder addAll(PermissionCollection col) {370if (col != null) {371for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {372perms.add(e.nextElement());373}374}375return this;376}377public Permissions toPermissions() {378final PermissionsBuilder builder = new PermissionsBuilder();379builder.addAll(perms);380return builder.perms;381}382}383384// Policy for the test...385public static class SimplePolicy extends Policy {386387static final Policy DEFAULT_POLICY = Policy.getPolicy();388389final Permissions permissions;390final Permissions allPermissions;391final ThreadLocal<AtomicBoolean> allowAll;392public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {393this.allowAll = allowAll;394395// Permission needed by the tested code exercised in the test396permissions = new Permissions();397permissions.add(new RuntimePermission("fileSystemProvider"));398permissions.add(new RuntimePermission("createClassLoader"));399permissions.add(new RuntimePermission("closeClassLoader"));400permissions.add(new RuntimePermission("getClassLoader"));401permissions.add(new RuntimePermission("accessDeclaredMembers"));402permissions.add(new RuntimePermission("accessSystemModules"));403permissions.add(new ReflectPermission("suppressAccessChecks"));404permissions.add(new PropertyPermission("*", "read"));405permissions.add(new FilePermission("<<ALL FILES>>", "read"));406407// these are used for configuring the test itself...408allPermissions = new Permissions();409allPermissions.add(new java.security.AllPermission());410}411412@Override413public boolean implies(ProtectionDomain domain, Permission permission) {414if (allowAll.get().get()) return allPermissions.implies(permission);415if (permissions.implies(permission)) return true;416if (permission instanceof java.lang.RuntimePermission) {417if (permission.getName().startsWith("accessClassInPackage.")) {418// add these along to the set of permission we have, when we419// discover that we need them.420permissions.add(permission);421return true;422}423}424if (DEFAULT_POLICY.implies(domain, permission)) return true;425return false;426}427428@Override429public PermissionCollection getPermissions(CodeSource codesource) {430return new PermissionsBuilder().addAll(allowAll.get().get()431? allPermissions : permissions).toPermissions();432}433434@Override435public PermissionCollection getPermissions(ProtectionDomain domain) {436return new PermissionsBuilder().addAll(allowAll.get().get()437? allPermissions : permissions).toPermissions();438}439}440441}442443444