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.
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 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.ObjectInput;
27 import java.io.ObjectOutput;
28 import java.io.OutputStream;
29 import java.net.ServerSocket;
30 import java.net.Socket;
31 import java.util.ArrayList;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.function.Consumer;
37 import com.sun.jdi.VMDisconnectedException;
38 import com.sun.jdi.VirtualMachine;
39 import jdk.jshell.execution.JdiExecutionControl;
40 import jdk.jshell.execution.JdiInitiator;
41 import jdk.jshell.execution.Util;
42 import jdk.jshell.spi.ExecutionControl;
43 import jdk.jshell.spi.ExecutionControl.EngineTerminationException;
44 import jdk.jshell.spi.ExecutionEnv;
45 import static org.testng.Assert.fail;
46 import static jdk.jshell.execution.Util.remoteInputOutput;
47 
48 class MyExecutionControl extends JdiExecutionControl {
49 
50     private static final String REMOTE_AGENT = MyRemoteExecutionControl.class.getName();
51     private static final int TIMEOUT = 2000;
52 
53     private VirtualMachine vm;
54     private Process process;
55 
56     /**
57      * Creates an ExecutionControl instance based on a JDI
58      * {@code ListeningConnector} or {@code LaunchingConnector}.
59      *
60      * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
61      * commands and results. This socket also transports the user
62      * input/output/error.
63      *
64      * @param env the context passed by
65          * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
66      * @return the channel
67      * @throws IOException if there are errors in set-up
68      */
make(ExecutionEnv env, UserJdiUserRemoteTest test)69     static ExecutionControl make(ExecutionEnv env, UserJdiUserRemoteTest test) throws IOException {
70         try (final ServerSocket listener = new ServerSocket(0)) {
71             // timeout for socket
72             listener.setSoTimeout(TIMEOUT);
73             int port = listener.getLocalPort();
74 
75             // Set-up the JDI connection
76             List<String> opts = new ArrayList<>(env.extraRemoteVMOptions());
77             opts.add("-classpath");
78             opts.add(System.getProperty("java.class.path")
79                     + System.getProperty("path.separator")
80                     + System.getProperty("user.dir"));
81             JdiInitiator jdii = new JdiInitiator(port,
82                     opts, REMOTE_AGENT, true, null, TIMEOUT, Collections.emptyMap());
83             VirtualMachine vm = jdii.vm();
84             Process process = jdii.process();
85 
86             List<Consumer<String>> deathListeners = new ArrayList<>();
87             deathListeners.add(s -> env.closeDown());
88             Util.detectJdiExitEvent(vm, s -> {
89                 for (Consumer<String> h : deathListeners) {
90                     h.accept(s);
91                 }
92             });
93 
94             // Set-up the commands/reslts on the socket.  Piggy-back snippet
95             // output.
96             Socket socket = listener.accept();
97             // out before in -- match remote creation so we don't hang
98             OutputStream out = socket.getOutputStream();
99             Map<String, OutputStream> outputs = new HashMap<>();
100             outputs.put("out", env.userOut());
101             outputs.put("err", env.userErr());
102             outputs.put("aux", test.auxStream);
103             Map<String, InputStream> input = new HashMap<>();
104             input.put("in", env.userIn());
105             ExecutionControl myec = remoteInputOutput(socket.getInputStream(),
106                     out, outputs, input,
107                     (objIn, objOut) -> new MyExecutionControl(objOut, objIn, vm, process, deathListeners));
108             test.currentEC = myec;
109             return myec;
110         }
111     }
112 
113     /**
114      * Create an instance.
115      *
116      * @param out the output for commands
117      * @param in the input for responses
118      */
MyExecutionControl(ObjectOutput out, ObjectInput in, VirtualMachine vm, Process process, List<Consumer<String>> deathListeners)119     private MyExecutionControl(ObjectOutput out, ObjectInput in,
120             VirtualMachine vm, Process process,
121             List<Consumer<String>> deathListeners) {
122         super(out, in);
123         this.vm = vm;
124         this.process = process;
125         deathListeners.add(s -> disposeVM());
126     }
127 
128     @Override
close()129     public void close() {
130         super.close();
131         disposeVM();
132     }
133 
disposeVM()134     private synchronized void disposeVM() {
135         try {
136             if (vm != null) {
137                 vm.dispose(); // This could NPE, so it is caught below
138                 vm = null;
139             }
140         } catch (VMDisconnectedException ex) {
141             // Ignore if already closed
142         } catch (Throwable e) {
143             fail("disposeVM threw: " + e);
144         } finally {
145             if (process != null) {
146                 process.destroy();
147                 process = null;
148             }
149         }
150     }
151 
152     @Override
vm()153     protected synchronized VirtualMachine vm() throws EngineTerminationException {
154         if (vm == null) {
155             throw new EngineTerminationException("VM closed");
156         } else {
157             return vm;
158         }
159     }
160 
161 }
162