VirtualMachineManager

Java Code Examples for com.sun.jdi.VirtualMachineManager

https://www.programcreek.com/java-api-examples/index.php?api=com.sun.jdi.VirtualMachineManager

The following are top voted examples for showing how to use com.sun.jdi.VirtualMachineManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples. 

 
Example 1
Project: fiji   File: StartDebugging.java View source code 6 votes vote downvote up
private  VirtualMachine launchVirtualMachine() {

		VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
		LaunchingConnector defConnector = vmm.defaultConnector();
		Transport transport = defConnector.transport();
		List<LaunchingConnector> list = vmm.launchingConnectors();
		for (LaunchingConnector conn: list)
			System.out.println(conn.name());
		Map<String, Connector.Argument> arguments = defConnector.defaultArguments();
		Set<String> s = arguments.keySet();
		for (String string: s)
			System.out.println(string);
		Connector.Argument mainarg = arguments.get("main");
		String s1 = System.getProperty("java.class.path");
		mainarg.setValue("-classpath \"" + s1 + "\" fiji.MainClassForDebugging " + plugInName);

		try {
			return defConnector.launch(arguments);
		} catch (IOException exc) {
			throw new Error("Unable to launch target VM: " + exc);
		} catch (IllegalConnectorArgumentsException exc) {
			IJ.handleException(exc);
		} catch (VMStartException exc) {
			throw new Error("Target VM failed to initialize: " +
			                exc.getMessage());
		}
		return null;
	}

Example 2
Project: proxyhotswap   File: JDIRedefiner.java View source code 6 votes vote downvote up
private VirtualMachine connect(int port) throws IOException {
    VirtualMachineManager manager = Bootstrap.virtualMachineManager();

    // Find appropiate connector
    List<AttachingConnector> connectors = manager.attachingConnectors();
    AttachingConnector chosenConnector = null;
    for (AttachingConnector c : connectors) {
        if (c.transport().name().equals(TRANSPORT_NAME)) {
            chosenConnector = c;
            break;
        }
    }
    if (chosenConnector == null) {
        throw new IllegalStateException("Could not find socket connector");
    }

    // Set port argument
    AttachingConnector connector = chosenConnector;
    Map<String, Argument> defaults = connector.defaultArguments();
    Argument arg = defaults.get(PORT_ARGUMENT_NAME);
    if (arg == null) {
        throw new IllegalStateException("Could not find port argument");
    }
    arg.setValue(Integer.toString(port));

    // Attach
    try {
        System.out.println("Connector arguments: " + defaults);
        return connector.attach(defaults);
    } catch (IllegalConnectorArgumentsException e) {
        throw new IllegalArgumentException("Illegal connector arguments", e);
    }
}
Example 3
Project: robovm-eclipse   File: AbstractLaunchConfigurationDelegate.java View source code 6 votes vote downvote up
private VirtualMachine attachToVm(IProgressMonitor monitor, int port) throws CoreException {
    VirtualMachineManager manager = Bootstrap.virtualMachineManager();
    AttachingConnector connector = null;
    for (Iterator<?> it = manager.attachingConnectors().iterator(); it.hasNext();) {
        AttachingConnector con = (AttachingConnector) it.next();
        if ("dt_socket".equalsIgnoreCase(con.transport().name())) {
            connector = con;
            break;
        }
    }
    if (connector == null) {
        throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID, "Couldn't find socket transport"));
    }
    Map<String, Argument> defaultArguments = connector.defaultArguments();
    defaultArguments.get("hostname").setValue("localhost");
    defaultArguments.get("port").setValue("" + port);
    int retries = 60;
    CoreException exception = null;
    while (retries > 0) {
        try {
            return connector.attach(defaultArguments);
        } catch (Exception e) {
            exception = new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Couldn't connect to JDWP server at localhost:" + port, e));
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        if (monitor.isCanceled()) {
            return null;
        }
        retries--;
    }
    throw exception;
}

