Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,31 @@ public CompletableFuture<Messages.Response> dispatchRequest(Messages.Request req
response.success = true;

Command command = Command.parse(request.command);
Arguments cmdArgs = JsonUtils.fromJson(request.arguments, command.getArgumentType());

if (debugContext.isVmTerminated() && command != Command.DISCONNECT) {
return CompletableFuture.completedFuture(response);
}
if (!debugContext.isInitialized()
&& command != Command.INITIALIZE
&& command != Command.DISCONNECT
&& command != Command.UNSUPPORTED) {
final String errorMessage = String.format(
"'%s' request is rejected since the debug session has not been initialized yet.", request.command);
logger.log(Level.SEVERE, errorMessage);
ErrorCode errorCode = ErrorCode.SESSION_NOT_INITIALIZED;
if (command == Command.LAUNCH) {
errorCode = ErrorCode.LAUNCH_FAILURE;
} else if (command == Command.ATTACH) {
errorCode = ErrorCode.ATTACH_FAILURE;
}
return AdapterUtils.createAsyncErrorResponse(response, errorCode, errorMessage);
}
if (debugContext.isInitialized() && command == Command.INITIALIZE) {
final String errorMessage = "'initialize' request is rejected since the debug session has already been initialized.";
logger.log(Level.SEVERE, errorMessage);
return AdapterUtils.createAsyncErrorResponse(response, ErrorCode.UNKNOWN_FAILURE, errorMessage);
}
Arguments cmdArgs = JsonUtils.fromJson(request.arguments, command.getArgumentType());
List<IDebugRequestHandler> handlers = this.debugContext.getLaunchMode() == LaunchMode.DEBUG
? requestHandlersForDebug.get(command) : requestHandlersForNoDebug.get(command);
if (handlers != null && !handlers.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ public enum ErrorCode {
EVALUATION_COMPILE_ERROR(2001),
EVALUATE_NOT_SUSPENDED_THREAD(2002),
HCR_FAILURE(3001),
INVALID_DAP_HEADER(3002);
INVALID_DAP_HEADER(3002),
SESSION_NOT_INITIALIZED(3003);

private int id;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.microsoft.java.debug.core.Configuration;
Expand Down Expand Up @@ -55,6 +56,12 @@ public List<Command> getTargetCommands() {

@Override
public CompletableFuture<Response> handle(Command command, Arguments arguments, Response response, IDebugAdapterContext context) {
if (!context.isInitialized()) {
final String errorMessage = "'attach' request is rejected since the debug session has not been initialized yet.";
logger.log(Level.SEVERE, errorMessage);
return CompletableFuture.completedFuture(
AdapterUtils.setErrorResponse(response, ErrorCode.SESSION_NOT_INITIALIZED, errorMessage));
}
AttachArguments attachArguments = (AttachArguments) arguments;
context.setAttached(true);
context.setSourcePaths(attachArguments.sourcePaths);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@ static void terminate(IDebugAdapterContext context) {
Process debuggeeProcess = context.getDebuggeeProcess();
if (debuggeeProcess != null) {
debuggeeProcess.destroy();
} else if (context.getProcessId() > 0) {
Optional<ProcessHandle> debuggeeHandle = ProcessHandle.of(context.getProcessId());
if (debuggeeHandle.isPresent()) {
debuggeeHandle.get().destroy();
} else {
long pid = context.getProcessId();
if (pid > 0 && pid != ProcessHandle.current().pid()) {
Optional<ProcessHandle> debuggeeHandle = ProcessHandle.of(pid);
if (debuggeeHandle.isPresent()) {
debuggeeHandle.get().destroy();
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,23 @@ public CompletableFuture<Response> launchInTerminal(LaunchArguments launchArgume
vmHandler.setVmProvider(vmProvider);
final String launchInTerminalErrorFormat = "Failed to launch debuggee in terminal. Reason: %s";

ListeningConnector listenConnector = null;
Map<String, Connector.Argument> args = null;
boolean listenerStarted = false;
try {
List<ListeningConnector> connectors = vmProvider.getVirtualMachineManager().listeningConnectors();
ListeningConnector listenConnector = connectors.get(0);
Map<String, Connector.Argument> args = listenConnector.defaultArguments();
listenConnector = connectors.get(0);
args = listenConnector.defaultArguments();
((Connector.IntegerArgument) args.get("timeout")).setValue(ATTACH_TERMINAL_TIMEOUT);
Connector.Argument localAddress = args.get("localAddress");
if (localAddress != null) {
localAddress.setValue("127.0.0.1");
}
String address = listenConnector.startListening(args);
listenerStarted = true;

final ListeningConnector activeConnector = listenConnector;
final Map<String, Connector.Argument> activeArgs = args;
final String[] names = launchArguments.mainClass.split("[/\\.]");
final String terminalName = "Debug: " + names[names.length - 1];
String[] cmds = LaunchRequestHandler.constructLaunchCommands(launchArguments, false, address);
Expand All @@ -102,81 +112,89 @@ public CompletableFuture<Response> launchInTerminal(LaunchArguments launchArgume
// the local .m2 repository path, it may exceed the limit.
context.getProtocolServer().sendRequest(request, RUNINTERMINAL_TIMEOUT)
.whenComplete((runResponse, ex) -> {
if (runResponse != null) {
if (runResponse.success) {
try {
try {
if (runResponse != null) {
if (runResponse.success) {
try {
RunInTerminalResponseBody terminalResponse = JsonUtils.fromJson(
JsonUtils.toJson(runResponse.body), RunInTerminalResponseBody.class);
context.setProcessId(terminalResponse.processId);
context.setShellProcessId(terminalResponse.shellProcessId);
} catch (JsonSyntaxException e) {
logger.severe("Failed to resolve runInTerminal response: " + e.toString());
}
VirtualMachine vm = listenConnector.accept(args);
vmHandler.connectVirtualMachine(vm);
context.setDebugSession(new DebugSession(vm));
logger.info("Launching debuggee in terminal console succeeded.");
if (context.getShellProcessId() > 0) {
ProcessHandle debuggeeProcess = LaunchUtils.findJavaProcessInTerminalShell(context.getShellProcessId(), cmds[0], 0);
if (debuggeeProcess != null) {
context.setProcessId(debuggeeProcess.pid());
try {
RunInTerminalResponseBody terminalResponse = JsonUtils.fromJson(
JsonUtils.toJson(runResponse.body), RunInTerminalResponseBody.class);
context.setProcessId(terminalResponse.processId);
context.setShellProcessId(terminalResponse.shellProcessId);
} catch (JsonSyntaxException e) {
logger.severe("Failed to resolve runInTerminal response: " + e.toString());
}
VirtualMachine vm = activeConnector.accept(activeArgs);
vmHandler.connectVirtualMachine(vm);
context.setDebugSession(new DebugSession(vm));
logger.info("Launching debuggee in terminal console succeeded.");
if (context.getShellProcessId() > 0) {
ProcessHandle debuggeeProcess = LaunchUtils.findJavaProcessInTerminalShell(
context.getShellProcessId(), cmds[0], 0);
if (debuggeeProcess != null) {
context.setProcessId(debuggeeProcess.pid());
}
}
resultFuture.complete(response);
} catch (TransportTimeoutException e) {
int commandLength = StringUtils.length(launchArguments.cwd) + 1;
for (String cmd : cmds) {
commandLength += StringUtils.length(cmd) + 1;
}
}
resultFuture.complete(response);
} catch (TransportTimeoutException e) {
int commandLength = StringUtils.length(launchArguments.cwd) + 1;
for (String cmd : cmds) {
commandLength += StringUtils.length(cmd) + 1;
}

final int threshold = SystemUtils.IS_OS_WINDOWS ? 8092 : 32 * 1024;
String errorMessage = String.format(launchInTerminalErrorFormat, e.toString());
if (commandLength >= threshold) {
errorMessage = "Failed to launch debuggee in terminal. The possible reason is the command line too long. "
+ "More details: " + e.toString();
logger.severe(errorMessage
+ "\r\n"
+ "The estimated command line length is " + commandLength + ". "
+ "Try to enable shortenCommandLine option in the debug launch configuration.");
}
final int threshold = SystemUtils.IS_OS_WINDOWS ? 8092 : 32 * 1024;
String errorMessage = String.format(launchInTerminalErrorFormat, e.toString());
if (commandLength >= threshold) {
errorMessage = "Failed to launch debuggee in terminal. The possible reason is the command line too long. "
+ "More details: " + e.toString();
logger.severe(errorMessage
+ "\r\n"
+ "The estimated command line length is " + commandLength + ". "
+ "Try to enable shortenCommandLine option in the debug launch configuration.");
}

resultFuture.completeExceptionally(
new DebugException(
errorMessage,
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
)
);
} catch (IOException | IllegalConnectorArgumentsException e) {
resultFuture.completeExceptionally(
new DebugException(
String.format(launchInTerminalErrorFormat, e.toString()),
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
)
);
}
} else {
resultFuture.completeExceptionally(
new DebugException(
errorMessage,
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
)
);
} catch (IOException | IllegalConnectorArgumentsException e) {
resultFuture.completeExceptionally(
new DebugException(
String.format(launchInTerminalErrorFormat, e.toString()),
String.format(launchInTerminalErrorFormat, runResponse.message),
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
)
);
}
} else {
if (ex instanceof CompletionException && ex.getCause() != null) {
ex = ex.getCause();
}
String errorMessage = String.format(launchInTerminalErrorFormat, ex != null ? ex.toString() : "Null response");
resultFuture.completeExceptionally(
new DebugException(
String.format(launchInTerminalErrorFormat, runResponse.message),
String.format(launchInTerminalErrorFormat, errorMessage),
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
)
);
}
} else {
if (ex instanceof CompletionException && ex.getCause() != null) {
ex = ex.getCause();
}
String errorMessage = String.format(launchInTerminalErrorFormat, ex != null ? ex.toString() : "Null response");
resultFuture.completeExceptionally(
new DebugException(
String.format(launchInTerminalErrorFormat, errorMessage),
ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId()
)
);
} finally {
stopListeningQuietly(activeConnector, activeArgs);
}
});
} catch (IOException | IllegalConnectorArgumentsException e) {
} catch (IOException | IllegalConnectorArgumentsException | RuntimeException e) {
if (listenerStarted) {
stopListeningQuietly(listenConnector, args);
}
resultFuture.completeExceptionally(
new DebugException(
String.format(launchInTerminalErrorFormat, e.toString()),
Expand Down Expand Up @@ -246,4 +264,15 @@ public void preLaunch(LaunchArguments launchArguments, IDebugAdapterContext cont
context.setMainClass(LaunchRequestHandler.parseMainClassWithoutModuleName(launchArguments.mainClass));
context.setStepFilters(launchArguments.stepFilters);
}

private static void stopListeningQuietly(ListeningConnector connector, Map<String, Connector.Argument> args) {
if (connector == null) {
return;
}
try {
connector.stopListening(args);
} catch (IOException | IllegalConnectorArgumentsException e) {
logger.fine("Failed to close JDI listening socket: " + e.toString());
}
}
}
Loading
Loading