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.FilePermission;
  25 import java.io.IOException;
  26 import java.lang.reflect.Field;
  27 import java.lang.reflect.ReflectPermission;
  28 import java.net.URI;
  29 import java.nio.file.FileSystem;
  30 import java.nio.file.FileSystems;
  31 import java.nio.file.Files;
  32 import java.nio.file.Path;
  33 import java.security.CodeSource;
  34 import java.security.Permission;
  35 import java.security.PermissionCollection;
  36 import java.security.Permissions;
  37 import java.security.Policy;
  38 import java.security.ProtectionDomain;
  39 import java.util.ArrayList;
  40 import java.util.Arrays;
  41 import java.util.Collections;
  42 import java.util.Enumeration;
  43 import java.util.Iterator;
  44 import java.util.List;
  45 import java.util.PropertyPermission;
  46 import java.util.Set;
  47 import java.util.TreeSet;
  48 import java.util.concurrent.atomic.AtomicBoolean;
  49 import java.util.concurrent.atomic.AtomicLong;
  50 import java.util.stream.Stream;
  51 
  52 /**
  53  * @test
  54  * @bug 8065552
  55  * @summary test that all fields returned by getDeclaredFields() can be
  56  *          set accessible if the right permission is granted; this test
  57  *          loads all the classes in the BCL, get their declared fields,
  58  *          and call setAccessible(false) followed by setAccessible(true);
  59  * @run main/othervm FieldSetAccessibleTest UNSECURE
  60  * @run main/othervm FieldSetAccessibleTest SECURE
  61  *
  62  * @author danielfuchs
  63  */
  64 public class FieldSetAccessibleTest {
  65 
  66     static final List<String> skipped = new ArrayList<>();
  67     static final List<String> cantread = new ArrayList<>();
  68     static final List<String> failed = new ArrayList<>();
  69     static final AtomicLong classCount = new AtomicLong();
  70     static final AtomicLong fieldCount = new AtomicLong();
  71     static long startIndex = 0;
  72     static long maxSize = Long.MAX_VALUE;
  73     static long maxIndex = Long.MAX_VALUE;
  74 
  75     // You can use -Dtest.list.classes=true if you want this test to print
  76     // out a list of all the classes it has loaded for each of the
  77     // three loaders (boot CL, extension CL, application CL)
  78     final static boolean listClassesByLoader = Boolean.parseBoolean(
  79         System.getProperty("test.list.classes", "false"));
  80 
  81 
  82     // Test that all fields for any given class can be made accessibles
  83     static void testSetFieldsAccessible(Class<?> c) {
  84         for (Field f : c.getDeclaredFields()) {
  85             fieldCount.incrementAndGet();
  86             f.setAccessible(false);
  87             f.setAccessible(true);
  88         }
  89     }
  90 
  91     // Performs a series of test on the given class.
  92     // At this time, we only call testSetFieldsAccessible(c)
  93     public static boolean test(Class<?> c) {
  94         //System.out.println(c.getName());
  95         classCount.incrementAndGet();
  96 
  97         // Call getDeclaredFields() and try to set their accessible flag.
  98         testSetFieldsAccessible(c);
  99 
 100         // add more tests here...
 101 
 102         return c == Class.class;
 103     }
 104 
 105     // The ClassLoader that will be passed at Class.forName in order to
 106     // load this class. We currently always use the System ClassLoader.
 107     static ClassLoader getClassLoaderFor(String classFileName) {
 108         return ClassLoaders.getFor(classFileName);
 109     }
 110 
 111     // Can be used to verify assumptions about the defining class loader
 112     // of a given class.
 113     static void checkClassLoaderFor(Class<?> c) {
 114         ClassLoaders.checkFor(c);
 115     }
 116 
 117     // Prints a summary at the end of the test.
 118     static void printSummary(long secs, long millis, long nanos) {
 119         ClassLoaders.printClasses();
 120         System.out.println("Tested " + fieldCount.get() + " fields of "
 121                 + classCount.get() + " classes in "
 122                 + secs + "s " + millis + "ms " + nanos + "ns");
 123     }
 124 
 125 
 126     static class ClassLoaders {
 127         final static ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
 128         final static ClassLoader extensionClassLoader = systemClassLoader.getParent();
 129         final static Set<String> bootClasses = new TreeSet<>();
 130         final static Set<String> applicationClasses = new TreeSet<>();
 131         final static Set<String> extensionClasses = new TreeSet<>();
 132 
 133         static ClassLoader getFor(String classFileName) {
 134             return ClassLoaders.systemClassLoader;
 135         }
 136         static void checkFor(Class<?> c) {
 137             final ClassLoader cl = c.getClassLoader();
 138             if (cl != null) {
 139                 if (cl != systemClassLoader && cl != extensionClassLoader) {
 140                     System.err.println("Unexpected loader for " + c + ": " + cl);
 141                 }
 142                 if (cl == extensionClassLoader) {
 143                     extensionClasses.add(c.getName());
 144                 }
 145                 if (cl == systemClassLoader) {
 146                     applicationClasses.add(c.getName());
 147                 }
 148             } else {
 149                 bootClasses.add(c.getName());
 150             }
 151         }
 152 
 153         static void printClasses() {
 154             if (listClassesByLoader) {
 155                 System.out.println("\n-------------    Boot  Classes    -------------\n");
 156                 bootClasses.stream().forEachOrdered(s -> System.out.println(s));
 157                 System.out.println("\n-------------  Extension Classes  -------------\n");
 158                 extensionClasses.stream().forEachOrdered(s -> System.out.println(s));
 159                 System.out.println("\n------------- Application Classes -------------\n");
 160                 applicationClasses.stream().forEachOrdered(s -> System.out.println(s));
 161                 System.out.println("\n-----------------------------------------------\n");
 162             }
 163         }
 164     }
 165 
 166     /**
 167      * @param args the command line arguments:
 168      *
 169      *     SECURE|UNSECURE [startIndex (default=0)] [maxSize (default=Long.MAX_VALUE)]
 170      *
 171      * @throws java.lang.Exception if the test fails
 172      */
 173     public static void main(String[] args) throws Exception {
 174         if (args == null || args.length == 0) {
 175             args = new String[] {"SECURE", "0"};
 176         } else if (args.length > 3) {
 177             throw new RuntimeException("Expected at most one argument. Found "
 178                     + Arrays.asList(args));
 179         }
 180         try {
 181             if (args.length > 1) {
 182                 startIndex = Long.parseLong(args[1]);
 183                 if (startIndex < 0) {
 184                     throw new IllegalArgumentException("startIndex args[1]: "
 185                             + startIndex);
 186                 }
 187             }
 188             if (args.length > 2) {
 189                 maxSize = Long.parseLong(args[2]);
 190                 if (maxSize <= 0) {
 191                     maxSize = Long.MAX_VALUE;
 192                 }
 193                 maxIndex = (Long.MAX_VALUE - startIndex) < maxSize
 194                         ? Long.MAX_VALUE : startIndex + maxSize;
 195             }
 196             TestCase.valueOf(args[0]).run();
 197         } catch (OutOfMemoryError oome) {
 198             System.err.println(classCount.get());
 199             throw oome;
 200         }
 201     }
 202 
 203     public static void run(TestCase test) {
 204         System.out.println("Testing " + test);
 205         test(listAllClassNames());
 206         System.out.println("Passed " + test);
 207     }
 208 
 209     static Iterable<String> listAllClassNames() {
 210         return new ClassNameJrtStreamBuilder();
 211     }
 212 
 213     static void test(Iterable<String> iterable) {
 214         final long start = System.nanoTime();
 215         boolean classFound = false;
 216         int index = 0;
 217         for (String s: iterable) {
 218             if (index == maxIndex) break;
 219             try {
 220                 if (index < startIndex) continue;
 221                 if (test(getClassLoaderFor(s), s)) {
 222                     classFound = true;
 223                 }
 224             } finally {
 225                 index++;
 226             }
 227         }
 228         long elapsed = System.nanoTime() - start;
 229         long secs = elapsed / 1000_000_000;
 230         long millis = (elapsed % 1000_000_000) / 1000_000;
 231         long nanos  = elapsed % 1000_000;
 232         System.out.println("Unreadable path elements: " + cantread);
 233         System.out.println("Skipped path elements: " + skipped);
 234         System.out.println("Failed path elements: " + failed);
 235         printSummary(secs, millis, nanos);
 236 
 237         if (!failed.isEmpty()) {
 238             throw new RuntimeException("Test failed for the following classes: " + failed);
 239         }
 240         if (!classFound && startIndex == 0 && index < maxIndex) {
 241             // this is just to verify that we have indeed parsed rt.jar
 242             // (or the java.base module)
 243             throw  new RuntimeException("Test failed: Class.class not found...");
 244         }
 245         if (classCount.get() == 0 && startIndex == 0) {
 246             throw  new RuntimeException("Test failed: no class found?");
 247         }
 248     }
 249 
 250     static boolean test(ClassLoader loader, String s) {
 251         try {
 252             if (s.startsWith("WrapperGenerator")) {
 253                 System.out.println("Skipping "+ s);
 254                 return false;
 255             }
 256             final Class<?> c = Class.forName(
 257                     s.replace('/', '.').substring(0, s.length() - 6),
 258                     false,
 259                     loader);
 260             checkClassLoaderFor(c);
 261             return test(c);
 262         } catch (Exception t) {
 263             t.printStackTrace(System.err);
 264             failed.add(s);
 265         } catch (NoClassDefFoundError e) {
 266             e.printStackTrace(System.err);
 267             failed.add(s);
 268         }
 269         return false;
 270     }
 271 
 272     static class ClassNameJrtStreamBuilder implements Iterable<String>{
 273 
 274         final FileSystem jrt;
 275         final List<Path> roots = new ArrayList<>();
 276         ClassNameJrtStreamBuilder() {
 277              jrt = FileSystems.getFileSystem(URI.create("jrt:/"));
 278              for (Path root : jrt.getRootDirectories()) {
 279                  roots.add(root);
 280              }
 281         }
 282 
 283         Stream<String> build() {
 284             return roots.stream().flatMap(this::toStream)
 285                     .filter(x -> x.getNameCount() > 1)
 286                     .map( x-> x.subpath(1, x.getNameCount()))
 287                     .map( x -> x.toString())
 288                     .filter(s -> s.endsWith(".class"));
 289         }
 290 
 291         @Override
 292         public Iterator<String> iterator() {
 293             return build().iterator();
 294         }
 295 
 296         private Stream<Path> toStream(Path root) {
 297             try {
 298                 return Files.walk(root);
 299             } catch(IOException x) {
 300                 x.printStackTrace(System.err);
 301                 skipped.add(root.toString());
 302             }
 303             return Collections.<Path>emptyList().stream();
 304         }
 305 
 306     }
 307 
 308     // Test with or without a security manager
 309     public static enum TestCase {
 310         UNSECURE, SECURE;
 311         public void run() throws Exception {
 312             System.out.println("Running test case: " + name());
 313             Configure.setUp(this);
 314             FieldSetAccessibleTest.run(this);
 315         }
 316     }
 317 
 318     // A helper class to configure the security manager for the test,
 319     // and bypass it when needed.
 320     static class Configure {
 321         static Policy policy = null;
 322         static final ThreadLocal<AtomicBoolean> allowAll = new ThreadLocal<AtomicBoolean>() {
 323             @Override
 324             protected AtomicBoolean initialValue() {
 325                 return  new AtomicBoolean(false);
 326             }
 327         };
 328         static void setUp(TestCase test) {
 329             switch (test) {
 330                 case SECURE:
 331                     if (policy == null && System.getSecurityManager() != null) {
 332                         throw new IllegalStateException("SecurityManager already set");
 333                     } else if (policy == null) {
 334                         policy = new SimplePolicy(TestCase.SECURE, allowAll);
 335                         Policy.setPolicy(policy);
 336                         System.setSecurityManager(new SecurityManager());
 337                     }
 338                     if (System.getSecurityManager() == null) {
 339                         throw new IllegalStateException("No SecurityManager.");
 340                     }
 341                     if (policy == null) {
 342                         throw new IllegalStateException("policy not configured");
 343                     }
 344                     break;
 345                 case UNSECURE:
 346                     if (System.getSecurityManager() != null) {
 347                         throw new IllegalStateException("SecurityManager already set");
 348                     }
 349                     break;
 350                 default:
 351                     throw new InternalError("No such testcase: " + test);
 352             }
 353         }
 354         static void doPrivileged(Runnable run) {
 355             allowAll.get().set(true);
 356             try {
 357                 run.run();
 358             } finally {
 359                 allowAll.get().set(false);
 360             }
 361         }
 362     }
 363 
 364     // A Helper class to build a set of permissions.
 365     final static class PermissionsBuilder {
 366         final Permissions perms;
 367         public PermissionsBuilder() {
 368             this(new Permissions());
 369         }
 370         public PermissionsBuilder(Permissions perms) {
 371             this.perms = perms;
 372         }
 373         public PermissionsBuilder add(Permission p) {
 374             perms.add(p);
 375             return this;
 376         }
 377         public PermissionsBuilder addAll(PermissionCollection col) {
 378             if (col != null) {
 379                 for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
 380                     perms.add(e.nextElement());
 381                 }
 382             }
 383             return this;
 384         }
 385         public Permissions toPermissions() {
 386             final PermissionsBuilder builder = new PermissionsBuilder();
 387             builder.addAll(perms);
 388             return builder.perms;
 389         }
 390     }
 391 
 392     // Policy for the test...
 393     public static class SimplePolicy extends Policy {
 394 
 395         final Permissions permissions;
 396         final Permissions allPermissions;
 397         final ThreadLocal<AtomicBoolean> allowAll;
 398         public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
 399             this.allowAll = allowAll;
 400 
 401             // Permission needed by the tested code exercised in the test
 402             permissions = new Permissions();
 403             permissions.add(new RuntimePermission("fileSystemProvider"));
 404             permissions.add(new RuntimePermission("createClassLoader"));
 405             permissions.add(new RuntimePermission("closeClassLoader"));
 406             permissions.add(new RuntimePermission("getClassLoader"));
 407             permissions.add(new RuntimePermission("accessDeclaredMembers"));
 408             permissions.add(new ReflectPermission("suppressAccessChecks"));
 409             permissions.add(new PropertyPermission("*", "read"));
 410             permissions.add(new FilePermission("<<ALL FILES>>", "read"));
 411 
 412             // these are used for configuring the test itself...
 413             allPermissions = new Permissions();
 414             allPermissions.add(new java.security.AllPermission());
 415         }
 416 
 417         @Override
 418         public boolean implies(ProtectionDomain domain, Permission permission) {
 419             if (allowAll.get().get()) return allPermissions.implies(permission);
 420             if (permissions.implies(permission)) return true;
 421             if (permission instanceof java.lang.RuntimePermission) {
 422                 if (permission.getName().startsWith("accessClassInPackage.")) {
 423                     // add these along to the set of permission we have, when we
 424                     // discover that we need them.
 425                     permissions.add(permission);
 426                     return true;
 427                 }
 428             }
 429             return false;
 430         }
 431 
 432         @Override
 433         public PermissionCollection getPermissions(CodeSource codesource) {
 434             return new PermissionsBuilder().addAll(allowAll.get().get()
 435                     ? allPermissions : permissions).toPermissions();
 436         }
 437 
 438         @Override
 439         public PermissionCollection getPermissions(ProtectionDomain domain) {
 440             return new PermissionsBuilder().addAll(allowAll.get().get()
 441                     ? allPermissions : permissions).toPermissions();
 442         }
 443     }
 444 
 445 }