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