Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b9ebfb20a4d94d5b66ddafe0823ce30e267968af (plain) (blame)
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
/*******************************************************************************
 * Copyright (c) 2010, 2014 TUBITAK BILGEM-ITI and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Onur Akdemir (TUBITAK BILGEM-ITI) - Multi-process debugging (Bug 237306)
 *     Marc Khouzam (Ericsson) - Workaround for Bug 352998
 *     Marc Khouzam (Ericsson) - Update breakpoint handling for GDB >= 7.4 (Bug 389945)
 *     Alvaro Sanchez-Leon (Ericsson) - Breakpoint Enable does not work after restarting the application (Bug 456959)
 *******************************************************************************/
package org.eclipse.cdt.dsf.gdb.service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.eclipse.cdt.debug.core.CDebugUtils;
import org.eclipse.cdt.dsf.concurrent.CountingRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.DsfExecutor;
import org.eclipse.cdt.dsf.concurrent.ImmediateDataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.ImmediateExecutor;
import org.eclipse.cdt.dsf.concurrent.ImmediateRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
import org.eclipse.cdt.dsf.concurrent.Sequence;
import org.eclipse.cdt.dsf.datamodel.DMContexts;
import org.eclipse.cdt.dsf.datamodel.IDMContext;
import org.eclipse.cdt.dsf.debug.service.IBreakpoints.IBreakpointsTargetDMContext;
import org.eclipse.cdt.dsf.debug.service.IMemory.IMemoryDMContext;
import org.eclipse.cdt.dsf.debug.service.IMultiDetach;
import org.eclipse.cdt.dsf.debug.service.IMultiTerminate;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IContainerDMContext;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IExitedDMEvent;
import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService.ICommandControlDMContext;
import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
import org.eclipse.cdt.dsf.gdb.internal.GdbPlugin;
import org.eclipse.cdt.dsf.gdb.service.IGDBTraceControl.ITraceRecordSelectedChangedDMEvent;
import org.eclipse.cdt.dsf.gdb.service.command.IGDBControl;
import org.eclipse.cdt.dsf.mi.service.IMICommandControl;
import org.eclipse.cdt.dsf.mi.service.IMIContainerDMContext;
import org.eclipse.cdt.dsf.mi.service.IMIExecutionDMContext;
import org.eclipse.cdt.dsf.mi.service.IMIProcessDMContext;
import org.eclipse.cdt.dsf.mi.service.IMIRunControl;
import org.eclipse.cdt.dsf.mi.service.IMIRunControl.MIRunMode;
import org.eclipse.cdt.dsf.mi.service.MIBreakpointsManager;
import org.eclipse.cdt.dsf.mi.service.MIProcesses;
import org.eclipse.cdt.dsf.mi.service.command.CommandFactory;
import org.eclipse.cdt.dsf.mi.service.command.output.MIAddInferiorInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.MIInfo;
import org.eclipse.cdt.dsf.service.DsfServiceEventHandler;
import org.eclipse.cdt.dsf.service.DsfSession;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunch;

/**
 * Adding support for multi-process with GDB 7.2
 * 
 * @since 4.0
 */
public class GDBProcesses_7_2 extends GDBProcesses_7_1 implements IMultiTerminate, IMultiDetach {

	abstract private class ConditionalRequestMonitor extends ImmediateDataRequestMonitor<Boolean> {

    	private Iterator<? extends IDMContext> fIterator;
    	private boolean fAll = true;
    	private DataRequestMonitor<Boolean> fParentMonitor;

		private ConditionalRequestMonitor(Iterator<? extends IDMContext> it, boolean all, DataRequestMonitor<Boolean> parentMonitor) {
			super(parentMonitor);
			fAll = all;
			fParentMonitor = parentMonitor;
			fIterator = it;
		}

		@Override
    	protected void handleCompleted() {
			if (!isSuccess()) {
				fParentMonitor.setStatus(getStatus());
				fParentMonitor.done();
				return;
			}

			if (getData() != fAll) {
				fParentMonitor.setData(getData());
				fParentMonitor.done();
			}
			else if (!fIterator.hasNext()) {
				fParentMonitor.setData(fAll);
				fParentMonitor.done();
			}
			else {
				proceed(fIterator, fAll, fParentMonitor);
			}
    	}
		
		abstract protected void proceed(Iterator<? extends IDMContext> it, boolean all, DataRequestMonitor<Boolean> parentMonitor);
	}
    