Example 4
Project: openjdk   File: SACoreAttachingConnector.java View source code 6 votes vote downvote up
private VirtualMachine createVirtualMachine(Class vmImplClass,
                                            String javaExec, String corefile)
    throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    java.lang.reflect.Method connectByCoreMethod = vmImplClass.getMethod(
                             "createVirtualMachineForCorefile",
                              new Class[] {
                                  VirtualMachineManager.class,
                                  String.class, String.class,
                                  Integer.TYPE
                              });
    return (VirtualMachine) connectByCoreMethod.invoke(null,
                              new Object[] {
                                  Bootstrap.virtualMachineManager(),
                                  javaExec,
                                  corefile,
                                  new Integer(0)
                              });
}
Example 5
Project: eclipse.jdt.debug   File: JDIDebugPlugin.java View source code 6 votes vote downvote up
/**
 * Returns the detected version of JDI support. This is intended to
 * distinguish between clients that support JDI 1.4 methods like hot code
 * replace.
 * 
 * @return an array of version numbers, major followed by minor
 * @since 2.1
 */
public static int[] getJDIVersion() {
	if (fJDIVersion == null) {
		fJDIVersion = new int[2];
		VirtualMachineManager mgr = Bootstrap.virtualMachineManager();
		fJDIVersion[0] = mgr.majorInterfaceVersion();
		fJDIVersion[1] = mgr.minorInterfaceVersion();
	}
	return fJDIVersion;
}
Example 6
Project: Sorbet   File: Main.java View source code 6 votes vote downvote up
public static VirtualMachine createVirtualMachine(String main, String args) {
	
	VirtualMachineManager manager = Bootstrap.virtualMachineManager();
	
	LaunchingConnector connector = manager.defaultConnector();
	
	Map<String, Connector.Argument> arguments = connector.defaultArguments();
	 	
	arguments.get("main").setValue(main);
	if (args != null) {
		arguments.get("options").setValue(args);
	}
	
	try {
		VirtualMachine vm = connector.launch(arguments);
		
		// Forward standard out and standard error
		new StreamTunnel(vm.process().getInputStream(), System.out);
		new StreamTunnel(vm.process().getErrorStream(), System.err);
		
		return vm;
	} catch (IOException e) {
           throw new Error("Error: Could not launch target VM: " + e.getMessage());
       } catch (IllegalConnectorArgumentsException e) {
		StringBuffer illegalArguments = new StringBuffer();
		
		for (String arg : e.argumentNames()) {
			illegalArguments.append(arg);
		}
		
           throw new Error("Error: Could not launch target VM because of illegal arguments: " + illegalArguments.toString());
       } catch (VMStartException e) {
           throw new Error("Error: Could not launch target VM: " + e.getMessage());
       }
}

