com.sun.jdi.VirtualMachine Java Examples

The following examples show how to use com.sun.jdi.VirtualMachine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HelloWorld.java    From java-svc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws AttachException, IOException, IllegalConnectorArgumentsException {
	if (args.length != 2) {
		System.out.println("Must provide host and port!");
		System.exit(2);
	}
	String host = args[0];
	String port = args[1];
	VirtualMachine vm = null;
	try {
		vm = connect(host, port);
		vm.resume();
		System.out.println("The process at " + JdiUtils.prettyPrint(host, port) + " is running " + vm.name()
				+ " version " + vm.version());
		System.out.println("Press <enter> to quit, and to terminate the application connected to.");
		System.in.read();
		vm.exit(0);
	} catch (Exception e) {
		e.printStackTrace();
		System.out.println("Could not connect to " + JdiUtils.prettyPrint(host, port));
		System.out.println("Message was: " + e.getMessage() + "\nExiting...");
	}
}
 
Example #2
Source File: RawCommandLineLauncher.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public VirtualMachine
    launch(Map<String,? extends Connector.Argument> arguments)
    throws IOException, IllegalConnectorArgumentsException,
           VMStartException
{
    String command = argument(ARG_COMMAND, arguments).value();
    String address = argument(ARG_ADDRESS, arguments).value();

    String quote = argument(ARG_QUOTE, arguments).value();

    if (quote.length() > 1) {
        throw new IllegalConnectorArgumentsException("Invalid length",
                                                     ARG_QUOTE);
    }

    TransportService.ListenKey listener = transportService.startListening(address);

    try {
        return launch(tokenizeCommand(command, quote.charAt(0)),
                      address, listener, transportService);
    } finally {
        transportService.stopListening(listener);
    }
}
 
Example #3
Source File: SADebugServerAttachingConnector.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private VirtualMachine createVirtualMachine(Class vmImplClass,
                                            String debugServerName)
    throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    java.lang.reflect.Method connectByServerMethod =
                        vmImplClass.getMethod(
                               "createVirtualMachineForServer",
                               new Class[] {
                                   VirtualMachineManager.class,
                                   String.class,
                                   Integer.TYPE
                               });
    return (VirtualMachine) connectByServerMethod.invoke(null,
                               new Object[] {
                                   Bootstrap.virtualMachineManager(),
                                   debugServerName,
                                   new Integer(0)
                               });
}
 
Example #4
Source File: VariableMirrorTranslator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static ReferenceType getOrLoadClass(VirtualMachine vm, String name) {
    List<ReferenceType> types = vm.classesByName(name);
    if (types.size() > 0) {
        if (types.size() == 1) {
            return types.get(0);
        }
        try {
            ReferenceType preferedType = JPDAUtils.getPreferredReferenceType(types, null);
            if (preferedType != null) {
                return preferedType;
            }
        } catch (VMDisconnectedExceptionWrapper ex) {
            throw ex.getCause();
        }
        // No preferred, just take the first one:
        return types.get(0);
    }
    // DO NOT TRY TO LOAD CLASSES AT ALL! See http://www.netbeans.org/issues/show_bug.cgi?id=168949
    return null;
}
 
Example #5
Source File: SACoreAttachingConnector.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote 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 #6
Source File: SocketAttachingConnector.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public VirtualMachine
    attach(Map<String,? extends Connector.Argument> arguments)
    throws IOException, IllegalConnectorArgumentsException
{
    String host = argument(ARG_HOST, arguments).value();
    if (host.length() > 0) {
        host = host + ":";
    }
    String address = host + argument(ARG_PORT, arguments).value();
    return super.attach(address, arguments);
}
 
Example #7
Source File: JdiInitiator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private VirtualMachine launchTarget() {
    LaunchingConnector launcher = (LaunchingConnector) connector;
    try {
        VirtualMachine new_vm = timedVirtualMachineCreation(() -> launcher.launch(connectorArgs), null);
        process = new_vm.process();
        return new_vm;
    } catch (Throwable ex) {
        throw reportLaunchFail(ex, "launch");
    }
}
 
Example #8
Source File: DebugJUnitRunner.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static void shutdown(VirtualMachine vm) {
	try {
		process.destroy();
		// process.waitFor();
		vm.exit(0);
	} catch (Exception e) {
		// ignore
	}
}
 
