1 /*
  2  * Copyright (c) 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.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 package jdk.jshell.execution;
 26 
 27 import java.lang.reflect.InvocationTargetException;
 28 import java.lang.reflect.Method;
 29 import java.util.concurrent.atomic.AtomicReference;
 30 
 31 /**
 32  * An implementation of {@link jdk.jshell.spi.ExecutionControl} which executes
 33  * in the same JVM as the JShell-core.
 34  *
 35  * @author Grigory Ptashko
 36  * @since 9
 37  */
 38 public class LocalExecutionControl extends DirectExecutionControl {
 39 
 40     private final Object STOP_LOCK = new Object();
 41     private boolean userCodeRunning = false;
 42     private ThreadGroup execThreadGroup;
 43 
 44     /**
 45      * Creates an instance, delegating loader operations to the specified
 46      * delegate.
 47      *
 48      * @param loaderDelegate the delegate to handle loading classes
 49      */
 50     public LocalExecutionControl(LoaderDelegate loaderDelegate) {
 51         super(loaderDelegate);
 52     }
 53 
 54     /**
 55      * Create an instance using the default class loading.
 56      */
 57     public LocalExecutionControl() {
 58     }
 59 
 60     @Override
 61     protected String invoke(Method doitMethod) throws Exception {
 62         execThreadGroup = new ThreadGroup("JShell process local execution");
 63 
 64         AtomicReference<InvocationTargetException> iteEx = new AtomicReference<>();
 65         AtomicReference<IllegalAccessException> iaeEx = new AtomicReference<>();
 66         AtomicReference<NoSuchMethodException> nmeEx = new AtomicReference<>();
 67         AtomicReference<Boolean> stopped = new AtomicReference<>(false);
 68 
 69         Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
 70             if (e instanceof InvocationTargetException) {
 71                 if (e.getCause() instanceof ThreadDeath) {
 72                     stopped.set(true);
 73                 } else {
 74                     iteEx.set((InvocationTargetException) e);
 75                 }
 76             } else if (e instanceof IllegalAccessException) {
 77                 iaeEx.set((IllegalAccessException) e);
 78             } else if (e instanceof NoSuchMethodException) {
 79                 nmeEx.set((NoSuchMethodException) e);
 80             } else if (e instanceof ThreadDeath) {
 81                 stopped.set(true);
 82             }
 83         });
 84 
 85         final Object[] res = new Object[1];
 86         Thread snippetThread = new Thread(execThreadGroup, () -> {
 87             try {
 88                 res[0] = doitMethod.invoke(null, new Object[0]);
 89             } catch (InvocationTargetException e) {
 90                 if (e.getCause() instanceof ThreadDeath) {
 91                     stopped.set(true);
 92                 } else {
 93                     iteEx.set(e);
 94                 }
 95             } catch (IllegalAccessException e) {
 96                 iaeEx.set(e);
 97             } catch (ThreadDeath e) {
 98                 stopped.set(true);
 99             }
100         });
101 
102         snippetThread.start();
103         Thread[] threadList = new Thread[execThreadGroup.activeCount()];
104         execThreadGroup.enumerate(threadList);
105         for (Thread thread : threadList) {
106             if (thread != null) {
107                 thread.join();
108             }
109         }
110 
111         if (stopped.get()) {
112             throw new StoppedException();
113         }
114 
115         if (iteEx.get() != null) {
116             throw iteEx.get();
117         } else if (nmeEx.get() != null) {
118             throw nmeEx.get();
119         } else if (iaeEx.get() != null) {
120             throw iaeEx.get();
121         }
122 
123         return valueString(res[0]);
124     }
125 
126     @Override
127     @SuppressWarnings({"deprecation", "removal"})
128     public void stop() throws EngineTerminationException, InternalException {
129         synchronized (STOP_LOCK) {
130             if (!userCodeRunning) {
131                 return;
132             }
133             if (execThreadGroup == null) {
134                 throw new InternalException("Process-local code snippets thread group is null. Aborting stop.");
135             }
136 
137             execThreadGroup.stop();
138         }
139     }
140 
141     @Override
142     protected void clientCodeEnter() {
143         synchronized (STOP_LOCK) {
144             userCodeRunning = true;
145         }
146     }
147 
148     @Override
149     protected void clientCodeLeave() {
150         synchronized (STOP_LOCK) {
151             userCodeRunning = false;
152         }
153     }
154 
155 }