1 /*
   2  * Copyright (c) 2007, 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  */
  25 
  26 
  27 package org.graalvm.compiler.core.test.deopt;
  28 
  29 import jdk.vm.ci.code.InstalledCode;
  30 import jdk.vm.ci.meta.ResolvedJavaMethod;
  31 
  32 import org.junit.Assert;
  33 import org.junit.Test;
  34 
  35 import org.graalvm.compiler.code.CompilationResult;
  36 import org.graalvm.compiler.core.test.GraalCompilerTest;
  37 import org.graalvm.compiler.nodes.AbstractEndNode;
  38 import org.graalvm.compiler.nodes.FixedNode;
  39 import org.graalvm.compiler.nodes.FixedWithNextNode;
  40 import org.graalvm.compiler.nodes.LoopBeginNode;
  41 import org.graalvm.compiler.nodes.StructuredGraph;
  42 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
  43 
  44 public final class MonitorDeoptTest extends GraalCompilerTest {
  45 
  46     private enum State {
  47         INITIAL,
  48         ALLOWING_SAFEPOINT,
  49         RUNNING_GRAAL,
  50         INVALIDATED,
  51         RUNNING_INTERPRETER,
  52         TERMINATED
  53     }
  54 
  55     static final long TIMEOUT = 5000;
  56 
  57     private static class Monitor {
  58         private volatile State state = State.INITIAL;
  59 
  60         public synchronized void setState(State newState) {
  61             state = newState;
  62             notifyAll();
  63         }
  64 
  65         public synchronized boolean tryUpdateState(State oldState, State newState) {
  66             if (state == oldState) {
  67                 state = newState;
  68                 notifyAll();
  69                 return true;
  70             } else {
  71                 return false;
  72             }
  73         }
  74 
  75         public synchronized void waitState(State targetState) throws InterruptedException {
  76             long startTime = System.currentTimeMillis();
  77             while (state != targetState && System.currentTimeMillis() - startTime < TIMEOUT) {
  78                 wait(100);
  79             }
  80             if (state != targetState) {
  81                 throw new IllegalStateException("Timed out waiting for " + targetState);
  82             }
  83         }
  84 
  85         /**
  86          * Change the current state to {@link State#ALLOWING_SAFEPOINT} and do a short wait to allow
  87          * a safepoint to happen. Then restore the state to the original value.
  88          *
  89          * @param expectedState
  90          * @throws InterruptedException
  91          */
  92         public synchronized void safepoint(State expectedState) throws InterruptedException {
  93             if (state == expectedState) {
  94                 state = State.ALLOWING_SAFEPOINT;
  95                 wait(1);
  96                 if (state != State.ALLOWING_SAFEPOINT) {
  97                     throw new InternalError("Other threads can not update the state from ALLOWING_SAFEPOINT: " + state);
  98                 }
  99                 state = expectedState;
 100                 notifyAll();
 101             }
 102         }
 103 
 104         public synchronized State getState() {
 105             return state;
 106         }
 107 
 108         public synchronized void invalidate(InstalledCode code) throws InterruptedException {
 109             // wait for the main thread to start
 110             waitState(State.RUNNING_GRAAL);
 111 
 112             state = State.INVALIDATED;
 113             code.invalidate();
 114         }
 115     }
 116 
 117     public static boolean test(Monitor monitor) throws InterruptedException {
 118         // initially, we're running as Graal compiled code
 119         monitor.setState(State.RUNNING_GRAAL);
 120 
 121         boolean timedOut = true;
 122         long startTime = System.currentTimeMillis();
 123         long safepointCheckTime = startTime;
 124         while (System.currentTimeMillis() - startTime < TIMEOUT) {
 125             // wait for the compiled code to be invalidated
 126             if (monitor.tryUpdateState(State.INVALIDATED, State.RUNNING_INTERPRETER)) {
 127                 timedOut = false;
 128                 break;
 129             }
 130             if (System.currentTimeMillis() - safepointCheckTime > 200) {
 131                 /*
 132                  * It's possible for a safepoint to be triggered by external code before
 133                  * invalidation is ready. Allow a safepoint to occur if required but don't allow
 134                  * invalidation to proceed.
 135                  */
 136                 monitor.safepoint(State.RUNNING_GRAAL);
 137                 safepointCheckTime = System.currentTimeMillis();
 138             }
 139         }
 140         if (timedOut) {
 141             throw new InternalError("Timed out while waiting for code to be invalidated: " + monitor.getState());
 142         }
 143 
 144         for (int i = 0; i < 500; i++) {
 145             // wait for the control thread to send the TERMINATED signal
 146             if (monitor.getState() == State.TERMINATED) {
 147                 return true;
 148             }
 149 
 150             try {
 151                 Thread.sleep(10);
 152             } catch (InterruptedException e) {
 153             }
 154         }
 155 
 156         // we're running for more than 5 s in the interpreter
 157         // probably the control thread is deadlocked
 158         return false;
 159     }
 160 
 161     private static LoopBeginNode findFirstLoop(StructuredGraph graph) {
 162         FixedNode node = graph.start();
 163         for (;;) {
 164             if (node instanceof LoopBeginNode) {
 165                 return (LoopBeginNode) node;
 166             } else if (node instanceof FixedWithNextNode) {
 167                 node = ((FixedWithNextNode) node).next();
 168             } else if (node instanceof AbstractEndNode) {
 169                 node = ((AbstractEndNode) node).merge();
 170             } else {
 171                 Assert.fail(String.format("unexpected node %s in graph of test method", node));
 172             }
 173         }
 174     }
 175 
 176     /**
 177      * Remove the safepoint from the first loop in the test method, so only the safepoints on
 178      * MonitorEnter and MonitorExit remain in the loop. That way, we can make sure it deopts inside
 179      * the MonitorEnter by invalidating the code while holding the lock.
 180      */
 181     private static void removeLoopSafepoint(StructuredGraph graph) {
 182         LoopBeginNode loopBegin = findFirstLoop(graph);
 183         loopBegin.disableSafepoint();
 184     }
 185 
 186     @Test
 187     public void run0() throws Throwable {
 188         ResolvedJavaMethod javaMethod = getResolvedJavaMethod("test");
 189 
 190         StructuredGraph graph = parseEager(javaMethod, AllowAssumptions.YES);
 191         removeLoopSafepoint(graph);
 192 
 193         CompilationResult compilationResult = compile(javaMethod, graph);
 194         final InstalledCode installedCode = getBackend().createDefaultInstalledCode(graph.getDebug(), javaMethod, compilationResult);
 195 
 196         final Monitor monitor = new Monitor();
 197 
 198         Thread controlThread = new Thread(new Runnable() {
 199 
 200             @Override
 201             public void run() {
 202                 try {
 203                     // Wait for thread to reach RUNNING_GRAAL and then invalidate the code
 204                     monitor.invalidate(installedCode);
 205 
 206                     // wait for the main thread to continue running in the interpreter
 207                     monitor.waitState(State.RUNNING_INTERPRETER);
 208 
 209                     // terminate the main thread
 210                     monitor.setState(State.TERMINATED);
 211                 } catch (InterruptedException e) {
 212                 }
 213             }
 214         });
 215 
 216         controlThread.start();
 217 
 218         boolean result = test(monitor);
 219         Assert.assertTrue(result);
 220     }
 221 }