    private class CanDetachRequestMonitor extends ConditionalRequestMonitor {

		private CanDetachRequestMonitor(Iterator<? extends IDMContext> it, boolean all, DataRequestMonitor<Boolean> parentMonitor) {
			super(it, all, parentMonitor);
		}

		@Override
		protected void proceed(Iterator<? extends IDMContext> it, boolean all, DataRequestMonitor<Boolean> parentMonitor) {
			canDetachDebuggerFromProcess(it.next(), new CanDetachRequestMonitor(it, all, parentMonitor));
		}

	}

	private class CanTerminateRequestMonitor extends ConditionalRequestMonitor {

		private CanTerminateRequestMonitor(Iterator<? extends IDMContext> it, boolean all, DataRequestMonitor<Boolean> parentMonitor) {
			super(it, all, parentMonitor);
		}

		@Override
		protected void proceed(Iterator<? extends IDMContext> it, boolean all, DataRequestMonitor<Boolean> parentMonitor) {
			canTerminate((IThreadDMContext)it.next(), new CanTerminateRequestMonitor(it, all, parentMonitor));
		}
	}

	/**
     * The id of the single thread to be used during event visualization. 
     * @since 4.1 
     */
    protected static final String TRACE_VISUALIZATION_THREAD_ID = "1"; //$NON-NLS-1$

    private CommandFactory fCommandFactory;
    private IGDBControl fCommandControl;
    private IGDBBackend fBackend;

	private final static String INVALID = "invalid";   //$NON-NLS-1$
	
	/**
	 * Keep track if we need to reconnect to the target
	 * due to a workaround because of a GDB 7.2 bug.
	 * Bug 352998
	 */
	private boolean fNeedToReconnect;
	
    /**
     * Set of processes that are currently being restarted.
     * We use this set for such things as not removing breakpoints
     * because we know the process will be restarted.
     */
	private Set<IContainerDMContext> fProcRestarting = new HashSet<IContainerDMContext>();

	/** 
	 * Indicates that we are currently visualizing trace data.
	 */
	private boolean fTraceVisualization;

	public GDBProcesses_7_2(DsfSession session) {
		super(session);
	}

	@Override
	public void initialize(final RequestMonitor requestMonitor) {
		super.initialize(new ImmediateRequestMonitor(requestMonitor) {
			@Override
			protected void handleSuccess() {
				doInitialize(requestMonitor);
			}
		});
	}

	/**
	 * This method initializes this service after our superclass's initialize()
	 * method succeeds.
	 * 
	 * @param requestMonitor
	 *            The call-back object to notify when this service's
	 *            initialization is done.
	 */
	private void doInitialize(RequestMonitor requestMonitor) {
        register(new String[]{ IMultiDetach.class.getName(), IMultiTerminate.class.getName() }, new Hashtable<String,String>());

		fCommandControl = getServicesTracker().getService(IGDBControl.class);
        fCommandFactory = getServicesTracker().getService(IMICommandControl.class).getCommandFactory();
    	fBackend = getServicesTracker().getService(IGDBBackend.class);
    	
    	requestMonitor.done();
	}

	@Override
	public void shutdown(RequestMonitor requestMonitor) {
		super.shutdown(requestMonitor);
	}
	
	/** @since 4.1 */
	protected boolean getTraceVisualization() {
		return fTraceVisualization;
	}

	/** @since 4.1 */
	protected void setTraceVisualization(boolean visualizing) {
		fTraceVisualization = visualizing;
	}
	
	@Override
    public IMIContainerDMContext createContainerContextFromGroupId(ICommandControlDMContext controlDmc, String groupId) {
    	String pid = getGroupToPidMap().get(groupId);
    	if (pid == null) {
    		// For GDB 7.2, the groupId is no longer the pid, so use our wildcard pid instead
    		pid = MIProcesses.UNKNOWN_PROCESS_ID;
    	}
    	IProcessDMContext processDmc = createProcessContext(controlDmc, pid);
    	return createContainerContext(processDmc, groupId);
    }
    
