[Esbox-commits] r115 - in trunk/org.indt.esbox.debug: . META-INF src src/org src/org/indt src/org/indt/esbox src/org/indt/esbox/debug src/org/indt/esbox/debug/internal src/org/indt/esbox/debug/ui

raul at garage.maemo.org raul at garage.maemo.org
Thu Oct 11 15:56:51 EEST 2007


Author: raul
Date: 2007-10-11 15:56:51 +0300 (Thu, 11 Oct 2007)
New Revision: 115

Added:
   trunk/org.indt.esbox.debug/.classpath
   trunk/org.indt.esbox.debug/.project
   trunk/org.indt.esbox.debug/META-INF/
   trunk/org.indt.esbox.debug/META-INF/MANIFEST.MF
   trunk/org.indt.esbox.debug/build.properties
   trunk/org.indt.esbox.debug/plugin.xml
   trunk/org.indt.esbox.debug/src/
   trunk/org.indt.esbox.debug/src/org/
   trunk/org.indt.esbox.debug/src/org/indt/
   trunk/org.indt.esbox.debug/src/org/indt/esbox/
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/DebugActivator.java
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBCDIDebugger.java
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBServerCDIDebugger.java
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxMIProcessAdapter.java
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/ui/
   trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/ui/GDBServerDebuggerPage.java
Log:
Initial import of debug component.

Added: trunk/org.indt.esbox.debug/.classpath
===================================================================
--- trunk/org.indt.esbox.debug/.classpath	                        (rev 0)
+++ trunk/org.indt.esbox.debug/.classpath	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>

Added: trunk/org.indt.esbox.debug/.project
===================================================================
--- trunk/org.indt.esbox.debug/.project	                        (rev 0)
+++ trunk/org.indt.esbox.debug/.project	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>org.indt.esbox.debug</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.pde.ManifestBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.pde.SchemaBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.pde.PluginNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>

Added: trunk/org.indt.esbox.debug/META-INF/MANIFEST.MF
===================================================================
--- trunk/org.indt.esbox.debug/META-INF/MANIFEST.MF	                        (rev 0)
+++ trunk/org.indt.esbox.debug/META-INF/MANIFEST.MF	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,20 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Debug Plug-in
+Bundle-SymbolicName: org.indt.esbox.debug;singleton:=true
+Bundle-Version: 1.0.0
+Bundle-Activator: org.indt.esbox.debug.DebugActivator
+Bundle-Vendor: INdT
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.eclipse.cdt.core,
+ org.eclipse.cdt.debug.core,
+ org.eclipse.cdt.debug.mi.core,
+ org.eclipse.cdt.debug.mi.ui,
+ org.eclipse.debug.ui,
+ org.indt.esbox.core,
+ org.eclipse.cdt.debug.ui,
+ org.eclipse.cdt.debug.gdbjtag.ui,
+ org.eclipse.cdt,
+ org.eclipse.cdt.ui
+Eclipse-LazyStart: true

Added: trunk/org.indt.esbox.debug/build.properties
===================================================================
--- trunk/org.indt.esbox.debug/build.properties	                        (rev 0)
+++ trunk/org.indt.esbox.debug/build.properties	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               plugin.xml

Added: trunk/org.indt.esbox.debug/plugin.xml
===================================================================
--- trunk/org.indt.esbox.debug/plugin.xml	                        (rev 0)
+++ trunk/org.indt.esbox.debug/plugin.xml	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.2"?>
+<plugin>
+   <extension
+         point="org.eclipse.cdt.debug.core.CDebugger">
+      <debugger
+            class="org.indt.esbox.debug.internal.ESboxGDBCDIDebugger"
+            cpu="native"
+            id="esboxGDBDebugger"
+            modes="run,core,attach"
+            name="ESbox GDB Debugger"
+            platform="*">
+      </debugger>
+      <debugger
+            class="org.indt.esbox.debug.internal.ESboxGDBServerCDIDebugger"
+            cpu="*"
+            id="esboxGDBServerDebugger"
+            modes="run"
+            name="ESbox GDB Server Debugger"
+            platform="*">
+      </debugger>
+   </extension>
+   <extension
+         point="org.eclipse.cdt.debug.ui.CDebuggerPage">
+      <debuggerPage
+            class="org.eclipse.cdt.debug.mi.internal.ui.GDBDebuggerPage"
+            debuggerID="esboxGDBDebugger"
+            id="esboxGDBDebuggerPage">
+      </debuggerPage>
+      <debuggerPage
+            class="org.indt.esbox.debug.ui.GDBServerDebuggerPage"
+            debuggerID="esboxGDBServerDebugger"
+            id="esboxGDBServerDebuggerPage">
+      </debuggerPage>
+   </extension>
+
+</plugin>

