Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/lang/Class/getDeclaredField/ClassDeclaredFieldsTest.java
38828 views
/*1* Copyright (c) 2014, 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* @run main/othervm ClassDeclaredFieldsTest UNSECURE43* @run main/othervm ClassDeclaredFieldsTest SECURE44*45* @author danielfuchs46*/47public class ClassDeclaredFieldsTest {4849// Test with or without a security manager50public static enum TestCase {51UNSECURE, SECURE;52public void run() throws Exception {53System.out.println("Running test case: " + name());54Configure.setUp(this);55test(this);56}57}58/**59* @param args the command line arguments60*/61public static void main(String[] args) throws Exception {62System.out.println(System.getProperty("java.version"));63if (args == null || args.length == 0) {64args = new String[] { "SECURE" };65} else if (args.length != 1) {66throw new IllegalArgumentException("Only one arg expected: "67+ Arrays.asList(args));68}69TestCase.valueOf(args[0]).run();70}7172static void test(TestCase test) {73for (Field f : Class.class.getDeclaredFields()) {74f.setAccessible(true);75System.out.println("Field "+f.getName()+" is now accessible.");76if (f.getName().equals("classLoader")) {77throw new RuntimeException("Found "+f.getName()+" field!");78}79}80try {81Class.class.getDeclaredField("classLoader");82throw new RuntimeException("Expected NoSuchFieldException for"83+ " 'classLoader' field not raised");84} catch(NoSuchFieldException x) {85System.out.println("Got expected exception: " + x);86}87System.out.println("Passed "+test);88}8990// A helper class to configure the security manager for the test,91// and bypass it when needed.92static class Configure {93static Policy policy = null;94static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {95@Override96protected AtomicBoolean initialValue() {97return new AtomicBoolean(false);98}99};100static void setUp(TestCase test) {101switch (test) {102case SECURE:103if (policy == null && System.getSecurityManager() != null) {104throw new IllegalStateException("SecurityManager already set");105} else if (policy == null) {106policy = new SimplePolicy(TestCase.SECURE, allowAll);107Policy.setPolicy(policy);108System.setSecurityManager(new SecurityManager());109}110if (System.getSecurityManager() == null) {111throw new IllegalStateException("No SecurityManager.");112}113if (policy == null) {114throw new IllegalStateException("policy not configured");115}116break;117case UNSECURE:118if (System.getSecurityManager() != null) {119throw new IllegalStateException("SecurityManager already set");120}121break;122default:123throw new InternalError("No such testcase: " + test);124}125}126static void doPrivileged(Runnable run) {127allowAll.get().set(true);128try {129run.run();130} finally {131allowAll.get().set(false);132}133}134}135136// A Helper class to build a set of permissions.137final static class PermissionsBuilder {138final Permissions perms;139public PermissionsBuilder() {140this(new Permissions());141}142public PermissionsBuilder(Permissions perms) {143this.perms = perms;144}145public PermissionsBuilder add(Permission p) {146perms.add(p);147return this;148}149public PermissionsBuilder addAll(PermissionCollection col) {150if (col != null) {151for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {152perms.add(e.nextElement());153}154}155return this;156}157public Permissions toPermissions() {158final PermissionsBuilder builder = new PermissionsBuilder();159builder.addAll(perms);160return builder.perms;161}162}163164// Policy for the test...165public static class SimplePolicy extends Policy {166167final Permissions permissions;168final Permissions allPermissions;169final ThreadLocal<AtomicBoolean> allowAll; // actually: this should be in a thread locale170public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {171this.allowAll = allowAll;172// we don't actually need any permission to create our173// FileHandlers because we're passing invalid parameters174// which will make the creation fail...175permissions = new Permissions();176permissions.add(new RuntimePermission("accessDeclaredMembers"));177permissions.add(new ReflectPermission("suppressAccessChecks"));178179// these are used for configuring the test itself...180allPermissions = new Permissions();181allPermissions.add(new java.security.AllPermission());182183}184185@Override186public boolean implies(ProtectionDomain domain, Permission permission) {187if (allowAll.get().get()) return allPermissions.implies(permission);188return permissions.implies(permission);189}190191@Override192public PermissionCollection getPermissions(CodeSource codesource) {193return new PermissionsBuilder().addAll(allowAll.get().get()194? allPermissions : permissions).toPermissions();195}196197@Override198public PermissionCollection getPermissions(ProtectionDomain domain) {199return new PermissionsBuilder().addAll(allowAll.get().get()200? allPermissions : permissions).toPermissions();201}202}203204}205206207