Example 7
Project: HotswapAgent   File: JDIRedefiner.java View source code 6 votes vote downvote up
private VirtualMachine connect(int port) throws IOException {
	VirtualMachineManager manager = Bootstrap.virtualMachineManager();
	
	// Find appropiate connector
	List<AttachingConnector> connectors = manager.attachingConnectors();
	AttachingConnector chosenConnector = null;
	for (AttachingConnector c : connectors) {
		if (c.transport().name().equals(TRANSPORT_NAME)) {
			chosenConnector = c;
			break;
		}
	}
	if (chosenConnector == null) {
		throw new IllegalStateException("Could not find socket connector");
	}
	
	// Set port argument
	AttachingConnector connector = chosenConnector;
	Map<String, Argument> defaults = connector.defaultArguments();
	Argument arg = defaults.get(PORT_ARGUMENT_NAME);
	if (arg == null) {
		throw new IllegalStateException("Could not find port argument");
	}
	arg.setValue(Integer.toString(port));
	
	// Attach
	try {
		System.out.println("Connector arguments: " + defaults);
		return connector.attach(defaults);
	} catch (IllegalConnectorArgumentsException e) {
		throw new IllegalArgumentException("Illegal connector arguments", e);
	}
}
Example 8
Project: gravel   File: VMAcquirer.java View source code 6 votes vote downvote up
private AttachingConnector getConnector() {
  VirtualMachineManager vmManager = Bootstrap
      .virtualMachineManager();
  for (AttachingConnector connector : vmManager
      .attachingConnectors()) {
    if ("com.sun.jdi.SocketAttach".equals(connector
        .name())) {
      return (AttachingConnector) connector;
    }
  }
  throw new IllegalStateException();
}
Example 9
Project: ceylon-compiler   File: TracerImpl.java View source code 6 votes vote downvote up
public void start() throws Exception {
    VirtualMachineManager vmm = com.sun.jdi.Bootstrap.virtualMachineManager();
    LaunchingConnector conn = vmm.defaultConnector();
    Map<String, Argument> defaultArguments = conn.defaultArguments();
    defaultArguments.get("main").setValue(mainClass);
    defaultArguments.get("options").setValue("-cp " + classPath);
    System.out.println(defaultArguments);
    vm = conn.launch(defaultArguments);
    err = vm.process().getErrorStream();
    out = vm.process().getInputStream();
    eq = vm.eventQueue();
    rm = vm.eventRequestManager();
    outer: while (true) {
        echo(err, System.err);
        echo(out, System.out);
        events = eq.remove();
        for (Event event : events) {
            if (event instanceof VMStartEvent) {
                System.out.println(event);
                break outer;
            } else if (event instanceof VMDisconnectEvent
                    || event instanceof VMDeathEvent) {
                System.out.println(event);
                vm = null;
                rm = null;
                eq = null;
                break outer;
            }
        }
        events.resume();
    }
    echo(err, System.err);
    echo(out, System.out);
}
Example 10
Project: j   File: VMConnection.java View source code 6 votes vote downvote up
public static VMConnection getConnection(Jdb jdb)
{
    VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
    LaunchingConnector connector = vmm.defaultConnector();
    Map map = connector.defaultArguments();
    String javaHome = jdb.getJavaHome();
    ((Connector.Argument)map.get("home")).setValue(javaHome);
    String javaExecutable = jdb.getJavaExecutable();
    ((Connector.Argument)map.get("vmexec")).setValue(javaExecutable);

    // Command line.
    FastStringBuffer sb = new FastStringBuffer(jdb.getMainClass());
    String mainClassArgs = jdb.getMainClassArgs();
    if (mainClassArgs != null && mainClassArgs.length() > 0) {
        sb.append(' ');
        sb.append(mainClassArgs);
    }
    ((Connector.Argument)map.get("main")).setValue(sb.toString());

    // CLASSPATH and VM options.
    sb.setLength(0);
    String vmArgs = jdb.getVMArgs();
    if (vmArgs != null) {
        vmArgs = vmArgs.trim();
        if (vmArgs.length() > 0) {
            sb.append(vmArgs);
            sb.append(' ');
        }
    }
    String classPath = jdb.getClassPath();
    if (classPath != null) {
        classPath = classPath.trim();
        if (classPath.length() > 0) {
            sb.append("-classpath ");
            sb.append(classPath);
        }
    }
    ((Connector.Argument)map.get("options")).setValue(sb.toString());

    ((Connector.Argument)map.get("suspend")).setValue("true");
    return new VMConnection(connector, map);
}
Example 11
Project: eclipse.jdt.ui   File: InvocationCountPerformanceMeter.java View source code 6 votes vote downvote up
private void attach(String host, int port) throws IOException, IllegalConnectorArgumentsException {
	VirtualMachineManager manager= Bootstrap.virtualMachineManager();
	List<AttachingConnector> connectors= manager.attachingConnectors();
	AttachingConnector connector= connectors.get(0);
	Map<String, Connector.Argument> args= connector.defaultArguments();

	args.get("port").setValue(String.valueOf(port)); //$NON-NLS-1$
	args.get("hostname").setValue(host); //$NON-NLS-1$
	fVM= connector.attach(args);
}
Example 12
Project: dcevm   File: JDIRedefiner.java View source code 6 votes vote downvote up
private VirtualMachine connect(int port) throws IOException {
    VirtualMachineManager manager = Bootstrap.virtualMachineManager();

    // Find appropiate connector
    List<AttachingConnector> connectors = manager.attachingConnectors();
    AttachingConnector chosenConnector = null;
    for (AttachingConnector c : connectors) {
        if (c.transport().name().equals(TRANSPORT_NAME)) {
            chosenConnector = c;
            break;
        }
    }
    if (chosenConnector == null) {
        throw new IllegalStateException("Could not find socket connector");
    }

    // Set port argument
    AttachingConnector connector = chosenConnector;
    Map<String, Argument> defaults = connector.defaultArguments();
    Argument arg = defaults.get(PORT_ARGUMENT_NAME);
    if (arg == null) {
        throw new IllegalStateException("Could not find port argument");
    }
    arg.setValue(Integer.toString(port));

    // Attach
    try {
        System.out.println("Connector arguments: " + defaults);
        return connector.attach(defaults);
    } catch (IllegalConnectorArgumentsException e) {
        throw new IllegalArgumentException("Illegal connector arguments", e);
    }
}
Example 13
Project: visage-compiler   File: VisageBootstrap.java View source code 6 votes vote downvote up
public static VirtualMachineManager virtualMachineManager() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        JDIPermission vmmPermission =
                new JDIPermission("virtualMachineManager");
        sm.checkPermission(vmmPermission);
    }
    synchronized (lock) {
        if (vmm == null) {
            vmm = new VisageVirtualMachineManager();
        }
    }
    return vmm;
}
Example 14
Project: XRobot   File: LaunchEV3ConfigDelegate.java View source code 5 votes vote downvote up
public void run() {
  		try {
		Thread.sleep(5000);
	} catch (InterruptedException e) {
	}
  		
	LeJOSEV3Util.message("Starting debugger ...");
	
	// Find the socket attach connector
	VirtualMachineManager mgr=Bootstrap.virtualMachineManager();
	
	List<?> connectors = mgr.attachingConnectors();
	
	AttachingConnector chosen=null;
	for (Iterator<?> iterator = connectors.iterator(); iterator
			.hasNext();) {
		AttachingConnector conn = (AttachingConnector) iterator.next();
		if(conn.name().contains("SocketAttach")) {
			chosen=conn;
			break;
		}
	}
	
	if(chosen == null) {
		LeJOSEV3Util.error("No suitable connector");
	} else {
		Map<String, Argument> connectorArgs = chosen.defaultArguments();
		
		Connector.IntegerArgument portArg = (IntegerArgument) connectorArgs.get("port");
		Connector.StringArgument hostArg = (StringArgument) connectorArgs.get("hostname");
		portArg.setValue(8000);
		
		//LeJOSEV3Util.message("hostArg is " + hostArg);
		hostArg.setValue(brickName);
	
		VirtualMachine vm;
				
		int retries = 10;
		while (true) {
			try {
				vm = chosen.attach(connectorArgs);
				break;
			} catch (Exception e) {
				if (--retries == 0) {
					LeJOSEV3Util.message("Failed to attach to the debugger: " + e);
					return;
				}
	    		try {
					Thread.sleep(2000);
				} catch (InterruptedException e1) {
				}
			}
		}
		LeJOSEV3Util.message("Connection established");
		
		JDIDebugModel.newDebugTarget(launch, vm, simpleName, null, true, true, true);	
	}
}
Example 15
Project: eclipse.jdt.core   File: DebugEvaluationSetup.java View source code 5 votes vote downvote up
protected void setUp() {
	if (this.context == null) {
		// Launch VM in evaluation mode
		int debugPort = Util.getFreePort();
		int evalPort = Util.getFreePort();
		LocalVMLauncher launcher;
		try {
			launcher = LocalVMLauncher.getLauncher();
			launcher.setVMArguments(new String[]{"-verify"});
			launcher.setVMPath(JRE_PATH);
			launcher.setEvalPort(evalPort);
			launcher.setEvalTargetPath(EVAL_DIRECTORY);
			launcher.setDebugPort(debugPort);
			this.launchedVM = launcher.launch();
		} catch (TargetException e) {
			throw new Error(e.getMessage());
		}

		// Thread that read the stout of the VM so that the VM doesn't block
		try {
			startReader("VM's stdout reader", this.launchedVM.getInputStream(), System.out);
		} catch (TargetException e) {
		}

		// Thread that read the sterr of the VM so that the VM doesn't block
		try {
			startReader("VM's sterr reader", this.launchedVM.getErrorStream(), System.err);
		} catch (TargetException e) {
		}

		// Start JDI connection (try 10 times)
		for (int i = 0; i < 10; i++) {
			try {
				VirtualMachineManager manager = org.eclipse.jdi.Bootstrap.virtualMachineManager();
				List connectors = manager.attachingConnectors();
				if (connectors.size() == 0)
					break;
				AttachingConnector connector = (AttachingConnector)connectors.get(0);
				Map args = connector.defaultArguments();
				Connector.Argument argument = (Connector.Argument)args.get("port");
				if (argument != null) {
					argument.setValue(String.valueOf(debugPort));
				}
				argument = (Connector.Argument)args.get("hostname");
				if (argument != null) {
					argument.setValue(launcher.getTargetAddress());
				}
				argument = (Connector.Argument)args.get("timeout");
				if (argument != null) {
					argument.setValue("10000");
				}
				this.vm = connector.attach(args);

				// workaround pb with some VMs
				this.vm.resume();

				break;
			} catch (IllegalConnectorArgumentsException e) {
				e.printStackTrace();
				try {
					System.out.println("Could not contact the VM at " + launcher.getTargetAddress() + ":" + debugPort + ". Retrying...");
					Thread.sleep(100);
				} catch (InterruptedException e2) {
				}
			} catch (IOException e) {
				e.printStackTrace();
				try {
					System.out.println("Could not contact the VM at " + launcher.getTargetAddress() +":"+ debugPort +". Retrying...");Thread.sleep(100);}catch(InterruptedException e2){}}}if(this.vm ==null){if(this.launchedVM !=null){// If the VM is not running, output error streamtry{if(!this.launchedVM.isRunning()){InputStreamin=this.launchedVM.getErrorStream();int read;do{
							read =in.read();if(read !=-1)System.out.print((char)read);}while(read !=-1);}}catch(TargetException e){}catch(IOException e){}// Shut it downtry{if(this.target !=null){this.target.disconnect();// Close the socket first so that the OS resource has a chance to be freed.}intretry=0;while(this.launchedVM.isRunning()&&(++retry<20)){try{Thread.sleep(retry*100);}catch(InterruptedException e){}}if(this.launchedVM.isRunning()){this.launchedVM.shutDown();}}catch(TargetException e){}}System.err.println("Could not contact the VM");return;}// Create contextthis.context =newEvaluationContext();// Create targetthis.target =newTargetInterface();this.target.connect("localhost", evalPort,30000);// allow 30s max to connect (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=188127)// Create name environmentthis.env =newFileSystem(Util.getJavaClassLibs(),newString[0],null);}super.setUp();}
Example 16
Project: jnode   File: Hotswap.java View source code 5 votes vote downvote up
private void connect(String host, String port, String name) throws Exception {
        // connect to JVM
        boolean useSocket = (port != null);

        VirtualMachineManager manager = Bootstrap.virtualMachineManager();
        List<AttachingConnector> connectors = manager.attachingConnectors();
        AttachingConnector connector = null;
//      System.err.println("Connectors available");
        for (int i = 0; i < connectors.size(); i++) {
            AttachingConnector tmp = connectors.get(i);
//          System.err.println("conn "+i+"  name="+tmp.name()+" transport="+tmp.transport().name()+
//          " description="+tmp.description());
            if (!useSocket && tmp.transport().name().equals("dt_shmem")) {
                connector = tmp;
                break;
            }
            if (useSocket && tmp.transport().name().equals("dt_socket")) {
                connector = tmp;
                break;
            }
        }
        if (connector == null) {
            throw new IllegalStateException("Cannot find shared memory connector");
        }

        Map<String, Argument> args = connector.defaultArguments();
//      Iterator iter = args.keySet().iterator();
//      while (iter.hasNext()) {
//          Object key = iter.next();
//          Object val = args.get(key);
//          System.err.println("key:"+key.toString()+" = "+val.toString());
//      }
        Connector.Argument arg;
        // use name if using dt_shmem
        if (!useSocket) {
            arg = (Connector.Argument) args.get("name");
            arg.setValue(name);
        } else {
            // use port if using dt_socket
            arg = (Connector.Argument) args.get("port");
            arg.setValue(port);
            if (host != null) {
                arg = (Connector.Argument) args.get("hostname");
                arg.setValue(host);
            }
        }
        vm = connector.attach(args);

        // query capabilities
        if (!vm.canRedefineClasses()) {
            throw new Exception("JVM doesn't support class replacement");
        }
//      if (!vm.canAddMethod()) {
//          throw new Exception("JVM doesn't support adding method");
//      }
//      System.err.println("attached!");
    }
Example 17
Project: Greenfoot   File: VMReference.java View source code 5 votes vote downvote up
/**
 * Launch a remote debug VM using a TCP/IP socket.
 * 
 * @param initDir
 *            the directory to have as a current directory in the remote VM
 * @param mgr
 *            the virtual machine manager
 * @return an instance of a VirtualMachine or null if there was an error
 */
public VirtualMachine localhostSocketLaunch(File initDir, DebuggerTerminal term, VirtualMachineManager mgr)
{
    final int CONNECT_TRIES = 5; // try to connect max of 5 times
    final int CONNECT_WAIT = 500; // wait half a sec between each connect

    int portNumber;
    String [] launchParams;

    // launch the VM using the runtime classpath.
    Boot boot = Boot.getInstance();
    File [] filesPath = BPClassLoader.toFiles(boot.getRuntimeUserClassPath());
    String allClassPath = BPClassLoader.toClasspathString(filesPath);
    
    ArrayList<String> paramList = new ArrayList<String>(10);
    paramList.add(Config.getJDKExecutablePath(null, "java"));
    
    //check if any vm args are specified in Config, at the moment these
    //are only Locale options: user.language and user.country
    
    paramList.addAll(Config.getDebugVMArgs());
    
    paramList.add("-classpath");
    paramList.add(allClassPath);
    paramList.add("-Xdebug");
    paramList.add("-Xnoagent");
    if (Config.isMacOS()) {
        paramList.add("-Xdock:icon=" + Config.getBlueJIconPath() + "/" + Config.getVMIconsName());
        paramList.add("-Xdock:name=" + Config.getVMDockName());
    }
    paramList.add("-Xrunjdwp:transport=dt_socket,server=y");
    
    // set index of memory transport, this may be used later if socket launch
    // will not work
    transportIndex = paramList.size() - 1;
    paramList.add(SERVER_CLASSNAME);
    
    // set output encoding if specified, default is to use system default
    // this gets passed to ExecServer's main as an arg which can then be 
    // used to specify encoding
    streamEncoding = Config.getPropString("bluej.terminal.encoding", null);
    isDefaultEncoding = (streamEncoding == null);
    if(!isDefaultEncoding) {
        paramList.add(streamEncoding);
    }
    
    launchParams = (String[]) paramList.toArray(new String[0]);

    String transport = Config.getPropString("bluej.vm.transport");
    
    AttachingConnector tcpipConnector = null;
    AttachingConnector shmemConnector = null;

    Throwable tcpipFailureReason = null;
    Throwable shmemFailureReason = null;
    
    // Attempt to connect via TCP/IP transport
    
    List connectors = mgr.attachingConnectors();
    AttachingConnector connector = null;

    // find the known connectors
    Iterator it = connectors.iterator();
    while (it.hasNext()) {
        AttachingConnector c = (AttachingConnector) it.next();
        
        if (c.transport().name().equals("dt_socket")) {
            tcpipConnector = c;
        }
        else if (c.transport().name().equals("dt_shmem")) {
            shmemConnector = c;
        }
    }

    connector = tcpipConnector;

    // If the transport has been explicitly set the shmem in bluej.defs,
    // try to use the dt_shmem connector first.
    if (transport.equals("dt_shmem") && shmemConnector != null)
        connector = null;

    for (int i = 0; i < CONNECT_TRIES; i++) {
        
        if (connector != null) {
            try {
                final StringBuffer listenMessage = new StringBuffer();
                remoteVMprocess = launchVM(initDir, launchParams, listenMessage, term);
                
                portNumber = extractPortNumber(listenMessage.toString());if(portNumber ==-1){
                    closeIO();
                    remoteVMprocess.destroy();
                    remoteVMprocess =null;thrownewException(){publicvoid printStackTrace(){Debug.message("Could not find port number to connect to debugger");Debug.message("Line received from debugger was: "+ listenMessage);}};}Map arguments = connector.defaultArguments();Connector.Argument hostnameArg =(Connector.Argument) arguments.get("hostname");Connector.Argument portArg =(Connector.Argument) arguments.get("port");Connector.Argument timeoutArg =(Connector.Argument) arguments.get("timeout");if(hostnameArg ==null|| portArg ==null){thrownewException(){publicvoid printStackTrace(){Debug.message("incompatible JPDA socket launch connector");}};}
                
                hostnameArg.setValue("127.0.0.1");
                portArg.setValue(Integer.toString(portNumber));if(timeoutArg !=null){// The timeout appears to be in milliseconds.// The default is apparently no timeout.
                    timeoutArg.setValue("1000");}VirtualMachine m =null;try{
                    m = connector.attach(arguments);}catch(Throwable t){// failed to connect.
                    closeIO();
                    remoteVMprocess.destroy();
                    remoteVMprocess =null;throw t;}Debug.log("Connected to debug VM via dt_socket transport...");
                machine = m;
                setupEventHandling();
                waitForStartup();Debug.log("Communication with debug VM fully established.");return m;}catch(Throwable t){
                tcpipFailureReason = t;}}// Attempt launch using shared memory transport, if available
        
        connector = shmemConnector;if(connector !=null){try{Map arguments = connector.defaultArguments();Connector.Argument addressArg =(Connector.Argument) arguments.get("name");if(addressArg ==null){thrownewException(){publicvoid printStackTrace(){Debug.message("Shared memory connector is incompatible - no 'name' argument");}};}else{String shmName ="bluej"+ shmCount++;
                    addressArg.setValue(shmName);
                    
                    launchParams[transportIndex]="-Xrunjdwp:transport=dt_shmem,address="+ shmName +",server=y,suspend=y";StringBuffer listenMessage =newStringBuffer();
                    remoteVMprocess = launchVM(initDir, launchParams, listenMessage,term);VirtualMachine m =null;try{
                        m = connector.attach(arguments);}catch(Throwable t){// failed to connect.
                        closeIO();
                        remoteVMprocess.destroy();
                        remoteVMprocess =null;throw t;}Debug.log("Connected to debug VM via dt_shmem transport...");
                    machine = m;
                    setupEventHandling();
                    waitForStartup();Debug.log("Communication with debug VM fully established.");return m;}}catch(Throwable t){
                shmemFailureReason = t;}}// Do a small wait between connection attemptstry{if(i != CONNECT_TRIES -1)Thread.sleep(CONNECT_WAIT);}catch(InterruptedException ie){break;}
        connector = tcpipConnector;}// failed to connectDebug.message("Failed to connect to debug VM. Reasons follow:");if(tcpipConnector !=null&& tcpipFailureReason !=null){Debug.message("dt_socket transport:");
        tcpipFailureReason.printStackTrace();}if(shmemConnector !=null&& shmemFailureReason !=null){Debug.message("dt_shmem transport:");
        tcpipFailureReason.printStackTrace();}if(shmemConnector ==null&& tcpipConnector ==null){Debug.message(" No suitable transports available.");}returnnull;}
