JdiDefaultExecutionControl.java revision 3931:ca18223ce9ee
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 */
25package jdk.jshell.execution;
26
27import java.io.IOException;
28import java.io.InputStream;
29import java.io.ObjectInput;
30import java.io.ObjectOutput;
31import java.io.OutputStream;
32import java.net.InetAddress;
33import java.net.ServerSocket;
34import java.net.Socket;
35import java.util.ArrayList;
36import java.util.HashMap;
37import java.util.List;
38import java.util.Map;
39import java.util.function.Consumer;
40import com.sun.jdi.BooleanValue;
41import com.sun.jdi.ClassNotLoadedException;
42import com.sun.jdi.Field;
43import com.sun.jdi.IncompatibleThreadStateException;
44import com.sun.jdi.InvalidTypeException;
45import com.sun.jdi.ObjectReference;
46import com.sun.jdi.StackFrame;
47import com.sun.jdi.ThreadReference;
48import com.sun.jdi.VMDisconnectedException;
49import com.sun.jdi.VirtualMachine;
50import jdk.jshell.spi.ExecutionControl;
51import jdk.jshell.spi.ExecutionEnv;
52import static jdk.jshell.execution.Util.remoteInputOutput;
53
54/**
55 * The implementation of {@link jdk.jshell.spi.ExecutionControl} that the
56 * JShell-core uses by default.
57 * Launches a remote process -- the "remote agent".
58 * Interfaces to the remote agent over a socket and via JDI.
59 * Designed to work with {@link RemoteExecutionControl}.
60 *
61 * @author Robert Field
62 * @author Jan Lahoda
63 */
64public class JdiDefaultExecutionControl extends JdiExecutionControl {
65
66    private VirtualMachine vm;
67    private Process process;
68    private final String remoteAgent;
69
70    private final Object STOP_LOCK = new Object();
71    private boolean userCodeRunning = false;
72
73    /**
74     * Creates an ExecutionControl instance based on a JDI
75     * {@code ListeningConnector} or {@code LaunchingConnector}.
76     *
77     * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
78     * commands and results. This socket also transports the user
79     * input/output/error.
80     *
81     * @param env the context passed by
82     * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
83     * @param remoteAgent the remote agent to launch
84     * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
85     * otherwise we start explicitly and use ListeningConnector
86     * @param host explicit hostname to use, if null use discovered
87     * hostname, applies to listening only (!isLaunch)
88     * @return the channel
89     * @throws IOException if there are errors in set-up
90     */
91    static ExecutionControl create(ExecutionEnv env, String remoteAgent,
92            boolean isLaunch, String host, int timeout) throws IOException {
93        try (final ServerSocket listener = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
94            // timeout on I/O-socket
95            listener.setSoTimeout(timeout);
96            int port = listener.getLocalPort();
97
98            // Set-up the JDI connection
99            JdiInitiator jdii = new JdiInitiator(port,
100                    env.extraRemoteVMOptions(), remoteAgent, isLaunch, host, timeout);
101            VirtualMachine vm = jdii.vm();
102            Process process = jdii.process();
103
104            List<Consumer<String>> deathListeners = new ArrayList<>();
105            Util.detectJdiExitEvent(vm, s -> {
106                for (Consumer<String> h : deathListeners) {
107                    h.accept(s);
108                }
109            });
110
111            // Set-up the commands/reslts on the socket.  Piggy-back snippet
112            // output.
113            Socket socket = listener.accept();
114            // out before in -- match remote creation so we don't hang
115            OutputStream out = socket.getOutputStream();
116            Map<String, OutputStream> outputs = new HashMap<>();
117            outputs.put("out", env.userOut());
118            outputs.put("err", env.userErr());
119            Map<String, InputStream> input = new HashMap<>();
120            input.put("in", env.userIn());
121            return remoteInputOutput(socket.getInputStream(), out, outputs, input,
122                    (objIn, objOut) -> new JdiDefaultExecutionControl(env,
123                                        objOut, objIn, vm, process, remoteAgent, deathListeners));
124        }
125    }
126
127    /**
128     * Create an instance.
129     *
130     * @param cmdout the output for commands
131     * @param cmdin the input for responses
132     */
133    private JdiDefaultExecutionControl(ExecutionEnv env,
134            ObjectOutput cmdout, ObjectInput cmdin,
135            VirtualMachine vm, Process process, String remoteAgent,
136            List<Consumer<String>> deathListeners) {
137        super(cmdout, cmdin);
138        this.vm = vm;
139        this.process = process;
140        this.remoteAgent = remoteAgent;
141        // We have now succeeded in establishing the connection.
142        // If there is an exit now it propagates all the way up
143        // and the VM should be disposed of.
144        deathListeners.add(s -> env.closeDown());
145        deathListeners.add(s -> disposeVM());
146     }
147
148    @Override
149    public String invoke(String classname, String methodname)
150            throws RunException,
151            EngineTerminationException, InternalException {
152        String res;
153        synchronized (STOP_LOCK) {
154            userCodeRunning = true;
155        }
156        try {
157            res = super.invoke(classname, methodname);
158        } finally {
159            synchronized (STOP_LOCK) {
160                userCodeRunning = false;
161            }
162        }
163        return res;
164    }
165
166    /**
167     * Interrupts a running remote invoke by manipulating remote variables
168     * and sending a stop via JDI.
169     *
170     * @throws EngineTerminationException the execution engine has terminated
171     * @throws InternalException an internal problem occurred
172     */
173    @Override
174    public void stop() throws EngineTerminationException, InternalException {
175        synchronized (STOP_LOCK) {
176            if (!userCodeRunning) {
177                return;
178            }
179
180            vm().suspend();
181            try {
182                OUTER:
183                for (ThreadReference thread : vm().allThreads()) {
184                    // could also tag the thread (e.g. using name), to find it easier
185                    for (StackFrame frame : thread.frames()) {
186                        if (remoteAgent.equals(frame.location().declaringType().name()) &&
187                                (    "invoke".equals(frame.location().method().name())
188                                || "varValue".equals(frame.location().method().name()))) {
189                            ObjectReference thiz = frame.thisObject();
190                            Field inClientCode = thiz.referenceType().fieldByName("inClientCode");
191                            Field expectingStop = thiz.referenceType().fieldByName("expectingStop");
192                            Field stopException = thiz.referenceType().fieldByName("stopException");
193                            if (((BooleanValue) thiz.getValue(inClientCode)).value()) {
194                                thiz.setValue(expectingStop, vm().mirrorOf(true));
195                                ObjectReference stopInstance = (ObjectReference) thiz.getValue(stopException);
196
197                                vm().resume();
198                                debug("Attempting to stop the client code...\n");
199                                thread.stop(stopInstance);
200                                thiz.setValue(expectingStop, vm().mirrorOf(false));
201                            }
202
203                            break OUTER;
204                        }
205                    }
206                }
207            } catch (ClassNotLoadedException | IncompatibleThreadStateException | InvalidTypeException ex) {
208                throw new InternalException("Exception on remote stop: " + ex);
209            } finally {
210                vm().resume();
211            }
212        }
213    }
214
215    @Override
216    public void close() {
217        super.close();
218        disposeVM();
219    }
220
221    private synchronized void disposeVM() {
222        try {
223            if (vm != null) {
224                vm.dispose(); // This could NPE, so it is caught below
225                vm = null;
226            }
227        } catch (VMDisconnectedException ex) {
228            // Ignore if already closed
229        } catch (Throwable ex) {
230            debug(ex, "disposeVM");
231        } finally {
232            if (process != null) {
233                process.destroy();
234                process = null;
235            }
236        }
237    }
238
239    @Override
240    protected synchronized VirtualMachine vm() throws EngineTerminationException {
241        if (vm == null) {
242            throw new EngineTerminationException("VM closed");
243        } else {
244            return vm;
245        }
246    }
247
248    /**
249     * Log debugging information. Arguments as for {@code printf}.
250     *
251     * @param format a format string as described in Format string syntax
252     * @param args arguments referenced by the format specifiers in the format
253     * string.
254     */
255    private static void debug(String format, Object... args) {
256        // Reserved for future logging
257    }
258
259    /**
260     * Log a serious unexpected internal exception.
261     *
262     * @param ex the exception
263     * @param where a description of the context of the exception
264     */
265    private static void debug(Throwable ex, String where) {
266        // Reserved for future logging
267    }
268
269}
270