Added: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/DebugActivator.java
===================================================================
--- trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/DebugActivator.java	                        (rev 0)
+++ trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/DebugActivator.java	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,431 @@
+/*******************************************************************************
+ * Copyright (c) 2007 INdT.
+ * 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:
+ *    Raul Herbster (raul at embedded.ufcg.edu.br) (UFCG) - initial API and implementation
+ *******************************************************************************/
+
+package org.indt.esbox.debug;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.eclipse.cdt.debug.mi.core.IMITTY;
+import org.eclipse.cdt.debug.mi.core.MIException;
+import org.eclipse.cdt.debug.mi.core.MIPlugin;
+import org.eclipse.cdt.debug.mi.core.MIProcess;
+import org.eclipse.cdt.debug.mi.core.MISession;
+import org.eclipse.cdt.debug.mi.core.MITTYAdapter;
+import org.eclipse.cdt.debug.mi.core.cdi.Session;
+import org.eclipse.cdt.debug.mi.core.command.CLITargetAttach;
+import org.eclipse.cdt.debug.mi.core.command.CommandFactory;
+import org.eclipse.cdt.debug.mi.core.command.MIStackListFrames;
+import org.eclipse.cdt.debug.mi.core.command.MITargetSelect;
+import org.eclipse.cdt.debug.mi.core.output.MIInfo;
+import org.eclipse.cdt.utils.pty.PTY;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Preferences;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.indt.esbox.core.CoreActivator;
+import org.indt.esbox.core.ESboxPreferenceConstants;
+import org.indt.esbox.debug.internal.ESboxMIProcessAdapter;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class DebugActivator extends AbstractUIPlugin {
+
+	// The plug-in ID
+	public static final String PLUGIN_ID = "org.indt.esbox.debug";
+
+	// The shared instance
+	private static DebugActivator plugin;
+	
+	private static final String GDBINIT = ".gdbinit"; 
+
+	private static final String GDB = "gdb";
+	
+	private static final int CMDTIMEOUT = 1000;
+	
+	private static final int LAUNCHTIMEOUT = 1000;
+	
+	/**
+	 * The constructor
+	 */
+	public DebugActivator() {
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+	 */
+	public void start(BundleContext context) throws Exception {
+		super.start(context);
+		plugin = this;
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+	 */
+	public void stop(BundleContext context) throws Exception {
+		plugin = null;
+		super.stop(context);
+	}
+
+	/**
+	 * Returns the shared instance
+	 *
+	 * @return the shared instance
+	 */
+	public static DebugActivator getDefault() {
+		return plugin;
+	}
+
+	/**
+	 * Returns an image descriptor for the image file at the given
+	 * plug-in relative path.
+	 *
+	 * @param path the path
+	 * @return the image descriptor
+	 */
+	public static ImageDescriptor getImageDescriptor(String path) {
+		return AbstractUIPlugin.imageDescriptorFromPlugin("org.indt.esbox.debug", path);
+	}
+	
+	/**
+	 * Convenience method which returns the unique identifier of this plugin.
+	 */
+	public static String getUniqueIdentifier() {
+		if (getDefault() == null) {
+			// If the default instance is not yet initialized,
+			// return a static identifier. This identifier must
+			// match the plugin id defined in plugin.xml
+			return PLUGIN_ID;
+		}
+		return getDefault().getBundle().getSymbolicName();
+	}
+	
+	/**
+	 * Creates a GDB session for a C binary. 
+	 * @param gdb the string for start GDB debugger.
+	 * @param program the programm to be debugged.
+	 * @param cwd the location for running GDB.
+	 * @param gdbinit the gdbinit file
+	 * @param monitor the monitor for task progress.
+	 * @return the session created.
+	 * @throws IOException if any trouble related to I/O occurrs.
+	 * @throws MIException if any problem related to GDB invocation.
+	 */
+	public Session createCSession(String gdb, File program, File cwd, String gdbinit, IProgressMonitor monitor) throws IOException, MIException {		
+		IMITTY pty = null;
+		boolean failed = false;
+
+		try {
+			PTY pseudo = new PTY();
+			pty = new MITTYAdapter(pseudo);
+		} catch (IOException e) {
+			// Should we not print/log this ?
+		}
+
+		try {
+			return createCSession(gdb, program, cwd, gdbinit, pty, monitor);
+		} catch (IOException exc) {
+			failed = true;
+			throw exc;
+		} catch (MIException exc) {
+			failed = true;
+			throw exc;
+		} finally {
+			if (failed) {
+				// Shutdown the pty console.
+				if (pty != null) {
+					try {
+						OutputStream out = pty.getOutputStream();
+						if (out != null) {
+							out.close();
+						}
+						InputStream in = pty.getInputStream();
+						if (in != null) {
+							in.close();
+						}
+					} catch (IOException e) {
+					}
+				}
+			}
+		}
+	}
+	
+	/**
+	 * Creates a GDB session for a C binary. 
+	 * @param gdb the string for start GDB debugger.
+	 * @param program the programm to be debugged.
+	 * @param cwd the location for running GDB.
+	 * @param gdbinit the gdbinit file
+	 * @param pty the pty to stablish communication with process.
+	 * @param monitor the monitor for task progress.
+	 * @return the session created.
+	 * @throws IOException if any trouble related to I/O occurrs.
+	 * @throws MIException if any problem related to GDB invocation.
+	 */
+	public Session createCSession(String gdb, File program, File cwd, String gdbinit, IMITTY pty, IProgressMonitor monitor) throws IOException, MIException {		
+		if (gdb == null || gdb.length() == 0) {
+			gdb =  GDB;
+		}
+		
+		if (gdbinit == null || gdbinit.length() == 0) {
+			gdbinit = GDBINIT;
+		}
+
+		if (monitor == null) {
+			monitor = new NullProgressMonitor();
+		}
+		
+		String sboxDirPath = getSBoxDirPath(cwd);
+		String sboxExePath = getSBoxExePath(program);
+		
+		
+		String[] args;
+		if (pty != null) {
+			if (program == null) {
+				args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "-q", "-nw", "-tty", pty.getSlaveName(), "-i", "mi"}; 
+			} else {
+				args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "-q", "-nw", "-tty", pty.getSlaveName(), "-i", "mi", sboxExePath};
+			}
+		} else {
+			if (program == null) {
+				args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "-q", "-nw", "-i", "mi"}; 
+			} else {
+				args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "-q", "-nw", "-i", "mi", sboxExePath}; 
+			}
+		}
+
+		MIProcess pgdb = new ESboxMIProcessAdapter(args, monitor);		
+		MISession session;
+		try {
+			session = createMISession(pgdb, pty, MISession.PROGRAM);
+		} catch (MIException e) {
+			pgdb.destroy();
+			throw e;
+		}
+		// Try to detect if we have been attach/connected via "target remote localhost:port"
+		// or "attach" and set the state to be suspended.
+		try {
+			CommandFactory factory = session.getCommandFactory();
+			MIStackListFrames frames = factory.createMIStackListFrames();
+			session.postCommand(frames);
+			MIInfo info = frames.getMIInfo();
+			if (info == null) {
+				pgdb.destroy();
+				throw new MIException(MIPlugin.getResourceString("src.common.No_answer")); //$NON-NLS-1$
+			}
+			//@@@ We have to manually set the suspended state since we have some stackframes
+			session.getMIInferior().setSuspended();
+			session.getMIInferior().update();
+		} catch (MIException e) {
+			// If an exception is thrown that means ok
+			// we did not attach/connect to any target.
+		}		
+		return new Session(session, false);
+
+	}
+	
+	/**
+	 * Creates a session for core sessions.
+	 * @param gdb the string for start GDB debugger.
+	 * @param program the programm to be debugged.
+	 * @param cwd the location for running GDB.
+	 * @param core file for core sessions.
+	 * @param gdbinit the gdbinit file
+	 * @param monitor the monitor for task progress.
+	 * @return the session created.
+	 * @throws IOException if any trouble related to I/O occurrs.
+	 * @throws MIException if any problem related to GDB invocation.
+	 */
+	public Session createCSession(String gdb, File program, File core, File cwd, String gdbinit, IProgressMonitor monitor) throws IOException, MIException {	
+		if (gdb == null || gdb.length() == 0) {
+			gdb =  GDB;
+		}
+		
+		if (gdbinit == null || gdbinit.length() == 0) {
+			gdbinit = GDBINIT;
+		}
+
+		if (monitor == null) {
+			monitor = new NullProgressMonitor();
+		}
+
+		String sboxDirPath = getSBoxDirPath(cwd);
+		String sboxExePath = getSBoxExePath(program);
+		
+		String[] args;
+		if (program == null) {
+			args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "--quiet", "-nw", "-i", "mi", "-c", core.getAbsolutePath()}; 
+		} else {
+			args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "--quiet", "-nw", "-i", "mi", "-c", core.getAbsolutePath(), sboxExePath}; 
+		}
+		MIProcess pgdb = new ESboxMIProcessAdapter(args, monitor);
+		MISession session;
+		try {
+			session = createMISession(pgdb, null, MISession.CORE);
+			//@@@ We have to manually set the suspended state when doing post-mortem
+			session.getMIInferior().setSuspended();
+		} catch (MIException e) {
+			pgdb.destroy();
+			throw e;
+		}
+		return new Session(session);
+	}
+	
+	/**
+	 * Creates a session for attach sessions.
+	 * @param gdb the string for start GDB debugger.
+	 * @param program the programm to be debugged.
+	 * @param pid the PID of the process.
+	 * @param targetParams the parameters used for creating sessions.
+	 * @param cwd the location for running GDB.
+	 * @param gdbinit the gdbinit file
+	 * @param monitor the monitor for task progress.
+	 * @return the session created.
+	 * @throws IOException if any trouble related to I/O occurrs.
+	 * @throws MIException if any problem related to GDB invocation.
+	 */
+	public Session createCSession(String gdb, File program, int pid, String[] targetParams, File cwd, String gdbinit, IProgressMonitor monitor) throws IOException, MIException {		
+		if (gdb == null || gdb.length() == 0) {
+			gdb =  GDB;
+		}
+
+		if (gdbinit == null || gdbinit.length() == 0) {
+			gdbinit = GDBINIT;
+		}
+
+		if (monitor == null) {
+			monitor = new NullProgressMonitor();
+		}
+
+		String sboxDirPath = getSBoxDirPath(cwd);
+		String sboxExePath = getSBoxExePath(program);
+		
+		String[] args;
+		if (program == null) {
+			args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "--quiet", "-nw", "-i", "mi"}; 
+		} else {
+			args = new String[] {gdb, "--cd="+sboxDirPath, "--command="+gdbinit, "--quiet", "-nw", "-i", "mi", sboxExePath};
+		}
+		MIProcess pgdb = new ESboxMIProcessAdapter(args, monitor);
+		MISession session;
+		try {
+			session = createMISession(pgdb, null, MISession.ATTACH);
+		} catch (MIException e) {
+			pgdb.destroy();
+			throw e;
+		}
+		CommandFactory factory = session.getCommandFactory();
+		try {
+			if (targetParams != null && targetParams.length > 0) {
+				MITargetSelect target = factory.createMITargetSelect(targetParams);
+				session.postCommand(target);
+				MIInfo info = target.getMIInfo();
+				if (info == null) {
+					throw new MIException(MIPlugin.getResourceString("src.common.No_answer")); //$NON-NLS-1$
+				}
+			}
+			if (pid > 0) {
+				CLITargetAttach attach = factory.createCLITargetAttach(pid);
+				session.postCommand(attach);
+				MIInfo info = attach.getMIInfo();
+				if (info == null) {
+					throw new MIException(MIPlugin.getResourceString("src.common.No_answer")); //$NON-NLS-1$
+				}
+				session.getMIInferior().setInferiorPID(pid);
+				// @@@ for attach we nee to manually set the connected state
+				// attach does not send the ^connected ack
+				session.getMIInferior().setConnected();
+			}
+		} catch (MIException e) {
+			pgdb.destroy();
+			throw e;
+		}
+		//@@@ We have to manually set the suspended state when we attach
+		session.getMIInferior().setSuspended();
+		session.getMIInferior().update();
+		return new Session(session, true);
+	}
+	
+	/**
+	 * Create session for MI process. These kind of sessions are for debugging applications.
+	 * @param process 
+	 * @param pty
+	 * @param timeout
+	 * @param type
+	 * @param launchTimeout
+	 * @return
+	 * @throws MIException
+	 */
+	public MISession createMISession(MIProcess process, IMITTY pty, int timeout, int type, int launchTimeout) throws MIException {
+		return new MISession(process, pty, timeout, type, launchTimeout);
+	}
+
+	/**
+	 * Create a new MI session.
+	 * @param process
+	 * @param pty
+	 * @param type
+	 * @return
+	 * @throws MIException
+	 */
+	public MISession createMISession(MIProcess process, IMITTY pty, int type) throws MIException {
+		return createMISession(process, pty, CMDTIMEOUT, type, LAUNCHTIMEOUT);
+	}
+	
+	/**
+	 * Return the path of the file inside Scratchbox.
+	 * @param cwd the file from which the correct path will be extracted.
+	 * @return the path of the program inside Scratchbox. 
+	 */
+	private String getSBoxDirPath(File cwd) {
+		Preferences preferences = CoreActivator.getDefault().getPluginPreferences();
+		String sandbox = preferences.getString(ESboxPreferenceConstants.SBOX_SANDBOX.toString());	
+		String extDirPath = cwd.getAbsolutePath();		
+		String sboxDirPath;		
+		
+		if (extDirPath.indexOf(sandbox) != -1) {
+			sboxDirPath = extDirPath.substring(sandbox.length());
+		} else {
+			sboxDirPath = extDirPath;
+		}
+		
+		return sboxDirPath;
+	}
+	
+	/**
+	 * Return the path of the program inside Scratchbox.
+	 * @param program the program from which the correct path will be extracted.
+	 * @return the path of the program inside Scratchbox. 
+	 */
+	private String getSBoxExePath(File program) {
+		Preferences preferences = CoreActivator.getDefault().getPluginPreferences();
+		String sandbox = preferences.getString(ESboxPreferenceConstants.SBOX_SANDBOX.toString());				
+		String extExePath = program.getAbsolutePath();				
+		String sboxExePath;
+				
+		if (extExePath.indexOf(sandbox) != -1) {
+			sboxExePath = extExePath.substring(sandbox.length());
+		} else {
+			sboxExePath = extExePath;
+		}
+		
+		return sboxExePath;
+	}
+
+	
+}

Added: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBCDIDebugger.java
===================================================================
--- trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBCDIDebugger.java	                        (rev 0)
+++ trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBCDIDebugger.java	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,351 @@
+/*******************************************************************************
+ * Copyright (c) 2007 INdT.
+ * 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:
+ *    Raul Herbster (raul at embedded.ufcg.edu.br) (UFCG) - initial API and implementation
+ *******************************************************************************/
+
+package org.indt.esbox.debug.internal;
+
+import java.io.File;
+import java.text.DateFormat;
+import java.text.MessageFormat;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import org.eclipse.cdt.core.CCorePlugin;
+import org.eclipse.cdt.core.IBinaryParser.IBinaryObject;
+import org.eclipse.cdt.debug.core.ICDIDebugger2;
+import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
+import org.eclipse.cdt.debug.core.cdi.CDIException;
+import org.eclipse.cdt.debug.core.cdi.ICDISession;
+import org.eclipse.cdt.debug.core.cdi.model.ICDITarget;
+import org.eclipse.cdt.debug.mi.core.IMILaunchConfigurationConstants;
+import org.eclipse.cdt.debug.mi.core.MIPlugin;
+import org.eclipse.cdt.debug.mi.core.cdi.Session;
+import org.eclipse.cdt.debug.mi.core.cdi.SharedLibraryManager;
+import org.eclipse.cdt.debug.mi.core.cdi.model.Target;
+import org.eclipse.cdt.utils.BinaryObjectAdapter;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.MultiStatus;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.OperationCanceledException;
+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.ILaunchConfiguration;
+import org.eclipse.debug.core.model.IProcess;
+import org.indt.esbox.debug.DebugActivator;
+
+/**
+ * Debugger for ESbox applications. This is a debugger front-end for GDB; it correctly launches
+ * the application and create all sections for debugging the application.
+ */
+public class ESboxGDBCDIDebugger implements ICDIDebugger2 {
+
+	ILaunch fLaunch;
+
+
+	public ICDISession createSession(ILaunch launch, File executable,
+			IProgressMonitor monitor) throws CoreException {
+		fLaunch = launch;
+		ILaunchConfiguration config = launch.getLaunchConfiguration();
+		Session dsession = null;
+		String debugMode = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_START_MODE,
+				ICDTLaunchConfigurationConstants.DEBUGGER_MODE_RUN);
+
+		if (monitor == null) {
+			monitor = new NullProgressMonitor();
+		}
+		if (monitor.isCanceled()) {
+			throw new OperationCanceledException();
+		}
+
+		if (debugMode.equals(ICDTLaunchConfigurationConstants.DEBUGGER_MODE_RUN)) {
+			dsession = createLaunchSession(config, executable, monitor);
+		} else if (debugMode.equals(ICDTLaunchConfigurationConstants.DEBUGGER_MODE_ATTACH)) {
+			dsession = createAttachSession(config, executable, monitor);
+		} else if (debugMode.equals(ICDTLaunchConfigurationConstants.DEBUGGER_MODE_CORE)) {
+			dsession = createCoreSession(config, executable, monitor);
+		}
+		if (dsession != null) {
+			ICDITarget[] dtargets = dsession.getTargets();
+			for (int i = 0; i < dtargets.length; i++) {
+				Process debugger = dsession.getSessionProcess(dtargets[i]);
+				if (debugger != null) {
+					IProcess debuggerProcess = DebugPlugin.newProcess(launch, debugger, renderDebuggerProcessLabel());
+					launch.addProcess(debuggerProcess);
+				}
+			}
+		}
+
+		return dsession;
+	}
+	
+	/* (non-Javadoc)
+	 * @see org.eclipse.cdt.debug.core.ICDIDebugger#createDebuggerSession(org.eclipse.debug.core.ILaunch, org.eclipse.cdt.core.IBinaryParser.IBinaryExecutable, org.eclipse.core.runtime.IProgressMonitor)
+	 */
+	public ICDISession createDebuggerSession(ILaunch launch, IBinaryObject exe, IProgressMonitor monitor)
+			throws CoreException {
+		return this.createSession(launch, exe.getPath().toFile(), monitor);
+	}
+
+	/**
+	 * Create a launch session. 
+	 * @param config
+	 * @param exe
+	 * @param monitor
+	 * @return
+	 * @throws CoreException
+	 */
+	public Session createLaunchSession(ILaunchConfiguration config, File exe, IProgressMonitor monitor) throws CoreException {
+		Session session = null;
+		boolean failed = false;
+		try {
+			String gdb = config.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUG_NAME, "gdb"); //$NON-NLS-1$
+			boolean usePty = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL, true);
+			File cwd = getProjectPath(config).toFile();
+			String gdbinit = config.getAttribute(IMILaunchConfigurationConstants.ATTR_GDB_INIT, ".gdbinit"); //$NON-NLS-1$			
+			if (usePty) {
+				session = DebugActivator.getDefault().createCSession(gdb, exe, cwd, gdbinit, monitor);
+			} else {
+				session = DebugActivator.getDefault().createCSession(gdb, exe, cwd, gdbinit, null, monitor);
+			}
+			initializeLibraries(config, session);
+			return session;
+		} catch (Exception e) {
+			// Catch all wrap them up and rethrow
+			failed = true;
+			if (e instanceof CoreException) {
+				throw (CoreException)e;
+			}
+			throw newCoreException(e);
+		} finally {
+			if (failed) {
+				if (session != null) {
+					try {
+						session.terminate();
+					} catch (Exception ex) {
+						// ignore the exception here.
+					}
+				}
+			}
+		}
+	}
+
+	/**
+	 * Create an attach session.
+	 * @param config
+	 * @param exe
+	 * @param monitor
+	 * @return
+	 * @throws CoreException
+	 */
+	public Session createAttachSession(ILaunchConfiguration config, File exe, IProgressMonitor monitor) throws CoreException {
+		Session session = null;
+		boolean failed = false;
+		try {
+			String gdb = config.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUG_NAME, "gdb"); //$NON-NLS-1$
+			int pid = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_ATTACH_PROCESS_ID, -1);
+			File cwd = getProjectPath(config).toFile();
+			String gdbinit = config.getAttribute(IMILaunchConfigurationConstants.ATTR_GDB_INIT, ".gdbinit"); //$NON-NLS-1$
+			session = DebugActivator.getDefault().createCSession(gdb, exe, pid, null, cwd, gdbinit, monitor);
+			initializeLibraries(config, session);
+			return session;
+		} catch (Exception e) {
+			// Catch all wrap them up and rethrow
+			failed = true;
+			if (e instanceof CoreException) {
+				throw (CoreException)e;
+			}
+			throw newCoreException(e);
+		} finally {
+			if (failed) {
+				if (session != null) {
+					try {
+						session.terminate();
+					} catch (Exception ex) {
+						// ignore the exception here.
+					}
+				}
+			}
+		}
+	}
+
+	/**
+	 * 
+	 * @param config
+	 * @param exe
+	 * @param monitor
+	 * @return
+	 * @throws CoreException
+	 */
+	public Session createCoreSession(ILaunchConfiguration config, File exe, IProgressMonitor monitor) throws CoreException {
+		Session session = null;
+		boolean failed = false;
+		try {
+			String gdb = config.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUG_NAME, "gdb"); //$NON-NLS-1$
+			File cwd = getProjectPath(config).toFile();
+			IPath coreFile = new Path(config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH, (String)null));
+			String gdbinit = config.getAttribute(IMILaunchConfigurationConstants.ATTR_GDB_INIT, ".gdbinit"); //$NON-NLS-1$
+			session = DebugActivator.getDefault().createCSession(gdb, exe, coreFile.toFile(), cwd, gdbinit, monitor);
+			initializeLibraries(config, session);
+			return session;
+		} catch (Exception e) {
+			// Catch all wrap them up and rethrow
+			failed = true;
+			if (e instanceof CoreException) {
+				throw (CoreException)e;
+			}
+			throw newCoreException(e);
+		} finally {
+			if (failed) {
+				if (session != null) {
+					try {
+						session.terminate();
+					} catch (Exception ex) {
+						// ignore the exception here.
+					}
+				}
+			}
+		}
+	}
+
+	/**
+	 * 
+	 * @param config
+	 * @param session
+	 * @throws CoreException
+	 */
+	protected void initializeLibraries(ILaunchConfiguration config, Session session) throws CoreException {
+		try {
+			SharedLibraryManager sharedMgr = session.getSharedLibraryManager();
+			boolean autolib = config.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUGGER_AUTO_SOLIB, IMILaunchConfigurationConstants.DEBUGGER_AUTO_SOLIB_DEFAULT);
+			boolean stopOnSolibEvents = config.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUGGER_STOP_ON_SOLIB_EVENTS, IMILaunchConfigurationConstants.DEBUGGER_STOP_ON_SOLIB_EVENTS_DEFAULT);
+			List p = config.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUGGER_SOLIB_PATH, Collections.EMPTY_LIST);
+			ICDITarget[] dtargets = session.getTargets();
+			for (int i = 0; i < dtargets.length; ++i) {
+				Target target = (Target)dtargets[i];
+				try {
+					sharedMgr.setAutoLoadSymbols(target, autolib);
+					sharedMgr.setStopOnSolibEvents(target, stopOnSolibEvents);
+					// The idea is that if the user set autolib, by default
+					// we provide with the capability of deferred breakpoints
+					// And we set setStopOnSolib events for them(but they should not see those things.
+					//
+					// If the user explicitly set stopOnSolibEvents well it probably
+					// means that they wanted to see those events so do no do deferred breakpoints.
+					if (autolib && !stopOnSolibEvents) {
+						sharedMgr.setDeferredBreakpoint(target,true);
+						sharedMgr.setStopOnSolibEvents(target, true);
+					}
+				} catch (CDIException e) {
+					// Ignore this error
+					// it seems to be a real problem on many gdb platform
+				}
+				if (p.size() > 0) {
+					String[] oldPaths = sharedMgr.getSharedLibraryPaths(target);
+					String[] paths = new String[oldPaths.length + p.size()];
+					System.arraycopy(p.toArray(new String[p.size()]), 0, paths, 0, p.size());
+					System.arraycopy(oldPaths, 0, paths, p.size(), oldPaths.length);
+					sharedMgr.setSharedLibraryPaths(target, paths);
+				}
+			}
+		} catch (CDIException e) {
+			throw newCoreException(MIPlugin.getResourceString("src.GDBDebugger.Error_initializing_shared_lib_options") + e.getMessage(), e); //$NON-NLS-1$
+		}
+	}
+
+	public static IPath getProjectPath(ILaunchConfiguration configuration) throws CoreException {
+		String projectName = getProjectName(configuration);
+		if (projectName != null) {
+			projectName = projectName.trim();
+			if (projectName.length() > 0) {
+				IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
+				IPath p = project.getLocation();
+				if (p != null) {
+					return p;
+				}
+			}
+		}
+		return Path.EMPTY;
+	}
+
+	/**
+	 * Return the project name from the given launch configuration.
+	 * @param configuration the configuration from with the project name is extract.
+	 * @return the name of the project.
+	 * @throws CoreException
+	 */
+	public static String getProjectName(ILaunchConfiguration configuration) throws CoreException {
+		return configuration.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)null);
+	}
+
+	/**
+	 * Return the launch object.
+	 * @return the launch object.
+	 */
+	protected ILaunch getLauch() {
+		return fLaunch;
+	}
+
+	/**
+	 * 
+	 * @return
+	 */
+	protected String renderDebuggerProcessLabel() {
+		String format = "{0} ({1})"; //$NON-NLS-1$
+		String timestamp = DateFormat.getInstance().format(new Date(System.currentTimeMillis()));
+		String message = MIPlugin.getResourceString("src.GDBDebugger.Debugger_process"); //$NON-NLS-1$
+		return MessageFormat.format(format, new String[]{message, timestamp}); //$NON-NLS-1$
+	}
+
+	/**
+	 * Throws a core exception with an error status object built from the given
+	 * lower level exception.
+	 * 
+	 * @param exception
+	 *            lower level exception associated with the error, or
+	 *            <code>null</code> if none
+	 * @return a core exception created from the the given message and lower level exception.
+	 */
+	protected CoreException newCoreException(Throwable exception) {
+		String message = MIPlugin.getResourceString("src.GDBDebugger.Error_creating_session") + exception.getMessage();//$NON-NLS-1$
+		int code =  ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR;
+		String ID = DebugActivator.getUniqueIdentifier();
+		MultiStatus status = new MultiStatus(ID, code, message, exception);
+		status.add(new Status(IStatus.ERROR, ID, code, exception == null ? new String() : exception.getLocalizedMessage(), exception));
+		return new CoreException(status);
+	}
+
+	/**
+	 * Throws a core exception with an error status object built from the given
+	 * message and lower level exception.
+	 * 
+	 * @param message
+	 *            the status message
+	 * @param exception
+	 *            lower level exception associated with the error, or
+	 *            <code>null</code> if none
+	 * @return a core exception created from the the given message and lower level exception.
+	 */
+	protected CoreException newCoreException(String message, Throwable exception) {
+		int code =  ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR;
+		String ID = DebugActivator.getUniqueIdentifier();
+		MultiStatus status = new MultiStatus(ID, code, message, exception);
+		status.add(new Status(IStatus.ERROR, ID, code, exception == null ? new String() : exception.getLocalizedMessage(), exception));
+		return new CoreException(status);
+	}
+	
+}


