Debug java program without command line arguments

59 Views Asked by At

I have written a java program that is run by an executable (which I cannot edit). Thus, I can't provide the usual JVM command line arguments for debugging since the JVM is started by the executable.

I have written the following code in my java program:

import com.sun.jdi.Bootstrap;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.ListeningConnector;
import com.sun.jdi.connect.Connector.Argument;
import java.util.Map;

public class DebugStarter {

    private static final int ACCEPT_TIMEOUT = 20000; // 20 seconds
    private static final int PORT = 8000;

    public static void StartDebugger() throws Exception {
        System.out.println("Starting JVM debugger...");
        ListeningConnector connector = Bootstrap.virtualMachineManager().listeningConnectors().stream()
                .filter(c -> c.transport().name().equals("dt_socket"))
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("No dt_socket connector found"));
        
        Map<String, Argument> arguments = connector.defaultArguments();
        arguments.get("port").setValue(String.valueOf(PORT));;
        arguments.get("timeout").setValue(String.valueOf(ACCEPT_TIMEOUT));;
        arguments.get("localAddress").setValue(String.valueOf("localhost"));;
        
        System.out.println("Custom arguments:");
        System.out.println(arguments);
        for (Map.Entry<String, Argument> entry : arguments.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue().value());
        }
        
        System.out.println("Waiting for debugger to connect on port " + arguments);

       VirtualMachine vm = connector.accept(arguments);

        System.out.println("Debugger connected!");

    }
}

It is simply run in my java program with the line DebugStarter.StartDebugger();.

The program pauses on the line VirtualMachine vm = connector.accept(arguments); to wait for the debugger to connect. I have written the following in my VsCode launch.json:

{
            "type": "java",
            "name": "Debug (Attach) - Remote",
            "request": "attach",
            "hostName": "localhost",
            "port": 8000
        }

But when I run the VsCode debugger with the above configuration, the program prints Ignoring cmd 23/1/7 from the VM. Then, after about 1 second, the VsCode debugger prints Timeout occurred while waiting for packet 23. Vscode debugger error and at the same time, the program prints

Ignoring cmd 24/1/6 from the VM

The values 23 and 24 are increased each time the program is run. On the next try, the values are 26 and 27.

0

There are 0 best solutions below