Example 18
Project: classlib6   File: Hotswap.java View source code 5 votes vote downvote up
private void connect(String host, String port, String name) throws Exception {
        // connect to JVM
        boolean useSocket = (port != null);

        VirtualMachineManager manager = Bootstrap.virtualMachineManager();
        List connectors = manager.attachingConnectors();
        AttachingConnector connector = null;
//      System.err.println("Connectors available");
        for (int i = 0; i < connectors.size(); i++) {
            AttachingConnector tmp = (AttachingConnector) connectors.get(i);
//          System.err.println("conn "+i+"  name="+tmp.name()+" transport="+tmp.transport().name()+
//          " description="+tmp.description());
            if (!useSocket && tmp.transport().name().equals("dt_shmem")) {
                connector = tmp;
                break;
            }
            if (useSocket && tmp.transport().name().equals("dt_socket")) {
                connector = tmp;
                break;
            }
        }
        if (connector == null) {
            throw new IllegalStateException("Cannot find shared memory connector");
        }

        Map args = connector.defaultArguments();
//      Iterator iter = args.keySet().iterator();
//      while (iter.hasNext()) {
//          Object key = iter.next();
//          Object val = args.get(key);
//          System.err.println("key:"+key.toString()+" = "+val.toString());
//      }
        Connector.Argument arg;
        // use name if using dt_shmem
        if (!useSocket) {
            arg = (Connector.Argument) args.get("name");
            arg.setValue(name);
        } else {
            // use port if using dt_socket
            arg = (Connector.Argument) args.get("port");
            arg.setValue(port);
            if (host != null) {
                arg = (Connector.Argument) args.get("hostname");
                arg.setValue(host);
            }
        }
        vm = connector.attach(args);

        // query capabilities
        if (!vm.canRedefineClasses()) {
            throw new Exception("JVM doesn't support class replacement");
        }
//      if (!vm.canAddMethod()) {
//          throw new Exception("JVM doesn't support adding method");
//      }
//      System.err.println("attached!");
    }
posted @ 2017-09-11 17:45  吃饭了吗  阅读(392)  评论(0编辑  收藏  举报