Property changes on: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBCDIDebugger.java
___________________________________________________________________
Name: svn:executable
   + *

Added: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBServerCDIDebugger.java
===================================================================
--- trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBServerCDIDebugger.java	                        (rev 0)
+++ trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBServerCDIDebugger.java	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,180 @@
+/*******************************************************************************
+ * Copyright (c) 2007 INdT.
+ * 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:
+ *    Raul Herbster (raul at embedded.ufcg.edu.br) (UFCG) - initial API and implementation
+ *******************************************************************************/
+
+package org.indt.esbox.debug.internal;
+
+import java.io.File;
+
+import org.eclipse.cdt.core.IBinaryParser.IBinaryObject;
+import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
+import org.eclipse.cdt.debug.core.cdi.model.ICDITarget;
+import org.eclipse.cdt.debug.mi.core.IGDBServerMILaunchConfigurationConstants;
+import org.eclipse.cdt.debug.mi.core.IMIConstants;
+import org.eclipse.cdt.debug.mi.core.IMILaunchConfigurationConstants;
+import org.eclipse.cdt.debug.mi.core.MIException;
+import org.eclipse.cdt.debug.mi.core.MIPlugin;
+import org.eclipse.cdt.debug.mi.core.MISession;
+import org.eclipse.cdt.debug.mi.core.cdi.Session;
+import org.eclipse.cdt.debug.mi.core.cdi.model.Target;
+import org.eclipse.cdt.debug.mi.core.command.CommandFactory;
+import org.eclipse.cdt.debug.mi.core.command.MIGDBSet;
+import org.eclipse.cdt.debug.mi.core.command.MITargetSelect;
+import org.eclipse.cdt.debug.mi.core.output.MIInfo;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Preferences;
+import org.eclipse.debug.core.ILaunchConfiguration;
+import org.indt.esbox.core.CoreActivator;
+import org.indt.esbox.core.ESboxPreferenceConstants;
+import org.indt.esbox.core.scratchbox.ScratchboxCommandLauncher;
+import org.indt.esbox.debug.DebugActivator;
+
+/**
+ *  
+ */
+public class ESboxGDBServerCDIDebugger extends ESboxGDBCDIDebugger {
+
+	public static final String ATTR_GDB_SERVER = ICDTLaunchConfigurationConstants.CDT_LAUNCH_ID + ".gdb_server"; //$NON-NLS-1$
+
+	public static final boolean GDB_SERVER_DEFAULT = false;	
+		
+	/* (non-Javadoc)
+	 * @see org.eclipse.cdt.debug.mi.core.GDBCDIDebugger#createLaunchSession(org.eclipse.debug.core.ILaunchConfiguration, org.eclipse.cdt.core.IBinaryParser.IBinaryExecutable, org.eclipse.core.runtime.IProgressMonitor)
+	 */
+	public Session createLaunchSession(ILaunchConfiguration config, IBinaryObject exe, IProgressMonitor monitor)
+			throws CoreException {
+			
+		boolean gdbserver = GDB_SERVER_DEFAULT;
+
+		try {
+			gdbserver = config.getAttribute(ATTR_GDB_SERVER, GDB_SERVER_DEFAULT);
+		} catch (CoreException e) {
+			e.printStackTrace();
+		}
+
+		if (gdbserver) {			
+			// start GDB server inside scratchbox
+			startGDBServer(exe);
+			// add 0.5 secs wait for starting GDB server
+			try {
+				Thread.sleep(500);
+			} catch (InterruptedException e) {
+				e.printStackTrace();
+			}
+		}		
+
+		Session session = null;
+		boolean failed = false;
+		try {			
+			String gdb = config.getAttribute(IMILaunchConfigurationConstants.ATTR_DEBUG_NAME, "gdb"); 
+			File cwd = getProjectPath(config).toFile();
+			String gdbinit = config.getAttribute(IMILaunchConfigurationConstants.ATTR_GDB_INIT, ".gdbinit");
+			if (config.getAttribute(IGDBServerMILaunchConfigurationConstants.ATTR_REMOTE_TCP, false)) {
+				String remote = config.getAttribute(IGDBServerMILaunchConfigurationConstants.ATTR_HOST, "invalid");
+				remote += ":";
+				remote += config.getAttribute(IGDBServerMILaunchConfigurationConstants.ATTR_PORT, "invalid"); 
+				String[] args = new String[] {"remote", remote}; 
+				session = DebugActivator.getDefault().createCSession(gdb, exe.getPath().toFile(), 0, args, cwd, gdbinit, monitor);
+			} else {
+				MIPlugin plugin = MIPlugin.getDefault();
+				Preferences prefs = plugin.getPluginPreferences();
+				int launchTimeout = prefs.getInt(IMIConstants.PREF_REQUEST_LAUNCH_TIMEOUT);
+
+				String remote = config.getAttribute(IGDBServerMILaunchConfigurationConstants.ATTR_DEV, "invalid"); 
+				String remoteBaud = config.getAttribute(IGDBServerMILaunchConfigurationConstants.ATTR_DEV_SPEED, "invalid");				
+				session = DebugActivator.getDefault().createCSession(gdb, exe.getPath().toFile(), -1, null, cwd, gdbinit, monitor);
+				ICDITarget[] targets = session.getTargets();
+				for (int i = 0; i < targets.length; ++i) {
+					Target target = (Target)targets[i];
+					MISession miSession = target.getMISession();
+					CommandFactory factory = miSession.getCommandFactory();
+					MIGDBSet setRemoteBaud = factory.createMIGDBSet(new String[]{"remotebaud", remoteBaud}); 
+					// Set serial line parameters
+					miSession.postCommand(setRemoteBaud, launchTimeout);
+					MIInfo info = setRemoteBaud.getMIInfo();
+					if (info == null) {
+						throw new MIException (MIPlugin.getResourceString("src.GDBServerDebugger.Can_not_set_Baud")); 
+					}
+					MITargetSelect select = factory.createMITargetSelect(new String[] {"remote", remote}); 
+					miSession.postCommand(select, launchTimeout);
+					select.getMIInfo();
+					if (info == null) {
+						throw new MIException (MIPlugin.getResourceString("src.common.No_answer")); 
+					}
+				}
+			}
+			initializeLibraries(config, session);
+			return session;
+		} catch (Exception e) {
+			// Catch all wrap them up and rethrow
+			failed = true;
+			if (e instanceof CoreException) {
+				throw (CoreException)e;
+			}
+			throw newCoreException(e);
+		} finally {
+			if (failed) {
+				if (session != null) {
+					try {
+						session.terminate();
+					} catch (Exception ex) {
+						// ignore the exception here.
+					}
+				}
+			}
+		}
+
+	}
+
+	/**
+	 * @param exe
+	 * 
+	 * Method that starts GDB server inside Scratchbox with binary that comes
+	 * from param. Command that will run inside Scratchbox can modify in Window ->
+	 * Preferences -> Scratchbox Preferences
+	 */
+	private void startGDBServer(IBinaryObject exe) {
+
+		// get preferences from SbCorePlugin		
+		Preferences prefs = CoreActivator.getDefault().getPluginPreferences();
+
+		// Scratchbox command launcher
+		ScratchboxCommandLauncher launcher = new ScratchboxCommandLauncher();
+
+		Path wd = (Path) exe.getPath();		
+		wd = (Path) wd.removeLastSegments(1);
+
+		// TODO verify which type of connection (if ARMEL, there are two)
+		
+		String command = prefs.getString(ESboxPreferenceConstants.SBOX_GDB_REMOTE_QEMU.toString());
+				
+		// check if command exist
+		if (command.length() > 0) {
+			command = command.replaceAll("\\$\\{binary\\}", exe.getName());			
+			Path cmd = new Path(command);
+			
+			Process p = launcher.execute(cmd, new String[] {},
+					new String[] {}, wd);
+
+			if (p == null) {
+				System.out.println("Error starting GDB server inside Scratchbox");
+			}
+
+//			// print all output to console
+//			new SbStreamMonitor(p.getInputStream(), true, new String("Starting GDB server inside Scratchbox"));
+//			// print all errors to console
+//			new SbStreamMonitor(p.getErrorStream(), false, null);
+		}
+	}	
+	
+	
+}


