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