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         @SuppressWarnings("deprecation")
 63         ThreadGroup group = new ThreadGroup("JShell process local execution");
 64         execThreadGroup = group;
 65 
 66         AtomicReference<InvocationTargetException> iteEx = new AtomicReference<>();
 67         AtomicReference<IllegalAccessException> iaeEx = new AtomicReference<>();
 68         AtomicReference<NoSuchMethodException> nmeEx = new AtomicReference<>();
 69         AtomicReference<Boolean> stopped = new AtomicReference<>(false);
 70 
 71         Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
 72             if (e instanceof InvocationTargetException) {
 73                 if (e.getCause() instanceof ThreadDeath) {
 74                     stopped.set(true);
 75                 } else {
 76                     iteEx.set((InvocationTargetException) e);
 77                 }
 78             } else if (e instanceof IllegalAccessException) {
 79                 iaeEx.set((IllegalAccessException) e);
 80             } else if (e instanceof NoSuchMethodException) {
 81                 nmeEx.set((NoSuchMethodException) e);
 82             } else if (e instanceof ThreadDeath) {
 83                 stopped.set(true);
 84             }
 85         });
 86 
 87         final Object[] res = new Object[1];
 88         Thread snippetThread = new Thread(execThreadGroup, () -> {
 89             try {
 90                 res[0] = doitMethod.invoke(null, new Object[0]);
 91             } catch (InvocationTargetException e) {
 92                 if (e.getCause() instanceof ThreadDeath) {
 93                     stopped.set(true);
 94                 } else {
 95                     iteEx.set(e);
 96                 }
 97             } catch (IllegalAccessException e) {
 98                 iaeEx.set(e);
 99             } catch (ThreadDeath e) {
100                 stopped.set(true);
101             }
102         });
103 
104         snippetThread.start();
105         Thread[] threadList = new Thread[execThreadGroup.activeCount()];
106         execThreadGroup.enumerate(threadList);
107         for (Thread thread : threadList) {
108             if (thread != null) {
109                 thread.join();
110             }
111         }
112 
113         if (stopped.get()) {
114             throw new StoppedException();
115         }
116 
117         if (iteEx.get() != null) {
118             throw iteEx.get();
119         } else if (nmeEx.get() != null) {
120             throw nmeEx.get();
121         } else if (iaeEx.get() != null) {
122             throw iaeEx.get();
123         }
124 
125         return valueString(res[0]);
126     }
127 
128     @Override
129     @SuppressWarnings({"deprecation", "removal"})
130     public void stop() throws EngineTerminationException, InternalException {
131         synchronized (STOP_LOCK) {
132             if (!userCodeRunning) {
133                 return;
134             }
135             if (execThreadGroup == null) {
136                 throw new InternalException("Process-local code snippets thread group is null. Aborting stop.");
137             }
138 
139             execThreadGroup.stop();
140         }
141     }
142 
143     @Override
144     protected void clientCodeEnter() {
145         synchronized (STOP_LOCK) {
146             userCodeRunning = true;
147         }
148     }
149 
150     @Override
151     protected void clientCodeLeave() {
152         synchronized (STOP_LOCK) {
153             userCodeRunning = false;
154         }
155     }
156 
157 }