Property changes on: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxGDBServerCDIDebugger.java
___________________________________________________________________
Name: svn:executable
   + *

Added: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxMIProcessAdapter.java
===================================================================
--- trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxMIProcessAdapter.java	                        (rev 0)
+++ trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxMIProcessAdapter.java	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,122 @@
+/*******************************************************************************
+ * Copyright (c) 2007 INdT.
+ * 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:
+ *    Raul Herbster (raul at embedded.ufcg.edu.br) (UFCG) - initial API and implementation
+ *******************************************************************************/
+
+package org.indt.esbox.debug.internal;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+
+import org.eclipse.cdt.debug.mi.core.IMIConstants;
+import org.eclipse.cdt.debug.mi.core.MIPlugin;
+import org.eclipse.cdt.debug.mi.core.MIProcessAdapter;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Preferences;
+import org.indt.esbox.core.scratchbox.ScratchboxCommandLauncher;
+import org.indt.esbox.debug.DebugActivator;
+
+/**
+ * 
+ */
+public class ESboxMIProcessAdapter extends MIProcessAdapter {
+
+	public ESboxMIProcessAdapter(String[] args, IProgressMonitor monitor) throws IOException {
+		super(args,monitor);
+	}
+
+	/**
+	 * Do some basic synchronisation, gdb may take some time to load for
+	 * whatever reasons and we need to be able to let the user bailout.
+	 * 
+	 * @param args
+	 * @return Process
+	 * @throws IOException
+	 */
+	protected Process getGDBProcess(String[] args, IProgressMonitor monitor) throws IOException {
+		int ONE_SECOND = 1000;
+
+		/*
+		if (DebugActivator.getDefault().isDebugging()) {
+			StringBuffer sb = new StringBuffer();
+			for (int i = 0; i < args.length; ++i) {
+				sb.append(args[i]);
+				sb.append(' ');
+			}			
+		}
+		*/	
+								
+		ScratchboxCommandLauncher launcher = new ScratchboxCommandLauncher();
+		
+		final Process pgdb = launcher.execute(null, args, new String[] {}, new Path("."));
+		
+		Thread syncStartup = new Thread("GDB Start") { //$NON-NLS-1$
+			public void run() {
+				try {
+					String line;
+					InputStream stream = pgdb.getInputStream();
+					Reader r = new InputStreamReader(stream);
+					BufferedReader reader = new BufferedReader(r);
+					while ((line = reader.readLine()) != null) {
+						line = line.trim();
+						//System.out.println("GDB " + line);
+						if (line.endsWith("(gdb)")) { //$NON-NLS-1$
+							break;
+						}
+					}
+				} catch (Exception e) {
+					// Do nothing, ignore the errors
+				}
+			}
+		};
+		syncStartup.start();
+
+		MIPlugin miPlugin = MIPlugin.getDefault();
+		Preferences prefs = miPlugin.getPluginPreferences();
+		int timepass = 0;
+		int launchTimeout = prefs.getInt(IMIConstants.PREF_REQUEST_LAUNCH_TIMEOUT);
+		if (launchTimeout <= 0) {
+			// Simulate we are waiting forever.
+			launchTimeout = Integer.MAX_VALUE;
+		}
+
+		// To respect the IProgressMonitor we can not use wait/notify
+		// instead we have to loop and check for the monitor to allow to cancel the thread.
+		// The monitor is check every 1 second delay;
+		for (timepass = 0; timepass < launchTimeout; timepass += ONE_SECOND) {
+			if (syncStartup.isAlive() && !monitor.isCanceled()) {
+				try {
+					Thread.sleep(ONE_SECOND);
+				} catch (InterruptedException e) {
+					// ignore
+				}
+			} else {
+				break;
+			}
+		}
+		try {
+			syncStartup.interrupt();
+			syncStartup.join(ONE_SECOND);
+		} catch (InterruptedException e) {
+			// ignore
+		}
+		if (monitor.isCanceled()) {
+			pgdb.destroy();			
+			throw new IOException("Error creating Scratchbox debugger session");
+		} else if (timepass > launchTimeout) {
+			pgdb.destroy();			
+			throw new IOException("Error launching Scratchbox debugger session, timeout");
+		}
+		return pgdb;
+	}
+}