Example #9
Source File: GenericAttachingConnector.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attach to a target VM using the specified arguments - the address
 * of the target VM is specified by the <code>address</code> connector
 * argument.
 */
public VirtualMachine
    attach(Map<String,? extends Connector.Argument> args)
    throws IOException, IllegalConnectorArgumentsException
{
    String address = argument(ARG_ADDRESS, args).value();
    return attach(address, args);
}
 
Example #10
Source File: RemoteFXScreenshot.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static InterfaceType getInterface(VirtualMachine vm, ThreadReference tr, String name) {
    ReferenceType t = getType(vm, tr, name);
    if (t instanceof InterfaceType) {
        return (InterfaceType)t;
    }
    logger.log(Level.WARNING, "{0} is not an interface but {1}", new Object[]{name, t}); // NOI18N
    return null;
}
 
Example #11
Source File: GenericListeningConnector.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public VirtualMachine
    accept(Map<String,? extends Connector.Argument> args)
    throws IOException, IllegalConnectorArgumentsException
{
    String ts = argument(ARG_TIMEOUT, args).value();
    int timeout = 0;
    if (ts.length() > 0) {
        timeout = Integer.decode(ts).intValue();
    }

    TransportService.ListenKey listener = listenMap.get(args);
    Connection connection;
    if (listener != null) {
        connection = transportService.accept(listener, timeout, 0);
    } else {
        /*
         * Keep compatibility with previous releases - if the
         * debugger hasn't called startListening then we do a
         * once-off accept
         */
         startListening(args);
         listener = listenMap.get(args);
         assert listener != null;
         connection = transportService.accept(listener, timeout, 0);
         stopListening(args);
    }
    return Bootstrap.virtualMachineManager().createVirtualMachine(connection);
}
 
Example #12
Source File: JPDADebuggerImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if this debugger supports fix & continue
 * (HotSwap).
 *
 * @return <code>true</code> if this debugger supports fix & continue
 */
@Override
public boolean canFixClasses () {
    VirtualMachine vm = getVirtualMachine ();
    if (vm == null) {
        return false;
    }
    return VirtualMachineWrapper.canRedefineClasses0(vm);
}
 
Example #13
Source File: GenericAttachingConnector.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attach to a target VM using the specified address and Connector arguments.
 */
public VirtualMachine attach(String address, Map<String, ? extends Connector.Argument> args)
    throws IOException, IllegalConnectorArgumentsException
{
    String ts  = argument(ARG_TIMEOUT, args).value();
    int timeout = 0;
    if (ts.length() > 0) {
        timeout = Integer.decode(ts).intValue();
    }
    Connection connection = transportService.attach(address, timeout, 0);
    return Bootstrap.virtualMachineManager().createVirtualMachine(connection);
}
 
Example #14
Source File: GenericAttachingConnector.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attach to a target VM using the specified address and Connector arguments.
 */
public VirtualMachine attach(String address, Map<String, ? extends Connector.Argument> args)
    throws IOException, IllegalConnectorArgumentsException
{
    String ts  = argument(ARG_TIMEOUT, args).value();
    int timeout = 0;
    if (ts.length() > 0) {
        timeout = Integer.decode(ts).intValue();
    }
    Connection connection = transportService.attach(address, timeout, 0);
    return Bootstrap.virtualMachineManager().createVirtualMachine(connection);
}
 
Example #15
Source File: SocketAttachingConnector.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public VirtualMachine
    attach(Map<String,? extends Connector.Argument> arguments)
    throws IOException, IllegalConnectorArgumentsException
{
    String host = argument(ARG_HOST, arguments).value();
    if (host.length() > 0) {
        host = host + ":";
    }
    String address = host + argument(ARG_PORT, arguments).value();
    return super.attach(address, arguments);
}
 
Example #16
Source File: SAPIDAttachingConnector.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private VirtualMachine createVirtualMachine(Class virtualMachineImplClass, int pid)
    throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    java.lang.reflect.Method createByPIDMethod
              = virtualMachineImplClass.getMethod("createVirtualMachineForPID",
                 new Class[] {
                     VirtualMachineManager.class,
                     Integer.TYPE, Integer.TYPE
                 });
    return (VirtualMachine) createByPIDMethod.invoke(null,
                 new Object[] {
                     Bootstrap.virtualMachineManager(),
                     new Integer(pid),
                     new Integer(0)
                 });
}
 