    @Override
	protected boolean doIsDebuggerAttachSupported() {
		// Multi-process is not applicable to post-mortem sessions (core)
		// or to non-attach remote sessions.
		if (fBackend.getSessionType() == SessionType.CORE) {
			return false;
		}

		if (fBackend.getSessionType() == SessionType.REMOTE && !fBackend.getIsAttachSession()) {
			return false;
		}
		
		// Multi-process does not work for all-stop right now
		IMIRunControl runControl = getServicesTracker().getService(IMIRunControl.class);
		if (runControl != null && runControl.getRunMode() == MIRunMode.ALL_STOP) {
			// Only one process is allowed in all-stop (for now)
			return getNumConnected() == 0;
			// NOTE: when we support multi-process in all-stop mode,
			// we will need to interrupt the target to when doing the attach.
		}

		return true;
	}

	@Override
    public void attachDebuggerToProcess(IProcessDMContext procCtx, DataRequestMonitor<IDMContext> rm) {
		attachDebuggerToProcess(procCtx, null, rm);
	}
	
    /**
	 * @since 4.0
	 */
	@Override
	public void attachDebuggerToProcess(final IProcessDMContext procCtx, final String binaryPath, final DataRequestMonitor<IDMContext> dataRm) {
		if (procCtx instanceof IMIProcessDMContext) {
	    	if (!doIsDebuggerAttachSupported()) {
	            dataRm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Attach not supported.", null)); //$NON-NLS-1$
	            dataRm.done();    		
	    		return;
	    	}
	    	
	    	// Use a sequence for better control of each step
	    	ImmediateExecutor.getInstance().execute(new Sequence(getExecutor(), dataRm) {
	    		private IMIContainerDMContext fContainerDmc;

		        private Step[] steps = new Step[] {
		        		// If this is not the very first inferior, we first need create the new inferior
		                new Step() { 
		                    @Override
		                    public void execute(final RequestMonitor rm) {
		                    	if (isInitialProcess()) {
		                    		// If it is the first inferior, GDB has already created it for us
		                    		// We really should get the id from GDB instead of hard-coding it
		        					fContainerDmc = createContainerContext(procCtx, "i1"); //$NON-NLS-1$
		                    		rm.done();
		                    		return;
		                    	}
		                    	
		            	    	ICommandControlDMContext controlDmc = DMContexts.getAncestorOfType(procCtx, ICommandControlDMContext.class);
		            	        fCommandControl.queueCommand(
		            	        		fCommandFactory.createMIAddInferior(controlDmc),
		            	        		new ImmediateDataRequestMonitor<MIAddInferiorInfo>(rm) {
		            	        			@Override
		            	        			protected void handleSuccess() {
		            	        				final String groupId = getData().getGroupId();
		            	        				if (groupId == null || groupId.trim().length() == 0) {
		            	        					rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid gdb group id.", null)); //$NON-NLS-1$
		            	        				} else {
		            	        					fContainerDmc = createContainerContext(procCtx, groupId);
		            	        				}
		            	        				rm.done();
		            	        			}
		            	        		});
		                    }
		                },
		                new Step() { 
		                    @Override
		                    public void execute(final RequestMonitor rm) {
		                    	// Because of a GDB 7.2 bug, for remote-attach sessions,
		                    	// we need to be disconnected from the target
		                    	// when we set the very first binary to be used.
		                    	// So, lets disconnect.
		                    	// Bug 352998
		                    	if (needFixForGDB72Bug352998()) {
		                    		// The bug only applies to remote sessions
		                    		if (fBackend.getSessionType() == SessionType.REMOTE) {
		                    			assert fBackend.getIsAttachSession();
		                    			assert binaryPath != null;

		                    			// We only need the workaround for the very first process we attach to
		                    			if (isInitialProcess()) {	
		                    				ICommandControlDMContext controlDmc = DMContexts.getAncestorOfType(procCtx, ICommandControlDMContext.class);
		                    				fCommandControl.queueCommand(
		                    						fCommandFactory.createMITargetDisconnect(controlDmc),
		                    						new ImmediateDataRequestMonitor<MIInfo>(rm) {
		                    							@Override
		                    							protected void handleSuccess() {
		                    								fNeedToReconnect = true;
		                    								rm.done();
		                    							}
		                    						});
		                    				return;
		                    			}
		                    		}
		                    	}
		                    	
		                    	rm.done();
		                    }
		                },
	    				new Step() { 
	    					@Override
	    					public void execute(final RequestMonitor rm) {
	    						// Now, set the binary to be used.
	    						if (binaryPath != null) {
    				    			fCommandControl.queueCommand(
    				    					fCommandFactory.createMIFileExecAndSymbols(fContainerDmc, binaryPath), 
			    							new ImmediateDataRequestMonitor<MIInfo>(rm) {
    				    						@Override
    				    						protected void handleCompleted() {
    						                    	// Because of a GDB 7.2 bug, for remote-attach sessions,
    						                    	// we need to be disconnected from the target
    						                    	// when we set the very first binary to be used.
    						                    	// Now that we have disconnected and set the binary,
    				    							// we may need to reconnect to the target.
    				    							// If we were unable to set the binary (e.g., if the specified path
    				    							// is invalid) we also need to reconnect to the target before 
    				    							// aborting the rest of the sequence.
    						                    	// Bug 352998
    				    							
    				    							if (fNeedToReconnect) {
    				    								fNeedToReconnect = false;

    				    								// Set the status in case it is an error, so that when rm.done() is automatically
    				    								// called, we continue to abort the sequence if we are dealing with a failure.
    				    								rm.setStatus(getStatus());
    				    							
    						                    		connectToTarget(procCtx, rm);  				    								
    				    							} else {
    				    								super.handleCompleted();
    				    							}
    				    						};
    				    					});
    				    			return;
	    						}

	    						assert fNeedToReconnect == false;
	    				    	rm.done();
	    					}
	    				},
		                // Now, actually do the attach
		                new Step() { 
		                    @Override
		                    public void execute(RequestMonitor rm) {
	    						// For non-stop mode, we do a non-interrupting attach
	    						// Bug 333284
	    						boolean shouldInterrupt = true;
								IMIRunControl runControl = getServicesTracker().getService(IMIRunControl.class);
								if (runControl != null && runControl.getRunMode() == MIRunMode.NON_STOP) {
									shouldInterrupt = false;
								}

	    						fCommandControl.queueCommand(
	    								fCommandFactory.createMITargetAttach(fContainerDmc, ((IMIProcessDMContext)procCtx).getProcId(), shouldInterrupt),
		    							new ImmediateDataRequestMonitor<MIInfo>(rm));
		                    }
		                },
						// Initialize memory data for this process.
	    				new Step() { 
	    					@Override
	    					public void execute(RequestMonitor rm) {
								IGDBMemory memory = getServicesTracker().getService(IGDBMemory.class);
								IMemoryDMContext memContext = DMContexts.getAncestorOfType(fContainerDmc, IMemoryDMContext.class);
								if (memory == null || memContext == null) {
									rm.done();
									return;
								}
								memory.initializeMemoryData(memContext, rm);
	    					}
	    				},
                    	// Start tracking this process' breakpoints.
		                new Step() { 
		                    @Override
		                    public void execute(RequestMonitor rm) {
		                    	MIBreakpointsManager bpmService = getServicesTracker().getService(MIBreakpointsManager.class);
		                    	bpmService.startTrackingBpForProcess(fContainerDmc, rm);
		                    }
		                },
		                // Turn on reverse debugging if it was enabled as a launch option
		                new Step() { 
		                    @Override
		                    public void execute(RequestMonitor rm) {								
								IReverseRunControl reverseService = getServicesTracker().getService(IReverseRunControl.class);
								if (reverseService != null) {
									ILaunch launch = procCtx.getAdapter(ILaunch.class);
									if (launch != null) {
										try {
											boolean reverseEnabled = 
												launch.getLaunchConfiguration().getAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_REVERSE,
														                                     IGDBLaunchConfigurationConstants.DEBUGGER_REVERSE_DEFAULT);
											if (reverseEnabled) {
												reverseService.enableReverseMode(fCommandControl.getContext(), true, rm);
												return;
											}
										} catch (CoreException e) {
											// Ignore, just don't set reverse
										}
									}
								}
								rm.done();
		                    }
		                },
                    	// Store the fully formed container context so it can be returned to the caller
		                // and mark that we are not dealing with the first process anymore.
		                new Step() { 
		                    @Override
		                    public void execute(RequestMonitor rm) {
								dataRm.setData(fContainerDmc);
	                    		setIsInitialProcess(false);

								rm.done();
		                    }
		                },
		    	};
		        
	    		@Override public Step[] getSteps() { return steps; }
	    	});
	    } else {
            dataRm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid process context.", null)); //$NON-NLS-1$
            dataRm.done();
	    }
	}
	
	private void connectToTarget(IProcessDMContext procCtx, RequestMonitor rm) {
		ILaunch launch = procCtx.getAdapter(ILaunch.class);
		assert launch != null;
		if (launch != null) {
			Map<String, Object> attributes = null;
			try {
				attributes = launch.getLaunchConfiguration().getAttributes();
			} catch (CoreException e) {}

			boolean isTcpConnection = CDebugUtils.getAttribute(
					attributes,
					IGDBLaunchConfigurationConstants.ATTR_REMOTE_TCP,
					false);

			if (isTcpConnection) {
				String remoteTcpHost = CDebugUtils.getAttribute(
						attributes,
						IGDBLaunchConfigurationConstants.ATTR_HOST, INVALID);
				String remoteTcpPort = CDebugUtils.getAttribute(
						attributes,
						IGDBLaunchConfigurationConstants.ATTR_PORT, INVALID);

				fCommandControl.queueCommand(
						fCommandFactory.createMITargetSelect(fCommandControl.getContext(), 
								remoteTcpHost, remoteTcpPort, true), 
								new ImmediateDataRequestMonitor<MIInfo>(rm));
			} else {
				String serialDevice = CDebugUtils.getAttribute(
						attributes,
						IGDBLaunchConfigurationConstants.ATTR_DEV, INVALID);

				fCommandControl.queueCommand(
						fCommandFactory.createMITargetSelect(fCommandControl.getContext(), 
								serialDevice, true), 
								new ImmediateDataRequestMonitor<MIInfo>(rm));
			}
		} else {
    		rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Cannot reconnect to target.", null)); //$NON-NLS-1$
    		rm.done();
    	}
	}
	
	@Override
    public void detachDebuggerFromProcess(IDMContext dmc, final RequestMonitor rm) {
    	
		ICommandControlDMContext controlDmc = DMContexts.getAncestorOfType(dmc, ICommandControlDMContext.class);
		final IMIContainerDMContext containerDmc = DMContexts.getAncestorOfType(dmc, IMIContainerDMContext.class);
		
    	if (controlDmc != null && containerDmc != null) {
        	if (!doCanDetachDebuggerFromProcess()) {
                rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Detach not supported.", null)); //$NON-NLS-1$
                rm.done();
                return;
        	}

			IMIRunControl runControl = getServicesTracker().getService(IMIRunControl.class);
			if (runControl != null && !runControl.isTargetAcceptingCommands()) {
				fBackend.interrupt();
			}

        	fCommandControl.queueCommand(
        			fCommandFactory.createMITargetDetach(controlDmc, containerDmc.getGroupId()),
    				new DataRequestMonitor<MIInfo>(getExecutor(), rm) {
    					@Override
    					protected void handleCompleted() {
    						if (isSuccess()) {
    						// Bug in GDB 7.2 where removing an inferior will lead to a crash when running other processes.
    						// I'm hoping it will be fixed in 7.2.1
//    			        	fCommandControl.queueCommand(
//    			        			fCommandFactory.createMIRemoveInferior(fCommandControl.getContext(), containerDmc.getGroupId()),
//    			    				new DataRequestMonitor<MIInfo>(getExecutor(), rm));
    							rm.done();
    						} else {
    							// This command fails with GDB 7.2 because of a GDB bug, which was fixed with GDB 7.2.1
    							// In case we get here, we assume we are using GDB 7.2 (although we should not) and we work
    							// around it.
    							// Also, with GDB 7.2, removing the inferior does not work because of another bug, so we just don't do it.
    					       	fCommandControl.queueCommand(
    				        			fCommandFactory.createMITargetDetach(containerDmc),
    				    				new DataRequestMonitor<MIInfo>(getExecutor(), rm));
    						}
    					}
    				});
    	} else {
            rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid context.", null)); //$NON-NLS-1$
            rm.done();
	    }
	}
	
	@Override
	protected boolean doIsDebugNewProcessSupported() {
		// Multi-process is not applicable to post-mortem sessions (core)
		// or to non-attach remote sessions.
		SessionType type = fBackend.getSessionType();
		
		if (type == SessionType.CORE) {
			return false;
		}

		if (type == SessionType.REMOTE && !fBackend.getIsAttachSession()) {
			return false;
		}

		// Multi-process does not work for all-stop right now
		IMIRunControl runControl = getServicesTracker().getService(IMIRunControl.class);
		if (runControl != null && runControl.getRunMode() == MIRunMode.ALL_STOP) {
			// Only one process is allowed in all-stop (for now)
			return getNumConnected() == 0;
			// NOTE: when we support multi-process in all-stop mode,
			// we will need to interrupt the target to when starting 
			// the new process.
		}

		return true;
	}

	@Override
	protected Sequence getDebugNewProcessSequence(DsfExecutor executor, boolean isInitial, IDMContext dmc, String file, 
												  Map<String, Object> attributes, DataRequestMonitor<IDMContext> rm) {
		return new DebugNewProcessSequence_7_2(executor, isInitial, dmc, file, attributes, rm);
	}
	
	@Override
	public void getProcessesBeingDebugged(final IDMContext dmc, final DataRequestMonitor<IDMContext[]> rm) {
		if (getTraceVisualization()) {
			// If we are visualizing data during a live session, we should not ask GDB for the list of threads,
			// because we will get the list of active threads, while GDB only cares about thread 1 for visualization.
			final IMIContainerDMContext containerDmc = DMContexts.getAncestorOfType(dmc, IMIContainerDMContext.class);
			if (containerDmc != null) {
				IProcessDMContext procDmc = DMContexts.getAncestorOfType(containerDmc, IProcessDMContext.class);
				rm.setData(new IMIExecutionDMContext[]{createExecutionContext(containerDmc, 
                        createThreadContext(procDmc, TRACE_VISUALIZATION_THREAD_ID),
                        TRACE_VISUALIZATION_THREAD_ID)});
				rm.done();
				return;
			}
		}
		
		super.getProcessesBeingDebugged(dmc, rm);
	}
	
	/** 
	 * Creates the container context that is to be used for the new process that will
	 * be created by the restart operation.
	 * This container does not have its pid yet, while the container of the process
	 * that is being restarted does have its pid.
	 * Starting with GDB 7.2, the groupId stays the same when restarting a process, so
	 * we should re-use it; this is particularly important since we support multi-process
	 * and we need the proper groupId
	 * 
	 * @since 4.0
	 */
	@Override
	protected IMIContainerDMContext createContainerContextForRestart(String groupId) {
    	IProcessDMContext processDmc = createProcessContext(fCommandControl.getContext(), MIProcesses.UNKNOWN_PROCESS_ID);
		return createContainerContext(processDmc, groupId);
	}

	@Override
	public void restart(final IContainerDMContext containerDmc, Map<String, Object> attributes,
            			DataRequestMonitor<IContainerDMContext> rm) {
		fProcRestarting.add(containerDmc);
		super.restart(containerDmc, attributes, new ImmediateDataRequestMonitor<IContainerDMContext>(rm) {
			@Override
			protected void handleCompleted() {
				if (!isSuccess()) {
					fProcRestarting.remove(containerDmc);
				}
				setData(getData());
				super.handleCompleted();
			}
		});
	}
	
    /** @since 4.0 */
    @DsfServiceEventHandler
    @Override
	public void eventDispatched(IExitedDMEvent e) {
		IDMContext dmc = e.getDMContext();

		if (dmc instanceof IContainerDMContext) {
			MIBreakpointsManager bpmService = getServicesTracker().getService(MIBreakpointsManager.class);

			// Time to remove the tracking of a restarting process
			boolean restarting = fProcRestarting.remove(dmc);

			if (bpmService != null) {
				if (!restarting) {
					// Process exited, remove it from the thread break point filtering
					bpmService.removeTargetFilter((IContainerDMContext) dmc);

					if (dmc instanceof IBreakpointsTargetDMContext) {
						// A process has died, we should stop tracking its breakpoints, but only if it is not restarting
						// We only do this when the process is a breakpointTargetDMC itself (GDB < 7.4);
						// we don't want to stop tracking breakpoints when breakpoints are only set once
						// for all processes (GDB >= 7.4)
						if (fBackend.getSessionType() != SessionType.CORE) {
							IBreakpointsTargetDMContext bpTargetDmc = (IBreakpointsTargetDMContext) dmc;
							bpmService.stopTrackingBreakpoints(bpTargetDmc, new ImmediateRequestMonitor() {
								@Override
								protected void handleCompleted() {
									// Ok, no need to report any error because we may have already shutdown.
									// We need to override handleCompleted to avoid risking having a error printout in the log
								}
							});
						}
					}
				}
			}
		}
    	
    	super.eventDispatched(e);
    }
    
    /** 
     * GDB 7.2 has a bug which causes a gdbserver crash if we set the binary after we
     * have connected to the target.  Because GDB 7.2.1 was not released when CDT 8.0
     * was released, we need to workaround the bug in Eclipse.
     * 
     * This method can be overridden to easily disable the workaround, for versions
     * of GDB that no longer have the bug.
     * 
     * See http://sourceware.org/ml/gdb-patches/2011-03/msg00531.html
     * and Bug 352998
     * 
     * @since 4.1 
     */
    protected boolean needFixForGDB72Bug352998() {
    	return true;
    }
    
    /**
	 * @since 4.1
	 */
    @DsfServiceEventHandler
    public void eventDispatched(ITraceRecordSelectedChangedDMEvent e) {
    	setTraceVisualization(e.isVisualizationModeEnabled());
    }

	/**
	 * @since 4.6
	 */
	@Override
	public void canDetachDebuggerFromSomeProcesses(IDMContext[] dmcs, final DataRequestMonitor<Boolean> rm) {
		canDetachFromProcesses(dmcs, false, rm);
	}

	/**
	 * @since 4.6
	 */
	@Override
	public void canDetachDebuggerFromAllProcesses(IDMContext[] dmcs, DataRequestMonitor<Boolean> rm) {
		canDetachFromProcesses(dmcs, true, rm);
	}

	/**
	 * @since 4.6
	 */
	protected void canDetachFromProcesses(IDMContext[] dmcs, boolean all, DataRequestMonitor<Boolean> rm) {
		Set<IMIContainerDMContext> contDmcs = new HashSet<IMIContainerDMContext>();
		for (IDMContext c : dmcs) {
			IMIContainerDMContext contDmc = DMContexts.getAncestorOfType(c, IMIContainerDMContext.class);
			if (contDmc != null) {
				contDmcs.add(contDmc);
			}
		}

		Iterator<IMIContainerDMContext> it = contDmcs.iterator();
		if (!it.hasNext()) {
			rm.setData(false);
			rm.done();
			return;
		}
		canDetachDebuggerFromProcess(it.next(), new CanDetachRequestMonitor(it, all, rm));
	}

	/**
	 * @since 4.6
	 */
	@Override
	public void detachDebuggerFromProcesses(IDMContext[] dmcs, final RequestMonitor rm) {
		Set<IMIContainerDMContext> contDmcs = new HashSet<IMIContainerDMContext>();
		for (IDMContext c : dmcs) {
			IMIContainerDMContext contDmc = DMContexts.getAncestorOfType(c, IMIContainerDMContext.class);
			if (contDmc != null) {
				contDmcs.add(contDmc);
			}
		}
		if (contDmcs.isEmpty()) {
			rm.done();
			return;
		}

		CountingRequestMonitor crm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), rm);
		crm.setDoneCount(contDmcs.size());
		for (IMIContainerDMContext contDmc : contDmcs) {
			detachDebuggerFromProcess(contDmc, crm);
		}
	}

	/**
	 * @since 4.6
	 */
	@Override
	public void canTerminateSome(IThreadDMContext[] dmcs, DataRequestMonitor<Boolean> rm) {
		canTerminate(dmcs, false, rm);
	}

	/**
	 * @since 4.6
	 */
	@Override
	public void canTerminateAll(IThreadDMContext[] dmcs, DataRequestMonitor<Boolean> rm) {
		canTerminate(dmcs, true, rm);
	}

	/**
	 * @since 4.6
	 */
	protected void canTerminate(IThreadDMContext[] dmcs, boolean all, DataRequestMonitor<Boolean> rm) {
		Iterator<IThreadDMContext> it = Arrays.asList(dmcs).iterator();
		if (!it.hasNext()) {
			rm.setData(false);
			rm.done();
			return;
		}
		canTerminate(it.next(), new CanTerminateRequestMonitor(it, all, rm));
	}

	/**
	 * @since 4.6
	 */
	@Override
	public void terminate(IThreadDMContext[] dmcs, RequestMonitor rm) {
		if (dmcs.length == 0) {
			rm.done();
			return;
		}

		CountingRequestMonitor crm = new CountingRequestMonitor(ImmediateExecutor.getInstance(), rm);
		crm.setDoneCount(dmcs.length);
		for (IThreadDMContext threadDmc : dmcs) {
			terminate(threadDmc, crm);
		}
	}
}

Back to the top