1 /*
   2  * Copyright (c) 2015, 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 package org.graalvm.compiler.core.test;
  24 
  25 import org.graalvm.compiler.java.GraphBuilderPhase;
  26 import org.graalvm.compiler.nodes.StructuredGraph;
  27 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
  28 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins;
  29 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
  30 import org.graalvm.compiler.options.OptionValues;
  31 import org.graalvm.compiler.phases.OptimisticOptimizations;
  32 import org.junit.Test;
  33 import org.objectweb.asm.ClassWriter;
  34 import org.objectweb.asm.Label;
  35 import org.objectweb.asm.MethodVisitor;
  36 import org.objectweb.asm.Opcodes;
  37 
  38 import jdk.vm.ci.code.BailoutException;
  39 import jdk.vm.ci.meta.ResolvedJavaMethod;
  40 
  41 /**
  42  * Exercise handling of unbalanced monitor operations by the parser. Algorithmically Graal assumes
  43  * that locks are statically block structured but that isn't something enforced by the bytecodes. In
  44  * HotSpot a dataflow is performed to ensure they are properly structured and methods with
  45  * unstructured locking aren't compiled and fall back to the interpreter. Having the Graal parser
  46  * handle this directly is simplifying for targets of Graal since they don't have to provide a data
  47  * flow that checks this property.
  48  */
  49 public class UnbalancedMonitorsTest extends GraalCompilerTest {
  50     private static final String CLASS_NAME = UnbalancedMonitorsTest.class.getName();
  51     private static final String INNER_CLASS_NAME = CLASS_NAME + "$UnbalancedMonitors";
  52     private static final String CLASS_NAME_INTERNAL = CLASS_NAME.replace('.', '/');
  53     private static final String INNER_CLASS_NAME_INTERNAL = INNER_CLASS_NAME.replace('.', '/');
  54 
  55     public UnbalancedMonitorsTest() {
  56         exportPackage(JAVA_BASE, "jdk.internal.org.objectweb.asm");
  57     }
  58 
  59     private static AsmLoader LOADER = new AsmLoader(UnbalancedMonitorsTest.class.getClassLoader());
  60 
  61     @Test
  62     public void runWrongOrder() throws Exception {
  63         checkForBailout("wrongOrder");
  64     }
  65 
  66     @Test
  67     public void runTooFewExits() throws Exception {
  68         checkForBailout("tooFewExits");
  69     }
  70 
  71     @Test
  72     public void runTooManyExits() throws Exception {
  73         checkForBailout("tooManyExits");
  74     }
  75 
  76     @Test
  77     public void runTooFewExitsExceptional() throws Exception {
  78         checkForBailout("tooFewExitsExceptional");
  79     }
  80 
  81     @Test
  82     public void runTooManyExitsExceptional() throws Exception {
  83         checkForBailout("tooManyExitsExceptional");
  84     }
  85 
  86     private void checkForBailout(String name) throws ClassNotFoundException {
  87         ResolvedJavaMethod method = getResolvedJavaMethod(LOADER.findClass(INNER_CLASS_NAME), name);
  88         try {
  89             OptionValues options = getInitialOptions();
  90             StructuredGraph graph = new StructuredGraph.Builder(options, getDebugContext(options)).method(method).build();
  91             Plugins plugins = new Plugins(new InvocationPlugins());
  92             GraphBuilderConfiguration graphBuilderConfig = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true).withUnresolvedIsError(true);
  93             OptimisticOptimizations optimisticOpts = OptimisticOptimizations.NONE;
  94 
  95             GraphBuilderPhase.Instance graphBuilder = new GraphBuilderPhase.Instance(getMetaAccess(), getProviders().getStampProvider(), null, null, graphBuilderConfig, optimisticOpts, null);
  96             graphBuilder.apply(graph);
  97         } catch (BailoutException e) {
  98             if (e.getMessage().contains("unbalanced monitors")) {
  99                 return;
 100             }
 101             throw e;
 102         }
 103         assertTrue("should have bailed out", false);
 104     }
 105 
 106     static class Gen implements Opcodes {
 107 
 108     // @formatter:off
 109     // Template class used with Bytecode Outline to generate ASM code
 110     //    public static class UnbalancedMonitors {
 111     //
 112     //        public UnbalancedMonitors() {
 113     //        }
 114     //
 115     //        public Object wrongOrder(Object a, Object b) {
 116     //            synchronized (a) {
 117     //                synchronized (b) {
 118     //                    return b;
 119     //                }
 120     //            }
 121     //        }
 122     //
 123     //        public Object tooFewExits(Object a, Object b) {
 124     //            synchronized (a) {
 125     //                synchronized (b) {
 126     //                    return b;
 127     //                }
 128     //            }
 129     //        }
 130     //
 131     //        public boolean tooFewExitsExceptional(Object a, Object b) {
 132     //            synchronized (a) {
 133     //                synchronized (b) {
 134     //                    return b.equals(a);
 135     //                }
 136     //            }
 137     //        }
 138     //    }
 139     // @formatter:on
 140 
 141         public static byte[] generateClass() {
 142 
 143             ClassWriter cw = new ClassWriter(0);
 144 
 145             cw.visit(52, ACC_SUPER | ACC_PUBLIC, INNER_CLASS_NAME_INTERNAL, null, "java/lang/Object", null);
 146 
 147             cw.visitSource("UnbalancedMonitorsTest.java", null);
 148 
 149             cw.visitInnerClass(INNER_CLASS_NAME_INTERNAL, CLASS_NAME_INTERNAL, "UnbalancedMonitors", ACC_STATIC);
 150 
 151             visitConstructor(cw);
 152             visitWrongOrder(cw);
 153             visitBlockStructured(cw, true, false);
 154             visitBlockStructured(cw, true, true);
 155             visitBlockStructured(cw, false, false);
 156             visitBlockStructured(cw, false, true);
 157             cw.visitEnd();
 158 
 159             return cw.toByteArray();
 160         }
 161 
 162         private static void visitBlockStructured(ClassWriter cw, boolean normalReturnError, boolean tooMany) {
 163             String name = (tooMany ? "tooMany" : "tooFew") + "Exits" + (normalReturnError ? "" : "Exceptional");
 164             // Generate too many or too few exits down the either the normal or exceptional return
 165             // paths
 166             int exceptionalExitCount = normalReturnError ? 1 : (tooMany ? 2 : 0);
 167             int normalExitCount = normalReturnError ? (tooMany ? 2 : 0) : 1;
 168             MethodVisitor mv;
 169             mv = cw.visitMethod(ACC_PUBLIC, name, "(Ljava/lang/Object;Ljava/lang/Object;)Z", null, null);
 170             mv.visitCode();
 171             Label l0 = new Label();
 172             Label l1 = new Label();
 173             Label l2 = new Label();
 174             mv.visitTryCatchBlock(l0, l1, l2, null);
 175             Label l3 = new Label();
 176             mv.visitTryCatchBlock(l2, l3, l2, null);
 177             Label l4 = new Label();
 178             Label l5 = new Label();
 179             Label l6 = new Label();
 180             mv.visitTryCatchBlock(l4, l5, l6, null);
 181             Label l7 = new Label();
 182             mv.visitTryCatchBlock(l2, l7, l6, null);
 183             Label l8 = new Label();
 184             mv.visitLabel(l8);
 185             mv.visitVarInsn(ALOAD, 1);
 186             mv.visitInsn(DUP);
 187             mv.visitVarInsn(ASTORE, 3);
 188             mv.visitInsn(MONITORENTER);
 189             mv.visitLabel(l4);
 190             mv.visitVarInsn(ALOAD, 2);
 191             mv.visitInsn(DUP);
 192             mv.visitVarInsn(ASTORE, 4);
 193             mv.visitInsn(MONITORENTER);
 194             mv.visitLabel(l0);
 195             mv.visitVarInsn(ALOAD, 2);
 196             mv.visitVarInsn(ALOAD, 1);
 197             mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z", false);
 198             mv.visitVarInsn(ALOAD, 4);
 199             mv.visitInsn(MONITOREXIT);
 200             mv.visitLabel(l1);
 201             for (int i = 0; i < normalExitCount; i++) {
 202                 mv.visitVarInsn(ALOAD, 3);
 203                 mv.visitInsn(MONITOREXIT);
 204             }
 205             mv.visitLabel(l5);
 206             mv.visitInsn(IRETURN);
 207             mv.visitLabel(l2);
 208             mv.visitFrame(Opcodes.F_FULL, 5, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object",
 209                             "java/lang/Object"}, 1, new Object[]{"java/lang/Throwable"});
 210             mv.visitVarInsn(ALOAD, 4);
 211             mv.visitInsn(MONITOREXIT);
 212             mv.visitLabel(l3);
 213             mv.visitInsn(ATHROW);
 214             mv.visitLabel(l6);
 215             mv.visitFrame(Opcodes.F_FULL, 4, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object"}, 1,
 216                             new Object[]{"java/lang/Throwable"});
 217             for (int i = 0; i < exceptionalExitCount; i++) {
 218                 mv.visitVarInsn(ALOAD, 3);
 219                 mv.visitInsn(MONITOREXIT);
 220             }
 221             mv.visitLabel(l7);
 222             mv.visitInsn(ATHROW);
 223             Label l9 = new Label();
 224             mv.visitLabel(l9);
 225             mv.visitMaxs(2, 5);
 226             mv.visitEnd();
 227         }
 228 
 229         private static void visitWrongOrder(ClassWriter cw) {
 230             MethodVisitor mv;
 231             mv = cw.visitMethod(ACC_PUBLIC, "wrongOrder", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", null, null);
 232             mv.visitCode();
 233             Label l0 = new Label();
 234             Label l1 = new Label();
 235             Label l2 = new Label();
 236             mv.visitTryCatchBlock(l0, l1, l2, null);
 237             Label l3 = new Label();
 238             mv.visitTryCatchBlock(l2, l3, l2, null);
 239             Label l4 = new Label();
 240             Label l5 = new Label();
 241             Label l6 = new Label();
 242             mv.visitTryCatchBlock(l4, l5, l6, null);
 243             Label l7 = new Label();
 244             mv.visitTryCatchBlock(l2, l7, l6, null);
 245             Label l8 = new Label();
 246             mv.visitLabel(l8);
 247             mv.visitVarInsn(ALOAD, 1);
 248             mv.visitInsn(DUP);
 249             mv.visitVarInsn(ASTORE, 3);
 250             mv.visitInsn(MONITORENTER);
 251             mv.visitLabel(l4);
 252             mv.visitVarInsn(ALOAD, 2);
 253             mv.visitInsn(DUP);
 254             mv.visitVarInsn(ASTORE, 4);
 255             mv.visitInsn(MONITORENTER);
 256             mv.visitLabel(l0);
 257             mv.visitVarInsn(ALOAD, 2);
 258             mv.visitVarInsn(ALOAD, 3);
 259             mv.visitInsn(MONITOREXIT);
 260             mv.visitLabel(l1);
 261             // Swapped exit order with exit above
 262             mv.visitVarInsn(ALOAD, 4);
 263             mv.visitInsn(MONITOREXIT);
 264             mv.visitLabel(l5);
 265             mv.visitInsn(ARETURN);
 266             mv.visitLabel(l2);
 267             mv.visitFrame(Opcodes.F_FULL, 5, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object",
 268                             "java/lang/Object"}, 1, new Object[]{"java/lang/Throwable"});
 269             mv.visitVarInsn(ALOAD, 4);
 270             mv.visitInsn(MONITOREXIT);
 271             mv.visitLabel(l3);
 272             mv.visitInsn(ATHROW);
 273             mv.visitLabel(l6);
 274             mv.visitFrame(Opcodes.F_FULL, 4, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object"}, 1,
 275                             new Object[]{"java/lang/Throwable"});
 276             mv.visitVarInsn(ALOAD, 3);
 277             mv.visitInsn(MONITOREXIT);
 278             mv.visitLabel(l7);
 279             mv.visitInsn(ATHROW);
 280             Label l9 = new Label();
 281             mv.visitLabel(l9);
 282             mv.visitMaxs(2, 5);
 283             mv.visitEnd();
 284         }
 285 
 286         private static void visitConstructor(ClassWriter cw) {
 287             MethodVisitor mv;
 288             mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
 289             mv.visitCode();
 290             Label l0 = new Label();
 291             mv.visitLabel(l0);
 292             mv.visitVarInsn(ALOAD, 0);
 293             mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
 294             Label l1 = new Label();
 295             mv.visitLabel(l1);
 296             mv.visitInsn(RETURN);
 297             Label l2 = new Label();
 298             mv.visitLabel(l2);
 299             mv.visitMaxs(1, 1);
 300             mv.visitEnd();
 301         }
 302     }
 303 
 304     public static class AsmLoader extends ClassLoader {
 305         Class<?> loaded;
 306 
 307         public AsmLoader(ClassLoader parent) {
 308             super(parent);
 309         }
 310 
 311         @Override
 312         protected Class<?> findClass(String name) throws ClassNotFoundException {
 313             if (name.equals(INNER_CLASS_NAME)) {
 314                 if (loaded != null) {
 315                     return loaded;
 316                 }
 317                 byte[] bytes = Gen.generateClass();
 318                 return (loaded = defineClass(name, bytes, 0, bytes.length));
 319             } else {
 320                 return super.findClass(name);
 321             }
 322         }
 323     }
 324 }
--- EOF ---