|
| 1 | +package pw.dasbrain.lamarr; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.ObjectInputStream; |
| 6 | +import java.io.ObjectOutputStream; |
| 7 | +import java.net.ServerSocket; |
| 8 | +import java.net.Socket; |
| 9 | +import java.net.URISyntaxException; |
| 10 | +import java.util.HashMap; |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +import com.sun.tools.attach.AgentInitializationException; |
| 14 | +import com.sun.tools.attach.AgentLoadException; |
| 15 | +import com.sun.tools.attach.AttachNotSupportedException; |
| 16 | +import com.sun.tools.attach.VirtualMachine; |
| 17 | + |
| 18 | +import jdk.jshell.execution.StreamingExecutionControl; |
| 19 | +import jdk.jshell.spi.ExecutionControl; |
| 20 | +import jdk.jshell.spi.ExecutionControlProvider; |
| 21 | +import jdk.jshell.spi.ExecutionEnv; |
| 22 | + |
| 23 | +public class InstrumentationExecutionControlProvider implements ExecutionControlProvider { |
| 24 | + |
| 25 | + @Override |
| 26 | + public String name() { |
| 27 | + return "instrumentation"; |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public ExecutionControl generate(ExecutionEnv env, Map<String, String> parameters) |
| 32 | + throws Throwable { |
| 33 | + ServerSocket so = new ServerSocket(0); |
| 34 | + so.setSoTimeout(5000); |
| 35 | + attach(parameters.get("pid"), so.getLocalPort()); |
| 36 | + Socket s = so.accept(); |
| 37 | + ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); |
| 38 | + out.flush(); |
| 39 | + ObjectInputStream in = new ObjectInputStream(s.getInputStream()); |
| 40 | + return new StreamingExecutionControl(out, in); |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + public Map<String, String> defaultParameters() { |
| 45 | + Map<String, String> result = new HashMap<>(); |
| 46 | + result.put("pid", ""); |
| 47 | + return result; |
| 48 | + } |
| 49 | + |
| 50 | + private static void attach(String pid, int port) throws AttachNotSupportedException, |
| 51 | + IOException, AgentLoadException, AgentInitializationException, URISyntaxException { |
| 52 | + VirtualMachine vm = VirtualMachine.attach(pid); |
| 53 | + try { |
| 54 | + vm.loadAgent(new File(InstrumentationExecutionControlProvider.class |
| 55 | + .getProtectionDomain().getCodeSource().getLocation().toURI()).toString(), |
| 56 | + port + ""); |
| 57 | + } finally { |
| 58 | + vm.detach(); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments