Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a466f628e1dfac7e5609fedc3e79294306dd1ae9 (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
/*******************************************************************************
 * Copyright (c) 2011 Ericsson 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:
 *     Ericsson - initial API and implementation
 *******************************************************************************/
package org.eclipse.cdt.dsf.gdb.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.cdt.debug.core.CDebugUtils;
import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.DsfExecutor;
import org.eclipse.cdt.dsf.concurrent.IDsfStatusConstants;
import org.eclipse.cdt.dsf.concurrent.ImmediateExecutor;
import org.eclipse.cdt.dsf.concurrent.ReflectionSequence;
import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
import org.eclipse.cdt.dsf.datamodel.DMContexts;
import org.eclipse.cdt.dsf.debug.service.IBreakpoints.IBreakpointsTargetDMContext;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IContainerDMContext;
import org.eclipse.cdt.dsf.debug.service.command.ICommand;
import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
import org.eclipse.cdt.dsf.gdb.IGdbDebugConstants;
import org.eclipse.cdt.dsf.gdb.internal.GdbPlugin;
import org.eclipse.cdt.dsf.gdb.launching.InferiorRuntimeProcess;
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.command.CommandFactory;
import org.eclipse.cdt.dsf.mi.service.command.MIInferiorProcess;
import org.eclipse.cdt.dsf.mi.service.command.output.MIBreakInsertInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.MIBreakpoint;
import org.eclipse.cdt.dsf.mi.service.command.output.MIInfo;
import org.eclipse.cdt.dsf.service.DsfServicesTracker;
import org.eclipse.cdt.utils.pty.PTY;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.model.IProcess;

/**
 * This class causes a process to start (run for the first time), or to
 * be restarted.  The complexity is due to the handling of reverse debugging,
 * which this class transparently enables if necessary.
 * 
 * This sequence is used for GDB >= 7.0 which supports reverse debugging.
 * 
 * @since 4.0
 */
public class StartOrRestartProcessSequence_7_0 extends ReflectionSequence {
		
	private IGDBControl fCommandControl;
	private CommandFactory fCommandFactory;
	private IGDBProcesses fProcService;
	private IReverseRunControl fReverseService;
	private IGDBBackend fBackend;
	
	private DsfServicesTracker fTracker;

	// This variable will be used to store the original container context,
	// but once the new process is start (restarted), it will contain the new
	// container context.  This new container context has for parent the process
	// context, which holds the new pid.
	private IContainerDMContext fContainerDmc;
	
	// If the user requested a stop_on_main, this variable will hold the breakpoint
	private MIBreakpoint fUserBreakpoint;
	// Since the stop_on_main option allows the user to set the breakpoint on any
	// symbol, we use this variable to know if the stop_on_main breakpoint was really
	// on the main() method.
	private boolean fUserBreakpointIsOnMain;
	
	private boolean fReverseEnabled;
	private final Map<String, Object> fAttributes;
	
	// Indicates if the sequence is being used for a restart or a start
	private final boolean fRestart;
	
	private PTY fPty;
	
	// Store the dataRM so that we can fill it with the new container context, which we must return
	// Although we can access this through Sequence.getRequestMonitor(), we would loose the type-checking.
	// Therefore, doing it like this is more future-proof.
	private final DataRequestMonitor<IContainerDMContext> fDataRequestMonitor;

	
	protected IContainerDMContext getContainerContext() {
		return fContainerDmc;
	}
	
	protected MIBreakpoint getUserBreakpoint() {
		return fUserBreakpoint;
	}
	
	protected boolean getUserBreakpointIsOnMain() {
		return fUserBreakpointIsOnMain;
	}

	    
	public StartOrRestartProcessSequence_7_0(DsfExecutor executor, IContainerDMContext containerDmc, Map<String, Object> attributes, 
										 boolean restart, DataRequestMonitor<IContainerDMContext> rm) {
		super(executor, rm);
		
		assert executor != null;
		assert containerDmc != null;
		if (attributes == null) {
			// If no attributes are specified, simply use an empty map.
			attributes = new HashMap<String, Object>();
		}
		
		fContainerDmc = containerDmc;
		fAttributes = attributes;
		fRestart = restart;
		fDataRequestMonitor = rm;
	}

	@Override
	protected String[] getExecutionOrder(String group) {
		if (GROUP_TOP_LEVEL.equals(group)) {
				return new String[] {
						"stepInitializeBaseSequence",  //$NON-NLS-1$
						"stepInsertStopOnMainBreakpoint",  //$NON-NLS-1$
						"stepSetBreakpointForReverse",   //$NON-NLS-1$
						"stepInitializeInputOutput",   //$NON-NLS-1$
						"stepCreateConsole",    //$NON-NLS-1$
						"stepRunProgram",   //$NON-NLS-1$
						"stepSetReverseOff",   //$NON-NLS-1$
						"stepEnableReverse",   //$NON-NLS-1$
						"stepContinue",   //$NON-NLS-1$
						"stepCleanupBaseSequence",   //$NON-NLS-1$
				};
		}
		return null;
	}
	
	/** 
	 * Initialize the members of the StartOrRestartProcessSequence_7_0 class.
	 * This step is mandatory for the rest of the sequence to complete.
	 */
	@Execute
	public void stepInitializeBaseSequence(RequestMonitor rm) {
		fTracker = new DsfServicesTracker(GdbPlugin.getBundleContext(), fContainerDmc.getSessionId());
		fCommandControl = fTracker.getService(IGDBControl.class);
        fCommandFactory = fTracker.getService(IMICommandControl.class).getCommandFactory();		
		fProcService = fTracker.getService(IGDBProcesses.class);
		fBackend = fTracker.getService(IGDBBackend.class);

        if (fCommandControl == null || fCommandFactory == null || fProcService == null) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Cannot obtain service", null)); //$NON-NLS-1$
			rm.done();
			return;
		}
        
		fReverseService = fTracker.getService(IReverseRunControl.class);
		if (fReverseService != null) {
			// Although the option to use reverse debugging could be on, we only check
			// it if we actually have a reverse debugging service.  There is no point
			// in trying to handle reverse debugging if it is not available.
			fReverseEnabled = CDebugUtils.getAttribute(fAttributes, 
													   IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_REVERSE,
													   IGDBLaunchConfigurationConstants.DEBUGGER_REVERSE_DEFAULT);
		}

		rm.done();
	}
	
	/** 
	 * Rollback method for {@link #stepInitializeBaseSequence()}
	 */
	@RollBack("stepInitializeBaseSequence")
	public void rollBackInitializeBaseSequence(RequestMonitor rm) {
		if (fTracker != null) fTracker.dispose();
		fTracker = null;
		rm.done();
	}
	
	/**
	 * If the user requested a 'stopOnMain', let's set the temporary breakpoint
	 * where the user specified.
	 */
	@Execute
	public void stepInsertStopOnMainBreakpoint(final RequestMonitor rm) {
		boolean userRequestedStop = CDebugUtils.getAttribute(fAttributes, 
															 ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN,
															 false);

		if (userRequestedStop) {
			String userStopSymbol = CDebugUtils.getAttribute(fAttributes, 
															 ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN_SYMBOL,
															 ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT);

			IBreakpointsTargetDMContext bpTargetDmc = DMContexts.getAncestorOfType(getContainerContext(), IBreakpointsTargetDMContext.class);

			fCommandControl.queueCommand(
					fCommandFactory.createMIBreakInsert(bpTargetDmc, true, false, null, 0, userStopSymbol, 0),
					new DataRequestMonitor<MIBreakInsertInfo>(ImmediateExecutor.getInstance(), rm) {
						@Override
						public void handleSuccess() {
							if (getData() != null) {
								MIBreakpoint[] breakpoints = getData().getMIBreakpoints();
								if (breakpoints.length > 0) {
									fUserBreakpoint = breakpoints[0];
								}
							}
							rm.done();
						}
					});
		} else {
			rm.done();
		}
	}

	/**
	 * If reverse debugging, set a breakpoint on main to be able to enable reverse
	 * as early as possible.
	 * If the user has requested a stop at the same point, we could skip this breakpoint
	 * however, we have to first set it to find out!  So, we just leave it.
	 */
	@Execute
	public void stepSetBreakpointForReverse(final RequestMonitor rm) {
		if (fReverseEnabled) {
			IBreakpointsTargetDMContext bpTargetDmc = DMContexts.getAncestorOfType(getContainerContext(), IBreakpointsTargetDMContext.class);

			fCommandControl.queueCommand(
					fCommandFactory.createMIBreakInsert(bpTargetDmc, true, false, null, 0, 
							                            ICDTLaunchConfigurationConstants.DEBUGGER_STOP_AT_MAIN_SYMBOL_DEFAULT, 0),
					new DataRequestMonitor<MIBreakInsertInfo>(ImmediateExecutor.getInstance(), rm) {
						@Override
						public void handleSuccess() {
							if (getData() != null) {
								MIBreakpoint[] breakpoints = getData().getMIBreakpoints();
								if (breakpoints.length > 0 && fUserBreakpoint != null) {
									fUserBreakpointIsOnMain = breakpoints[0].getAddress().equals(fUserBreakpoint.getAddress());
								}
							}
							rm.done();
						}
					});
		} else {
			rm.done();
		}
	}
	
    /**
     * This method does the necessary work to setup the input/output streams for the
     * inferior process, by either preparing the PTY to be used, or by simply leaving
     * the PTY null, which indicates that the input/output streams of the CLI should
     * be used instead; this decision is based on the type of session.
     */
	@Execute
    public void stepInitializeInputOutput(final RequestMonitor rm) {
    	if (fBackend.getSessionType() == SessionType.REMOTE && !fBackend.getIsAttachSession()) {
    		// Remote non-attach sessions don't support multi-process and therefore will not
    		// start new processes.  Those sessions will only start the one process, which should
    		// not have a console, because it's output is handled by GDB server.
    		fPty = null;
    		rm.done();
    	} else {
    		// Every other type of session that can get to this code, is starting a new process
    		// and requires a pty for it.
    		try {
    			fPty = new PTY();

    			// Tell GDB to use this PTY
    			fCommandControl.queueCommand(
    					fCommandFactory.createMIInferiorTTYSet((IMIContainerDMContext)getContainerContext(), fPty.getSlaveName()), 
    					new DataRequestMonitor<MIInfo>(ImmediateExecutor.getInstance(), rm) {
    						@Override
    						protected void handleFailure() {
    							// We were not able to tell GDB to use the PTY
    							// so we won't use it at all.
    			    			fPty = null;
    			        		rm.done();
    						}
    					});
    		} catch (IOException e) {
    			fPty = null;
        		rm.done();
    		}
    	}
    }
	
	/**
	 * Before running the program, we must create its console for IO.
	 */
	@Execute
	public void stepCreateConsole(final RequestMonitor rm) {
				Process inferiorProcess;
		    	if (fPty == null) {
		    		inferiorProcess = new MIInferiorProcess(fContainerDmc, fBackend.getMIOutputStream());
		    	} else {
		    		inferiorProcess = new MIInferiorProcess(fContainerDmc, fPty);
		    	}

		    	final Process inferior = inferiorProcess;
				final ILaunch launch = (ILaunch)getContainerContext().getAdapter(ILaunch.class);
				final String groupId = ((IMIContainerDMContext)getContainerContext()).getGroupId();

				// For multi-process, we cannot simply use the name given by the backend service
				// because we may not be starting that process, but another one.
				// Instead, we can look in the attributes for the binary name, which we stored
				// there for this case, specifically.
				// Bug 342351
				IGDBBackend backend = fTracker.getService(IGDBBackend.class);
				String defaultPathName = backend.getProgramPath().lastSegment();
				if (defaultPathName == null) {
					defaultPathName = ""; //$NON-NLS-1$
				}
				String progPathName =
						CDebugUtils.getAttribute(fAttributes,
								ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
								defaultPathName);
				final String pathLabel = new Path(progPathName).lastSegment();    			 

				// Add the inferior to the launch.  
				// This cannot be done on the executor or things deadlock.
				DebugPlugin.getDefault().asyncExec(new Runnable() {
					public void run() {
						String label = pathLabel;
						if (fRestart) {
							// For a restart, remove the old inferior
							IProcess[] launchProcesses = launch.getProcesses();
							for (IProcess process : launchProcesses) {
								String groupAttribute = process.getAttribute(IGdbDebugConstants.INFERIOR_GROUPID_ATTR);
								if (groupId.equals(groupAttribute)) {
									launch.removeProcess(process);
									// Use the exact same label as before
									label = process.getLabel();
									break;
								}
							}
						}

						// Add the inferior
			            InferiorRuntimeProcess runtimeInferior = new InferiorRuntimeProcess(launch, inferior, label, null);
			            runtimeInferior.setAttribute(IGdbDebugConstants.INFERIOR_GROUPID_ATTR, groupId);
			            launch.addProcess(runtimeInferior);

						rm.done();
					}
				});
	}
	
	/**
	 * Now, run the program.
	 */
	@Execute
	public void stepRunProgram(final RequestMonitor rm) {
		ICommand<MIInfo> command;
		if (useContinueCommand()) {
			command = fCommandFactory.createMIExecContinue(fContainerDmc);
		} else {
			command = fCommandFactory.createMIExecRun(fContainerDmc);	
		}
		fCommandControl.queueCommand(command, new DataRequestMonitor<MIInfo>(ImmediateExecutor.getInstance(), rm) {
			@Override
			protected void handleSuccess() {
				// Now that the process is started, the pid has been allocated
				// so we need to fetch the proper container context
				// We replace our current context which does not have the pid, with one that has the pid.
				if (fContainerDmc instanceof IMIContainerDMContext) {	
					fContainerDmc = fProcService.createContainerContextFromGroupId(fCommandControl.getContext(), ((IMIContainerDMContext)fContainerDmc).getGroupId());
					
					// This is the container context that this sequence is supposed to return: set the dataRm
					fDataRequestMonitor.setData(fContainerDmc);					
				} else {
					assert false : "Container context was not an IMIContainerDMContext"; //$NON-NLS-1$
				}
				rm.done();
			}
		});
	}
	
	/**
	 * In case of a restart, we must mark reverse debugging as disabled because
	 * GDB has turned it off. We may have to turn it back on after.
	 */
	@Execute
	public void stepSetReverseOff(RequestMonitor rm) {
		if (fRestart) {
			GDBRunControl_7_0 reverseService = fTracker.getService(GDBRunControl_7_0.class);
			if (reverseService != null) {
				reverseService.setReverseModeEnabled(false);
			}
		}
		rm.done();
	}
	
	/**
	 * Since we have started the program, we can turn on reverse debugging if needed.
	 * We know the program will stop since we set a breakpoint on main, to enable reverse.
	 */
	@Execute
	public void stepEnableReverse(RequestMonitor rm) {
		if (fReverseEnabled) {
			fReverseService.enableReverseMode(fCommandControl.getContext(), true, rm);
		} else {
			rm.done();
		}
	}
	
	/**
	 * Finally, if we are enabling reverse, and the userSymbolStop is not on main,
	 * we should do a continue because we are currently stopped on main but that 
	 * is not what the user requested
	 */
	@Execute
	public void stepContinue(RequestMonitor rm) {
		if (fReverseEnabled && !fUserBreakpointIsOnMain) {
			fCommandControl.queueCommand(fCommandFactory.createMIExecContinue(fContainerDmc),
					new DataRequestMonitor<MIInfo>(ImmediateExecutor.getInstance(), rm));
		} else {
			rm.done();
		}
	}
	
	/**
	 * Cleanup now that the sequence has been run.
	 */
	@Execute
	public void stepCleanupBaseSequence(final RequestMonitor rm) {
		fTracker.dispose();
		fTracker = null;
		rm.done();
	}
	
    /**
     * This method indicates if we should use the -exec-continue command
     * instead of the -exec-run command.
     * This method can be overridden to allow for customization.
     */
    protected boolean useContinueCommand() {
    	// Note that restart does not apply to remote sessions
    	IGDBBackend backend = fTracker.getService(IGDBBackend.class);
		if (backend == null) {
			return false;
		}
    	// When doing remote non-attach debugging, we use -exec-continue instead of -exec-run
		// For remote attach, if we get here it is that we are starting a new process
		// (multi-process), so we want to use -exec-run
    	return backend.getSessionType() == SessionType.REMOTE && !backend.getIsAttachSession();
    }

}

Back to the top