forked from consulo/consulo-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebuggerManagerImpl.java
More file actions
537 lines (481 loc) · 21.5 KB
/
DebuggerManagerImpl.java
File metadata and controls
537 lines (481 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.debugger.impl;
import com.intellij.java.debugger.DebuggerManager;
import com.intellij.java.debugger.NameMapper;
import com.intellij.java.debugger.PositionManager;
import com.intellij.java.debugger.engine.DebugProcess;
import com.intellij.java.debugger.engine.DebugProcessListener;
import com.intellij.java.debugger.engine.DebuggerUtils;
import com.intellij.java.debugger.impl.apiAdapters.TransportServiceWrapper;
import com.intellij.java.debugger.impl.engine.DebugProcessEvents;
import com.intellij.java.debugger.impl.engine.DebugProcessImpl;
import com.intellij.java.debugger.impl.engine.DebuggerManagerThreadImpl;
import com.intellij.java.debugger.impl.engine.RemoteDebugProcessHandler;
import com.intellij.java.debugger.impl.settings.DebuggerSettings;
import com.intellij.java.debugger.impl.ui.GetJPDADialog;
import com.intellij.java.debugger.impl.ui.breakpoints.BreakpointManager;
import com.intellij.java.debugger.impl.ui.tree.render.BatchEvaluator;
import com.intellij.java.debugger.localize.JavaDebuggerLocalize;
import com.intellij.java.execution.configurations.RemoteConnection;
import com.intellij.java.language.impl.projectRoots.ex.JavaSdkUtil;
import com.intellij.java.language.projectRoots.JavaSdkVersion;
import com.intellij.java.language.psi.PsiClass;
import consulo.annotation.component.ServiceImpl;
import consulo.application.Application;
import consulo.application.progress.ProgressManager;
import consulo.component.persist.State;
import consulo.component.persist.Storage;
import consulo.component.persist.StoragePathMacros;
import consulo.content.bundle.Sdk;
import consulo.execution.ExecutionResult;
import consulo.java.execution.configurations.OwnJavaParameters;
import consulo.java.language.bundle.JavaSdkTypeUtil;
import consulo.logging.Logger;
import consulo.platform.Platform;
import consulo.process.ExecutionException;
import consulo.process.KillableProcessHandler;
import consulo.process.ProcessHandler;
import consulo.process.event.ProcessAdapter;
import consulo.process.event.ProcessEvent;
import consulo.project.Project;
import consulo.ui.UIAccess;
import consulo.ui.annotation.RequiredUIAccess;
import consulo.util.collection.Lists;
import consulo.util.collection.SmartList;
import consulo.util.lang.StringUtil;
import consulo.virtualFileSystem.VirtualFile;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javax.swing.*;
import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
@Singleton
@State(name = "DebuggerManager", storages = {@Storage(StoragePathMacros.WORKSPACE_FILE)})
@ServiceImpl
public class DebuggerManagerImpl extends DebuggerManagerEx {
private static final Logger LOG = Logger.getInstance(DebuggerManagerImpl.class);
private final Project myProject;
private final HashMap<ProcessHandler, DebuggerSession> mySessions = new HashMap<>();
private final BreakpointManager myBreakpointManager;
private final List<NameMapper> myNameMappers = Lists.newLockFreeCopyOnWriteList();
private final List<Function<DebugProcess, PositionManager>> myCustomPositionManagerFactories = new SmartList<>();
private final MyDebuggerStateManager myDebuggerStateManager = new MyDebuggerStateManager();
private final DebuggerContextListener mySessionListener = (newContext, event) -> {
DebuggerSession session = newContext.getDebuggerSession();
if (event == DebuggerSession.Event.PAUSE && myDebuggerStateManager.myDebuggerSession != session) {
// if paused in non-active session; switch current session
myDebuggerStateManager.setState(newContext, session != null ? session.getState() : DebuggerSession.State.DISPOSED, event);
return;
}
if (myDebuggerStateManager.myDebuggerSession == session) {
myDebuggerStateManager.fireStateChanged(newContext, event);
}
if (event == DebuggerSession.Event.ATTACHED) {
listener().sessionAttached(session);
}
else if (event == DebuggerSession.Event.DETACHED) {
listener().sessionDetached(session);
}
else if (event == DebuggerSession.Event.DISPOSE) {
dispose(session);
if (myDebuggerStateManager.myDebuggerSession == session) {
myDebuggerStateManager.setState(
DebuggerContextImpl.EMPTY_CONTEXT,
DebuggerSession.State.DISPOSED,
DebuggerSession.Event.DISPOSE
);
}
}
};
private static final String DEBUG_KEY_NAME = "idea.xdebug.key";
@Override
public void addClassNameMapper(NameMapper mapper) {
myNameMappers.add(mapper);
}
@Override
public void removeClassNameMapper(NameMapper mapper) {
myNameMappers.remove(mapper);
}
@Override
public String getVMClassQualifiedName(@Nonnull PsiClass aClass) {
for (NameMapper nameMapper : myNameMappers) {
String qName = nameMapper.getQualifiedName(aClass);
if (qName != null) {
return qName;
}
}
return aClass.getQualifiedName();
}
@Inject
public DebuggerManagerImpl(Project project) {
myProject = project;
myBreakpointManager = new BreakpointManager(myProject, this);
}
@Nonnull
private DebuggerManagerListener listener() {
return myProject.getMessageBus().syncPublisher(DebuggerManagerListener.class);
}
@Nullable
@Override
@RequiredUIAccess
public DebuggerSession getSession(DebugProcess process) {
UIAccess.assertIsUIThread();
return getSessions().stream().filter(debuggerSession -> process == debuggerSession.getProcess()).findFirst().orElse(null);
}
@Nonnull
@Override
public Collection<DebuggerSession> getSessions() {
synchronized (mySessions) {
Collection<DebuggerSession> values = mySessions.values();
return values.isEmpty() ? Collections.emptyList() : new ArrayList<>(values);
}
}
/**
* @deprecated to be removed with {@link DebuggerManager#registerPositionManagerFactory(Function)}
*/
@Deprecated
public Stream<Function<DebugProcess, PositionManager>> getCustomPositionManagerFactories() {
return myCustomPositionManagerFactories.stream();
}
@Override
@Nullable
@RequiredUIAccess
public DebuggerSession attachVirtualMachine(@Nonnull DebugEnvironment environment) throws ExecutionException {
UIAccess.assertIsUIThread();
DebugProcessEvents debugProcess = new DebugProcessEvents(myProject);
DebuggerSession session = DebuggerSession.create(environment.getSessionName(), debugProcess, environment);
ExecutionResult executionResult = session.getProcess().getExecutionResult();
if (executionResult == null) {
return null;
}
session.getContextManager().addListener(mySessionListener);
getContextManager().setState(
DebuggerContextUtil.createDebuggerContext(
session,
session.getContextManager().getContext().getSuspendContext()
),
session.getState(),
DebuggerSession.Event.CONTEXT
);
ProcessHandler processHandler = executionResult.getProcessHandler();
synchronized (mySessions) {
mySessions.put(processHandler, session);
}
if (!(processHandler instanceof RemoteDebugProcessHandler)) {
// add listener only to non-remote process handler:
// on Unix systems destroying process does not cause VMDeathEvent to be generated,
// so we need to call debugProcess.stop() explicitly for graceful termination.
// RemoteProcessHandler on the other hand will call debugProcess.stop() as a part of destroyProcess() and detachProcess() implementation,
// so we shouldn't add the listener to avoid calling stop() twice
processHandler.addProcessListener(new ProcessAdapter() {
@Override
public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
ProcessHandler processHandler = event.getProcessHandler();
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
// if current thread is a "debugger manager thread", stop will execute synchronously
// it is KillableProcessHandler responsibility to terminate VM
debugProcess.stop(
willBeDestroyed
&& !(processHandler instanceof KillableProcessHandler killableProcessHandler && killableProcessHandler.canKillProcess())
);
// wait at most 10 seconds: the problem is that debugProcess.stop() can hang if there are troubles in the debuggee
// if processWillTerminate() is called from AWT thread debugProcess.waitFor() will block it and the whole app will hang
if (!DebuggerManagerThreadImpl.isManagerThread()) {
if (SwingUtilities.isEventDispatchThread()) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(
() -> {
ProgressManager.getInstance()
.getProgressIndicator()
.setIndeterminate(true);
debugProcess.waitFor(10000);
},
"Waiting For Debugger Response",
false,
debugProcess.getProject()
);
}
else {
debugProcess.waitFor(10000);
}
}
}
}
});
}
listener().sessionCreated(session);
if (debugProcess.isDetached() || debugProcess.isDetaching()) {
session.dispose();
return null;
}
if (environment.isRemote()) {
// optimization: that way BatchEvaluator will not try to lookup the class file in remote VM
// which is an expensive operation when executed first time
debugProcess.putUserData(BatchEvaluator.REMOTE_SESSION_KEY, Boolean.TRUE);
}
return session;
}
@Override
public DebugProcessImpl getDebugProcess(ProcessHandler processHandler) {
synchronized (mySessions) {
DebuggerSession session = mySessions.get(processHandler);
return session != null ? session.getProcess() : null;
}
}
@SuppressWarnings("UnusedDeclaration")
@Nullable
public DebuggerSession getDebugSession(ProcessHandler processHandler) {
synchronized (mySessions) {
return mySessions.get(processHandler);
}
}
@Override
public void addDebugProcessListener(ProcessHandler processHandler, DebugProcessListener listener) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.addDebugProcessListener(listener);
}
else {
processHandler.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.addDebugProcessListener(listener);
}
processHandler.removeProcessListener(this);
}
});
}
}
@Override
public void removeDebugProcessListener(ProcessHandler processHandler, DebugProcessListener listener) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.removeDebugProcessListener(listener);
}
else {
processHandler.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
DebugProcessImpl debugProcess = getDebugProcess(processHandler);
if (debugProcess != null) {
debugProcess.removeDebugProcessListener(listener);
}
processHandler.removeProcessListener(this);
}
});
}
}
@Override
public boolean isDebuggerManagerThread() {
return DebuggerManagerThreadImpl.isManagerThread();
}
@Nonnull
@Override
public BreakpointManager getBreakpointManager() {
return myBreakpointManager;
}
@Nonnull
@Override
public DebuggerContextImpl getContext() {
return getContextManager().getContext();
}
@Nonnull
@Override
public DebuggerStateManager getContextManager() {
return myDebuggerStateManager;
}
@Override
public void registerPositionManagerFactory(Function<DebugProcess, PositionManager> factory) {
myCustomPositionManagerFactories.add(factory);
}
@Override
public void unregisterPositionManagerFactory(Function<DebugProcess, PositionManager> factory) {
myCustomPositionManagerFactories.remove(factory);
}
/* Remoting */
@RequiredUIAccess
private static void checkTargetJPDAInstalled(OwnJavaParameters parameters) throws ExecutionException {
Sdk jdk = parameters.getJdk();
if (jdk == null) {
throw new ExecutionException(JavaDebuggerLocalize.errorJdkNotSpecified().get());
}
JavaSdkVersion version = JavaSdkTypeUtil.getVersion(jdk);
String versionString = jdk.getVersionString();
if (version == JavaSdkVersion.JDK_1_0 || version == JavaSdkVersion.JDK_1_1) {
throw new ExecutionException(JavaDebuggerLocalize.errorUnsupportedJdkVersion(versionString).get());
}
if (Platform.current().os().isWindows() && version == JavaSdkVersion.JDK_1_2) {
VirtualFile homeDirectory = jdk.getHomeDirectory();
if (homeDirectory == null || !homeDirectory.isValid()) {
throw new ExecutionException(JavaDebuggerLocalize.errorInvalidJdkHome(versionString).get());
}
//noinspection HardCodedStringLiteral
File dllFile = new File(
homeDirectory.getPath().replace('/', File.separatorChar) +
File.separator + "bin" + File.separator + "jdwp.dll"
);
if (!dllFile.exists()) {
GetJPDADialog dialog = new GetJPDADialog();
dialog.show();
throw new ExecutionException(JavaDebuggerLocalize.errorDebugLibrariesMissing().get());
}
}
}
/**
* for Target JDKs versions 1.2.x - 1.3.0 the Classic VM should be used for debugging
*/
@Deprecated
private static boolean shouldForceClassicVM(Sdk jdk) {
return false;
}
@RequiredUIAccess
@SuppressWarnings({"HardCodedStringLiteral"})
public static RemoteConnection createDebugParameters(
OwnJavaParameters parameters,
boolean debuggerInServerMode,
int transport,
String debugPort,
boolean checkValidity
) throws ExecutionException {
if (checkValidity) {
checkTargetJPDAInstalled(parameters);
}
boolean useSockets = transport == DebuggerSettings.SOCKET_TRANSPORT;
String address = "";
if (StringUtil.isEmptyOrSpaces(debugPort)) {
try {
address = DebuggerUtils.getInstance().findAvailableDebugAddress(transport).address();
}
catch (ExecutionException e) {
if (checkValidity) {
throw e;
}
}
}
else {
address = debugPort;
}
TransportServiceWrapper transportService = TransportServiceWrapper.createTransportService(transport);
String debugAddress = debuggerInServerMode && useSockets ? "127.0.0.1:" + address : address;
String debuggeeRunProperties = "transport=" + transportService.transportId() + ",address=" + debugAddress;
if (debuggerInServerMode) {
debuggeeRunProperties += ",suspend=y,server=n";
}
else {
debuggeeRunProperties += ",suspend=n,server=y";
}
if (StringUtil.containsWhitespaces(debuggeeRunProperties)) {
debuggeeRunProperties = "\"" + debuggeeRunProperties + "\"";
}
String _debuggeeRunProperties = debuggeeRunProperties;
Application.get().runReadAction(() -> {
JavaSdkUtil.addRtJar(parameters.getClassPath());
Sdk jdk = parameters.getJdk();
boolean forceClassicVM = shouldForceClassicVM(jdk);
boolean forceNoJIT = shouldForceNoJIT(jdk);
String debugKey = Platform.current().jvm().getRuntimeProperty(DEBUG_KEY_NAME, "-Xdebug");
boolean needDebugKey = shouldAddXdebugKey(jdk) || !"-Xdebug".equals(debugKey) /*the key is non-standard*/;
if (forceClassicVM || forceNoJIT || needDebugKey || !isJVMTIAvailable(jdk)) {
parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", "-Xrunjdwp:" + _debuggeeRunProperties);
}
else {
// use newer JVMTI if available
parameters.getVMParametersList().replaceOrPrepend("-Xrunjdwp:", "");
parameters.getVMParametersList().replaceOrPrepend("-agentlib:jdwp=", "-agentlib:jdwp=" + _debuggeeRunProperties);
}
if (forceNoJIT) {
parameters.getVMParametersList().replaceOrPrepend("-Djava.compiler=", "-Djava.compiler=NONE");
parameters.getVMParametersList().replaceOrPrepend("-Xnoagent", "-Xnoagent");
}
if (needDebugKey) {
parameters.getVMParametersList().replaceOrPrepend(debugKey, debugKey);
}
else {
// deliberately skip outdated parameter because it can disable full-speed debugging for some jdk builds
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6272174
parameters.getVMParametersList().replaceOrPrepend("-Xdebug", "");
}
parameters.getVMParametersList().replaceOrPrepend("-classic", forceClassicVM ? "-classic" : "");
});
return new RemoteConnection(useSockets, "127.0.0.1", address, debuggerInServerMode);
}
@Deprecated
private static boolean shouldForceNoJIT(Sdk jdk) {
return DebuggerSettings.getInstance().DISABLE_JIT;
}
@Deprecated
private static boolean shouldAddXdebugKey(Sdk jdk) {
if (jdk == null) {
return true; // conservative choice
}
return DebuggerSettings.getInstance().DISABLE_JIT;
}
@Deprecated
private static boolean isJVMTIAvailable(Sdk jdk) {
if (jdk == null) {
return false; // conservative choice
}
return true;
}
@RequiredUIAccess
public static RemoteConnection createDebugParameters(
OwnJavaParameters parameters,
GenericDebuggerRunnerSettings settings,
boolean checkValidity
) throws ExecutionException {
return createDebugParameters(parameters, settings.LOCAL, settings.getTransport(), settings.getDebugPort(), checkValidity);
}
private static class MyDebuggerStateManager extends DebuggerStateManager {
private DebuggerSession myDebuggerSession;
@Nonnull
@Override
public DebuggerContextImpl getContext() {
return myDebuggerSession == null ? DebuggerContextImpl.EMPTY_CONTEXT : myDebuggerSession.getContextManager().getContext();
}
@Override
@RequiredUIAccess
public void setState(
@Nonnull DebuggerContextImpl context,
DebuggerSession.State state,
DebuggerSession.Event event,
String description
) {
UIAccess.assertIsUIThread();
myDebuggerSession = context.getDebuggerSession();
if (myDebuggerSession != null) {
myDebuggerSession.getContextManager().setState(context, state, event, description);
}
else {
fireStateChanged(context, event);
}
}
}
private void dispose(DebuggerSession session) {
ProcessHandler processHandler = session.getProcess().getProcessHandler();
synchronized (mySessions) {
DebuggerSession removed = mySessions.remove(processHandler);
LOG.assertTrue(removed != null);
listener().sessionRemoved(session);
}
}
}