use visibleClasses() API method as a final resort in determining visibility of a...
[fedora-idea.git] / java / debugger / impl / src / com / intellij / debugger / engine / DebugProcessImpl.java
blob93a69ceb1abc0c02678d8186a8f6de56de13d80d
1 /*
2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com.intellij.debugger.engine;
18 import com.intellij.Patches;
19 import com.intellij.debugger.DebuggerBundle;
20 import com.intellij.debugger.DebuggerInvocationUtil;
21 import com.intellij.debugger.DebuggerManagerEx;
22 import com.intellij.debugger.PositionManager;
23 import com.intellij.debugger.actions.DebuggerActions;
24 import com.intellij.debugger.apiAdapters.ConnectionServiceWrapper;
25 import com.intellij.debugger.apiAdapters.TransportServiceWrapper;
26 import com.intellij.debugger.engine.evaluation.*;
27 import com.intellij.debugger.engine.events.DebuggerCommandImpl;
28 import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
29 import com.intellij.debugger.engine.jdi.ThreadReferenceProxy;
30 import com.intellij.debugger.engine.requests.MethodReturnValueWatcher;
31 import com.intellij.debugger.engine.requests.RequestManagerImpl;
32 import com.intellij.debugger.impl.DebuggerContextImpl;
33 import com.intellij.debugger.impl.DebuggerSession;
34 import com.intellij.debugger.impl.DebuggerUtilsEx;
35 import com.intellij.debugger.impl.PrioritizedTask;
36 import com.intellij.debugger.jdi.StackFrameProxyImpl;
37 import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
38 import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
39 import com.intellij.debugger.settings.DebuggerSettings;
40 import com.intellij.debugger.settings.NodeRendererSettings;
41 import com.intellij.debugger.ui.breakpoints.BreakpointManager;
42 import com.intellij.debugger.ui.breakpoints.RunToCursorBreakpoint;
43 import com.intellij.debugger.ui.tree.ValueDescriptor;
44 import com.intellij.debugger.ui.tree.render.*;
45 import com.intellij.execution.CantRunException;
46 import com.intellij.execution.ExecutionException;
47 import com.intellij.execution.ExecutionResult;
48 import com.intellij.execution.Executor;
49 import com.intellij.execution.configurations.CommandLineState;
50 import com.intellij.execution.configurations.RemoteConnection;
51 import com.intellij.execution.configurations.RunProfileState;
52 import com.intellij.execution.filters.ExceptionFilter;
53 import com.intellij.execution.filters.TextConsoleBuilder;
54 import com.intellij.execution.process.ProcessAdapter;
55 import com.intellij.execution.process.ProcessEvent;
56 import com.intellij.execution.process.ProcessListener;
57 import com.intellij.execution.process.ProcessOutputTypes;
58 import com.intellij.execution.runners.ProgramRunner;
59 import com.intellij.execution.runners.ProgramRunnerUtil;
60 import com.intellij.idea.ActionsBundle;
61 import com.intellij.openapi.application.ApplicationManager;
62 import com.intellij.openapi.diagnostic.Logger;
63 import com.intellij.openapi.editor.Document;
64 import com.intellij.openapi.extensions.Extensions;
65 import com.intellij.openapi.project.Project;
66 import com.intellij.openapi.ui.Messages;
67 import com.intellij.openapi.util.Comparing;
68 import com.intellij.openapi.util.Key;
69 import com.intellij.openapi.util.Pair;
70 import com.intellij.openapi.util.Ref;
71 import com.intellij.openapi.wm.WindowManager;
72 import com.intellij.psi.PsiDocumentManager;
73 import com.intellij.psi.PsiFile;
74 import com.intellij.psi.search.GlobalSearchScope;
75 import com.intellij.ui.classFilter.ClassFilter;
76 import com.intellij.ui.classFilter.DebuggerClassFilterProvider;
77 import com.intellij.util.Alarm;
78 import com.intellij.util.EventDispatcher;
79 import com.intellij.util.StringBuilderSpinAllocator;
80 import com.intellij.util.concurrency.Semaphore;
81 import com.sun.jdi.*;
82 import com.sun.jdi.connect.*;
83 import com.sun.jdi.request.EventRequest;
84 import com.sun.jdi.request.EventRequestManager;
85 import com.sun.jdi.request.StepRequest;
86 import org.jetbrains.annotations.NonNls;
87 import org.jetbrains.annotations.NotNull;
88 import org.jetbrains.annotations.Nullable;
90 import javax.swing.*;
91 import java.io.IOException;
92 import java.net.UnknownHostException;
93 import java.util.*;
94 import java.util.concurrent.atomic.AtomicBoolean;
95 import java.util.concurrent.atomic.AtomicInteger;
97 public abstract class DebugProcessImpl implements DebugProcess {
98 private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.DebugProcessImpl");
100 static final @NonNls String SOCKET_ATTACHING_CONNECTOR_NAME = "com.sun.jdi.SocketAttach";
101 static final @NonNls String SHMEM_ATTACHING_CONNECTOR_NAME = "com.sun.jdi.SharedMemoryAttach";
102 static final @NonNls String SOCKET_LISTENING_CONNECTOR_NAME = "com.sun.jdi.SocketListen";
103 static final @NonNls String SHMEM_LISTENING_CONNECTOR_NAME = "com.sun.jdi.SharedMemoryListen";
105 private final Project myProject;
106 private final RequestManagerImpl myRequestManager;
108 private VirtualMachineProxyImpl myVirtualMachineProxy = null;
109 protected EventDispatcher<DebugProcessListener> myDebugProcessDispatcher = EventDispatcher.create(DebugProcessListener.class);
110 protected EventDispatcher<EvaluationListener> myEvaluationDispatcher = EventDispatcher.create(EvaluationListener.class);
112 private final List<ProcessListener> myProcessListeners = new ArrayList<ProcessListener>();
114 protected static final int STATE_INITIAL = 0;
115 protected static final int STATE_ATTACHED = 1;
116 protected static final int STATE_DETACHING = 2;
117 protected static final int STATE_DETACHED = 3;
118 protected final AtomicInteger myState = new AtomicInteger(STATE_INITIAL);
120 private ExecutionResult myExecutionResult;
121 private RemoteConnection myConnection;
123 private ConnectionServiceWrapper myConnectionService;
124 private Map<String, Connector.Argument> myArguments;
126 private final List<NodeRenderer> myRenderers = new ArrayList<NodeRenderer>();
127 private final Map<Type, NodeRenderer> myNodeRederersMap = new com.intellij.util.containers.HashMap<Type, NodeRenderer>();
128 private final NodeRendererSettingsListener mySettingsListener = new NodeRendererSettingsListener() {
129 public void renderersChanged() {
130 myNodeRederersMap.clear();
131 myRenderers.clear();
132 loadRenderers();
136 private final SuspendManagerImpl mySuspendManager = new SuspendManagerImpl(this);
137 protected CompoundPositionManager myPositionManager = null;
138 private volatile DebuggerManagerThreadImpl myDebuggerManagerThread;
139 private final HashMap myUserData = new HashMap();
140 private static final int LOCAL_START_TIMEOUT = 15000;
142 private final Semaphore myWaitFor = new Semaphore();
143 private final AtomicBoolean myBreakpointsMuted = new AtomicBoolean(false);
144 private boolean myIsFailed = false;
145 protected DebuggerSession mySession;
146 protected @Nullable MethodReturnValueWatcher myReturnValueWatcher;
147 private final Alarm myStatusUpdateAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
149 protected DebugProcessImpl(Project project) {
150 myProject = project;
151 myRequestManager = new RequestManagerImpl(this);
152 NodeRendererSettings.getInstance().addListener(mySettingsListener);
153 loadRenderers();
156 private void loadRenderers() {
157 getManagerThread().invoke(new DebuggerCommandImpl() {
158 protected void action() throws Exception {
159 final NodeRendererSettings rendererSettings = NodeRendererSettings.getInstance();
160 for (final NodeRenderer renderer : rendererSettings.getAllRenderers()) {
161 if (renderer.isEnabled()) {
162 myRenderers.add(renderer);
169 @Nullable
170 public Pair<Method, Value> getLastExecutedMethod() {
171 if (myReturnValueWatcher == null) {
172 return null;
174 final Method method = myReturnValueWatcher.getLastExecutedMethod();
175 if (method == null) {
176 return null;
178 return new Pair<Method, Value>(method, myReturnValueWatcher.getLastMethodReturnValue());
181 public void setWatchMethodReturnValuesEnabled(boolean enabled) {
182 if (myReturnValueWatcher != null) {
183 myReturnValueWatcher.setFeatureEnabled(enabled);
187 public boolean isWatchMethodReturnValuesEnabled() {
188 return myReturnValueWatcher != null && myReturnValueWatcher.isFeatureEnabled();
191 public boolean canGetMethodReturnValue() {
192 return myReturnValueWatcher != null;
195 public NodeRenderer getAutoRenderer(ValueDescriptor descriptor) {
196 DebuggerManagerThreadImpl.assertIsManagerThread();
197 final Value value = descriptor.getValue();
198 Type type = value != null ? value.type() : null;
200 // in case evaluation is not possible, force default renderer
201 if (!DebuggerManagerEx.getInstanceEx(getProject()).getContext().isEvaluationPossible()) {
202 return getDefaultRenderer(type);
205 NodeRenderer renderer = myNodeRederersMap.get(type);
206 if(renderer == null) {
207 for (final NodeRenderer nodeRenderer : myRenderers) {
208 if (nodeRenderer.isApplicable(type)) {
209 renderer = nodeRenderer;
210 break;
213 if (renderer == null) {
214 renderer = getDefaultRenderer(type);
216 myNodeRederersMap.put(type, renderer);
219 return renderer;
222 public final NodeRenderer getDefaultRenderer(Value value) {
223 return getDefaultRenderer((value != null) ? value.type() : (Type)null);
226 public final NodeRenderer getDefaultRenderer(Type type) {
227 final NodeRendererSettings settings = NodeRendererSettings.getInstance();
229 final PrimitiveRenderer primitiveRenderer = settings.getPrimitiveRenderer();
230 if(primitiveRenderer.isApplicable(type)) {
231 return primitiveRenderer;
234 final ArrayRenderer arrayRenderer = settings.getArrayRenderer();
235 if(arrayRenderer.isApplicable(type)) {
236 return arrayRenderer;
239 final ClassRenderer classRenderer = settings.getClassRenderer();
240 LOG.assertTrue(classRenderer.isApplicable(type), type.name());
241 return classRenderer;
245 @SuppressWarnings({"HardCodedStringLiteral"})
246 protected void commitVM(VirtualMachine vm) {
247 if (!isInInitialState()) {
248 LOG.assertTrue(false, "State is invalid " + myState.get());
250 DebuggerManagerThreadImpl.assertIsManagerThread();
251 myPositionManager = createPositionManager();
252 if (LOG.isDebugEnabled()) {
253 LOG.debug("*******************VM attached******************");
255 checkVirtualMachineVersion(vm);
257 myVirtualMachineProxy = new VirtualMachineProxyImpl(this, vm);
259 String trace = System.getProperty("idea.debugger.trace");
260 if (trace != null) {
261 int mask = 0;
262 StringTokenizer tokenizer = new StringTokenizer(trace);
263 while (tokenizer.hasMoreTokens()) {
264 String token = tokenizer.nextToken();
265 if ("SENDS".compareToIgnoreCase(token) == 0) {
266 mask |= VirtualMachine.TRACE_SENDS;
268 else if ("RAW_SENDS".compareToIgnoreCase(token) == 0) {
269 mask |= 0x01000000;
271 else if ("RECEIVES".compareToIgnoreCase(token) == 0) {
272 mask |= VirtualMachine.TRACE_RECEIVES;
274 else if ("RAW_RECEIVES".compareToIgnoreCase(token) == 0) {
275 mask |= 0x02000000;
277 else if ("EVENTS".compareToIgnoreCase(token) == 0) {
278 mask |= VirtualMachine.TRACE_EVENTS;
280 else if ("REFTYPES".compareToIgnoreCase(token) == 0) {
281 mask |= VirtualMachine.TRACE_REFTYPES;
283 else if ("OBJREFS".compareToIgnoreCase(token) == 0) {
284 mask |= VirtualMachine.TRACE_OBJREFS;
286 else if ("ALL".compareToIgnoreCase(token) == 0) {
287 mask |= VirtualMachine.TRACE_ALL;
291 vm.setDebugTraceMode(mask);
295 private void stopConnecting() {
296 DebuggerManagerThreadImpl.assertIsManagerThread();
298 Map arguments = myArguments;
299 try {
300 if (arguments == null) {
301 return;
303 if(myConnection.isServerMode()) {
304 ListeningConnector connector = (ListeningConnector)findConnector(SOCKET_LISTENING_CONNECTOR_NAME);
305 if (connector == null) {
306 LOG.error("Cannot find connector: " + SOCKET_LISTENING_CONNECTOR_NAME);
308 connector.stopListening(arguments);
310 else {
311 if(myConnectionService != null) {
312 myConnectionService.close();
316 catch (IOException e) {
317 if (LOG.isDebugEnabled()) {
318 LOG.debug(e);
321 catch (IllegalConnectorArgumentsException e) {
322 if (LOG.isDebugEnabled()) {
323 LOG.debug(e);
326 catch (ExecutionException e) {
327 LOG.error(e);
329 finally {
330 closeProcess(true);
334 protected CompoundPositionManager createPositionManager() {
335 return new CompoundPositionManager(new PositionManagerImpl(this));
338 public void printToConsole(final String text) {
339 myExecutionResult.getProcessHandler().notifyTextAvailable(text, ProcessOutputTypes.SYSTEM);
344 * @param suspendContext
345 * @param stepThread
346 * @param depth
347 * @param hint may be null
349 protected void doStep(final SuspendContextImpl suspendContext, final ThreadReferenceProxyImpl stepThread, int depth, RequestHint hint) {
350 if (stepThread == null) {
351 return;
353 try {
354 if (LOG.isDebugEnabled()) {
355 LOG.debug("DO_STEP: creating step request for " + stepThread.getThreadReference());
357 deleteStepRequests();
358 EventRequestManager requestManager = getVirtualMachineProxy().eventRequestManager();
359 StepRequest stepRequest = requestManager.createStepRequest(stepThread.getThreadReference(), StepRequest.STEP_LINE, depth);
360 DebuggerSettings settings = DebuggerSettings.getInstance();
361 if (!(hint != null && hint.isIgnoreFilters()) /*&& depth == StepRequest.STEP_INTO*/) {
362 final String currentClassName = getCurrentClassName(stepThread);
363 final List<ClassFilter> activeFilters = new ArrayList<ClassFilter>();
364 if (settings.TRACING_FILTERS_ENABLED) {
365 for (ClassFilter filter : settings.getSteppingFilters()) {
366 if (filter.isEnabled()) {
367 activeFilters.add(filter);
371 for (DebuggerClassFilterProvider provider : Extensions.getExtensions(DebuggerClassFilterProvider.EP_NAME)) {
372 for (ClassFilter filter : provider.getFilters()) {
373 if (filter.isEnabled()) {
374 activeFilters.add(filter);
379 if (currentClassName == null || !DebuggerUtilsEx.isFiltered(currentClassName, activeFilters)) {
380 // add class filters
381 for (ClassFilter filter : activeFilters) {
382 stepRequest.addClassExclusionFilter(filter.getPattern());
387 // suspend policy to match the suspend policy of the context:
388 // if all threads were suspended, then during stepping all the threads must be suspended
389 // if only event thread were suspended, then only this particular thread must be suspended during stepping
390 stepRequest.setSuspendPolicy(suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD? EventRequest.SUSPEND_EVENT_THREAD : EventRequest.SUSPEND_ALL);
392 if (hint != null) {
393 //noinspection HardCodedStringLiteral
394 stepRequest.putProperty("hint", hint);
396 stepRequest.enable();
398 catch (ObjectCollectedException ignored) {
403 void deleteStepRequests() {
404 EventRequestManager requestManager = getVirtualMachineProxy().eventRequestManager();
405 List<StepRequest> stepRequests = requestManager.stepRequests();
406 if (stepRequests.size() > 0) {
407 final List<StepRequest> toDelete = new ArrayList<StepRequest>(stepRequests.size());
408 for (final StepRequest request : stepRequests) {
409 ThreadReference threadReference = request.thread();
410 // [jeka] on attempt to delete a request assigned to a thread with unknown status, a JDWP error occures
411 if (threadReference.status() != ThreadReference.THREAD_STATUS_UNKNOWN) {
412 toDelete.add(request);
415 requestManager.deleteEventRequests(toDelete);
419 @Nullable
420 private static String getCurrentClassName(ThreadReferenceProxyImpl thread) {
421 try {
422 if (thread != null && thread.frameCount() > 0) {
423 StackFrameProxyImpl stackFrame = thread.frame(0);
424 Location location = stackFrame.location();
425 ReferenceType referenceType = location.declaringType();
426 if (referenceType != null) {
427 return referenceType.name();
431 catch (EvaluateException e) {
433 return null;
436 private VirtualMachine createVirtualMachineInt() throws ExecutionException {
437 try {
438 if (myArguments != null) {
439 throw new IOException(DebuggerBundle.message("error.debugger.already.listening"));
442 final String address = myConnection.getAddress();
443 if (myConnection.isServerMode()) {
444 ListeningConnector connector = (ListeningConnector)findConnector(
445 myConnection.isUseSockets() ? SOCKET_LISTENING_CONNECTOR_NAME : SHMEM_LISTENING_CONNECTOR_NAME);
446 if (connector == null) {
447 throw new CantRunException(DebuggerBundle.message("error.debug.connector.not.found", DebuggerBundle.getTransportName(myConnection)));
449 myArguments = connector.defaultArguments();
450 if (myArguments == null) {
451 throw new CantRunException(DebuggerBundle.message("error.no.debug.listen.port"));
454 if (address == null) {
455 throw new CantRunException(DebuggerBundle.message("error.no.debug.listen.port"));
457 // negative port number means the caller leaves to debugger to decide at which hport to listen
458 //noinspection HardCodedStringLiteral
459 final Connector.Argument portArg = myConnection.isUseSockets() ? myArguments.get("port") : myArguments.get("name");
460 if (portArg != null) {
461 portArg.setValue(address);
463 //noinspection HardCodedStringLiteral
464 final Connector.Argument timeoutArg = myArguments.get("timeout");
465 if (timeoutArg != null) {
466 timeoutArg.setValue("0"); // wait forever
468 connector.startListening(myArguments);
469 myDebugProcessDispatcher.getMulticaster().connectorIsReady();
470 try {
471 return connector.accept(myArguments);
473 finally {
474 if(myArguments != null) {
475 try {
476 connector.stopListening(myArguments);
478 catch (IllegalArgumentException e) {
479 // ignored
481 catch (IllegalConnectorArgumentsException e) {
482 // ignored
487 else { // is client mode, should attach to already running process
488 AttachingConnector connector = (AttachingConnector)findConnector(
489 myConnection.isUseSockets() ? SOCKET_ATTACHING_CONNECTOR_NAME : SHMEM_ATTACHING_CONNECTOR_NAME
492 if (connector == null) {
493 throw new CantRunException( DebuggerBundle.message("error.debug.connector.not.found", DebuggerBundle.getTransportName(myConnection)));
495 myArguments = connector.defaultArguments();
496 if (myConnection.isUseSockets()) {
497 //noinspection HardCodedStringLiteral
498 final Connector.Argument hostnameArg = (Connector.Argument)myArguments.get("hostname");
499 if (hostnameArg != null && myConnection.getHostName() != null) {
500 hostnameArg.setValue(myConnection.getHostName());
502 if (address == null) {
503 throw new CantRunException(DebuggerBundle.message("error.no.debug.attach.port"));
505 //noinspection HardCodedStringLiteral
506 final Connector.Argument portArg = (Connector.Argument)myArguments.get("port");
507 if (portArg != null) {
508 portArg.setValue(address);
511 else {
512 if (address == null) {
513 throw new CantRunException(DebuggerBundle.message("error.no.shmem.address"));
515 //noinspection HardCodedStringLiteral
516 final Connector.Argument nameArg = myArguments.get("name");
517 if (nameArg != null) {
518 nameArg.setValue(address);
521 //noinspection HardCodedStringLiteral
522 final Connector.Argument timeoutArg = myArguments.get("timeout");
523 if (timeoutArg != null) {
524 timeoutArg.setValue("0"); // wait forever
527 myDebugProcessDispatcher.getMulticaster().connectorIsReady();
528 try {
529 if(SOCKET_ATTACHING_CONNECTOR_NAME.equals(connector.name()) && Patches.SUN_BUG_338675) {
530 String portString = myConnection.getAddress();
531 String hostString = myConnection.getHostName();
533 if (hostString == null || hostString.length() == 0) {
534 //noinspection HardCodedStringLiteral
535 hostString = "localhost";
537 hostString = hostString + ":";
539 final TransportServiceWrapper transportServiceWrapper = TransportServiceWrapper.getTransportService(connector.transport());
540 myConnectionService = transportServiceWrapper.attach(hostString + portString);
541 return myConnectionService.createVirtualMachine();
543 else {
544 return connector.attach(myArguments);
547 catch (IllegalArgumentException e) {
548 throw new CantRunException(e.getLocalizedMessage());
552 catch (IOException e) {
553 throw new ExecutionException(processError(e), e);
555 catch (IllegalConnectorArgumentsException e) {
556 throw new ExecutionException(processError(e), e);
558 finally {
559 myArguments = null;
560 myConnectionService = null;
564 public void showStatusText(final String text) {
565 myStatusUpdateAlarm.cancelAllRequests();
566 myStatusUpdateAlarm.addRequest(new Runnable() {
567 public void run() {
568 final WindowManager wm = WindowManager.getInstance();
569 if (wm != null) {
570 wm.getStatusBar(myProject).setInfo(text);
573 }, 50);
576 static Connector findConnector(String connectorName) throws ExecutionException {
577 VirtualMachineManager virtualMachineManager = null;
578 try {
579 virtualMachineManager = Bootstrap.virtualMachineManager();
581 catch (Error e) {
582 final String error = e.getClass().getName() + " : " + e.getLocalizedMessage();
583 throw new ExecutionException(DebuggerBundle.message("debugger.jdi.bootstrap.error", error));
585 List connectors;
586 if (SOCKET_ATTACHING_CONNECTOR_NAME.equals(connectorName) || SHMEM_ATTACHING_CONNECTOR_NAME.equals(connectorName)) {
587 connectors = virtualMachineManager.attachingConnectors();
589 else if (SOCKET_LISTENING_CONNECTOR_NAME.equals(connectorName) || SHMEM_LISTENING_CONNECTOR_NAME.equals(connectorName)) {
590 connectors = virtualMachineManager.listeningConnectors();
592 else {
593 return null;
595 for (Iterator it = connectors.iterator(); it.hasNext();) {
596 Connector connector = (Connector)it.next();
597 if (connectorName.equals(connector.name())) {
598 return connector;
601 return null;
604 private void checkVirtualMachineVersion(VirtualMachine vm) {
605 final String version = vm.version();
606 if ("1.4.0".equals(version)) {
607 SwingUtilities.invokeLater(new Runnable() {
608 public void run() {
609 Messages.showMessageDialog(
610 getProject(),
611 DebuggerBundle.message("warning.jdk140.unstable"), DebuggerBundle.message("title.jdk140.unstable"), Messages.getWarningIcon()
618 /*Event dispatching*/
619 public void addEvaluationListener(EvaluationListener evaluationListener) {
620 myEvaluationDispatcher.addListener(evaluationListener);
623 public void removeEvaluationListener(EvaluationListener evaluationListener) {
624 myEvaluationDispatcher.removeListener(evaluationListener);
627 public void addDebugProcessListener(DebugProcessListener listener) {
628 myDebugProcessDispatcher.addListener(listener);
631 public void removeDebugProcessListener(DebugProcessListener listener) {
632 myDebugProcessDispatcher.removeListener(listener);
635 public void addProcessListener(ProcessListener processListener) {
636 synchronized(myProcessListeners) {
637 if(getExecutionResult() != null) {
638 getExecutionResult().getProcessHandler().addProcessListener(processListener);
640 else {
641 myProcessListeners.add(processListener);
646 public void removeProcessListener(ProcessListener processListener) {
647 synchronized (myProcessListeners) {
648 if(getExecutionResult() != null) {
649 getExecutionResult().getProcessHandler().removeProcessListener(processListener);
651 else {
652 myProcessListeners.remove(processListener);
657 /* getters */
658 public RemoteConnection getConnection() {
659 return myConnection;
662 public ExecutionResult getExecutionResult() {
663 return myExecutionResult;
666 public <T> T getUserData(Key<T> key) {
667 return (T)myUserData.get(key);
670 public <T> void putUserData(Key<T> key, T value) {
671 myUserData.put(key, value);
674 public Project getProject() {
675 return myProject;
678 public boolean canRedefineClasses() {
679 return myVirtualMachineProxy != null && myVirtualMachineProxy.canRedefineClasses();
682 public boolean canWatchFieldModification() {
683 return myVirtualMachineProxy != null && myVirtualMachineProxy.canWatchFieldModification();
686 public boolean isInInitialState() {
687 return myState.get() == STATE_INITIAL;
690 public boolean isAttached() {
691 return myState.get() == STATE_ATTACHED;
694 public boolean isDetached() {
695 return myState.get() == STATE_DETACHED;
698 public boolean isDetaching() {
699 return myState.get() == STATE_DETACHING;
702 public RequestManagerImpl getRequestsManager() {
703 return myRequestManager;
706 public VirtualMachineProxyImpl getVirtualMachineProxy() {
707 DebuggerManagerThreadImpl.assertIsManagerThread();
708 if (myVirtualMachineProxy == null) {
709 throw new VMDisconnectedException();
711 return myVirtualMachineProxy;
714 public void appendPositionManager(final PositionManager positionManager) {
715 DebuggerManagerThreadImpl.assertIsManagerThread();
716 myPositionManager.appendPositionManager(positionManager);
717 DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().updateBreakpoints(this);
720 private RunToCursorBreakpoint myRunToCursorBreakpoint;
722 public void cancelRunToCursorBreakpoint() {
723 DebuggerManagerThreadImpl.assertIsManagerThread();
724 if (myRunToCursorBreakpoint != null) {
725 getRequestsManager().deleteRequest(myRunToCursorBreakpoint);
726 myRunToCursorBreakpoint.delete();
727 if (myRunToCursorBreakpoint.isRestoreBreakpoints()) {
728 final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(getProject()).getBreakpointManager();
729 breakpointManager.enableBreakpoints(this);
731 myRunToCursorBreakpoint = null;
735 protected void closeProcess(boolean closedByUser) {
736 DebuggerManagerThreadImpl.assertIsManagerThread();
738 if (myState.compareAndSet(STATE_INITIAL, STATE_DETACHING) || myState.compareAndSet(STATE_ATTACHED, STATE_DETACHING)) {
739 myVirtualMachineProxy = null;
740 myPositionManager = null;
742 try {
743 getManagerThread().close();
745 finally {
746 myState.set(STATE_DETACHED);
747 try {
748 myDebugProcessDispatcher.getMulticaster().processDetached(this, closedByUser);
750 finally {
751 setBreakpointsMuted(false);
752 myWaitFor.up();
759 private static String formatMessage(String message) {
760 final int lineLength = 90;
761 StringBuffer buf = new StringBuffer(message.length());
762 int index = 0;
763 while (index < message.length()) {
764 buf.append(message.substring(index, Math.min(index + lineLength, message.length()))).append('\n');
765 index += lineLength;
767 return buf.toString();
770 public static String processError(Exception e) {
771 String message;
773 if (e instanceof VMStartException) {
774 VMStartException e1 = (VMStartException)e;
775 message = e1.getLocalizedMessage();
777 else if (e instanceof IllegalConnectorArgumentsException) {
778 IllegalConnectorArgumentsException e1 = (IllegalConnectorArgumentsException)e;
779 final List<String> invalidArgumentNames = e1.argumentNames();
780 message = formatMessage(DebuggerBundle.message("error.invalid.argument", invalidArgumentNames.size()) + ": "+ e1.getLocalizedMessage()) + invalidArgumentNames;
781 if (LOG.isDebugEnabled()) {
782 LOG.debug(e1);
785 else if (e instanceof CantRunException) {
786 message = e.getLocalizedMessage();
788 else if (e instanceof VMDisconnectedException) {
789 message = DebuggerBundle.message("error.vm.disconnected");
791 else if (e instanceof UnknownHostException) {
792 message = DebuggerBundle.message("error.unknown.host") + ":\n" + e.getLocalizedMessage();
794 else if (e instanceof IOException) {
795 IOException e1 = (IOException)e;
796 final StringBuilder buf = StringBuilderSpinAllocator.alloc();
797 try {
798 buf.append(DebuggerBundle.message("error.cannot.open.debugger.port")).append(" : ");
799 buf.append(e1.getClass().getName() + " ");
800 final String localizedMessage = e1.getLocalizedMessage();
801 if (localizedMessage != null && localizedMessage.length() > 0) {
802 buf.append('"');
803 buf.append(localizedMessage);
804 buf.append('"');
806 if (LOG.isDebugEnabled()) {
807 LOG.debug(e1);
809 message = buf.toString();
811 finally {
812 StringBuilderSpinAllocator.dispose(buf);
815 else if (e instanceof ExecutionException) {
816 message = e.getLocalizedMessage();
818 else {
819 message = DebuggerBundle.message("error.exception.while.connecting", e.getClass().getName(), e.getLocalizedMessage());
820 if (LOG.isDebugEnabled()) {
821 LOG.debug(e);
824 return message;
827 public void dispose() {
828 NodeRendererSettings.getInstance().removeListener(mySettingsListener);
829 myStatusUpdateAlarm.dispose();
832 public DebuggerManagerThreadImpl getManagerThread() {
833 if (myDebuggerManagerThread == null) {
834 synchronized (this) {
835 if (myDebuggerManagerThread == null) {
836 myDebuggerManagerThread = new DebuggerManagerThreadImpl();
840 return myDebuggerManagerThread;
843 private static int getInvokePolicy(SuspendContext suspendContext) {
844 //return ThreadReference.INVOKE_SINGLE_THREADED;
845 return suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD ? ThreadReference.INVOKE_SINGLE_THREADED : 0;
848 public void waitFor() {
849 LOG.assertTrue(!DebuggerManagerThreadImpl.isManagerThread());
850 myWaitFor.waitFor();
853 public void waitFor(long timeout) {
854 LOG.assertTrue(!DebuggerManagerThreadImpl.isManagerThread());
855 myWaitFor.waitFor(timeout);
858 private abstract class InvokeCommand <E extends Value> {
859 private final List myArgs;
861 protected InvokeCommand(List args) {
862 if (args.size() > 0) {
863 myArgs = new ArrayList(args);
865 else {
866 myArgs = args;
870 public String toString() {
871 return "INVOKE: " + super.toString();
874 protected abstract E invokeMethod(int invokePolicy, final List args) throws InvocationException,
875 ClassNotLoadedException,
876 IncompatibleThreadStateException,
877 InvalidTypeException;
879 public E start(EvaluationContextImpl evaluationContext, Method method) throws EvaluateException {
880 DebuggerManagerThreadImpl.assertIsManagerThread();
881 SuspendContextImpl suspendContext = evaluationContext.getSuspendContext();
882 SuspendManagerUtil.assertSuspendContext(suspendContext);
884 ThreadReferenceProxyImpl invokeThread = suspendContext.getThread();
886 if (SuspendManagerUtil.isEvaluating(getSuspendManager(), invokeThread)) {
887 throw EvaluateExceptionUtil.NESTED_EVALUATION_ERROR;
890 Set<SuspendContextImpl> suspendingContexts = SuspendManagerUtil.getSuspendingContexts(getSuspendManager(), invokeThread);
891 final ThreadReference invokeThreadRef = invokeThread.getThreadReference();
893 myEvaluationDispatcher.getMulticaster().evaluationStarted(suspendContext);
894 beforeMethodInvocation(suspendContext, method);
896 Object resumeData = null;
897 try {
898 for (final SuspendContextImpl suspendingContext : suspendingContexts) {
899 final ThreadReferenceProxyImpl suspendContextThread = suspendingContext.getThread();
900 if (suspendContextThread != invokeThread) {
901 if (LOG.isDebugEnabled()) {
902 LOG.debug("Resuming " + invokeThread + " that is paused by " + suspendContextThread);
904 LOG.assertTrue(suspendContextThread == null || !invokeThreadRef.equals(suspendContextThread.getThreadReference()));
905 getSuspendManager().resumeThread(suspendingContext, invokeThread);
909 resumeData = SuspendManagerUtil.prepareForResume(suspendContext);
910 suspendContext.setIsEvaluating(evaluationContext);
912 getVirtualMachineProxy().clearCaches();
914 while (true) {
915 try {
916 return invokeMethodAndFork(suspendContext);
918 catch (ClassNotLoadedException e) {
919 ReferenceType loadedClass = evaluationContext.isAutoLoadClasses()? loadClass(evaluationContext, e.className(), evaluationContext.getClassLoader()) : null;
920 if (loadedClass == null) {
921 throw EvaluateExceptionUtil.createEvaluateException(e);
926 catch (ClassNotLoadedException e) {
927 throw EvaluateExceptionUtil.createEvaluateException(e);
929 catch (InvocationException e) {
930 throw EvaluateExceptionUtil.createEvaluateException(e);
932 catch (IncompatibleThreadStateException e) {
933 throw EvaluateExceptionUtil.createEvaluateException(e);
935 catch (InvalidTypeException e) {
936 throw EvaluateExceptionUtil.createEvaluateException(e);
938 catch (ObjectCollectedException e) {
939 throw EvaluateExceptionUtil.createEvaluateException(e);
941 catch (UnsupportedOperationException e) {
942 throw EvaluateExceptionUtil.createEvaluateException(e);
944 catch (InternalException e) {
945 throw EvaluateExceptionUtil.createEvaluateException(e);
947 finally {
948 suspendContext.setIsEvaluating(null);
949 if (resumeData != null) {
950 SuspendManagerUtil.restoreAfterResume(suspendContext, resumeData);
952 for (SuspendContextImpl suspendingContext : mySuspendManager.getEventContexts()) {
953 if (suspendingContexts.contains(suspendingContext) && !suspendingContext.isEvaluating() && !suspendingContext.suspends(invokeThread)) {
954 mySuspendManager.suspendThread(suspendingContext, invokeThread);
958 if (LOG.isDebugEnabled()) {
959 LOG.debug("getVirtualMachine().clearCaches()");
961 getVirtualMachineProxy().clearCaches();
962 afterMethodInvocation(suspendContext);
964 myEvaluationDispatcher.getMulticaster().evaluationFinished(suspendContext);
968 private E invokeMethodAndFork(final SuspendContextImpl context) throws InvocationException,
969 ClassNotLoadedException,
970 IncompatibleThreadStateException,
971 InvalidTypeException {
972 final int invokePolicy = getInvokePolicy(context);
973 final Exception[] exception = new Exception[1];
974 final Value[] result = new Value[1];
975 getManagerThread().startLongProcessAndFork(new Runnable() {
976 public void run() {
977 ThreadReferenceProxyImpl thread = context.getThread();
978 try {
979 try {
980 if (LOG.isDebugEnabled()) {
981 final VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy();
982 virtualMachineProxy.logThreads();
983 LOG.debug("Invoke in " + thread.name());
984 assertThreadSuspended(thread, context);
986 if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) {
987 // ensure args are not collected
988 for (Object arg : myArgs) {
989 if (arg instanceof ObjectReference) {
990 ((ObjectReference)arg).disableCollection();
994 result[0] = invokeMethod(invokePolicy, myArgs);
996 finally {
997 // assertThreadSuspended(thread, context);
998 if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) {
999 // ensure args are not collected
1000 for (Object arg : myArgs) {
1001 if (arg instanceof ObjectReference) {
1002 ((ObjectReference)arg).enableCollection();
1008 catch (Exception e) {
1009 exception[0] = e;
1014 if (exception[0] != null) {
1015 if (exception[0] instanceof InvocationException) {
1016 throw (InvocationException)exception[0];
1018 else if (exception[0] instanceof ClassNotLoadedException) {
1019 throw (ClassNotLoadedException)exception[0];
1021 else if (exception[0] instanceof IncompatibleThreadStateException) {
1022 throw (IncompatibleThreadStateException)exception[0];
1024 else if (exception[0] instanceof InvalidTypeException) {
1025 throw (InvalidTypeException)exception[0];
1027 else if (exception[0] instanceof RuntimeException) {
1028 throw (RuntimeException)exception[0];
1030 else {
1031 LOG.assertTrue(false);
1035 return (E)result[0];
1038 private void assertThreadSuspended(final ThreadReferenceProxyImpl thread, final SuspendContextImpl context) {
1039 LOG.assertTrue(context.isEvaluating());
1040 try {
1041 final boolean isSuspended = thread.isSuspended();
1042 LOG.assertTrue(isSuspended, thread);
1044 catch (ObjectCollectedException ignored) {
1049 public Value invokeMethod(final EvaluationContext evaluationContext, final ObjectReference objRef, final Method method, final List args) throws EvaluateException {
1050 return invokeInstanceMethod(evaluationContext, objRef, method, args, 0);
1053 public Value invokeInstanceMethod(final EvaluationContext evaluationContext, final ObjectReference objRef, final Method method,
1054 final List args, final int invocationOptions) throws EvaluateException {
1055 final ThreadReference thread = getEvaluationThread(evaluationContext);
1056 InvokeCommand<Value> invokeCommand = new InvokeCommand<Value>(args) {
1057 protected Value invokeMethod(int invokePolicy, final List args) throws InvocationException, ClassNotLoadedException, IncompatibleThreadStateException, InvalidTypeException {
1058 if (LOG.isDebugEnabled()) {
1059 LOG.debug("Invoke " + method.name());
1061 //try {
1062 // if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) {
1063 // // ensure target object wil not be collected
1064 // objRef.disableCollection();
1065 // }
1066 return objRef.invokeMethod(thread, method, args, invokePolicy | invocationOptions);
1068 //finally {
1069 // if (!Patches.IBM_JDK_DISABLE_COLLECTION_BUG) {
1070 // objRef.enableCollection();
1071 // }
1075 return invokeCommand.start((EvaluationContextImpl)evaluationContext, method);
1078 private static ThreadReference getEvaluationThread(final EvaluationContext evaluationContext) throws EvaluateException {
1079 ThreadReferenceProxy evaluationThread = evaluationContext.getSuspendContext().getThread();
1080 if(evaluationThread == null) {
1081 throw EvaluateExceptionUtil.NULL_STACK_FRAME;
1083 return evaluationThread.getThreadReference();
1086 public Value invokeMethod(final EvaluationContext evaluationContext, final ClassType classType,
1087 final Method method,
1088 final List args) throws EvaluateException {
1090 final ThreadReference thread = getEvaluationThread(evaluationContext);
1091 InvokeCommand<Value> invokeCommand = new InvokeCommand<Value>(args) {
1092 protected Value invokeMethod(int invokePolicy, final List args) throws InvocationException,
1093 ClassNotLoadedException,
1094 IncompatibleThreadStateException,
1095 InvalidTypeException {
1096 if (LOG.isDebugEnabled()) {
1097 LOG.debug("Invoke " + method.name());
1099 return classType.invokeMethod(thread, method, args, invokePolicy);
1102 return invokeCommand.start((EvaluationContextImpl)evaluationContext, method);
1105 public ArrayReference newInstance(final ArrayType arrayType,
1106 final int dimension)
1107 throws EvaluateException {
1108 return arrayType.newInstance(dimension);
1111 public ObjectReference newInstance(final EvaluationContext evaluationContext, final ClassType classType,
1112 final Method method,
1113 final List args) throws EvaluateException {
1114 final ThreadReference thread = getEvaluationThread(evaluationContext);
1115 InvokeCommand<ObjectReference> invokeCommand = new InvokeCommand<ObjectReference>(args) {
1116 protected ObjectReference invokeMethod(int invokePolicy, final List args) throws InvocationException,
1117 ClassNotLoadedException,
1118 IncompatibleThreadStateException,
1119 InvalidTypeException {
1120 if (LOG.isDebugEnabled()) {
1121 LOG.debug("New instance " + method.name());
1123 return classType.newInstance(thread, method, args, invokePolicy);
1126 return invokeCommand.start((EvaluationContextImpl)evaluationContext, method);
1129 public void clearCashes(int suspendPolicy) {
1130 if (!isAttached()) return;
1131 switch (suspendPolicy) {
1132 case EventRequest.SUSPEND_ALL:
1133 getVirtualMachineProxy().clearCaches();
1134 break;
1135 case EventRequest.SUSPEND_EVENT_THREAD:
1136 getVirtualMachineProxy().clearCaches();
1137 //suspendContext.getThread().clearAll();
1138 break;
1142 protected void beforeSuspend(SuspendContextImpl suspendContext) {
1143 clearCashes(suspendContext.getSuspendPolicy());
1146 private void beforeMethodInvocation(SuspendContextImpl suspendContext, Method method) {
1147 if (LOG.isDebugEnabled()) {
1148 LOG.debug(
1149 "before invocation in thread " + suspendContext.getThread().name() + " method " + (method == null ? "null" : method.name()));
1152 if (method != null) {
1153 showStatusText(DebuggerBundle.message("progress.evaluating", DebuggerUtilsEx.methodName(method)));
1155 else {
1156 showStatusText(DebuggerBundle.message("title.evaluating"));
1160 private void afterMethodInvocation(SuspendContextImpl suspendContext) {
1161 if (LOG.isDebugEnabled()) {
1162 LOG.debug("after invocation in thread " + suspendContext.getThread().name());
1164 showStatusText("");
1167 public ReferenceType findClass(EvaluationContext evaluationContext, String className,
1168 ClassLoaderReference classLoader) throws EvaluateException {
1169 try {
1170 DebuggerManagerThreadImpl.assertIsManagerThread();
1171 ReferenceType result = null;
1172 final VirtualMachineProxyImpl vmProxy = getVirtualMachineProxy();
1173 if (vmProxy == null) {
1174 throw new VMDisconnectedException();
1176 for (final ReferenceType refType : vmProxy.classesByName(className)) {
1177 if (refType.isPrepared() && isVisibleFromClassLoader(classLoader, refType)) {
1178 result = refType;
1179 break;
1182 final EvaluationContextImpl evalContext = (EvaluationContextImpl)evaluationContext;
1183 if (result == null && evalContext.isAutoLoadClasses()) {
1184 return loadClass(evalContext, className, classLoader);
1186 return result;
1188 catch (InvocationException e) {
1189 throw EvaluateExceptionUtil.createEvaluateException(e);
1191 catch (ClassNotLoadedException e) {
1192 throw EvaluateExceptionUtil.createEvaluateException(e);
1194 catch (IncompatibleThreadStateException e) {
1195 throw EvaluateExceptionUtil.createEvaluateException(e);
1197 catch (InvalidTypeException e) {
1198 throw EvaluateExceptionUtil.createEvaluateException(e);
1202 private static boolean isVisibleFromClassLoader(final ClassLoaderReference fromLoader, final ReferenceType refType) {
1203 final ClassLoaderReference typeLoader = refType.classLoader();
1204 if (typeLoader == null) {
1205 return true; // optimization: if class is loaded by a bootstrap loader, it is visible from every other loader
1207 for (ClassLoaderReference checkLoader = fromLoader; checkLoader != null; checkLoader = getParentLoader(checkLoader)) {
1208 if (Comparing.equal(typeLoader, checkLoader)) {
1209 return true;
1212 return fromLoader != null? fromLoader.visibleClasses().contains(refType) : false;
1215 @SuppressWarnings({"HardCodedStringLiteral"})
1216 private static ClassLoaderReference getParentLoader(final ClassLoaderReference fromLoader) {
1217 final ReferenceType refType = fromLoader.referenceType();
1218 Field field = refType.fieldByName("parent");
1219 if (field == null) {
1220 final List allFields = refType.allFields();
1221 for (Iterator it = allFields.iterator(); it.hasNext();) {
1222 final Field candidateField = (Field)it.next();
1223 try {
1224 final Type checkedType = candidateField.type();
1225 if (checkedType instanceof ReferenceType && DebuggerUtilsEx.isAssignableFrom("java.lang.ClassLoader", (ReferenceType)checkedType)) {
1226 field = candidateField;
1227 break;
1230 catch (ClassNotLoadedException e) {
1231 // ignore this and continue,
1232 // java.lang.ClassLoader must be loaded at the moment of check, so if this happens, the field's type is definitely not java.lang.ClassLoader
1236 return field != null? (ClassLoaderReference)fromLoader.getValue(field) : null;
1239 private String reformatArrayName(String className) {
1240 if (className.indexOf('[') == -1) return className;
1242 int dims = 0;
1243 while (className.endsWith("[]")) {
1244 className = className.substring(0, className.length() - 2);
1245 dims++;
1248 StringBuilder buffer = StringBuilderSpinAllocator.alloc();
1249 try {
1250 for (int i = 0; i < dims; i++) {
1251 buffer.append('[');
1253 String primitiveSignature = JVMNameUtil.getPrimitiveSignature(className);
1254 if(primitiveSignature != null) {
1255 buffer.append(primitiveSignature);
1257 else {
1258 buffer.append('L');
1259 buffer.append(className);
1260 buffer.append(';');
1262 return buffer.toString();
1264 finally {
1265 StringBuilderSpinAllocator.dispose(buffer);
1269 @SuppressWarnings({"HardCodedStringLiteral"})
1270 public ReferenceType loadClass(EvaluationContextImpl evaluationContext, String qName, ClassLoaderReference classLoader)
1271 throws InvocationException, ClassNotLoadedException, IncompatibleThreadStateException, InvalidTypeException, EvaluateException {
1273 DebuggerManagerThreadImpl.assertIsManagerThread();
1274 qName = reformatArrayName(qName);
1275 ReferenceType refType = null;
1276 VirtualMachineProxyImpl virtualMachine = getVirtualMachineProxy();
1277 final List classClasses = virtualMachine.classesByName("java.lang.Class");
1278 if (classClasses.size() > 0) {
1279 ClassType classClassType = (ClassType)classClasses.get(0);
1280 final Method forNameMethod;
1281 if (classLoader != null) {
1282 //forNameMethod = classClassType.concreteMethodByName("forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;");
1283 forNameMethod = DebuggerUtils.findMethod(classClassType, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;");
1285 else {
1286 //forNameMethod = classClassType.concreteMethodByName("forName", "(Ljava/lang/String;)Ljava/lang/Class;");
1287 forNameMethod = DebuggerUtils.findMethod(classClassType, "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
1289 final List<Mirror> args = new ArrayList<Mirror>(); // do not use unmodifiable lists because the list is modified by JPDA
1290 final StringReference qNameMirror = virtualMachine.mirrorOf(qName);
1291 args.add(qNameMirror);
1292 if (classLoader != null) {
1293 args.add(virtualMachine.mirrorOf(true));
1294 args.add(classLoader);
1296 final Value value = invokeMethod(evaluationContext, classClassType, forNameMethod, args);
1297 if (value instanceof ClassObjectReference) {
1298 refType = ((ClassObjectReference)value).reflectedType();
1301 return refType;
1304 public void logThreads() {
1305 if (LOG.isDebugEnabled()) {
1306 try {
1307 Collection<ThreadReferenceProxyImpl> allThreads = getVirtualMachineProxy().allThreads();
1308 for (ThreadReferenceProxyImpl threadReferenceProxy : allThreads) {
1309 LOG.debug("Thread name=" + threadReferenceProxy.name() + " suspendCount()=" + threadReferenceProxy.getSuspendCount());
1312 catch (Exception e) {
1313 LOG.debug(e);
1318 public SuspendManager getSuspendManager() {
1319 return mySuspendManager;
1322 public CompoundPositionManager getPositionManager() {
1323 return myPositionManager;
1325 //ManagerCommands
1327 public void stop(boolean forceTerminate) {
1328 this.getManagerThread().terminateAndInvoke(createStopCommand(forceTerminate), DebuggerManagerThreadImpl.COMMAND_TIMEOUT);
1331 public StopCommand createStopCommand(boolean forceTerminate) {
1332 return new StopCommand(forceTerminate);
1335 protected class StopCommand extends DebuggerCommandImpl {
1336 private final boolean myIsTerminateTargetVM;
1338 public StopCommand(boolean isTerminateTargetVM) {
1339 myIsTerminateTargetVM = isTerminateTargetVM;
1342 public Priority getPriority() {
1343 return Priority.HIGH;
1346 protected void action() throws Exception {
1347 if (isAttached()) {
1348 final VirtualMachineProxyImpl virtualMachineProxy = getVirtualMachineProxy();
1349 if (myIsTerminateTargetVM) {
1350 virtualMachineProxy.exit(-1);
1352 else {
1353 // some VM's (like IBM VM 1.4.2 bundled with WebSpere) does not
1354 // resume threads on dispose() like it should
1355 virtualMachineProxy.resume();
1356 virtualMachineProxy.dispose();
1359 else {
1360 stopConnecting();
1365 private class StepOutCommand extends ResumeCommand {
1366 public StepOutCommand(SuspendContextImpl suspendContext) {
1367 super(suspendContext);
1370 public void contextAction() {
1371 showStatusText(DebuggerBundle.message("status.step.out"));
1372 final SuspendContextImpl suspendContext = getSuspendContext();
1373 final ThreadReferenceProxyImpl thread = suspendContext.getThread();
1374 RequestHint hint = new RequestHint(thread, suspendContext, StepRequest.STEP_OUT);
1375 hint.setIgnoreFilters(mySession.shouldIgnoreSteppingFilters());
1376 if (myReturnValueWatcher != null) {
1377 myReturnValueWatcher.setTrackingEnabled(true);
1379 doStep(suspendContext, thread, StepRequest.STEP_OUT, hint);
1380 super.contextAction();
1384 private class StepIntoCommand extends ResumeCommand {
1385 private final boolean myForcedIgnoreFilters;
1386 private final RequestHint.SmartStepFilter mySmartStepFilter;
1388 public StepIntoCommand(SuspendContextImpl suspendContext, boolean ignoreFilters, final @Nullable RequestHint.SmartStepFilter smartStepFilter) {
1389 super(suspendContext);
1390 myForcedIgnoreFilters = ignoreFilters || smartStepFilter != null;
1391 mySmartStepFilter = smartStepFilter;
1394 public void contextAction() {
1395 showStatusText(DebuggerBundle.message("status.step.into"));
1396 final SuspendContextImpl suspendContext = getSuspendContext();
1397 final ThreadReferenceProxyImpl stepThread = suspendContext.getThread();
1398 final RequestHint hint = mySmartStepFilter != null?
1399 new RequestHint(stepThread, suspendContext, mySmartStepFilter) :
1400 new RequestHint(stepThread, suspendContext, StepRequest.STEP_INTO);
1401 if (myForcedIgnoreFilters) {
1402 try {
1403 mySession.setIgnoreStepFiltersFlag(stepThread.frameCount());
1405 catch (EvaluateException e) {
1406 LOG.info(e);
1409 hint.setIgnoreFilters(myForcedIgnoreFilters || mySession.shouldIgnoreSteppingFilters());
1410 doStep(suspendContext, stepThread, StepRequest.STEP_INTO, hint);
1411 super.contextAction();
1415 private class StepOverCommand extends ResumeCommand {
1416 private final boolean myIsIgnoreBreakpoints;
1418 public StepOverCommand(SuspendContextImpl suspendContext, boolean ignoreBreakpoints) {
1419 super(suspendContext);
1420 myIsIgnoreBreakpoints = ignoreBreakpoints;
1423 public void contextAction() {
1424 showStatusText(DebuggerBundle.message("status.step.over"));
1425 final SuspendContextImpl suspendContext = getSuspendContext();
1426 final ThreadReferenceProxyImpl steppingThread = suspendContext.getThread();
1427 // need this hint whil stepping over for JSR45 support:
1428 // several lines of generated java code may correspond to a single line in the source file,
1429 // from which the java code was generated
1430 RequestHint hint = new RequestHint(steppingThread, suspendContext, StepRequest.STEP_OVER);
1431 hint.setRestoreBreakpoints(myIsIgnoreBreakpoints);
1432 hint.setIgnoreFilters(myIsIgnoreBreakpoints || mySession.shouldIgnoreSteppingFilters());
1434 if (myReturnValueWatcher != null) {
1435 myReturnValueWatcher.setTrackingEnabled(true);
1437 doStep(suspendContext, steppingThread, StepRequest.STEP_OVER, hint);
1439 if (myIsIgnoreBreakpoints) {
1440 DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().disableBreakpoints(DebugProcessImpl.this);
1442 super.contextAction();
1446 private class RunToCursorCommand extends ResumeCommand {
1447 private final RunToCursorBreakpoint myRunToCursorBreakpoint;
1448 private final boolean myIgnoreBreakpoints;
1450 private RunToCursorCommand(SuspendContextImpl suspendContext, Document document, int lineIndex, final boolean ignoreBreakpoints) {
1451 super(suspendContext);
1452 myIgnoreBreakpoints = ignoreBreakpoints;
1453 final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager();
1454 myRunToCursorBreakpoint = breakpointManager.addRunToCursorBreakpoint(document, lineIndex, ignoreBreakpoints);
1457 public void contextAction() {
1458 showStatusText(DebuggerBundle.message("status.run.to.cursor"));
1459 cancelRunToCursorBreakpoint();
1460 if (myRunToCursorBreakpoint == null) {
1461 return;
1463 if (myIgnoreBreakpoints) {
1464 final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager();
1465 breakpointManager.disableBreakpoints(DebugProcessImpl.this);
1467 myRunToCursorBreakpoint.SUSPEND_POLICY = DebuggerSettings.SUSPEND_ALL;
1468 myRunToCursorBreakpoint.LOG_ENABLED = false;
1469 myRunToCursorBreakpoint.createRequest(getSuspendContext().getDebugProcess());
1470 DebugProcessImpl.this.myRunToCursorBreakpoint = myRunToCursorBreakpoint;
1471 super.contextAction();
1475 public abstract class ResumeCommand extends SuspendContextCommandImpl {
1477 public ResumeCommand(SuspendContextImpl suspendContext) {
1478 super(suspendContext);
1481 public Priority getPriority() {
1482 return Priority.HIGH;
1485 public void contextAction() {
1486 showStatusText(DebuggerBundle.message("status.process.resumed"));
1487 getSuspendManager().resume(getSuspendContext());
1488 myDebugProcessDispatcher.getMulticaster().resumed(getSuspendContext());
1492 private class PauseCommand extends DebuggerCommandImpl {
1493 public PauseCommand() {
1496 public void action() {
1497 if (!isAttached() || getVirtualMachineProxy().isPausePressed()) {
1498 return;
1500 logThreads();
1501 getVirtualMachineProxy().suspend();
1502 logThreads();
1503 SuspendContextImpl suspendContext = mySuspendManager.pushSuspendContext(EventRequest.SUSPEND_ALL, 0);
1504 myDebugProcessDispatcher.getMulticaster().paused(suspendContext);
1508 private class ResumeThreadCommand extends SuspendContextCommandImpl {
1509 private final ThreadReferenceProxyImpl myThread;
1511 public ResumeThreadCommand(SuspendContextImpl suspendContext, ThreadReferenceProxyImpl thread) {
1512 super(suspendContext);
1513 myThread = thread;
1516 public void contextAction() {
1517 if (getSuspendManager().isFrozen(myThread)) {
1518 getSuspendManager().unfreezeThread(myThread);
1519 return;
1522 final Set<SuspendContextImpl> suspendingContexts = SuspendManagerUtil.getSuspendingContexts(getSuspendManager(), myThread);
1523 for (Iterator<SuspendContextImpl> iterator = suspendingContexts.iterator(); iterator.hasNext();) {
1524 SuspendContextImpl suspendContext = iterator.next();
1525 if (suspendContext.getThread() == myThread) {
1526 DebugProcessImpl.this.getManagerThread().invoke(createResumeCommand(suspendContext));
1528 else {
1529 getSuspendManager().resumeThread(suspendContext, myThread);
1535 private class FreezeThreadCommand extends DebuggerCommandImpl {
1536 private final ThreadReferenceProxyImpl myThread;
1538 public FreezeThreadCommand(ThreadReferenceProxyImpl thread) {
1539 myThread = thread;
1542 protected void action() throws Exception {
1543 SuspendManager suspendManager = getSuspendManager();
1544 if (!suspendManager.isFrozen(myThread)) {
1545 suspendManager.freezeThread(myThread);
1550 private class PopFrameCommand extends SuspendContextCommandImpl {
1551 private final StackFrameProxyImpl myStackFrame;
1553 public PopFrameCommand(SuspendContextImpl context, StackFrameProxyImpl frameProxy) {
1554 super(context);
1555 myStackFrame = frameProxy;
1558 public void contextAction() {
1559 final ThreadReferenceProxyImpl thread = myStackFrame.threadProxy();
1560 try {
1561 if (!getSuspendManager().isSuspended(thread)) {
1562 notifyCancelled();
1563 return;
1566 catch (ObjectCollectedException e) {
1567 notifyCancelled();
1568 return;
1571 final SuspendContextImpl suspendContext = getSuspendContext();
1572 if (!suspendContext.suspends(thread)) {
1573 suspendContext.postponeCommand(this);
1574 return;
1577 if (myStackFrame.isBottom()) {
1578 DebuggerInvocationUtil.swingInvokeLater(myProject, new Runnable() {
1579 public void run() {
1580 Messages.showMessageDialog(myProject, DebuggerBundle.message("error.pop.bottom.stackframe"), ActionsBundle.actionText(DebuggerActions.POP_FRAME), Messages.getErrorIcon());
1583 return;
1586 try {
1587 thread.popFrames(myStackFrame);
1589 catch (final EvaluateException e) {
1590 DebuggerInvocationUtil.swingInvokeLater(myProject, new Runnable() {
1591 public void run() {
1592 Messages.showMessageDialog(myProject, DebuggerBundle.message("error.pop.stackframe", e.getLocalizedMessage()), ActionsBundle.actionText(DebuggerActions.POP_FRAME), Messages.getErrorIcon());
1595 LOG.info(e);
1597 finally {
1598 getSuspendManager().popFrame(suspendContext);
1603 @NotNull
1604 public GlobalSearchScope getSearchScope() {
1605 LOG.assertTrue(mySession != null, "Accessing debug session before its initialization");
1606 return mySession.getSearchScope();
1609 public @Nullable ExecutionResult attachVirtualMachine(final Executor executor,
1610 final ProgramRunner runner,
1611 final DebuggerSession session,
1612 final RunProfileState state,
1613 final RemoteConnection remoteConnection,
1614 boolean pollConnection) throws ExecutionException {
1615 mySession = session;
1616 myWaitFor.down();
1618 ApplicationManager.getApplication().assertIsDispatchThread();
1619 LOG.assertTrue(isInInitialState());
1621 myConnection = remoteConnection;
1623 createVirtualMachine(state, pollConnection);
1625 try {
1626 synchronized (myProcessListeners) {
1627 if (state instanceof CommandLineState) {
1628 final TextConsoleBuilder consoleBuilder = ((CommandLineState)state).getConsoleBuilder();
1629 if (consoleBuilder != null) {
1630 consoleBuilder.addFilter(new ExceptionFilter(session.getSearchScope()));
1633 myExecutionResult = state.execute(executor, runner);
1634 if (myExecutionResult == null) {
1635 fail();
1636 return null;
1638 for (ProcessListener processListener : myProcessListeners) {
1639 myExecutionResult.getProcessHandler().addProcessListener(processListener);
1641 myProcessListeners.clear();
1644 catch (ExecutionException e) {
1645 fail();
1646 throw e;
1649 if (ApplicationManager.getApplication().isUnitTestMode()) {
1650 return myExecutionResult;
1654 final Alarm debugPortTimeout = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
1656 myExecutionResult.getProcessHandler().addProcessListener(new ProcessAdapter() {
1657 public void processTerminated(ProcessEvent event) {
1658 debugPortTimeout.cancelAllRequests();
1661 public void startNotified(ProcessEvent event) {
1662 debugPortTimeout.addRequest(new Runnable() {
1663 public void run() {
1664 if(isInInitialState()) {
1665 ApplicationManager.getApplication().schedule(new Runnable() {
1666 public void run() {
1667 String message = DebuggerBundle.message("status.connect.failed", DebuggerBundle.getAddressDisplayName(remoteConnection), DebuggerBundle.getTransportName(remoteConnection));
1668 Messages.showErrorDialog(myProject, message, DebuggerBundle.message("title.generic.debug.dialog"));
1673 }, LOCAL_START_TIMEOUT);
1678 return myExecutionResult;
1681 private void fail() {
1682 synchronized (this) {
1683 if (myIsFailed) {
1684 // need this in order to prevent calling stop() twice
1685 return;
1687 myIsFailed = true;
1689 stop(false);
1692 private void createVirtualMachine(final RunProfileState state, final boolean pollConnection) {
1693 final Semaphore semaphore = new Semaphore();
1694 semaphore.down();
1696 final Ref<Boolean> connectorIsReady = Ref.create(false);
1697 myDebugProcessDispatcher.addListener(new DebugProcessAdapter() {
1698 public void connectorIsReady() {
1699 connectorIsReady.set(true);
1700 semaphore.up();
1701 myDebugProcessDispatcher.removeListener(this);
1706 this.getManagerThread().schedule(new DebuggerCommandImpl() {
1707 protected void action() {
1708 VirtualMachine vm = null;
1710 try {
1711 final long time = System.currentTimeMillis();
1712 while (System.currentTimeMillis() - time < LOCAL_START_TIMEOUT) {
1713 try {
1714 vm = createVirtualMachineInt();
1715 break;
1717 catch (final ExecutionException e) {
1718 if (pollConnection && !myConnection.isServerMode() && e.getCause() instanceof IOException) {
1719 synchronized (this) {
1720 try {
1721 wait(500);
1723 catch (InterruptedException ie) {
1724 break;
1728 else {
1729 fail();
1730 if (myExecutionResult != null || !connectorIsReady.get()) {
1731 // propagate exception only in case we succeded to obtain execution result,
1732 // otherwise it the error is induced by the fact that there is nothing to debug, and there is no need to show
1733 // this problem to the user
1734 SwingUtilities.invokeLater(new Runnable() {
1735 public void run() {
1736 ProgramRunnerUtil.handleExecutionError(myProject, state.getRunnerSettings().getRunProfile(), e);
1740 break;
1745 finally {
1746 semaphore.up();
1749 if (vm != null) {
1750 final VirtualMachine vm1 = vm;
1751 afterProcessStarted(new Runnable() {
1752 public void run() {
1753 getManagerThread().schedule(new DebuggerCommandImpl() {
1754 protected void action() throws Exception {
1755 commitVM(vm1);
1763 protected void commandCancelled() {
1764 try {
1765 super.commandCancelled();
1767 finally {
1768 semaphore.up();
1773 semaphore.waitFor();
1776 private void afterProcessStarted(final Runnable run) {
1777 class MyProcessAdapter extends ProcessAdapter {
1778 private boolean alreadyRun = false;
1780 public synchronized void run() {
1781 if(!alreadyRun) {
1782 alreadyRun = true;
1783 run.run();
1785 removeProcessListener(this);
1788 public void startNotified(ProcessEvent event) {
1789 run();
1792 MyProcessAdapter processListener = new MyProcessAdapter();
1793 addProcessListener(processListener);
1794 if(myExecutionResult != null) {
1795 if(myExecutionResult.getProcessHandler().isStartNotified()) {
1796 processListener.run();
1801 public boolean isPausePressed() {
1802 return myVirtualMachineProxy != null && myVirtualMachineProxy.isPausePressed();
1805 public DebuggerCommandImpl createPauseCommand() {
1806 return new PauseCommand();
1809 public ResumeCommand createResumeCommand(SuspendContextImpl suspendContext) {
1810 return createResumeCommand(suspendContext, PrioritizedTask.Priority.HIGH);
1813 public ResumeCommand createResumeCommand(SuspendContextImpl suspendContext, final PrioritizedTask.Priority priority) {
1814 final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(getProject()).getBreakpointManager();
1815 return new ResumeCommand(suspendContext) {
1816 public void contextAction() {
1817 breakpointManager.applyThreadFilter(DebugProcessImpl.this, null); // clear the filter on resume
1818 super.contextAction();
1821 public Priority getPriority() {
1822 return priority;
1827 public ResumeCommand createStepOverCommand(SuspendContextImpl suspendContext, boolean ignoreBreakpoints) {
1828 return new StepOverCommand(suspendContext, ignoreBreakpoints);
1831 public ResumeCommand createStepOutCommand(SuspendContextImpl suspendContext) {
1832 return new StepOutCommand(suspendContext);
1835 public ResumeCommand createStepIntoCommand(SuspendContextImpl suspendContext, boolean ignoreFilters, final RequestHint.SmartStepFilter smartStepFilter) {
1836 return new StepIntoCommand(suspendContext, ignoreFilters, smartStepFilter);
1839 public ResumeCommand createRunToCursorCommand(SuspendContextImpl suspendContext, Document document, int lineIndex,
1840 final boolean ignoreBreakpoints)
1841 throws EvaluateException {
1842 RunToCursorCommand runToCursorCommand = new RunToCursorCommand(suspendContext, document, lineIndex, ignoreBreakpoints);
1843 if(runToCursorCommand.myRunToCursorBreakpoint == null) {
1844 final PsiFile psiFile = PsiDocumentManager.getInstance(getProject()).getPsiFile(document);
1845 throw new EvaluateException(DebuggerBundle.message("error.running.to.cursor.no.executable.code", psiFile != null? psiFile.getName() : "<No File>", lineIndex), null);
1847 return runToCursorCommand;
1850 public DebuggerCommandImpl createFreezeThreadCommand(ThreadReferenceProxyImpl thread) {
1851 return new FreezeThreadCommand(thread);
1854 public SuspendContextCommandImpl createResumeThreadCommand(SuspendContextImpl suspendContext, ThreadReferenceProxyImpl thread) {
1855 return new ResumeThreadCommand(suspendContext, thread);
1858 public SuspendContextCommandImpl createPopFrameCommand(DebuggerContextImpl context, StackFrameProxyImpl stackFrame) {
1859 final SuspendContextImpl contextByThread =
1860 SuspendManagerUtil.findContextByThread(context.getDebugProcess().getSuspendManager(), stackFrame.threadProxy());
1861 return new PopFrameCommand(contextByThread, stackFrame);
1864 public void setBreakpointsMuted(final boolean muted) {
1865 if (isAttached()) {
1866 getManagerThread().schedule(new DebuggerCommandImpl() {
1867 protected void action() throws Exception {
1868 // set the flag before enabling/disabling cause it affects if breakpoints will create requests
1869 if (myBreakpointsMuted.getAndSet(muted) != muted) {
1870 final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager();
1871 if (muted) {
1872 breakpointManager.disableBreakpoints(DebugProcessImpl.this);
1874 else {
1875 breakpointManager.enableBreakpoints(DebugProcessImpl.this);
1881 else {
1882 myBreakpointsMuted.set(muted);
1887 public boolean areBreakpointsMuted() {
1888 return myBreakpointsMuted.get();