1 /*
   2  * Copyright (c) 2010, 2011, 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 /* @test
  25  * @summary smoke test for invokedynamic instructions
  26  * @build indify.Indify
  27  * @compile InvokeDynamicPrintArgs.java
  28  * @run main/othervm
  29  *      indify.Indify
  30  *      --verify-specifier-count=3
  31  *      --expand-properties --classpath ${test.classes}
  32  *      --java test.java.lang.invoke.InvokeDynamicPrintArgs --check-output
  33  * @run main/othervm
  34  *      indify.Indify
  35  *      --expand-properties --classpath ${test.classes}
  36  *      --java test.java.lang.invoke.InvokeDynamicPrintArgs --security-manager
  37  */
  38 
  39 package test.java.lang.invoke;
  40 
  41 import java.util.*;
  42 import java.io.*;
  43 
  44 import java.lang.invoke.*;
  45 import static java.lang.invoke.MethodHandles.*;
  46 import static java.lang.invoke.MethodType.*;
  47 
  48 public class InvokeDynamicPrintArgs {
  49     public static void main(String... av) throws Throwable {
  50         if (av.length > 0 && av[0].equals("--check-output"))  openBuf();
  51         if (av.length > 0 && av[0].equals("--security-manager"))  setSM();
  52         System.out.println("Printing some argument lists, starting with a empty one:");
  53         INDY_nothing().invokeExact();                 // BSM specifier #0 = {bsm}
  54         INDY_bar().invokeExact("bar arg", 1);         // BSM specifier #1 = {bsm2, Void.class, "void type"}
  55         INDY_bar2().invokeExact("bar2 arg", 222);     // BSM specifier #1 = (same)
  56         INDY_baz().invokeExact("baz arg", 2, 3.14);   // BSM specifier #2 = {bsm2, 1234.5}
  57         INDY_foo().invokeExact("foo arg");            // BSM specifier #0 = (same)
  58         // Hence, BSM specifier count should be 3.  See "--verify-specifier-count=3" above.
  59         System.out.println("Done printing argument lists.");
  60         closeBuf();
  61         checkConstantRefs();
  62     }
  63 
  64     private static void checkConstantRefs() throws Throwable {
  65         // check some constant references:
  66         assertEquals(MT_bsm(), MH_bsm().type());
  67         assertEquals(MT_bsm2(), MH_bsm2().type());
  68         try {
  69             assertEquals(MT_bsm(), non_MH_bsm().type());
  70             // if SM is installed, must throw before this point
  71             assertEquals(false, System.getSecurityManager() != null);
  72         } catch (SecurityException ex) {
  73             // if SM is installed, must throw to this point
  74             assertEquals(true, System.getSecurityManager() != null);
  75         }
  76     }
  77     private static void assertEquals(Object exp, Object act) {
  78         if (exp == act || (exp != null && exp.equals(act)))  return;
  79         throw new AssertionError("not equal: "+exp+", "+act);
  80     }
  81 
  82     private static void setSM() {
  83         // Test for severe security manager interactions (7050328).
  84         class SM extends SecurityManager {
  85             public void checkPackageAccess(String pkg) {
  86                 if (pkg.startsWith("test."))
  87                     throw new SecurityException("checkPackageAccess "+pkg);
  88             }
  89             public void checkMemberAccess(Class<?> clazz, int which) {
  90                 if (clazz == InvokeDynamicPrintArgs.class)
  91                     throw new SecurityException("checkMemberAccess "+clazz.getName()+" #"+which);
  92             }
  93             // allow these others:
  94             public void checkPermission(java.security.Permission perm) {
  95             }
  96         }
  97         System.setSecurityManager(new SM());
  98     }
  99 
 100     private static PrintStream oldOut;
 101     private static ByteArrayOutputStream buf;
 102     private static void openBuf() {
 103         oldOut = System.out;
 104         buf = new ByteArrayOutputStream();
 105         System.setOut(new PrintStream(buf));
 106     }
 107     private static void closeBuf() {
 108         if (buf == null)  return;
 109         System.out.flush();
 110         System.setOut(oldOut);
 111         String[] haveLines = new String(buf.toByteArray()).split("[\n\r]+");
 112         for (String line : haveLines)  System.out.println(line);
 113         Iterator<String> iter = Arrays.asList(haveLines).iterator();
 114         for (String want : EXPECT_OUTPUT) {
 115             String have = iter.hasNext() ? iter.next() : "[EOF]";
 116             if (want.equals(have))  continue;
 117             System.err.println("want line: "+want);
 118             System.err.println("have line: "+have);
 119             throw new AssertionError("unexpected output: "+have);
 120         }
 121         if (iter.hasNext())
 122             throw new AssertionError("unexpected output: "+iter.next());
 123     }
 124     private static final String[] EXPECT_OUTPUT = {
 125         "Printing some argument lists, starting with a empty one:",
 126         "[test.java.lang.invoke.InvokeDynamicPrintArgs, nothing, ()void][]",
 127         "[test.java.lang.invoke.InvokeDynamicPrintArgs, bar, (String,int)void, class java.lang.Void, void type!, 1, 234.5, 67.5, 89][bar arg, 1]",
 128         "[test.java.lang.invoke.InvokeDynamicPrintArgs, bar2, (String,int)void, class java.lang.Void, void type!, 1, 234.5, 67.5, 89][bar2 arg, 222]",
 129         "[test.java.lang.invoke.InvokeDynamicPrintArgs, baz, (String,int,double)void, 1234.5][baz arg, 2, 3.14]",
 130         "[test.java.lang.invoke.InvokeDynamicPrintArgs, foo, (String)void][foo arg]",
 131         "Done printing argument lists."
 132     };
 133 
 134     private static boolean doPrint = true;
 135     private static void printArgs(Object bsmInfo, Object... args) {
 136         String message = bsmInfo+Arrays.deepToString(args);
 137         if (doPrint)  System.out.println(message);
 138     }
 139     private static MethodHandle MH_printArgs() throws ReflectiveOperationException {
 140         shouldNotCallThis();
 141         return lookup().findStatic(lookup().lookupClass(),
 142                                    "printArgs", methodType(void.class, Object.class, Object[].class));
 143     }
 144 
 145     private static CallSite bsm(Lookup caller, String name, MethodType type) throws ReflectiveOperationException {
 146         // ignore caller and name, but match the type:
 147         Object bsmInfo = Arrays.asList(caller, name, type);
 148         return new ConstantCallSite(MH_printArgs().bindTo(bsmInfo).asCollector(Object[].class, type.parameterCount()).asType(type));
 149     }
 150     private static MethodType MT_bsm() {
 151         shouldNotCallThis();
 152         return methodType(CallSite.class, Lookup.class, String.class, MethodType.class);
 153     }
 154     private static MethodHandle MH_bsm() throws ReflectiveOperationException {
 155         shouldNotCallThis();
 156         return lookup().findStatic(lookup().lookupClass(), "bsm", MT_bsm());
 157     }
 158     private static MethodHandle non_MH_bsm() throws ReflectiveOperationException {
 159         return lookup().findStatic(lookup().lookupClass(), "bsm", MT_bsm());
 160     }
 161 
 162     /* Example of a constant call site with user-data.
 163      * In this case, the user data is exactly the BSM data.
 164      * Note that a CCS with user data must use the "hooked" constructor
 165      * to bind the CCS itself into the resulting target.
 166      * A normal constructor would not allow a circular relation
 167      * between the CCS and its target.
 168      */
 169     public static class PrintingCallSite extends ConstantCallSite {
 170         final Lookup caller;
 171         final String name;
 172         final Object[] staticArgs;
 173 
 174         PrintingCallSite(Lookup caller, String name, MethodType type, Object... staticArgs) throws Throwable {
 175             super(type, MH_createTarget());
 176             this.caller = caller;
 177             this.name = name;
 178             this.staticArgs = staticArgs;
 179         }
 180 
 181         public MethodHandle createTarget() {
 182             try {
 183                 return lookup().bind(this, "runTarget", genericMethodType(0, true)).asType(type());
 184             } catch (ReflectiveOperationException ex) {
 185                 throw new RuntimeException(ex);
 186             }
 187         }
 188 
 189         public Object runTarget(Object... dynamicArgs) {
 190             List<Object> bsmInfo = new ArrayList<>(Arrays.asList(caller, name, type()));
 191             bsmInfo.addAll(Arrays.asList(staticArgs));
 192             printArgs(bsmInfo, dynamicArgs);
 193             return null;
 194         }
 195 
 196         private static MethodHandle MH_createTarget() throws ReflectiveOperationException {
 197             shouldNotCallThis();
 198             return lookup().findVirtual(lookup().lookupClass(), "createTarget", methodType(MethodHandle.class));
 199         }
 200     }
 201     private static CallSite bsm2(Lookup caller, String name, MethodType type, Object... arg) throws Throwable {
 202         // ignore caller and name, but match the type:
 203         return new PrintingCallSite(caller, name, type, arg);
 204     }
 205     private static MethodType MT_bsm2() {
 206         shouldNotCallThis();
 207         return methodType(CallSite.class, Lookup.class, String.class, MethodType.class, Object[].class);
 208     }
 209     private static MethodHandle MH_bsm2() throws ReflectiveOperationException {
 210         shouldNotCallThis();
 211         return lookup().findStatic(lookup().lookupClass(), "bsm2", MT_bsm2());
 212     }
 213 
 214     private static MethodHandle INDY_nothing() throws Throwable {
 215         shouldNotCallThis();
 216         return ((CallSite) MH_bsm().invoke(lookup(),
 217                                                   "nothing", methodType(void.class)
 218                                                   )).dynamicInvoker();
 219     }
 220     private static MethodHandle INDY_foo() throws Throwable {
 221         shouldNotCallThis();
 222         return ((CallSite) MH_bsm().invoke(lookup(),
 223                                                   "foo", methodType(void.class, String.class)
 224                                                   )).dynamicInvoker();
 225     }
 226     private static MethodHandle INDY_bar() throws Throwable {
 227         shouldNotCallThis();
 228         return ((CallSite) MH_bsm2().invoke(lookup(),
 229                                                   "bar", methodType(void.class, String.class, int.class)
 230                                                   , Void.class, "void type!", 1, 234.5F, 67.5, (long)89
 231                                                   )).dynamicInvoker();
 232     }
 233     private static MethodHandle INDY_bar2() throws Throwable {
 234         shouldNotCallThis();
 235         return ((CallSite) MH_bsm2().invoke(lookup(),
 236                                                   "bar2", methodType(void.class, String.class, int.class)
 237                                                   , Void.class, "void type!", 1, 234.5F, 67.5, (long)89
 238                                                   )).dynamicInvoker();
 239     }
 240     private static MethodHandle INDY_baz() throws Throwable {
 241         shouldNotCallThis();
 242         return ((CallSite) MH_bsm2().invoke(lookup(),
 243                                                   "baz", methodType(void.class, String.class, int.class, double.class)
 244                                                   , 1234.5
 245                                                   )).dynamicInvoker();
 246     }
 247 
 248     private static void shouldNotCallThis() {
 249         // if this gets called, the transformation has not taken place
 250         if (System.getProperty("InvokeDynamicPrintArgs.allow-untransformed") != null)  return;
 251         throw new AssertionError("this code should be statically transformed away by Indify");
 252     }
 253 }