Example #17
Source File: Session.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public Session(VirtualMachine vm, ExecutionManager runtime,
               OutputListener diagnostics) {
    this.vm = vm;
    this.runtime = runtime;
    this.diagnostics = diagnostics;
    this.traceFlags = VirtualMachine.TRACE_NONE;
}
 
Example #18
Source File: SharedMemoryAttachingConnector.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public VirtualMachine
    attach(Map<String, ? extends Connector.Argument> arguments)
    throws IOException, IllegalConnectorArgumentsException
{
    String name = argument(ARG_NAME, arguments).value();
    return super.attach(name, arguments);
}
 
Example #19
Source File: VisualDebuggerListener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ClassType getClass(VirtualMachine vm, ThreadReference tr, String name) {
    ReferenceType t = getType(vm, tr, name);
    if (t instanceof ClassType) {
        return (ClassType)t;
    }
    // logger.log(Level.WARNING, "{0} is not a class but {1}", new Object[]{name, t}); // NOI18N
    return null;
}
 
Example #20
Source File: RemoteServices.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ArrayReference createTargetBytes(VirtualMachine vm, byte[] bytes,
                                                ByteValue[] mirrorBytesCache) throws InvalidTypeException,
                                                                                     ClassNotLoadedException,
                                                                                     InternalExceptionWrapper,
                                                                                     VMDisconnectedExceptionWrapper,
                                                                                     ObjectCollectedExceptionWrapper,
                                                                                     UnsupportedOperationExceptionWrapper {
    ArrayType bytesArrayClass = getArrayClass(vm, "byte[]");
    ArrayReference array = null;
    boolean disabledCollection = false;
    while (!disabledCollection) {
        array = ArrayTypeWrapper.newInstance(bytesArrayClass, bytes.length);
        try {
            ObjectReferenceWrapper.disableCollection(array);
            disabledCollection = true;
        } catch (ObjectCollectedExceptionWrapper ocex) {
            // Collected too soon, try again...
        }
    }
    List<Value> values = new ArrayList<Value>(bytes.length);
    for (int i = 0; i < bytes.length; i++) {
        byte b = bytes[i];
        ByteValue mb = mirrorBytesCache[128 + b];
        if (mb == null) {
            mb = VirtualMachineWrapper.mirrorOf(vm, b);
            mirrorBytesCache[128 + b] = mb;
        }
        values.add(mb);
    }
    ArrayReferenceWrapper.setValues(array, values);
    return array;
}
 
Example #21
Source File: VariableMirrorTranslator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void setValueToFinalField(ObjectReference obj, String name, ClassType clazz, Value fv, VirtualMachine vm, ThreadReference thread) throws InternalExceptionWrapper, VMDisconnectedExceptionWrapper, ClassNotPreparedExceptionWrapper, ClassNotLoadedException, ObjectCollectedExceptionWrapper, IncompatibleThreadStateException, UnsupportedOperationExceptionWrapper, InvalidTypeException, InvalidObjectException {
    ObjectReference fieldRef = getDeclaredOrInheritedField(clazz, name, vm, thread);
    if (fieldRef == null) {
        InvalidObjectException ioex = new InvalidObjectException("No field "+name+" of class "+clazz);
        throw ioex;
    }
    // field.setAccessible(true);
    ClassType fieldClassType = (ClassType) ValueWrapper.type(fieldRef);
    com.sun.jdi.Method setAccessibleMethod = ClassTypeWrapper.concreteMethodByName(
            fieldClassType, "setAccessible", "(Z)V");
    try {
        ObjectReferenceWrapper.invokeMethod(fieldRef, thread, setAccessibleMethod,
                                            Collections.singletonList(vm.mirrorOf(true)),
                                            ClassType.INVOKE_SINGLE_THREADED);
        // field.set(newInstance, fv);
        com.sun.jdi.Method setMethod = ClassTypeWrapper.concreteMethodByName(
                fieldClassType, "set", "(Ljava/lang/Object;Ljava/lang/Object;)V");
        if (fv instanceof PrimitiveValue) {
            PrimitiveType pt = (PrimitiveType) ValueWrapper.type(fv);
            ReferenceType fieldBoxingClass = EvaluatorVisitor.adjustBoxingType(clazz, pt, null);
            fv = EvaluatorVisitor.box((PrimitiveValue) fv, fieldBoxingClass, thread, null);
        }
        List<Value> args = Arrays.asList(new Value[] { obj, fv });
        ObjectReferenceWrapper.invokeMethod(fieldRef, thread, setMethod,
                                            args,
                                            ClassType.INVOKE_SINGLE_THREADED);
    } catch (InvocationException iex) {
        throw new InvalidObjectException(
                "Problem setting value "+fv+" to field "+name+" of class "+clazz+
                " : "+iex.exception());
    }
}
 
Example #22
Source File: GenericAttachingConnector.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attach to a target VM using the specified address and Connector arguments.
 */
public VirtualMachine attach(String address, Map<String, ? extends Connector.Argument> args)
    throws IOException, IllegalConnectorArgumentsException
{
    String ts  = argument(ARG_TIMEOUT, args).value();
    int timeout = 0;
    if (ts.length() > 0) {
        timeout = Integer.decode(ts).intValue();
    }
    Connection connection = transportService.attach(address, timeout, 0);
    return Bootstrap.virtualMachineManager().createVirtualMachine(connection);
}
 
Example #23
Source File: ProcessAttachDebugger.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String main_args[]) throws Exception {
    String pid = main_args[0];

    // find ProcessAttachingConnector

    List<AttachingConnector> l =
        Bootstrap.virtualMachineManager().attachingConnectors();
    AttachingConnector ac = null;
    for (AttachingConnector c: l) {
        if (c.name().equals("com.sun.jdi.ProcessAttach")) {
            ac = c;
            break;
        }
    }
    if (ac == null) {
        throw new RuntimeException("Unable to locate ProcessAttachingConnector");
    }

    Map<String,Connector.Argument> args = ac.defaultArguments();
    Connector.StringArgument arg = (Connector.StringArgument)args.get("pid");
    arg.setValue(pid);

    System.out.println("Debugger is attaching to: " + pid + " ...");

    VirtualMachine vm = ac.attach(args);

    System.out.println("Attached! Now listing threads ...");

    // list all threads

    for (ThreadReference thr: vm.allThreads()) {
        System.out.println(thr);
    }

    System.out.println("Debugger done.");
}
 
Example #24
Source File: AWTGrabHandler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean ungrabWindowFX_OLD(ThreadReference tr) {
    // com.sun.javafx.tk.quantum.WindowStage has:
    // field static Map<Window, WindowStage> platformWindows = new HashMap<>();
    // com.sun.glass.ui.Window.ungrabFocus()
    try {
        VirtualMachine vm = MirrorWrapper.virtualMachine(tr);
        List<ReferenceType> windowStageClassesByName = VirtualMachineWrapper.classesByName(vm, "com.sun.javafx.tk.quantum.WindowStage");
        if (windowStageClassesByName.isEmpty()) {
            logger.info("Unable to release FX X grab, no quantum WindowStage class in target VM "+VirtualMachineWrapper.description(vm));
            return false;
        }
        ClassType WindowStageClass = (ClassType) windowStageClassesByName.get(0);
        Field platformWindowsField = WindowStageClass.fieldByName("platformWindows");
        if (platformWindowsField == null) {
            logger.info("Unable to release FX X grab, no platformWindows field found in WindowStage in target VM "+VirtualMachineWrapper.description(vm));
            return false;
        }
        ObjectReference platformWindows = (ObjectReference) WindowStageClass.getValue(platformWindowsField);
        if (platformWindows == null) {
            logger.info("Unable to release FX X grab, no platformWindows field has null value in WindowStage in target VM "+VirtualMachineWrapper.description(vm));
            return false;
        }
    } catch (VMDisconnectedExceptionWrapper vmdex) {
        return true; // Disconnected, all is good.
    } catch (Exception ex) {
        logger.log(Level.INFO, "Unable to release FX X grab (if any).", ex);
        return true; // We do not know whether there was any grab
    }
    return true;
}
 
