1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import java.io.File;
  25 import java.io.FilePermission;
  26 import java.io.IOException;
  27 import java.lang.reflect.Field;
  28 import java.lang.reflect.ReflectPermission;
  29 import java.nio.file.Files;
  30 import java.nio.file.Path;
  31 import java.security.CodeSource;
  32 import java.security.Permission;
  33 import java.security.PermissionCollection;
  34 import java.security.Permissions;
  35 import java.security.Policy;
  36 import java.security.ProtectionDomain;
  37 import java.util.ArrayList;
  38 import java.util.Arrays;
  39 import java.util.Collections;
  40 import java.util.Enumeration;
  41 import java.util.Iterator;
  42 import java.util.List;
  43 import java.util.PropertyPermission;
  44 import java.util.concurrent.atomic.AtomicBoolean;
  45 import java.util.concurrent.atomic.AtomicLong;
  46 import java.util.jar.JarEntry;
  47 import java.util.jar.JarFile;
  48 import java.util.stream.Stream;
  49 
  50 /**
  51  * @test
  52  * @bug 8065552
  53  * @summary test that all fields returned by getDeclaredFields() can be
  54  *          set accessible if the right permission is granted; this test
  55  *          loads all the classes in the BCL, get their declared fields,
  56  *          and call setAccessible(false) followed by setAccessible(true);
  57  * @run main/othervm FieldSetAccessibleTest UNSECURE
  58  * @run main/othervm FieldSetAccessibleTest SECURE
  59  *
  60  * @author danielfuchs
  61  */
  62 public class FieldSetAccessibleTest {
  63 
  64     static final List<String> skipped = new ArrayList<>();
  65     static final List<String> cantread = new ArrayList<>();
  66     static final List<String> failed = new ArrayList<>();
  67     static final AtomicLong classCount = new AtomicLong();
  68     static final AtomicLong fieldCount = new AtomicLong();
  69     static long startIndex = 0;
  70     static long maxSize = Long.MAX_VALUE;
  71     static long maxIndex = Long.MAX_VALUE;
  72 
  73 
  74     static void testSetFieldsAccessible(Class<?> c) {
  75         for (Field f : c.getDeclaredFields()) {
  76             fieldCount.incrementAndGet();
  77             f.setAccessible(false);
  78             f.setAccessible(true);
  79         }
  80     }
  81 
  82 
  83     public static boolean test(Class<?> c) {
  84         //System.out.println(c.getName());
  85         classCount.incrementAndGet();
  86 
  87         // Call getDeclaredFields() and try to set their accessible flag.
  88         testSetFieldsAccessible(c);
  89 
  90         // add more tests here...
  91 
  92         return c == Class.class;
  93     }
  94 
  95     static ClassLoader getClassLoaderFor(String classFileName) {
  96         return null; // load all classes through the BCL.
  97     }
  98 
  99     static void checkClassLoaderFor(Class<?> c, ClassLoader loader) {
 100         if (loader == null) { // expects BCL
 101             if (c.getClassLoader() != loader) {
 102                 System.err.println("Unexpected loader for "+c+": "+c.getClassLoader());
 103             }
 104         }
 105     }
 106 
 107     static void printSummary(long secs, long millis, long nanos) {
 108         System.out.println("Tested " + fieldCount.get() + " fields of "
 109                 + classCount.get() + " classes in "
 110                 + secs + "s " + millis + "ms " + nanos + "ns");
 111     }
 112 
 113 
 114     /**
 115      * @param args the command line arguments:
 116      *
 117      *     SECURE|UNSECURE [startIndex (default=0)] [maxSize (default=Long.MAX_VALUE)]
 118      *
 119      * @throws java.lang.Exception if the test fails
 120      */
 121     public static void main(String[] args) throws Exception {
 122         if (args == null || args.length == 0) {
 123             args = new String[] {"SECURE", "0"};
 124         } else if (args.length > 3) {
 125             throw new RuntimeException("Expected at most one argument. Found "
 126                     + Arrays.asList(args));
 127         }
 128         try {
 129             if (args.length > 1) {
 130                 startIndex = Long.parseLong(args[1]);
 131                 if (startIndex < 0) {
 132                     throw new IllegalArgumentException("startIndex args[1]: "
 133                             + startIndex);
 134                 }
 135             }
 136             if (args.length > 2) {
 137                 maxSize = Long.parseLong(args[2]);
 138                 if (maxSize <= 0) {
 139                     maxSize = Long.MAX_VALUE;
 140                 }
 141                 maxIndex = (Long.MAX_VALUE - startIndex) < maxSize
 142                         ? Long.MAX_VALUE : startIndex + maxSize;
 143             }
 144             TestCase.valueOf(args[0]).run();
 145         } catch (OutOfMemoryError oome) {
 146             System.err.println(classCount.get());
 147             throw oome;
 148         }
 149     }
 150 
 151     public static void run(TestCase test) {
 152         System.out.println("Testing " + test);
 153         test(listAllClassNames());
 154         System.out.println("Passed " + test);
 155     }
 156 
 157     static Iterable<String> listAllClassNames() {
 158         return new ClassNameStreamBuilder();
 159     }
 160 
 161     static void test(Iterable<String> iterable) {
 162         final long start = System.nanoTime();
 163         boolean classFound = false;
 164         int index = 0;
 165         for (String s: iterable) {
 166             if (index == maxIndex) break;
 167             try {
 168                 if (index < startIndex) continue;
 169                 if (test(getClassLoaderFor(s), s)) {
 170                     classFound = true;
 171                 }
 172             } finally {
 173                 index++;
 174             }
 175         }
 176         long elapsed = System.nanoTime() - start;
 177         long secs = elapsed / 1000_000_000;
 178         long millis = (elapsed % 1000_000_000) / 1000_000;
 179         long nanos  = elapsed % 1000_000;
 180         System.out.println("Unreadable path elements: " + cantread);
 181         System.out.println("Skipped path elements: " + skipped);
 182         System.out.println("Failed path elements: " + failed);
 183         printSummary(secs, millis, nanos);
 184 
 185         if (!failed.isEmpty()) {
 186             throw new RuntimeException("Test failed for the following classes: " + failed);
 187         }
 188         if (!classFound && startIndex == 0 && index < maxIndex) {
 189             // this is just to verify that we have indeed parsed rt.jar
 190             // (or the java.base module)
 191             throw  new RuntimeException("Test failed: Class.class not found...");
 192         }
 193         if (classCount.get() == 0 && startIndex == 0) {
 194             throw  new RuntimeException("Test failed: no class found?");
 195         }
 196     }
 197 
 198     static boolean test(ClassLoader loader, String s) {
 199         try {
 200             if (s.startsWith("WrapperGenerator")) {
 201                 System.out.println("Skipping "+ s);
 202                 return false;
 203             }
 204             final Class<?> c = Class.forName(
 205                     s.replace('/', '.').substring(0, s.length() - 6),
 206                     false,
 207                     loader);
 208             checkClassLoaderFor(c, loader);
 209             return test(c);
 210         } catch (Exception t) {
 211             t.printStackTrace(System.err);
 212             failed.add(s);
 213         }
 214         return false;
 215     }
 216 
 217     static class ClassNameStreamBuilder implements Iterable<String>{
 218         String[] bcp;
 219         ClassNameStreamBuilder() {
 220             bcp = System.getProperty("sun.boot.class.path").split(File.pathSeparator);
 221         }
 222 
 223         Stream<String> bcpElementToStream(String s) {
 224             return s.endsWith(".jar") ? jarToStream(s) : folderToStream(s);
 225         }
 226 
 227         Stream<String> jarToStream(String jarName) {
 228             File f = new File(jarName);
 229             if (f.canRead() && f.isFile()) {
 230                 try {
 231                     JarFile jarFile = new JarFile(f);
 232                     return jarFile.stream()
 233                             .filter(e -> !e.isDirectory())
 234                             .map(JarEntry::getName)
 235                             .filter(s -> s.endsWith(".class"));
 236                 } catch(IOException x) {
 237                     x.printStackTrace(System.err);
 238                     skipped.add(jarName);
 239                 }
 240             } else {
 241                 cantread.add(jarName);
 242             }
 243             return Collections.<String>emptyList().stream();
 244         }
 245 
 246         Stream<String> folderToStream(String folderName) {
 247             final File root = new File(folderName);
 248             if (root.canRead() && root.isDirectory()) {
 249                 final Path rootPath = root.toPath();
 250                 try {
 251                     return Files.walk(rootPath)
 252                         .filter(p -> p.getFileName().toString().endsWith(".class"))
 253                         .map(rootPath::relativize)
 254                         .map(p -> p.toString().replace(File.separatorChar, '/'));
 255                 } catch (IOException x) {
 256                     x.printStackTrace(System.err);
 257                     skipped.add(folderName);
 258                 }
 259             } else {
 260                 cantread.add(folderName);
 261             }
 262             return Collections.<String>emptyList().stream();
 263         }
 264 
 265         public Stream<String> build() {
 266             return Stream.of(bcp).flatMap(this::bcpElementToStream);
 267         }
 268 
 269         @Override
 270         public Iterator<String> iterator() {
 271             return build().iterator();
 272         }
 273     }
 274 
 275     // Test with or without a security manager
 276     public static enum TestCase {
 277         UNSECURE, SECURE;
 278         public void run() throws Exception {
 279             System.out.println("Running test case: " + name());
 280             Configure.setUp(this);
 281             FieldSetAccessibleTest.run(this);
 282         }
 283     }
 284 
 285     // A helper class to configure the security manager for the test,
 286     // and bypass it when needed.
 287     static class Configure {
 288         static Policy policy = null;
 289         static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {
 290             @Override
 291             protected AtomicBoolean initialValue() {
 292                 return  new AtomicBoolean(false);
 293             }
 294         };
 295         static void setUp(TestCase test) {
 296             switch (test) {
 297                 case SECURE:
 298                     if (policy == null && System.getSecurityManager() != null) {
 299                         throw new IllegalStateException("SecurityManager already set");
 300                     } else if (policy == null) {
 301                         policy = new SimplePolicy(TestCase.SECURE, allowAll);
 302                         Policy.setPolicy(policy);
 303                         System.setSecurityManager(new SecurityManager());
 304                     }
 305                     if (System.getSecurityManager() == null) {
 306                         throw new IllegalStateException("No SecurityManager.");
 307                     }
 308                     if (policy == null) {
 309                         throw new IllegalStateException("policy not configured");
 310                     }
 311                     break;
 312                 case UNSECURE:
 313                     if (System.getSecurityManager() != null) {
 314                         throw new IllegalStateException("SecurityManager already set");
 315                     }
 316                     break;
 317                 default:
 318                     throw new InternalError("No such testcase: " + test);
 319             }
 320         }
 321         static void doPrivileged(Runnable run) {
 322             allowAll.get().set(true);
 323             try {
 324                 run.run();
 325             } finally {
 326                 allowAll.get().set(false);
 327             }
 328         }
 329     }
 330 
 331     // A Helper class to build a set of permissions.
 332     final static class PermissionsBuilder {
 333         final Permissions perms;
 334         public PermissionsBuilder() {
 335             this(new Permissions());
 336         }
 337         public PermissionsBuilder(Permissions perms) {
 338             this.perms = perms;
 339         }
 340         public PermissionsBuilder add(Permission p) {
 341             perms.add(p);
 342             return this;
 343         }
 344         public PermissionsBuilder addAll(PermissionCollection col) {
 345             if (col != null) {
 346                 for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
 347                     perms.add(e.nextElement());
 348                 }
 349             }
 350             return this;
 351         }
 352         public Permissions toPermissions() {
 353             final PermissionsBuilder builder = new PermissionsBuilder();
 354             builder.addAll(perms);
 355             return builder.perms;
 356         }
 357     }
 358 
 359     // Policy for the test...
 360     public static class SimplePolicy extends Policy {
 361 
 362         final Permissions permissions;
 363         final Permissions allPermissions;
 364         final ThreadLocal<AtomicBoolean> allowAll;
 365         public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
 366             this.allowAll = allowAll;
 367 
 368             // Permission needed by the tested code exercised in the test
 369             permissions = new Permissions();
 370             permissions.add(new RuntimePermission("createClassLoader"));
 371             permissions.add(new RuntimePermission("closeClassLoader"));
 372             permissions.add(new RuntimePermission("getClassLoader"));
 373             permissions.add(new RuntimePermission("accessDeclaredMembers"));
 374             permissions.add(new ReflectPermission("suppressAccessChecks"));
 375             permissions.add(new PropertyPermission("sun.boot.class.path", "read"));
 376             permissions.add(new FilePermission("<<ALL FILES>>", "read"));
 377 
 378             // these are used for configuring the test itself...
 379             allPermissions = new Permissions();
 380             allPermissions.add(new java.security.AllPermission());
 381         }
 382 
 383         @Override
 384         public boolean implies(ProtectionDomain domain, Permission permission) {
 385             if (allowAll.get().get()) return allPermissions.implies(permission);
 386             if (permissions.implies(permission)) return true;
 387             if (permission instanceof java.lang.RuntimePermission) {
 388                 if (permission.getName().startsWith("accessClassInPackage.")) {
 389                     // add these along to the set of permission we have, when we
 390                     // discover that we need them.
 391                     permissions.add(permission);
 392                     return true;
 393                 }
 394             }
 395             return false;
 396         }
 397 
 398         @Override
 399         public PermissionCollection getPermissions(CodeSource codesource) {
 400             return new PermissionsBuilder().addAll(allowAll.get().get()
 401                     ? allPermissions : permissions).toPermissions();
 402         }
 403 
 404         @Override
 405         public PermissionCollection getPermissions(ProtectionDomain domain) {
 406             return new PermissionsBuilder().addAll(allowAll.get().get()
 407                     ? allPermissions : permissions).toPermissions();
 408         }
 409     }
 410 
 411 }