Property changes on: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/internal/ESboxMIProcessAdapter.java
___________________________________________________________________
Name: svn:executable
   + *

Added: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/ui/GDBServerDebuggerPage.java
===================================================================
--- trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/ui/GDBServerDebuggerPage.java	                        (rev 0)
+++ trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/ui/GDBServerDebuggerPage.java	2007-10-11 12:56:51 UTC (rev 115)
@@ -0,0 +1,303 @@
+/*******************************************************************************
+ * Copyright (c) 2007 INdT.
+ * 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:
+ *    Raul Herbster (raul at embedded.ufcg.edu.br) (UFCG) - initial API and implementation
+ *******************************************************************************/
+
+package org.indt.esbox.debug.ui;
+
+import java.io.File;
+
+import org.eclipse.cdt.debug.mi.core.IGDBServerMILaunchConfigurationConstants;
+import org.eclipse.cdt.debug.mi.internal.ui.GDBDebuggerPage;
+import org.eclipse.cdt.debug.mi.internal.ui.MIUIMessages;
+import org.eclipse.cdt.debug.mi.internal.ui.PixelConverter;
+import org.eclipse.cdt.debug.mi.internal.ui.SerialPortSettingsBlock;
+import org.eclipse.cdt.debug.mi.internal.ui.TCPSettingsBlock;
+import org.eclipse.cdt.debug.mi.internal.ui.dialogfields.ComboDialogField;
+import org.eclipse.cdt.debug.mi.internal.ui.dialogfields.DialogField;
+import org.eclipse.cdt.debug.mi.internal.ui.dialogfields.IDialogFieldListener;
+import org.eclipse.cdt.debug.mi.internal.ui.dialogfields.LayoutUtil;
+import org.eclipse.cdt.utils.ui.controls.ControlFactory;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.debug.core.ILaunchConfiguration;
+import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StackLayout;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.TabFolder;
+import org.eclipse.swt.widgets.TabItem;
+import org.indt.esbox.debug.internal.ESboxGDBServerCDIDebugger;
+
+/**
+ * 
+ */
+public class GDBServerDebuggerPage extends GDBDebuggerPage {
+
+	private final static String CONNECTION_TCP = MIUIMessages.getString( "GDBServerDebuggerPage.0" ); //$NON-NLS-1$
+
+	private final static String CONNECTION_SERIAL = MIUIMessages.getString( "GDBServerDebuggerPage.1" ); //$NON-NLS-1$
+
+	private ComboDialogField fConnectionField;
+
+	private String[] fConnections = new String[]{ CONNECTION_TCP, CONNECTION_SERIAL };
+
+	private TCPSettingsBlock fTCPBlock;
+
+	private SerialPortSettingsBlock fSerialBlock;
+
+	private Composite fConnectionStack;
+	
+	private Button fGDBServerButton;
+
+	private boolean fIsInitializing = false;
+
+	/**
+	 * Constructor.
+	 */
+	public GDBServerDebuggerPage() {
+		super();
+		fConnectionField = createConnectionField();
+		fTCPBlock = new TCPSettingsBlock();
+		fSerialBlock = new SerialPortSettingsBlock();
+		fTCPBlock.addObserver( this );
+		fSerialBlock.addObserver( this );
+	}
+
+	/*
+	 *  (non-Javadoc)
+	 * @see org.eclipse.cdt.debug.mi.internal.ui.GDBDebuggerPage#createMainTab(org.eclipse.swt.widgets.TabFolder)
+	 */
+	public void createMainTab( TabFolder tabFolder ) {
+		TabItem tabItem = new TabItem( tabFolder, SWT.NONE );
+		tabItem.setText( MIUIMessages.getString( "GDBServerDebuggerPage.2" ) ); //$NON-NLS-1$
+		Composite comp = ControlFactory.createCompositeEx( fTabFolder, 1, GridData.FILL_BOTH );
+		((GridLayout)comp.getLayout()).makeColumnsEqualWidth = false;
+		tabItem.setControl( comp );
+		Composite subComp = ControlFactory.createCompositeEx( comp, 3, GridData.FILL_HORIZONTAL );
+		((GridLayout)subComp.getLayout()).makeColumnsEqualWidth = false;
+		Label label = ControlFactory.createLabel( subComp, MIUIMessages.getString( "GDBServerDebuggerPage.3" ) ); //$NON-NLS-1$
+		GridData gd = new GridData();
+		label.setLayoutData( gd );
+
+		fGDBServerButton = createCheckButton(comp, "Start GDBServer Automatically."); 
+		fGDBServerButton.setSelection(ESboxGDBServerCDIDebugger.GDB_SERVER_DEFAULT);
+		fGDBServerButton.addSelectionListener(new SelectionAdapter() {
+
+			public void widgetSelected(SelectionEvent evt) {
+				updateLaunchConfigurationDialog();
+
+			}
+		});
+				
+		fGDBCommandText = ControlFactory.createTextField( subComp, SWT.SINGLE | SWT.BORDER );
+		fGDBCommandText.addModifyListener( new ModifyListener() {
+
+			public void modifyText( ModifyEvent evt ) {
+				if ( !isInitializing() )
+					updateLaunchConfigurationDialog();
+			}
+		} );
+		Button button = createPushButton( subComp, MIUIMessages.getString( "GDBServerDebuggerPage.4" ), null ); //$NON-NLS-1$
+		button.addSelectionListener( new SelectionAdapter() {
+
+			public void widgetSelected( SelectionEvent evt ) {
+				if ( !isInitializing() ) {
+					handleGDBButtonSelected();
+					updateLaunchConfigurationDialog();
+				}
+			}
+
+			private void handleGDBButtonSelected() {
+				FileDialog dialog = new FileDialog( getShell(), SWT.NONE );
+				dialog.setText( MIUIMessages.getString( "GDBServerDebuggerPage.5" ) ); //$NON-NLS-1$
+				String gdbCommand = fGDBCommandText.getText().trim();
+				int lastSeparatorIndex = gdbCommand.lastIndexOf( File.separator );
+				if ( lastSeparatorIndex != -1 ) {
+					dialog.setFilterPath( gdbCommand.substring( 0, lastSeparatorIndex ) );
+				}
+				String res = dialog.open();
+				if ( res == null ) {
+					return;
+				}
+				fGDBCommandText.setText( res );
+			}
+		} );
+		label = ControlFactory.createLabel( subComp, MIUIMessages.getString( "GDBServerDebuggerPage.6" ) ); //$NON-NLS-1$
+		gd = new GridData();
+		label.setLayoutData( gd );
+		fGDBInitText = ControlFactory.createTextField( subComp, SWT.SINGLE | SWT.BORDER );
+		gd = new GridData( GridData.FILL_HORIZONTAL );
+		fGDBInitText.setLayoutData( gd );
+		fGDBInitText.addModifyListener( new ModifyListener() {
+
+			public void modifyText( ModifyEvent evt ) {
+				if ( !isInitializing() )
+					updateLaunchConfigurationDialog();
+			}
+		} );
+		button = createPushButton( subComp, MIUIMessages.getString( "GDBServerDebuggerPage.7" ), null ); //$NON-NLS-1$
+		button.addSelectionListener( new SelectionAdapter() {
+
+			public void widgetSelected( SelectionEvent evt ) {
+				if ( !isInitializing() ) {
+					handleGDBInitButtonSelected();
+					updateLaunchConfigurationDialog();
+				}
+			}
+
+			private void handleGDBInitButtonSelected() {
+				FileDialog dialog = new FileDialog( getShell(), SWT.NONE );
+				dialog.setText( MIUIMessages.getString( "GDBServerDebuggerPage.8" ) ); //$NON-NLS-1$
+				String gdbCommand = fGDBInitText.getText().trim();
+				int lastSeparatorIndex = gdbCommand.lastIndexOf( File.separator );
+				if ( lastSeparatorIndex != -1 ) {
+					dialog.setFilterPath( gdbCommand.substring( 0, lastSeparatorIndex ) );
+				}
+				String res = dialog.open();
+				if ( res == null ) {
+					return;
+				}
+				fGDBInitText.setText( res );
+			}
+		} );
+		extendMainTab( comp );
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see org.eclipse.cdt.debug.mi.internal.ui.GDBDebuggerPage#extendMainTab(org.eclipse.swt.widgets.Composite)
+	 */
+	protected void extendMainTab( Composite parent ) {
+		Composite comp = ControlFactory.createCompositeEx( parent, 2, GridData.FILL_BOTH );
+		((GridLayout)comp.getLayout()).makeColumnsEqualWidth = false;
+		fConnectionField.doFillIntoGrid( comp, 2 );
+		((GridData)fConnectionField.getComboControl( null ).getLayoutData()).horizontalAlignment = GridData.BEGINNING;
+		PixelConverter converter = new PixelConverter( comp );
+		LayoutUtil.setWidthHint( fConnectionField.getComboControl( null ), converter.convertWidthInCharsToPixels( 15 ) );
+		fConnectionStack = ControlFactory.createCompositeEx( comp, 1, GridData.FILL_BOTH );
+		StackLayout stackLayout = new StackLayout();
+		fConnectionStack.setLayout( stackLayout );
+		((GridData)fConnectionStack.getLayoutData()).horizontalSpan = 2;
+		fTCPBlock.createBlock( fConnectionStack );
+		fSerialBlock.createBlock( fConnectionStack );
+	}
+
+	private ComboDialogField createConnectionField() {
+		ComboDialogField field = new ComboDialogField( SWT.DROP_DOWN | SWT.READ_ONLY );
+		field.setLabelText( MIUIMessages.getString( "GDBServerDebuggerPage.9" ) ); //$NON-NLS-1$
+		field.setItems( fConnections );
+		field.setDialogFieldListener( new IDialogFieldListener() {
+
+			public void dialogFieldChanged( DialogField f ) {
+				if ( !isInitializing() )
+					connectionTypeChanged();
+			}
+		} );
+		return field;
+	}
+
+	protected void connectionTypeChanged() {
+		connectionTypeChanged0();
+		updateLaunchConfigurationDialog();
+	}
+
+	private void connectionTypeChanged0() {
+		((StackLayout)fConnectionStack.getLayout()).topControl = null;
+		int index = fConnectionField.getSelectionIndex();
+		if ( index >= 0 && index < fConnections.length ) {
+			String[] connTypes = fConnectionField.getItems();
+			if ( CONNECTION_TCP.equals( connTypes[index] ) )
+				((StackLayout)fConnectionStack.getLayout()).topControl = fTCPBlock.getControl();
+			else if ( CONNECTION_SERIAL.equals( connTypes[index] ) )
+				((StackLayout)fConnectionStack.getLayout()).topControl = fSerialBlock.getControl();
+		}
+		fConnectionStack.layout();
+	}
+
+	public boolean isValid( ILaunchConfiguration launchConfig ) {
+		if ( super.isValid( launchConfig ) ) {
+			setErrorMessage( null );
+			setMessage( null );
+			int index = fConnectionField.getSelectionIndex();
+			if ( index >= 0 && index < fConnections.length ) {
+				String[] connTypes = fConnectionField.getItems();
+				if ( CONNECTION_TCP.equals( connTypes[index] ) ) {
+					if ( !fTCPBlock.isValid( launchConfig ) ) {
+						setErrorMessage( fTCPBlock.getErrorMessage() );
+						return false;
+					}
+				}
+				else if ( CONNECTION_SERIAL.equals( connTypes[index] ) ) {
+					if ( !fSerialBlock.isValid( launchConfig ) ) {
+						setErrorMessage( fSerialBlock.getErrorMessage() );
+						return false;
+					}
+				}
+				return true;
+			}
+		}
+		return false;
+	}
+
+	public void initializeFrom( ILaunchConfiguration configuration ) {
+		setInitializing( true );
+		super.initializeFrom( configuration );
+		boolean isTcp = false;
+		try {
+			isTcp = configuration.getAttribute( IGDBServerMILaunchConfigurationConstants.ATTR_REMOTE_TCP, false );
+		}
+		catch( CoreException e ) {
+		}
+		fTCPBlock.initializeFrom( configuration );
+		fSerialBlock.initializeFrom( configuration );
+		fConnectionField.selectItem( (isTcp) ? 0 : 1 );
+		connectionTypeChanged0();
+		setInitializing( false );
+		updateGdbServerStateFromConfig(configuration);
+	}
+	
+    protected void updateGdbServerStateFromConfig(ILaunchConfiguration config) {
+    }
+
+	public void performApply( ILaunchConfigurationWorkingCopy configuration ) {
+		super.performApply( configuration );
+		if ( fConnectionField != null )
+			configuration.setAttribute( IGDBServerMILaunchConfigurationConstants.ATTR_REMOTE_TCP, fConnectionField.getSelectionIndex() == 0 );
+		fTCPBlock.performApply( configuration );
+		fSerialBlock.performApply( configuration );
+		configuration.setAttribute(ESboxGDBServerCDIDebugger.ATTR_GDB_SERVER, fGDBServerButton.getSelection());
+	}
+
+	public void setDefaults( ILaunchConfigurationWorkingCopy configuration ) {
+		super.setDefaults( configuration );
+		configuration.setAttribute( IGDBServerMILaunchConfigurationConstants.ATTR_REMOTE_TCP, false );
+		fTCPBlock.setDefaults( configuration );
+		fSerialBlock.setDefaults( configuration );
+    	configuration.setAttribute(ESboxGDBServerCDIDebugger.ATTR_GDB_SERVER,
+    			ESboxGDBServerCDIDebugger.GDB_SERVER_DEFAULT);
+	}
+
+	protected boolean isInitializing() {
+		return fIsInitializing;
+	}
+
+	private void setInitializing( boolean isInitializing ) {
+		fIsInitializing = isInitializing;
+	}
+}


Property changes on: trunk/org.indt.esbox.debug/src/org/indt/esbox/debug/ui/GDBServerDebuggerPage.java
___________________________________________________________________
Name: svn:executable
   + *



More information about the Esbox-commits mailing list