Example #25
Source File: GenericAttachingConnector.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attach to a target VM using the specified address and Connector arguments.
 */
public VirtualMachine attach(String address, Map<String, ? extends Connector.Argument> args)
    throws IOException, IllegalConnectorArgumentsException
{
    String ts  = argument(ARG_TIMEOUT, args).value();
    int timeout = 0;
    if (ts.length() > 0) {
        timeout = Integer.decode(ts).intValue();
    }
    Connection connection = transportService.attach(address, timeout, 0);
    return Bootstrap.virtualMachineManager().createVirtualMachine(connection);
}
 
Example #26
Source File: CharacterFormatter.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Value valueOf(String value, Type type, Map<String, Object> options) {
    VirtualMachine vm = type.virtualMachine();
    if (value == null) {
        return null;
    }
    if (value.length() == 3
            && value.startsWith("'")
            && value.endsWith("'")) {
        return type.virtualMachine().mirrorOf(value.charAt(1));
    }
    return vm.mirrorOf(value.charAt(0));
}
 
Example #27
Source File: FieldMonitor.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void addFieldWatch(VirtualMachine vm,
    ReferenceType refType) {
  EventRequestManager erm = vm.eventRequestManager();
  Field field = refType.fieldByName(FIELD_NAME);
  ModificationWatchpointRequest modificationWatchpointRequest = erm
      .createModificationWatchpointRequest(field);
  modificationWatchpointRequest.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
  modificationWatchpointRequest.setEnabled(true);
}
 
Example #28
Source File: Session.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Session(VirtualMachine vm, ExecutionManager runtime,
               OutputListener diagnostics) {
    this.vm = vm;
    this.runtime = runtime;
    this.diagnostics = diagnostics;
    this.traceFlags = VirtualMachine.TRACE_NONE;
}
 
Example #29
Source File: SharedMemoryAttachingConnector.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public VirtualMachine
    attach(Map<String, ? extends Connector.Argument> arguments)
    throws IOException, IllegalConnectorArgumentsException
{
    String name = argument(ARG_NAME, arguments).value();
    return super.attach(name, arguments);
}
 
Example #30
Source File: JdiDefaultExecutionControl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an ExecutionControl instance based on a JDI
 * {@code ListeningConnector} or {@code LaunchingConnector}.
 *
 * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
 * commands and results. This socket also transports the user
 * input/output/error.
 *
 * @param env the context passed by
 * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
 * @param remoteAgent the remote agent to launch
 * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
 * otherwise we start explicitly and use ListeningConnector
 * @param host explicit hostname to use, if null use discovered
 * hostname, applies to listening only (!isLaunch)
 * @return the channel
 * @throws IOException if there are errors in set-up
 */
static ExecutionControl create(ExecutionEnv env, String remoteAgent,
        boolean isLaunch, String host, int timeout) throws IOException {
    try (final ServerSocket listener = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
        // timeout on I/O-socket
        listener.setSoTimeout(timeout);
        int port = listener.getLocalPort();

        // Set-up the JDI connection
        JdiInitiator jdii = new JdiInitiator(port,
                env.extraRemoteVMOptions(), remoteAgent, isLaunch, host,
                timeout, Collections.emptyMap());
        VirtualMachine vm = jdii.vm();
        Process process = jdii.process();

        List<Consumer<String>> deathListeners = new ArrayList<>();
        Util.detectJdiExitEvent(vm, s -> {
            for (Consumer<String> h : deathListeners) {
                h.accept(s);
            }
        });

        // Set-up the commands/reslts on the socket.  Piggy-back snippet
        // output.
        Socket socket = listener.accept();
        // out before in -- match remote creation so we don't hang
        OutputStream out = socket.getOutputStream();
        Map<String, OutputStream> outputs = new HashMap<>();
        outputs.put("out", env.userOut());
        outputs.put("err", env.userErr());
        Map<String, InputStream> input = new HashMap<>();
        input.put("in", env.userIn());
        return remoteInputOutput(socket.getInputStream(), out, outputs, input,
                (objIn, objOut) -> new JdiDefaultExecutionControl(env,
                                    objOut, objIn, vm, process, remoteAgent, deathListeners));
    }
}