Path: blob/master/test/jdk/java/lang/Class/getDeclaredField/ClassDeclaredFieldsTest.java
41153 views
/*1* Copyright (c) 2014, 2019, 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.lang.reflect.Field;24import java.lang.reflect.ReflectPermission;25import java.security.CodeSource;26import java.security.Permission;27import java.security.PermissionCollection;28import java.security.Permissions;29import java.security.Policy;30import java.security.ProtectionDomain;31import java.util.Arrays;32import java.util.Enumeration;33import java.util.concurrent.atomic.AtomicBoolean;3435/**36* @test37* @bug 806555238* @summary test that all fields returned by getDeclaredFields() can be39* set accessible if the right permission is granted; this test40* also verifies that Class.classLoader final private field is41* hidden from reflection access.42* @modules java.base/java.lang:open43* @run main/othervm ClassDeclaredFieldsTest UNSECURE44* @run main/othervm -Djava.security.manager=allow ClassDeclaredFieldsTest SECURE45*46* @author danielfuchs47*/48public class ClassDeclaredFieldsTest {4950// Test with or without a security manager51public static enum TestCase {52UNSECURE, SECURE;53public void run() throws Exception {54System.out.println("Running test case: " + name());55Configure.setUp(this);56test(this);57}58}59/**60* @param args the command line arguments61*/62public static void main(String[] args) throws Exception {63System.out.println(System.getProperty("java.version"));64if (args == null || args.length == 0) {65args = new String[] { "SECURE" };66} else if (args.length != 1) {67throw new IllegalArgumentException("Only one arg expected: "68+ Arrays.asList(args));69}70TestCase.valueOf(args[0]).run();71}7273static void test(TestCase test) {74for (Field f : Class.class.getDeclaredFields()) {75f.setAccessible(true);76System.out.println("Field "+f.getName()+" is now accessible.");77if (f.getName().equals("classLoader")) {78throw new RuntimeException("Found "+f.getName()+" field!");79}80}81try {82Class.class.getDeclaredField("classLoader");83throw new RuntimeException("Expected NoSuchFieldException for"84+ " 'classLoader' field not raised");85} catch(NoSuchFieldException x) {86System.out.println("Got expected exception: " + x);87}88System.out.println("Passed "+test);89}9091// A helper class to configure the security manager for the test,92// and bypass it when needed.93static class Configure {94static Policy policy = null;95static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {96@Override97protected AtomicBoolean initialValue() {98return new AtomicBoolean(false);99}100};101static void setUp(TestCase test) {102switch (test) {103case SECURE:104if (policy == null && System.getSecurityManager() != null) {105throw new IllegalStateException("SecurityManager already set");106} else if (policy == null) {107policy = new SimplePolicy(TestCase.SECURE, allowAll);108Policy.setPolicy(policy);109System.setSecurityManager(new SecurityManager());110}111if (System.getSecurityManager() == null) {112throw new IllegalStateException("No SecurityManager.");113}114if (policy == null) {115throw new IllegalStateException("policy not configured");116}117break;118case UNSECURE:119if (System.getSecurityManager() != null) {120throw new IllegalStateException("SecurityManager already set");121}122break;123default:124throw new InternalError("No such testcase: " + test);125}126}127static void doPrivileged(Runnable run) {128allowAll.get().set(true);129try {130run.run();131} finally {132allowAll.get().set(false);133}134}135}136137// A Helper class to build a set of permissions.138static final class PermissionsBuilder {139final Permissions perms;140public PermissionsBuilder() {141this(new Permissions());142}143public PermissionsBuilder(Permissions perms) {144this.perms = perms;145}146public PermissionsBuilder add(Permission p) {147perms.add(p);148return this;149}150public PermissionsBuilder addAll(PermissionCollection col) {151if (col != null) {152for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {153perms.add(e.nextElement());154}155}156return this;157}158public Permissions toPermissions() {159final PermissionsBuilder builder = new PermissionsBuilder();160builder.addAll(perms);161return builder.perms;162}163}164165// Policy for the test...166public static class SimplePolicy extends Policy {167168static final Policy DEFAULT_POLICY = Policy.getPolicy();169final Permissions permissions;170final Permissions allPermissions;171final ThreadLocal<AtomicBoolean> allowAll; // actually: this should be in a thread locale172public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {173this.allowAll = allowAll;174// we don't actually need any permission to create our175// FileHandlers because we're passing invalid parameters176// which will make the creation fail...177permissions = new Permissions();178permissions.add(new RuntimePermission("accessDeclaredMembers"));179permissions.add(new ReflectPermission("suppressAccessChecks"));180181// these are used for configuring the test itself...182allPermissions = new Permissions();183allPermissions.add(new java.security.AllPermission());184185}186187@Override188public boolean implies(ProtectionDomain domain, Permission permission) {189if (allowAll.get().get()) return allPermissions.implies(permission);190return permissions.implies(permission) || DEFAULT_POLICY.implies(domain, permission);191}192193@Override194public PermissionCollection getPermissions(CodeSource codesource) {195return new PermissionsBuilder().addAll(allowAll.get().get()196? allPermissions : permissions).toPermissions();197}198199@Override200public PermissionCollection getPermissions(ProtectionDomain domain) {201return new PermissionsBuilder().addAll(allowAll.get().get()202? allPermissions : permissions).toPermissions();203}204}205206}207208209