1 /*
   2  * Copyright (c) 2007, 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 /*
  25  * @test
  26  * @bug 6552961 6558429
  27  * @summary Test privilegedCallable, privilegedCallableUsingCurrentClassLoader
  28  * @run main/othervm PrivilegedCallables
  29  * @author Martin Buchholz
  30  */
  31 
  32 import java.util.concurrent.*;
  33 import java.util.*;
  34 import java.security.*;
  35 import static java.util.concurrent.Executors.*;
  36 import java.lang.reflect.Field;
  37 import sun.misc.Unsafe;
  38 
  39 public class PrivilegedCallables {
  40     static final Unsafe UNSAFE;
  41     static {
  42         try {
  43             Field f = Unsafe.class.getDeclaredField("theUnsafe");
  44             f.setAccessible(true);
  45             UNSAFE = (Unsafe)f.get(null);
  46         } catch (NoSuchFieldException | IllegalAccessException e) {
  47             throw new RuntimeException(e);
  48         }
  49     }
  50 
  51     Callable<Integer> real;
  52 
  53     final Callable<Integer> realCaller = new Callable<Integer>() {
  54         public Integer call() throws Exception {
  55             return real.call(); }};
  56 
  57     final Random rnd = new Random();
  58 
  59     @SuppressWarnings("serial") Throwable[] throwables = {
  60         new Exception() {},
  61         new RuntimeException() {},
  62         new Error() {}
  63     };
  64     Throwable randomThrowable() {
  65         return throwables[rnd.nextInt(throwables.length)];
  66     }
  67 
  68     //----------------------------------------------------------------
  69     // A Policy class designed to make permissions fiddling very easy.
  70     //----------------------------------------------------------------
  71     static class Policy extends java.security.Policy {
  72         private Permissions perms;
  73 
  74         public void setPermissions(Permission...permissions) {
  75             perms = new Permissions();
  76             for (Permission permission : permissions)
  77                 perms.add(permission);
  78         }
  79 
  80         public Policy() { setPermissions(/* Nothing */); }
  81 
  82         public PermissionCollection getPermissions(CodeSource cs) {
  83             return perms;
  84         }
  85 
  86         public PermissionCollection getPermissions(ProtectionDomain pd) {
  87             return perms;
  88         }
  89 
  90         public boolean implies(ProtectionDomain pd, Permission p) {
  91             return perms.implies(p);
  92         }
  93 
  94         public void refresh() {}
  95     }
  96 
  97     void test(String[] args) {
  98         testPrivileged();
  99 
 100         final Policy policy = new Policy();
 101         Policy.setPolicy(policy);
 102         policy.setPermissions(new RuntimePermission("getClassLoader"),
 103                               new RuntimePermission("setContextClassLoader"),
 104                               new RuntimePermission("stopThread"));
 105         System.setSecurityManager(new SecurityManager());
 106 
 107         testPrivileged();
 108 
 109         policy.setPermissions(/* Nothing */);
 110 
 111         THROWS(AccessControlException.class,
 112                new F() {void f(){ privilegedCallableUsingCurrentClassLoader(realCaller); }},
 113                new F() {void f(){ privilegedThreadFactory(); }});
 114 
 115         policy.setPermissions(new RuntimePermission("setSecurityManager"));
 116         System.setSecurityManager(null);
 117     }
 118 
 119     void testPrivileged() {
 120         try { test(privilegedCallable(realCaller)); }
 121         catch (Throwable t) { unexpected(t); }
 122 
 123         try { test(privilegedCallableUsingCurrentClassLoader(realCaller)); }
 124         catch (Throwable t) { unexpected(t); }
 125 
 126         try { privilegedThreadFactory(); }
 127         catch (Throwable t) { unexpected(t); }
 128     }
 129 
 130     void test(final Callable<Integer> c) throws Throwable {
 131         for (int i = 0; i < 20; i++)
 132             if (rnd.nextBoolean()) {
 133                 final Throwable t = randomThrowable();
 134                 real = new Callable<Integer>() {
 135                     @SuppressWarnings("deprecation")
 136                     public Integer call() throws Exception {
 137                         UNSAFE.throwException(t);
 138                         return null; }};
 139                 try {
 140                     c.call();
 141                     fail("Expected exception not thrown");
 142                 } catch (Throwable tt) { check(t == tt); }
 143             } else {
 144                 final int n = rnd.nextInt();
 145                 real = new Callable<Integer>() {
 146                     public Integer call() { return n; }};
 147                 equal(c.call(), n);
 148             }
 149     }
 150 
 151     //--------------------- Infrastructure ---------------------------
 152     volatile int passed = 0, failed = 0;
 153     void pass() {passed++;}
 154     void fail() {failed++; Thread.dumpStack();}
 155     void fail(String msg) {System.err.println(msg); fail();}
 156     void unexpected(Throwable t) {failed++; t.printStackTrace();}
 157     void check(boolean cond) {if (cond) pass(); else fail();}
 158     void equal(Object x, Object y) {
 159         if (x == null ? y == null : x.equals(y)) pass();
 160         else fail(x + " not equal to " + y);}
 161     public static void main(String[] args) throws Throwable {
 162         new PrivilegedCallables().instanceMain(args);}
 163     void instanceMain(String[] args) throws Throwable {
 164         try {test(args);} catch (Throwable t) {unexpected(t);}
 165         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
 166         if (failed > 0) throw new AssertionError("Some tests failed");}
 167     abstract class F {abstract void f() throws Throwable;}
 168     void THROWS(Class<? extends Throwable> k, F... fs) {
 169         for (F f : fs)
 170             try {f.f(); fail("Expected " + k.getName() + " not thrown");}
 171             catch (Throwable t) {
 172                 if (k.isAssignableFrom(t.getClass())) pass();
 173                 else unexpected(t);}}
 174 }